diff --git a/3rdparty/Vulkan-Headers b/3rdparty/Vulkan-Headers index 2fa203425eb4..5d94bb4dcc96 160000 --- a/3rdparty/Vulkan-Headers +++ b/3rdparty/Vulkan-Headers @@ -1 +1 @@ -Subproject commit 2fa203425eb4af9dfc6b03f97ef72b0b5bcb8350 +Subproject commit 5d94bb4dcc968cccce1f601324fcaf3eda92a52b diff --git a/CMakeLists.txt b/CMakeLists.txt index 5caa0080a487..638123ee913f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -228,6 +228,14 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ControlFlow/include) add_test(NAME request_serializer COMMAND request_serializer_tests) set_tests_properties(request_serializer PROPERTIES TIMEOUT 20) + add_test_executable(heap_template_budget_tests + ${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp) + target_include_directories(heap_template_budget_tests PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/core/libs + ${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler + ${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ControlFlow/include) + add_test(NAME heap_template_budget COMMAND heap_template_budget_tests) + set_tests_properties(heap_template_budget PROPERTIES TIMEOUT 20) find_package(Python3 QUIET COMPONENTS Interpreter) add_test_executable(shader_ir_use_rewrite_tests core/shader/recompiler/IntermediateRepresentation/tests/UseRewrite.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index ac4c683009d9..748735553991 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -195,6 +195,18 @@ add_custom_command( VERBATIM ) +set(agcTextureDetileAddressedShaderSpv ${agcTextureDetileGeneratedDir}/TextureDetileAddressed.spv) +set(agcTextureDetileAddressedShaderHeader ${agcTextureDetileGeneratedDir}/TextureDetileAddressed_spv.h) +add_custom_command( + OUTPUT "${agcTextureDetileAddressedShaderHeader}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${agcTextureDetileGeneratedDir}" + COMMAND "$" -V --target-env vulkan1.1 -DADDRESSED=1 -o "${agcTextureDetileAddressedShaderSpv}" "${agcTextureDetileShaderSource}" + COMMAND ${CMAKE_COMMAND} -DINPUT=${agcTextureDetileAddressedShaderSpv} -DOUTPUT=${agcTextureDetileAddressedShaderHeader} + -DSYMBOL=TEXTURE_DETILE_ADDRESSED_SPV -P "${CMAKE_CURRENT_SOURCE_DIR}/embed_spirv.cmake" + DEPENDS "${agcTextureDetileShaderSource}" glslang-standalone + VERBATIM +) + set(agcTextureRepackShaderSource ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/TextureRepack.comp) set(agcTextureRepackShaderSpv ${agcTextureDetileGeneratedDir}/TextureRepack.spv) set(agcTextureRepackShaderHeader ${agcTextureDetileGeneratedDir}/TextureRepack_spv.h) @@ -207,6 +219,17 @@ add_custom_command( DEPENDS "${agcTextureRepackShaderSource}" glslang-standalone VERBATIM ) +set(agcTextureRepackAddressedShaderSpv ${agcTextureDetileGeneratedDir}/TextureRepackAddressed.spv) +set(agcTextureRepackAddressedShaderHeader ${agcTextureDetileGeneratedDir}/TextureRepackAddressed_spv.h) +add_custom_command( + OUTPUT "${agcTextureRepackAddressedShaderHeader}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${agcTextureDetileGeneratedDir}" + COMMAND "$" -V --target-env vulkan1.1 -DADDRESSED=1 -o "${agcTextureRepackAddressedShaderSpv}" "${agcTextureRepackShaderSource}" + COMMAND ${CMAKE_COMMAND} -DINPUT=${agcTextureRepackAddressedShaderSpv} -DOUTPUT=${agcTextureRepackAddressedShaderHeader} + -DSYMBOL=TEXTURE_REPACK_ADDRESSED_SPV -P "${CMAKE_CURRENT_SOURCE_DIR}/embed_spirv.cmake" + DEPENDS "${agcTextureRepackShaderSource}" glslang-standalone + VERBATIM +) set(agcDispatchArgumentsShaderSource ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/DispatchArguments.comp) set(agcDispatchArgumentsShaderSpv ${agcTextureDetileGeneratedDir}/DispatchArguments.spv) @@ -376,6 +399,7 @@ set(agcDriverSources ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawCache.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawCacheStatistics.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawCapture.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/HeapStages.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawDecode.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawLookup.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -458,6 +482,7 @@ set(agcDriverSources ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/DeferredDestruction.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/MemoryAccounting.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/PlaceholderImages.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/DescriptorHeapObjects.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/Recorder.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/ParallelCompare.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/ShaderInputState.cpp @@ -488,6 +513,7 @@ set(agcDriverSources ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/UnitShadow.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/Sampler.cpp ${agcSampleOrderShaderHeaders} + ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/BindlessHeap.cpp ${agcTextureDetileShaderHeader} ${agcReadbackHeaders} ${agcMultisampleUploadHeader} @@ -497,6 +523,8 @@ set(agcDriverSources ${agcStagingCopyBackShaderHeader} ${agcTextureDetileImageShaderHeader} ${agcTextureRepackShaderHeader} + ${agcTextureDetileAddressedShaderHeader} + ${agcTextureRepackAddressedShaderHeader} ${agcDispatchArgumentsShaderHeader} ${agcTextureDetileWordsShaderHeader} ${agcTextureDetileImageWordsShaderHeader} @@ -756,19 +784,33 @@ function(agc_add_default_test agcTest) endif() endfunction() -function(agc_add_draw_pipeline_test agcTestName) - add_test(NAME ${agcTestName}_draw_pipeline COMMAND ${agcTestName}_tests) - set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") +function(agc_add_env_test agcTestName agcTestTarget) + cmake_parse_arguments(PARSE_ARGV 2 agcEnvTest "NO_WORKING_DIRECTORY" "TIMEOUT" "ARGS;ENV") + add_test(NAME ${agcTestName} COMMAND ${agcTestTarget} ${agcEnvTest_ARGS}) + set_tests_properties(${agcTestName} PROPERTIES ENVIRONMENT "${agcEnvTest_ENV}" SKIP_RETURN_CODE 77) + if(NOT agcEnvTest_NO_WORKING_DIRECTORY) + set_tests_properties(${agcTestName} PROPERTIES WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + if(agcEnvTest_TIMEOUT) + set_tests_properties(${agcTestName} PROPERTIES TIMEOUT ${agcEnvTest_TIMEOUT}) endif() - add_test(NAME ${agcTestName}_plan_verify COMMAND ${agcTestName}_tests) - set_tests_properties(${agcTestName}_plan_verify PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1;APS5_VERIFY_DRAW_PLAN=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") if(WIN32) - set_tests_properties(${agcTestName}_plan_verify PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_tests_properties(${agcTestName} PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endfunction() +function(agc_add_draw_pipeline_test agcTestName) + agc_add_env_test(${agcTestName}_draw_pipeline ${agcTestName}_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) + agc_add_env_test(${agcTestName}_plan_verify ${agcTestName}_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1 APS5_VERIFY_DRAW_PLAN=1) +endfunction() + +function(agc_add_gpu_heap_test agcTestName) + agc_add_env_test(${agcTestName}_gpu_heap ${agcTestName}_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) +endfunction() + function(agc_add_spirv_mode_tests agcTest) if(NOT TARGET ${agcTest}) return() @@ -1116,7 +1158,7 @@ endif() if(BUILD_TESTING) get_directory_property(agcRegisteredTests TESTS) - list(FILTER agcRegisteredTests EXCLUDE REGEX "^(agc_pipeline_journal(_long_paths|_extended_paths)?|agc_driver_pipeline_journal(_undecodable_module)?|agc_pipeline_store_replay_growth|agc_pipeline_journal_replay_priority)$") + list(FILTER agcRegisteredTests EXCLUDE REGEX "^(agc_pipeline_journal(_long_paths|_extended_paths)?|agc_driver_pipeline_journal(_undecodable_module|_gpu_heap)?|agc_pipeline_store_replay_growth|agc_pipeline_journal_replay_priority)$") set_property(TEST ${agcRegisteredTests} APPEND PROPERTY ENVIRONMENT "APS5_NO_PIPELINE_JOURNAL=1") endif() diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp index 8f18242101b5..bd2f4c7ddad0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp @@ -75,11 +75,15 @@ struct DispatchVariant { std::vector> shaderDataPatches; std::uint64_t userDataMask = ~std::uint64_t{0}; std::shared_ptr vertexInfo; + std::shared_ptr ringTemplate; + std::vector> ringDescriptorPatches; + std::vector> ringDataPatches; std::shared_ptr memory; std::vector captured; std::vector> spans; std::atomic generation{0}; + mutable std::atomic cleanPendingSerial{~0ull}; }; struct DispatchEntry { diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp index 4d2c3bc14b95..2740b668fc7c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp @@ -58,6 +58,7 @@ struct PreparedGraphicsStage { ShaderRecompiler::ShaderStage stage = ShaderRecompiler::ShaderStage::Vertex; std::uint32_t pushOffset = 0; std::shared_ptr registration; + bool heapVariant = false; }; std::vector PrepareGraphicsStages(const DrawDecode& decoded, const ShaderRecompiler::SpirvTarget& target, bool deferUnprepared = false); @@ -123,6 +124,8 @@ class DrawKeySightings { enum class DrawVerdict { Drawn, Nothing, Rejected }; +enum class StageOrigin { Captured, HeapUnread, HeapRead }; + struct StageCapture { std::shared_ptr compiled; std::shared_ptr capture; @@ -131,8 +134,15 @@ struct StageCapture { std::vector> supplied; std::uint64_t forgetSerial = 0; std::uint32_t pushOffset = 0; - ShaderRecompiler::SrtUserDataUse userDataUse; std::uint64_t userDataMask = ~std::uint64_t{0}; + StageOrigin origin = StageOrigin::Captured; + std::shared_ptr heapWords; + std::shared_ptr> heapReadWords; + + const ShaderRecompiler::SrtUserDataUse& UserDataUse() const; + + bool Cacheable() const { return origin != StageOrigin::HeapUnread; } + bool Direct() const { return origin != StageOrigin::Captured; } }; struct RelocatableUserWord { @@ -163,7 +173,7 @@ struct DrawRelocationTrial { }; struct DrawRelocationCounters { - std::uint64_t lookups = 0, donors = 0, refused = 0, hits = 0, evicted = 0; + std::uint64_t lookups = 0, donors = 0, refused = 0, hits = 0, evicted = 0, admitted = 0; }; bool DecodeProgramsCurrent(const DrawDecode& decode, const ShaderRegistry& registry); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp index a8baa3a5fdcd..215296aef225 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp @@ -51,6 +51,7 @@ class DrawPipeline { static std::uint64_t DrainRequestsByOpcode(std::uint32_t opcode); static std::uint64_t DrainRequestsByReason(DrainReason reason); bool Busy() const; + std::uint32_t FullWaiters(); std::size_t Outstanding() const { return outstanding.load(std::memory_order_acquire); } bool Overlaps(std::uint64_t address, std::size_t bytes); bool OverlapsAny(std::span> ranges); @@ -98,6 +99,7 @@ class DrawPipeline { std::atomic decodeDrains{0}; std::uint64_t reportedDecodeDrains = 0; std::uint32_t idleWaiters = 0; + std::uint32_t fullWaiters = 0; std::size_t resumeAt = 0; bool committerWaiting = false; bool stopped = false; @@ -139,7 +141,7 @@ class DrawFinisher { LabelLookup PendingLabel(std::uint64_t address, std::size_t bytes, std::uint64_t& value); bool PendingOverlapsAny(std::span ranges); bool PendingKey(std::uint64_t key, std::uint64_t shape); - enum class DrainSite : std::uint32_t { Lookup, Reads, Packet, Kept, Count }; + enum class DrainSite : std::uint32_t { Lookup, Reads, Packet, Kept, Dispatch, Count }; static void NoteDrain(DrainSite site, bool drained); static std::string DrainText(); static void NoteDrainedOpcode(std::uint32_t opcode, bool besideCommits); @@ -149,6 +151,7 @@ class DrawFinisher { static bool Busy() { return outstanding.load(std::memory_order_acquire) != 0; } void Enqueue(Job job); void Enqueue(Job job, Pending held); + void EnqueueBeside(Job job, std::vector writes, std::uint64_t labelAddress = 0, std::vector labelBytes = {}); void Drain(); void Settle(); void ReleaseRan(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp new file mode 100644 index 000000000000..2ee225760110 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -0,0 +1,68 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_HEAPSTAGES_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_HEAPSTAGES_HPP + +#include "Optimization/ResourceProgram.hpp" +#include "UserDataUse.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::DriverDetail { + +struct DispatchVariant; + +bool HeapStageExcluded(ShaderRecompiler::ShaderStage stage); +bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage); +const char* HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan); +bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan); +bool HeapExcludedFor(const ShaderRecompiler::PreparedShaderInvocation& invocation); +bool HeapClassesExcluded(); +void RequireHeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress = false); +bool HeapStageFits(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress = false); + +bool SampleHeapStageVerify(); + +struct HeapStageReads { + std::shared_ptr>> ranges; + std::shared_ptr> values; + std::shared_ptr capture; + bool complete = false; +}; + +struct HeapStageMaterialized { + std::shared_ptr result; + std::shared_ptr words; + HeapStageReads reads; +}; + +void ResetHeapStageWords(ShaderRecompiler::HeapStageWords& words); + +void AppendWalkRead(std::vector>& runs, std::uint64_t address); + +void CoalesceWalkReads(std::vector>& runs, std::vector>& ranges); + +HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + ShaderRecompiler::MemoryRegionView memory, std::uint64_t shaderBase); +void NoteHeapDirect(); +void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, + const ShaderRecompiler::ResourceCapture* expectedCapture = nullptr); +std::uint64_t HeapStagesTaken(); + +std::uint64_t NextHeapDataOrigin(); +std::uint64_t HeapRingHitsVerified(); +std::uint64_t HeapRingHitsDiffering(); +std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, + const ShaderRecompiler::HeapStageWords& words); +void BuildRingWords(const DispatchVariant& variant, std::span user, const std::vector* refreshedData, ShaderRecompiler::HeapStageWords& words); +void VerifyHeapAccessor(const Graphics::CompiledShader& stage); +void VerifyRingWords(const ShaderRecompiler::RecompileResult& kept, const ShaderRecompiler::HeapStageWords& ring, + const ShaderRecompiler::RecompileResult& fresh, const ShaderRecompiler::HeapStageWords* freshWords); + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp new file mode 100644 index 000000000000..bb59f1e2d1be --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp @@ -0,0 +1,62 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_RECYCLEDSHARED_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_RECYCLEDSHARED_HPP + +#include +#include +#include +#include +#include + +namespace AgcDriver::DriverDetail { + +template +class RecycledShared { +public: + RecycledShared(std::size_t capacity, std::size_t probes) : capacity(capacity), probes(probes) {} + + template + std::shared_ptr Take(TReset&& reset) { + for (std::size_t probe = 0; probe < probes && probe < pool.size(); ++probe) { + auto& candidate = pool[cursor]; + advance(); + if (candidate.use_count() != 1) continue; + std::atomic_thread_fence(std::memory_order_acquire); + reset(*candidate); + ++reused; + return candidate; + } + auto made = std::make_shared(); + ++fresh; + if (pool.size() < capacity) { + pool.push_back(made); + } else if (!pool.empty()) { + pool[cursor] = made; + advance(); + } + return made; + } + + std::uint64_t Reused() const { + return reused; + } + + std::uint64_t Fresh() const { + return fresh; + } + +private: + void advance() { + cursor = cursor + 1 >= pool.size() ? 0 : cursor + 1; + } + + std::vector> pool; + std::size_t cursor = 0; + std::size_t capacity; + std::size_t probes; + std::uint64_t reused = 0; + std::uint64_t fresh = 0; +}; + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp index b7421e6a0482..48eb81d158d1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp @@ -57,6 +57,33 @@ inline std::uint32_t ThreadDimensionGroups(std::uint32_t threads, std::uint32_t struct DrawTail; +struct DrawStageContext { + const QueueState& queue; + const Submission& submission; + std::size_t packetOffset; + std::uint64_t traceToken; + const std::vector& programs; + const Graphics::State& graphics; + const ShaderRecompiler::ShaderPixelStageInfo& pixel; + const std::vector>& vertexInfos; + std::vector& memory; + const std::vector& linked; + const std::shared_ptr& localDevice; + ShaderMemory& shaderMemory; + std::vector& stageCaptures; + std::vector& recompiled; + const bool& drawHit; + const std::vector>& matched; + const std::vector>& matchedRegions; + bool profile; + std::uint64_t dumpTarget; + std::uint64_t dumpSlot1; + std::uint64_t& captures; + DrawPhaseTiming& phaseTiming; + std::array& phaseMs; + const std::optional& meshBarycentrics; +}; + class Driver { public: static Driver& Get(); @@ -111,9 +138,9 @@ class Driver { [[nodiscard]] std::vector> PreparedEntryHashes(const Shader* shader); [[nodiscard]] std::array PrebuiltLibraries(); static void FoldDrawOffsets(const ShaderRecompiler::RecompileResult& result, const DrawProgram& program, Pm4::DrawParameters& parameters); - static std::optional ClassifyIndirectDraw(const ShaderRecompiler::RecompileResult& result, const Graphics::State& graphics, const DrawProgram& frontProgram, const std::shared_ptr& localDevice, Pm4::DrawParameters& drawParameters, bool traceIndirect); + static std::optional ClassifyIndirectDraw(const ShaderRecompiler::RecompileResult& result, const Graphics::State& graphics, const DrawProgram& frontProgram, const std::shared_ptr& localDevice, Pm4::DrawParameters& drawParameters, bool traceIndirect, const ShaderRecompiler::HeapStageWords* heap = nullptr); static void tagVariantRuns(DispatchVariant& variant, std::span regions, const ShaderRecompiler::SrtUserDataUse& use, bool eligible, std::uint32_t hiddenWords, std::span> supplied = {}); - static void tagUserValueWords(DispatchVariant& variant, const DrawProgram& program); + static void tagUserValueWords(DispatchVariant& variant, const DrawProgram& program, const ShaderRecompiler::HeapStageWords* heap = nullptr); static std::uint64_t relocatedContentKey(const RelocatableUserWord& word, std::uint32_t value, bool& readable); static void applyShaderDataPatches(DispatchVariant& variant); static std::string dumpRequest(std::uint64_t address, const ShaderRecompiler::RecompileRequest& request, std::string_view suffix = {}); @@ -220,6 +247,8 @@ class Driver { void accountDrawVariant(const DispatchVariant& variant, bool added); void insertDrawEntry(std::uint64_t key, std::vector>& fresh, std::shared_ptr decode, std::uint64_t shape = 0, bool replaceShape = false); bool admitDrawKey(std::uint64_t key, std::uint64_t shape); + DrawKeySightings& drawKeySightingsTable(); + DrawKeySightings& drawShapeSightingsTable(); void eraseDrawEntry(std::uint64_t key, const std::shared_ptr& expected); std::shared_ptr findDrawRecipe(std::uint64_t key, const std::vector>& stages, const std::shared_ptr& donor = nullptr); void attachDrawRecipe(std::uint64_t key, const std::vector>& stages, std::shared_ptr recipe, const std::shared_ptr& donor = nullptr); @@ -241,7 +270,11 @@ class Driver { std::shared_ptr decodeDraw(const QueueState& queue, const Submission& submission, const Graphics::Context& context); void resolveDrawDecode(const QueueState& queue, const Submission& submission, const Graphics::Context& context, std::shared_ptr& decode, bool registerKey, std::uint64_t drawKey, bool profile); void lookupDraw(const Submission& submission, const std::shared_ptr& localDevice, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector& programs, const std::vector& roles, const std::vector>& vertexInfos, bool useDrawEntries, bool registerKey, bool profile, std::uint64_t& drawKey, std::shared_ptr& entry, std::vector>& matched, std::vector>& matchedRegions, bool& drawHit, bool& verifyHit, DrawPhaseTiming& phaseTiming, std::array& phaseMs, const std::shared_ptr& dataEntry, DrawDataCandidates& dataCandidates, std::vector& stageData); - std::shared_ptr materializeDrawStage(std::size_t i, std::uint32_t pushOffset, const QueueState& queue, const Submission& submission, std::size_t packetOffset, std::uint64_t traceToken, const std::vector& programs, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector>& vertexInfos, std::vector& memory, const std::vector& linked, const Pm4::DrawParameters& drawParameters, const std::shared_ptr& localDevice, ShaderMemory& shaderMemory, std::vector& stageCaptures, std::vector& recompiled, bool drawHit, const std::vector>& matched, const std::vector>& matchedRegions, bool profile, std::uint64_t dumpTarget, std::uint64_t dumpSlot1, std::uint64_t& captures, DrawPhaseTiming& phaseTiming, std::array& phaseMs, std::string& rejected, const std::optional& meshBarycentrics); + ShaderRecompiler::RecompileRequest drawStageRequest(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters); + bool drawStageExcluded(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters); + std::shared_ptr materializeDrawStage(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters, bool heapDraw); + bool materializeHeapDirect(const DrawStageContext& context, std::size_t i, const ShaderRecompiler::PreparedShaderInvocation& invocation, const ShaderRecompiler::RecompileRequest& request, PerformanceTimer& timing); + static std::runtime_error stageFailure(const DrawProgram& program, const ShaderRecompiler::RecompileRequest& request, const std::exception& error, std::span regions); static void recordStageDataPositions(DispatchVariant& variant, const ShaderRecompiler::ResourceCapture& capture, const std::vector& decodeReads); void cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawParameters& drawParameters, const std::optional& indirectCpu, const std::vector& programs, const std::vector& stageCaptures, const std::vector>& vertexInfos, const std::vector>& decodeReads, bool verifyHit, const std::vector>& matched, const std::vector& stageData, std::vector>& fresh, std::uint64_t drawKey, bool registerKey, const std::shared_ptr& decode, DrawPhaseTiming& phaseTiming, const std::vector& reused, const std::shared_ptr& entry, std::uint64_t shapeKey, bool shapeNeedsEntry = false); static bool drawPrecheck(); @@ -331,6 +364,7 @@ class Driver { bool labelPacketQueues(std::span packet, std::uint32_t opcode); bool enqueueLabelPacket(std::span packet, std::uint32_t opcode, std::uint32_t queue, std::optional interrupt); bool enqueueDmaPacket(std::span packet, std::uint32_t opcode, std::uint32_t queue, const QueueState& state); + bool sampleDumpQueues(std::span packet, std::uint32_t opcode, std::uint32_t queue); bool enqueueSampleDumpPacket(std::span packet, std::uint32_t opcode, std::uint32_t queue); bool enqueueConstantRamDump(std::span packet, std::uint32_t opcode, std::uint32_t queue, const QueueState& state); void commitStore(std::uint32_t queue, std::uint64_t address, std::span bytes); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp index f1419567989f..17f38ed9ad19 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp @@ -374,6 +374,8 @@ struct OwnedRecompileRequest { std::shared_ptr OwnRecompileRequest(const ShaderRecompiler::RecompileRequest& source, ShaderRecompiler::MemoryRegionView memory); ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, bool deferPreparation = false, std::shared_ptr* linking = nullptr); std::shared_ptr MaterializeInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr& capture, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address); +std::uint64_t HeapTemplatesBuiltInBackground(); +std::shared_ptr MaterializeHeapInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr& capture, ShaderRecompiler::HeapStageWords& words, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address); std::shared_ptr CaptureInvocation(ShaderMemory& memory, const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, ShaderRecompiler::PreparedShaderInvocation& invocation, std::shared_ptr* linking = nullptr); bool StageLinksUserDataCallees(const ShaderSnapshot& snapshot, std::size_t codeOffset); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp index b1592f10c877..af9c8b9f7674 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp @@ -177,8 +177,10 @@ void SetObservationHookForTest(void (*hook)(int point)); // tracker mutex, so every collect that bumped before it has finished its walk and every later // collect stamps newer. std::uint64_t TrackerGeneration(); +std::uint64_t StableTrackerGeneration(); void AdvanceTrackerGenerationForTest(std::uint64_t generation); std::uint64_t NewestStamp(std::uint64_t address, std::size_t bytes); +bool NoStampAfter(std::span> ranges, std::uint64_t generation); std::uint64_t UntrackedHint(std::uint64_t address, std::size_t bytes); // Whether no CPU write touched the range since `generation`: an uncached resetting collect of the // range's pages first (a game store not collected yet becomes a block stamp), then the compare over diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp index 4911d1032edd..bd3414b8c820 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp @@ -4,6 +4,7 @@ #define VK_NO_PROTOTYPES #include #include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include #include @@ -46,8 +47,10 @@ class PresentationPass { struct Target { VkRenderPass renderPass = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; }; - struct Slot { + struct Slot : Graphics::HeapSlotOwner { + using Graphics::HeapSlotOwner::ReleaseHeapSlots; VkDescriptorSet set = VK_NULL_HANDLE; VkImageView source = VK_NULL_HANDLE; std::uint32_t width = 0; @@ -74,12 +77,14 @@ class PresentationPass { void releaseDumpTarget(Slot& slot) noexcept; void ensureUploadImage(Slot& slot, VkExtent2D extent); void releaseUploadImage(Slot& slot) noexcept; - void draw(VkCommandBuffer commands, const Slot& slot, const Target& target, VkFramebuffer framebuffer, VkExtent2D extent, VkRect2D scissor, const std::int32_t (¶meters)[9]) const; + void draw(VkCommandBuffer commands, Slot& slot, const Target& target, VkFramebuffer framebuffer, VkExtent2D extent, VkRect2D scissor, const std::int32_t (¶meters)[9]) const; void recordInto(VkCommandBuffer commands, std::size_t slot, VkImage destination, VkFormat format, VkColorSpaceKHR colorSpace, VkExtent2D extent, VkImageLayout finalLayout, const AspectFitRect& rect); void release() noexcept; Graphics::Context context; + VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; VkSampler sampler = VK_NULL_HANDLE; + bool heap = false; VkDescriptorSetLayout descriptorLayout = VK_NULL_HANDLE; VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; VkDescriptorPool descriptorPool = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp index 8b3445b6845b..c5e0ee80c6d5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp @@ -3,6 +3,7 @@ #define VK_NO_PROTOTYPES #include +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include #include @@ -34,6 +35,7 @@ class PresentationUpscaler { struct Target { VkRenderPass renderPass = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; }; struct Surface { VkImage image = VK_NULL_HANDLE; @@ -42,7 +44,8 @@ class PresentationUpscaler { VkFormat format = VK_FORMAT_UNDEFINED; VkExtent2D extent{}; }; - struct Slot { + struct Slot : Graphics::HeapSlotOwner { + using Graphics::HeapSlotOwner::ReleaseHeapSlots; Surface stage; Surface upscaled; VkDescriptorSet easuSet = VK_NULL_HANDLE; @@ -51,16 +54,18 @@ class PresentationUpscaler { }; const Target& target(VkFormat format, VkImageLayout finalLayout, Filter filter); - void ensureSurface(Surface& surface, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage); - void releaseSurface(Surface& surface) noexcept; + void ensureSurface(Slot& slot, Surface& surface, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage); + void releaseSurface(Slot& slot, Surface& surface) noexcept; VkImageView createView(VkImage image, VkFormat format, VkImageUsageFlags usage) const; VkFramebuffer transientFramebuffer(Slot& slot, VkRenderPass renderPass, VkImage image, VkFormat format, VkExtent2D extent, VkImageLayout finalLayout); void bindSource(VkDescriptorSet set, VkImageView view) const; - void draw(VkCommandBuffer commands, const Target& target, VkFramebuffer framebuffer, VkExtent2D extent, VkDescriptorSet set, const void* parameters, std::uint32_t size) const; + void draw(VkCommandBuffer commands, Slot& slot, const Target& target, VkFramebuffer framebuffer, VkExtent2D extent, VkDescriptorSet set, VkImageView source, const void* parameters, std::uint32_t size) const; void release() noexcept; Graphics::Context context; float sharpness; + bool heap = false; + VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; VkSampler sampler = VK_NULL_HANDLE; VkDescriptorSetLayout descriptorLayout = VK_NULL_HANDLE; VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp index 3ab0d7e78df6..31fd44bddf69 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp @@ -85,6 +85,7 @@ struct DrawRecipe { std::uint32_t fragmentOutputs = 0; VkPipelineStageFlags shaderStages = 0; bool hasDepth = false; + bool movedBuffers = false; }; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp index 685a99cde621..5b608f79b1fb 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp @@ -80,6 +80,7 @@ class VulkanDevice { void SavePipelineCache(); // Compute pipelines this device built, by dispatches and by the journal replay (tests). std::uint64_t ComputePipelinesCreated() const; + std::uint64_t DescriptorHeapComputePipelines() const; ~VulkanDevice(); VulkanDevice(const VulkanDevice&) = delete; VulkanDevice& operator=(const VulkanDevice&) = delete; @@ -348,6 +349,7 @@ class VulkanDevice { // Whether dispatch-cache hits use recipes (APS5_NO_DISPATCH_RECIPE unset) and whether every // hit is verified (APS5_VERIFY_RECIPE=1). static bool DispatchRecipes(); + static std::string DispatchRecipeRefusalText(); static bool VerifyRecipes(); // Whether compute templates refresh their data buffers with a hit's words instead of keying // them (APS5_NO_TEMPLATE_DATA_REFRESH unset); the driver's data-only hits require it. @@ -361,8 +363,9 @@ class VulkanDevice { static void NoteRecipe(RecipeEvent event, RecipeKind kind); enum class DrawRecipePrecheck : std::size_t { NoRecipe, Device }; static void NoteDrawRecipeMiss(DrawRecipePrecheck miss); - using DrawTraceContext = Graphics::DrawTraceContext; static std::uint64_t DrawRecipeHits(); + static std::uint64_t DispatchRecipeTemplatesGone(); + using DrawTraceContext = Graphics::DrawTraceContext; // `recipe`, when given, receives the DrawRecipe a recorded, cacheable, reusable, direct draw // built for its draw-cache entry (design_cpu_final M8); null otherwise. void Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots = {}, std::shared_ptr* recipe = nullptr, const DrawTraceContext* trace = nullptr, std::uint64_t shape = 0, const std::vector* contentKey = nullptr); @@ -386,11 +389,13 @@ class VulkanDevice { IndirectDrawSupport DrawIndirectSupport() const; void EnqueueDraw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots = {}); bool PrebuildGraphicsLibraries(const Graphics::ShaderStages& stages, std::span shaders); + const Graphics::Context& contextRef(std::optional& scratch) const; public: // The device's Graphics::Context: a copy of the one built at setup (its instance functions // resolved then, its function table filled then), or with APS5_NO_CONTEXT_CACHE=1 built anew. Graphics::Context graphicsContext() const; + bool TimelineSemaphores() const; VkPipelineCreateFlags computePipelineFlags() const; std::uint32_t computeSubgroupSize(const ShaderRecompiler::RecompileResult& shader) const; VkPipelineShaderStageCreateFlags computeStageFlags(const ShaderRecompiler::RecompileResult& shader) const; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index 927e026835da..4243745aca7f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -2,6 +2,8 @@ #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/BufferCopy.hpp" @@ -27,6 +29,19 @@ namespace AgcDriver::DriverDetail { namespace { +template +class Lazy { +public: + template + const TValue& Get(TCompute&& compute) { + if (!value.has_value()) value.emplace(compute()); + return *value; + } + +private: + std::optional value; +}; + bool DispatchItemsEnabled() { static const bool enabled = [] { const char* text = std::getenv("APS5_PIPELINE_DISPATCH"); @@ -64,7 +79,7 @@ void ReportDispatchItems(bool profile) { std::snprintf(item, sizeof(item), " %s %llu", ItemFallbackNames[i], static_cast(itemFallbacks[i].load(std::memory_order_relaxed))); drained += item; } - std::fprintf(stderr, "[dispatch-item] %llu commit items (%llu recipes rebuilt on the committer, %llu queued after a cache miss, %llu queued without a recipe, %llu cached ones kept off the queue as not plain); drained instead, cumulative:%s\n", static_cast(itemCommits.load(std::memory_order_relaxed)), static_cast(itemRebuilds.load(std::memory_order_relaxed)), static_cast(itemMisses.load(std::memory_order_relaxed)), static_cast(itemRecipeLess.load(std::memory_order_relaxed)), static_cast(itemNotPlain.load(std::memory_order_relaxed)), drained.c_str()); + std::fprintf(stderr, "[dispatch-item] %llu commit items (%llu recipes rebuilt on the committer, %llu queued after a cache miss, %llu queued without a recipe, %llu cached ones kept off the queue as not plain); drained instead, cumulative:%s; recipes refused:%s\n", static_cast(itemCommits.load(std::memory_order_relaxed)), static_cast(itemRebuilds.load(std::memory_order_relaxed)), static_cast(itemMisses.load(std::memory_order_relaxed)), static_cast(itemRecipeLess.load(std::memory_order_relaxed)), static_cast(itemNotPlain.load(std::memory_order_relaxed)), drained.c_str(), VulkanDevice::DispatchRecipeRefusalText().c_str()); } } @@ -155,6 +170,26 @@ void Driver::dispatch(QueueState& queue, std::span packet, } const bool pipelineCandidate = !resolving && !fromAhead && DispatchItemsEnabled() && DrawPipeline::Active() && indirectArguments == 0 && deferredLabels().labels.empty() && !matchesCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesStreamCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesTableCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesIndexedCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute); const bool partialLastGroup = partialGroups != std::array{}; + Lazy htileClear; + Lazy> memoryValueFill; + Lazy> htileBufferMaskClear; + const auto htileClearAddress = [&] { return htileClear.Get([&] { return Graphics::HtileDepthClearAddress(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads); }); }; + const auto matchedMemoryValueFill = [&]() -> const std::optional& { + return memoryValueFill.Get([&] { return Graphics::MatchMemoryValueFill(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads, {packet[1], packet[2], packet[3]}); }); + }; + const auto matchedHtileBufferMaskClear = [&]() -> const std::optional& { + return htileBufferMaskClear.Get([&] { return Graphics::MatchHtileBufferMaskClear(std::span(snapshot.code).subspan(codeOffset), userData, compute, packet, indirectArguments); }); + }; + if (!resolving && DrawPipeline::Active() && DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread()) { + const auto code = std::span(snapshot.code).subspan(codeOffset); + const bool handled = !pipelineCandidate || Graphics::MatchMultisampledSingleClear(code, userData, compute.numThreads) || matchesFillKernel(code, userData, compute) || + (indirectArguments == 0 && (MatchDwordPatternFill(packet, code, userData, compute) || MatchConstantDwordFill(packet, code, userData, compute) || + MatchClampedGlobalFill(packet, code, userData, compute) || MatchMemoryValueBufferFill(packet, code, userData, compute) || + matchedMemoryValueFill().has_value())) || + htileClearAddress() != 0 || matchedHtileBufferMaskClear().has_value(); + if (handled) DrawFinisher::Get().Drain(); + DrawFinisher::NoteDrain(DrawFinisher::DrainSite::Dispatch, handled); + } std::optional> htileClearCompletion; Graphics::HtileMaskClear htileMask; if (resolving) { @@ -169,7 +204,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, return; } if (indirectArguments == 0 && (packet[4] & 0x20u) == 0) { - if (const auto fill = Graphics::MatchMemoryValueFill(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads, {packet[1], packet[2], packet[3]})) Graphics::NoteMemoryValueFill(*fill); + if (const auto& fill = matchedMemoryValueFill()) Graphics::NoteMemoryValueFill(*fill); } if (!partialLastGroup && fillBuffer(queue, submission.queue, packet, std::span(snapshot.code).subspan(codeOffset), userData, compute, localDevice)) { pendingDispatchPhases().outcome = DispatchOutcome::FillHle; @@ -177,13 +212,13 @@ void Driver::dispatch(QueueState& queue, std::span packet, return; } if (DrawPipeline::Active() && !pipelineCandidate) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, 0x15); - if (const auto htile = Graphics::HtileDepthClearAddress(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads); htile != 0) { + if (const auto htile = htileClearAddress(); htile != 0) { const auto threads = (packet[4] & 0x20u) != 0 ? static_cast(packet[1]) : static_cast(packet[1]) * compute.numThreads[0]; const auto nativeBytes = Graphics::HtileDepthClearBytes_nid_no_patch(std::span(snapshot.code).subspan(codeOffset), userData, compute, packet, indirectArguments); const auto bytes = static_cast(threads * 16u); if (Graphics::NoteHtileDepthClear(htile, bytes, nativeBytes)) htileClearCompletion = std::pair{htile, bytes}; if (nativeBytes != 0u) htileMask = {htile, nativeBytes, userData[5], userData[4]}; - } else if (const auto buffered = Graphics::MatchHtileBufferMaskClear(std::span(snapshot.code).subspan(codeOffset), userData, compute, packet, indirectArguments)) { + } else if (const auto& buffered = matchedHtileBufferMaskClear()) { if (Graphics::NoteHtileDepthClear(buffered->address, buffered->bytes, buffered->bytes)) htileClearCompletion = std::pair{buffered->address, buffered->bytes}; htileMask = *buffered; } @@ -211,6 +246,28 @@ void Driver::dispatch(QueueState& queue, std::span packet, localDevice->ComputeTarget((packet[4] & 0x8000u) != 0 ? 32u : 64u), {0, 0, 0, threadGroup != std::array{} ? 0u : 128u} }; + if (request.target.gpuResolvedImages && HeapStageExcluded(ShaderRecompiler::ShaderStage::Compute)) request.target.gpuResolvedImages = false; + if (request.target.gpuResolvedImages && HeapClassesExcluded()) { + try { + const auto invocation = InvocationFor(snapshot, codeOffset, request); + if (HeapExcludedFor(invocation)) { + Graphics::NoteHeapExcluded(Graphics::HeapExcluded::Dispatch); + request.target.gpuResolvedImages = false; + } + } catch (const DrawCompilePending&) { + return; + } catch (const std::exception& error) { + std::string reason = error.what(); + if (const auto newline = reason.find('\n'); newline != std::string::npos) reason.resize(newline); + if (SkipRefusedDispatches()) { + ReportRefusedDispatch(address, reason); + return; + } + char where[96]; + std::snprintf(where, sizeof(where), "compute shader 0x%llx: ", static_cast(address)); + throw std::runtime_error(where + reason); + } + } static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; static std::atomic captureMs{0}, keyMs{0}, recompileMs{0}, deviceMs{0}; static std::atomic cacheHits{0}; @@ -321,6 +378,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, } mix(reinterpret_cast(registeredShader.get())); + mix(request.target.gpuResolvedImages); if (fromAhead && key != ahead.key) { fromAhead = false; ++groupStats.keyMismatches; @@ -431,6 +489,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, timing.Mark("capture_resources"); compiledResult = MaterializeInBackground(invocation, capture, request.context.memory, address); + if (compiledResult->gpuResolvedImages) RequireHeapStageMappable(*compiledResult, compiledResult->workgroupMemoryDwords != 0); timing.Mark("materialize"); if (profile && compiledResult->cacheHit) cacheHits.fetch_add(1, std::memory_order_relaxed); const auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); @@ -595,7 +654,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, const auto epoch = DrawPipeline::EpochToken().load(std::memory_order_relaxed); const auto queueId = submission.queue; itemCommits.fetch_add(1, std::memory_order_relaxed); - DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Dispatch, [this, localDevice = std::move(localDevice), result = compiledResult, capture, registeredViews, snapshots = std::move(snapshots), liveWords = std::move(liveWords), groups, address, queueId, recipe, keepVariant, attach, prepareThreads, dataHit, epoch, htileClearCompletion, htileMask] { + auto commit = [this, localDevice = std::move(localDevice), result = compiledResult, capture, registeredViews, snapshots = std::move(snapshots), liveWords = std::move(liveWords), groups, address, queueId, recipe, keepVariant, attach, prepareThreads, dataHit, epoch, htileClearCompletion, htileMask] { DrawPipeline::FollowEpoch(epoch); GuestMemory::SetCurrentPacket(0x15, queueId); const auto& compiledCommit = *result; @@ -644,7 +703,15 @@ void Driver::dispatch(QueueState& queue, std::span packet, std::snprintf(where, sizeof(where), "compute shader 0x%llx: ", static_cast(address)); throw std::runtime_error(where + std::string(error.what())); } - }, std::move(itemWrites)); + }; + if (DrawFinisher::Overlap() && DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread()) { + auto held = itemWrites; + DrawFinisher::Get().EnqueueBeside([commit = std::move(commit), writes = std::move(itemWrites)]() mutable { + DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Dispatch, std::move(commit), std::move(writes)); + }, std::move(held)); + } else { + DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Dispatch, std::move(commit), std::move(itemWrites)); + } ReportDispatchItems(profile); return; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp index f3a1ef1830c7..dd6cdc7a1467 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp @@ -68,7 +68,12 @@ Driver::DispatchCacheFootprint Driver::DispatchCacheSize() { std::uint64_t Driver::variantBytes(const DispatchVariant& variant) { const auto held = [](const auto& values) { return static_cast(values.capacity() * sizeof(values[0])); }; - auto bytes = sizeof(DispatchVariant) + held(variant.runs) + held(variant.words) + held(variant.shared) + held(variant.dataPositions) + held(variant.dataSlots) + held(variant.runBases) + held(variant.shaderDataPatches) + held(variant.captured) + held(variant.spans) + (variant.registeredViews != nullptr ? held(*variant.registeredViews) : 0u) + (variant.vertexInfo != nullptr ? sizeof(ShaderRecompiler::ShaderVertexStageInfo) : 0) + (variant.memory != nullptr ? variant.memory->Bytes() : 0); + auto bytes = sizeof(DispatchVariant) + held(variant.runs) + held(variant.words) + held(variant.shared) + held(variant.dataPositions) + held(variant.dataSlots) + held(variant.runBases) + held(variant.shaderDataPatches) + held(variant.captured) + held(variant.spans) + (variant.registeredViews != nullptr ? held(*variant.registeredViews) : 0u) + (variant.vertexInfo != nullptr ? sizeof(ShaderRecompiler::ShaderVertexStageInfo) : 0) + (variant.memory != nullptr ? variant.memory->Bytes() : 0) + held(variant.ringDescriptorPatches) + held(variant.ringDataPatches); + if (variant.ringTemplate != nullptr) { + const auto& ring = *variant.ringTemplate; + bytes += sizeof(ring) + held(ring.userData) + held(ring.flattenedSrt) + held(ring.vertexAttributes) + held(ring.bindings); + for (const auto& words : ring.bindings) bytes += held(words); + } if (variant.linking != nullptr) { const auto& link = *variant.linking; bytes += sizeof(link) + held(link.callees) + held(link.code) + held(link.tableUserData) + held(link.dependencies); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp index c689c7909c4c..ae0264fde3fc 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp @@ -49,6 +49,7 @@ void Driver::appendEntryRegions(const DispatchVariant& variant, std::vector Driver::patchDataWords(const DispatchVariant& variant, const std::vector& words) { + if (variant.ringTemplate != nullptr && !variant.ringTemplate->flattenedSrt.empty()) return variant.compiled; auto patched = std::make_shared(*variant.compiled); auto& descriptor = patched->bindings[variant.flatBinding].guestDescriptor; for (std::size_t k = 0; k < variant.dataPositions.size(); ++k) { @@ -118,6 +119,13 @@ bool Driver::vouchedValidation() { return enabled; } +namespace { +bool verifyPendingSerialSkip() { + static const bool verify = std::getenv("APS5_VERIFY_PENDING_SERIAL_SKIP") != nullptr; + return verify; +} +} + EntryOutcome Driver::validateVariant(std::uint64_t program, std::uint32_t queue, const DispatchVariant& variant, std::span regions, std::uint64_t& imagesFlushed, std::uint64_t& runsSynced, std::optional& sampling, std::vector>* live) { if (live != nullptr) live->clear(); if (DrawPipeline::Active()) { @@ -155,7 +163,15 @@ EntryOutcome Driver::validateVariant(std::uint64_t program, std::uint32_t queue, auto pendingSerial = Graphics::StorageTexture::PendingSerial(); auto forget = GuestMemory::ForgetSerial(); - if (Graphics::StorageTexture::AnyPendingOverlaps(runs) || Graphics::AnyShadowedOverlaps(runs)) { + const bool wholeRuns = vouched.empty(); + bool pendingOverlaps = false; + if (!wholeRuns || variant.cleanPendingSerial.load(std::memory_order_acquire) != pendingSerial) { + pendingOverlaps = Graphics::StorageTexture::AnyPendingOverlaps(runs); + if (wholeRuns && !pendingOverlaps) variant.cleanPendingSerial.store(pendingSerial, std::memory_order_release); + } else if (verifyPendingSerialSkip()) { + if (Graphics::StorageTexture::AnyPendingOverlaps(runs) && Graphics::StorageTexture::PendingSerial() == pendingSerial) throw std::runtime_error("APS5_VERIFY_PENDING_SERIAL_SKIP: a dispatch variant skipped its pending image check at an unchanged serial while a pending image overlaps its runs"); + } + if (pendingOverlaps || Graphics::AnyShadowedOverlaps(runs)) { vouched.clear(); for (const auto& region : regions) { if (Graphics::StorageTexture::FlushPending(region.guestAddress, region.bytes.size(), nullptr, "dispatch-cache entry")) ++imagesFlushed; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 03de50683e76..ffffdca3f576 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -7,6 +7,9 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawProgramTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" @@ -31,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -40,6 +44,28 @@ namespace AgcDriver::DriverDetail { namespace { +bool verifyDecodeReuse() { + static const bool verify = std::getenv("APS5_VERIFY_DECODE_REUSE") != nullptr; + return verify; +} + + +struct RecycledRingWordsStorage {}; + +std::shared_ptr RecycledRingWords() { + constexpr std::size_t PoolSize = 1024, Probes = 16; + struct Pool : RecycledShared { + Pool() : RecycledShared(PoolSize, Probes) {} + }; + auto words = HostThreadLocal().Take([](ShaderRecompiler::HeapStageWords& candidate) { + candidate.userData.clear(); + candidate.drawKeyMemo.words.store(nullptr, std::memory_order_relaxed); + candidate.dataOrigin = 0; + }); + words->memoizeKey = false; + return words; +} + bool TraceShaderCorrelation() { static const bool enabled = std::getenv("APS5_TRACE_SHADER_CORRELATION") != nullptr; return enabled && AgcDriver::CaptureTrace::Enabled(); @@ -204,6 +230,15 @@ void noteFinisherHandOff(bool handed) { namespace { +bool MixesHeapAndGuestStages(std::span stages, std::span programResults) { + const auto guest = [&](const Graphics::CompiledShader& stage) { return std::ranges::find(programResults, stage.program) != programResults.end(); }; + return std::ranges::any_of(stages, [](const Graphics::CompiledShader& stage) { return stage.program->gpuResolvedImages; }) && std::ranges::any_of(stages, [&](const Graphics::CompiledShader& stage) { return guest(stage) && !stage.program->gpuResolvedImages; }); +} + +} + +namespace { + enum class HeldReason : std::size_t { Known, NoDecode, Size, NullVertex, NullFragment, NullOther, Bda, Buffer, Storage, Count }; std::array, static_cast(HeldReason::Count)> heldReasons{}; @@ -227,7 +262,7 @@ void noteHeld(HeldReason reason) { std::optional writesBeyondTargets(const ShaderRecompiler::RecompileResult& compiled) { using Role = ShaderRecompiler::DescriptorRole; for (const auto& binding : compiled.bindings) { - if (binding.role == Role::BdaPagetable && Graphics::ShaderStoresThroughAddresses(compiled.spirv)) return HeldReason::Bda; + if (binding.role == Role::BdaPagetable && Graphics::ProgramStoresThroughAddresses(compiled)) return HeldReason::Bda; if (binding.role == Role::GuestBuffers) { for (std::uint32_t element = 0; element < binding.count; ++element) { if (element >= binding.bufferWritten.size() || binding.bufferWritten[element]) return HeldReason::Buffer; @@ -259,8 +294,10 @@ void KeepUserDataTables(ShaderMemory& memory, const std::vector& pr DrawFinisher::Pending heldWrites(const DrawTail& tail) { DrawFinisher::Pending held; - held.key = tail.drawKey; - held.shape = tail.shapeKey; + if (!tail.drawHit) { + held.key = tail.drawKey; + held.shape = tail.shapeKey; + } if (tail.decode == nullptr) { noteHeld(HeldReason::NoDecode); return held; @@ -696,11 +733,16 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe if (stageData[i].compiled != nullptr) stageData[i].compiled = patchDataWords(*matched[i], stageData[i].words); } const auto relocatedDecode = decode; + bool admitRelocated = false; if (!userPatches.empty()) { std::lock_guard cacheLock(drawCacheMutex); if (drawHit || verifyHit) { ++drawRelocationCounters.hits; ++drawRelocationTrials[drawIdentity].hits; + if (drawHit && drawKey != 0 && !drawCache.contains(drawKey)) { + admitRelocated = drawKeySightingsTable().SeenBefore(drawKey); + if (admitRelocated) ++drawRelocationCounters.admitted; + } if (const auto alias = drawAliases.find(drawAlias); alias != drawAliases.end()) { const auto donor = drawCache.find(alias->second); if (donor != drawCache.end() && drawCacheHits - donor->second->touched > drawCacheEntries() / 8) { @@ -712,10 +754,15 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe } if (profile && drawRelocationCounters.lookups >= 100000) reportDrawRelocation(); } - if (!userPatches.empty() && !drawHit) { + const auto patchedDecode = [&] { auto current = std::make_shared(*decode); for (const auto& patch : userPatches) current->programs[patch.program].userData[patch.index] = patch.value; - decode = std::move(current); + return current; + }; + if (!userPatches.empty() && !drawHit) decode = patchedDecode(); + if (admitRelocated && std::all_of(matched.begin(), matched.end(), [](const std::shared_ptr& variant) { return variant != nullptr; })) { + std::vector> fresh(matched.begin(), matched.end()); + insertDrawEntry(drawKey, fresh, patchedDecode(), 0, false); } tail.patchedStages = std::any_of(stageData.begin(), stageData.end(), [](const StageDataHit& hit) { return hit.compiled != nullptr; }); tail.relocatedDecode = relocatedDecode; @@ -921,6 +968,27 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { std::memcpy(words.data() + offset, region.bytes.data(), count * sizeof(std::uint32_t)); } }; + const auto buildRingWords = [&](std::size_t i, const DispatchVariant& variant) { + auto words = RecycledRingWords(); + BuildRingWords(variant, programs[i].userData, &variant == matched[i].get() && stageData[i].compiled != nullptr ? &stageData[i].words : nullptr, *words); + if (words->vertexAttributes.empty()) return words; + if (!vertexInfos[i] || graphics.stages.mesh) { + decodeVertexInfo(i); + } else if (verifyDecodeReuse()) { + const auto kept = vertexInfos[i]; + decodeVertexInfo(i); + if (!vertexInfos[i] || !sameVertexInfo(*vertexInfos[i], *kept)) + throw std::runtime_error("APS5_VERIFY_DECODE_REUSE: a ring hit's vertex stage info decoded on the finisher differs from the queue worker's"); + } + require(vertexInfos[i].has_value(), "a ring vertex hit has no vertex stage info"); + const auto& vertex = *vertexInfos[i]; + for (auto& attribute : words->vertexAttributes) { + require(attribute.location < vertex.resourcesNum && attribute.location < vertex.resources.size(), "a ring vertex attribute lies outside the draw's vertex resources"); + attribute.resource = vertex.resources[attribute.location]; + if (vertex.fetchEmbedded) attribute.fetchIndex = vertex.resourcesDst[attribute.location].fetchIndex; + } + return words; + }; const auto joinedRuns = [](const std::vector>& runs) { std::vector> joined; for (const auto& run : runs) { @@ -943,6 +1011,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { std::vector words; freshRuns(i, runs, words); const auto& compiled = *stageCaptures[i].compiled; + if (kept.ringTemplate != nullptr) VerifyRingWords(*kept.compiled, *buildRingWords(i, kept), *stageCaptures[i].compiled, stageCaptures[i].heapWords.get()); const char* what = joinedRuns(runs) != joinedRuns(kept.runs) ? "runs" : words != kept.words ? "words" : vertexInfos[i].has_value() != (kept.vertexInfo != nullptr) || (vertexInfos[i] && !sameVertexInfo(*vertexInfos[i], *kept.vertexInfo)) ? "vertex stage info" : compiled.variantId != kept.compiled->variantId ? "variant" : compiled.pushConstants != kept.compiled->pushConstants ? "push constants" : nullptr; ++dataVerified; if (what == nullptr) return; @@ -956,8 +1025,13 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { std::vector> runs; std::vector words; freshRuns(i, runs, words); - const auto& fresh = *stageCaptures[i].compiled; - const auto& patched = *hit.compiled; + std::shared_ptr effective = hit.compiled, expected = stageCaptures[i].compiled; + if (kept.ringTemplate != nullptr) { + effective = PatchedHeapResult(*hit.compiled, *buildRingWords(i, kept)); + if (stageCaptures[i].heapWords != nullptr) expected = PatchedHeapResult(*stageCaptures[i].compiled, *stageCaptures[i].heapWords); + } + const auto& fresh = *expected; + const auto& patched = *effective; const bool sameBindings = fresh.bindings.size() == patched.bindings.size() && std::equal(fresh.bindings.begin(), fresh.bindings.end(), patched.bindings.begin(), [](const auto& a, const auto& b) { return a.kind == b.kind && a.role == b.role && a.binding == b.binding && a.count == b.count && a.guestDescriptor == b.guestDescriptor; }); const char* what = joinedRuns(runs) != joinedRuns(kept.runs) ? "runs" : words != hit.words ? "words" : fresh.variantId != patched.variantId ? "variant" : fresh.pushConstants != patched.pushConstants ? "push constants" : !sameBindings ? "bindings" : nullptr; ++stageDataVerified; @@ -966,66 +1040,111 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { std::snprintf(message, sizeof(message), "APS5_VERIFY_DRAW_DATA_HITS: stage %zu (program 0x%llx) of a stage data hit differs from its full build in its %s (%zu data positions refreshed)", i, static_cast(programs[i].binary.codeAddress), what, kept.dataPositions.size()); throw std::runtime_error(message); }; + const auto ringWords = [&](std::size_t i) { + if (matched[i]->ringTemplate == nullptr) return; + stageCaptures[i].heapWords = buildRingWords(i, *matched[i]); + stageCaptures[i].origin = StageOrigin::HeapRead; + }; + const auto adoptMatched = [&](std::size_t i) { + programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); + memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); + ringWords(i); + }; std::optional indirectCpu; std::size_t completedSubdraws = 0; std::vector pushOffsets(programs.size(), 0); std::optional meshBarycentrics; std::vector resultIndex(programs.size(), 0); + const DrawStageContext stageContext{queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, meshBarycentrics}; const bool fixedSlots = localDevice->GraphicsPipelineLibraries(); const bool hasFragment = std::ranges::any_of(programs, [](const DrawProgram& program) { return program.binary.stage == ShaderRecompiler::ShaderStage::Fragment; }); - for (std::size_t i = 0; i < programs.size(); ++i) { - if (roles[i] == Role::GeometryBack) continue; - const auto& program = programs[i]; - pushCursorBytes = Graphics::StagePushOffset(pushCursorBytes, program.binary.stage, fixedSlots); - require(pushCursorBytes <= Graphics::PushBlockBytes(fixedSlots), "stage push constant offset exceeds the pipeline push constant block"); - const auto pushBudget = Graphics::StagePushBudget(Graphics::StagePushLimit(graphics.stages, pushCursorBytes, graphics.depthRemap.mode != 0u), pushCursorBytes, program.binary.stage, fixedSlots, hasFragment); - pushOffsets[i] = pushCursorBytes; - if (drawHit) { - - programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); - memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); - } else { - const auto candidate = std::find_if(dataCandidates[i].begin(), dataCandidates[i].end(), [&](const auto& kept) { return kept.first->pushOffset == pushCursorBytes && kept.first->compiled->pushConstants.size() <= pushBudget; }); - if (candidate != dataCandidates[i].end() && !verifyDrawDataHits()) { - matched[i] = candidate->first; - stageCaptures[i].registeredViews = matched[i]->registeredViews; - matchedRegions[i] = std::move(candidate->second); - reused[i] = true; - programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); - memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); + const bool heapMode = Graphics::DescriptorHeapEnabled(); + const bool heapCheck = !drawHit && heapMode; + const bool heapDraw = heapMode && [&] { + const bool descriptorMemory = localDevice->Target().descriptorMemory; + std::uint32_t cursor = pushCursorBytes; + for (std::size_t i = 0; i < programs.size(); ++i) { + if (roles[i] == Role::GeometryBack) continue; + const auto stage = programs[i].binary.stage; + require(stage == Stage::Fragment || HeapPreRasterStage(stage), "a draw stage kind the GPU heap does not take"); + require(stage == Stage::Fragment || descriptorMemory, "a GPU heap draw on a device target without descriptor memory"); + cursor = Graphics::StagePushOffset(cursor, stage, fixedSlots); + if (HeapStageExcluded(stage) || (HeapClassesExcluded() && drawStageExcluded(stageContext, i, cursor, drawParameters))) return false; + } + return true; + }(); + const auto fitsDraw = [&](const ShaderRecompiler::RecompileResult& compiled) { return !heapMode || compiled.gpuResolvedImages == heapDraw; }; + const auto candidateForStage = [&](std::size_t i, std::uint32_t pushBudget) { + return std::find_if(dataCandidates[i].begin(), dataCandidates[i].end(), [&](const auto& kept) { + return kept.first->pushOffset == pushCursorBytes && kept.first->compiled->pushConstants.size() <= pushBudget && fitsDraw(*kept.first->compiled); + }); + }; + const auto runStages = [&]() -> std::optional { + for (std::size_t i = 0; i < programs.size(); ++i) { + if (roles[i] == Role::GeometryBack) continue; + const auto& program = programs[i]; + pushCursorBytes = Graphics::StagePushOffset(pushCursorBytes, program.binary.stage, fixedSlots); + require(pushCursorBytes <= Graphics::PushBlockBytes(fixedSlots), "stage push constant offset exceeds the pipeline push constant block"); + const auto pushBudget = Graphics::StagePushBudget(Graphics::StagePushLimit(graphics.stages, pushCursorBytes, graphics.depthRemap.mode != 0u), pushCursorBytes, program.binary.stage, fixedSlots, hasFragment); + pushOffsets[i] = pushCursorBytes; + if (drawHit) { + adoptMatched(i); } else { - if (!dataCandidates[i].empty() && !verifyDrawDataHits()) decodeVertexInfo(i); - if (program.binary.stage == ShaderRecompiler::ShaderStage::Fragment) { - for (auto previous = i; previous-- > 0;) { - if (programResults[previous] == nullptr) continue; - pixel = Graphics::DefaultUnexportedInputs(decode->pixel, programResults[previous]->parameterExports); - break; + if (reused[i] && !fitsDraw(*matched[i]->compiled)) { + reused[i] = false; + matched[i] = nullptr; + matchedRegions[i].clear(); + } + const auto candidate = reused[i] ? dataCandidates[i].end() : candidateForStage(i, pushBudget); + if (reused[i]) { + adoptMatched(i); + } else if (candidate != dataCandidates[i].end() && !verifyDrawDataHits()) { + matched[i] = candidate->first; + stageCaptures[i].registeredViews = matched[i]->registeredViews; + matchedRegions[i] = std::move(candidate->second); + reused[i] = true; + adoptMatched(i); + } else { + if (!dataCandidates[i].empty() && !verifyDrawDataHits()) decodeVertexInfo(i); + if (program.binary.stage == ShaderRecompiler::ShaderStage::Fragment) { + for (auto previous = i; previous-- > 0;) { + if (programResults[previous] == nullptr) continue; + pixel = Graphics::DefaultUnexportedInputs(decode->pixel, programResults[previous]->parameterExports); + break; + } } + compiledStages.push_back(materializeDrawStage(stageContext, i, pushCursorBytes, drawParameters, heapDraw)); + programResults[i] = compiledStages.back().get(); + if (verifyHit && matched[i] != nullptr && matched[i]->ringTemplate != nullptr) VerifyRingWords(*matched[i]->compiled, *buildRingWords(i, *matched[i]), *programResults[i], stageCaptures[i].heapWords.get()); + if (candidate != dataCandidates[i].end()) verifyDataStage(i, *candidate->first); + if (stageData[i].compiled != nullptr && verifyDrawDataHits()) verifyStageData(i); } - compiledStages.push_back(materializeDrawStage(i, pushCursorBytes, queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics)); - if (!rejected.empty()) return DrawVerdict::Rejected; - programResults[i] = compiledStages.back().get(); - if (candidate != dataCandidates[i].end()) verifyDataStage(i, *candidate->first); - if (stageData[i].compiled != nullptr && verifyDrawDataHits()) verifyStageData(i); + if (dataEntry != nullptr && reused[i]) ++dataStagesReused; + else if (dataEntry != nullptr) ++dataStagesCompiled; } - if (dataEntry != nullptr && reused[i]) ++dataStagesReused; - else if (dataEntry != nullptr) ++dataStagesCompiled; - } - const auto& result = *programResults[i]; - if (i == 0 && drawParameters.indirect) { - indirectCpu = ClassifyIndirectDraw(result, graphics, programs.front(), localDevice, drawParameters, traceIndirect); - if (EmptyIndirectSkip()) CpuIndirectPrograms()[programs.front().binary.codeAddress] = indirectCpu.has_value(); - } else if (i == 0) { - fold(result, drawParameters); - } - try { - require(result.pushConstants.size() <= pushBudget, "stage push constants exceed the pipeline push constant block"); - stages.push_back({program.binary.stage, &result, result.pushConstants.empty() ? 0u : pushCursorBytes, stageCaptures[i].registeredViews.get()}); - pushCursorBytes += static_cast(result.pushConstants.size()); - } catch (...) { - TraceMaterializationFailure(trace.token, submission, packetOffset, "push-constant-validation", completedSubdraws, std::current_exception()); - throw; + const auto& result = *programResults[i]; + if (i == 0 && drawParameters.indirect) { + indirectCpu = ClassifyIndirectDraw(result, graphics, programs.front(), localDevice, drawParameters, traceIndirect, stageCaptures[0].heapWords.get()); + if (EmptyIndirectSkip()) CpuIndirectPrograms()[programs.front().binary.codeAddress] = indirectCpu.has_value(); + } else if (i == 0) { + fold(result, drawParameters); + } + try { + require(result.pushConstants.size() <= pushBudget, "stage push constants exceed the pipeline push constant block"); + stages.push_back({program.binary.stage, &result, result.pushConstants.empty() ? 0u : pushCursorBytes, stageCaptures[i].registeredViews.get(), stageCaptures[i].heapWords.get()}); + pushCursorBytes += static_cast(result.pushConstants.size()); + } catch (...) { + TraceMaterializationFailure(trace.token, submission, packetOffset, "push-constant-validation", completedSubdraws, std::current_exception()); + throw; + } + if (stages.back().heap != nullptr && SampleHeapStageVerify()) VerifyHeapAccessor(stages.back()); } + return std::nullopt; + }; + if (const auto verdict = runStages()) return *verdict; + if (heapCheck) { + require(!MixesHeapAndGuestStages(stages, programResults), "a draw mixes GPU heap and per-draw stages"); + if (!heapDraw) Graphics::NoteHeapExcluded(Graphics::HeapExcluded::Draw); } if (stageDataVerified != 0) { @@ -1047,7 +1166,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { }; for (std::size_t i = 0; i < programs.size(); ++i) { const auto& capture = stageCaptures[i]; - if (reused[i] || capture.compiled == nullptr || !CacheableResult(*capture.compiled)) continue; + if (reused[i] || capture.compiled == nullptr || !capture.Cacheable() || !CacheableResult(*capture.compiled)) continue; stored = true; const auto& words = programs[i].userData; for (std::size_t w = 0; w < words.size(); ++w) { @@ -1120,11 +1239,12 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { if (programResults[0]->meshBarycentrics != meshBarycentrics) { const auto pushBytes = programResults[0]->pushConstants.size(); const auto exports = programResults[0]->parameterExports; - compiledStages.push_back(materializeDrawStage(0, pushOffsets[0], queue, submission, packetOffset, traceToken, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics)); - if (!rejected.empty()) return DrawVerdict::Rejected; + compiledStages.push_back(materializeDrawStage(stageContext, 0, pushOffsets[0], drawParameters, heapDraw)); + require(fitsDraw(*compiledStages.back()), "a rebuilt mesh stage left the GPU heap mode of its draw"); programResults[0] = compiledStages.back().get(); stages[0].program = programResults[0]; stages[0].registeredImageViews = stageCaptures[0].registeredViews.get(); + stages[0].heap = stageCaptures[0].heapWords.get(); require(programResults[0]->pushConstants.size() == pushBytes && programResults[0]->parameterExports == exports, "pairing the mesh program with its pixel shader changed the push constants or the parameter exports the pixel shader was built for"); } require(programResults[0]->meshBarycentrics == meshBarycentrics, "the mesh program was compiled for a different barycentric layout than its pixel shader"); @@ -1218,7 +1338,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const auto sameInfo = [&](const std::optional& a, const std::optional& b) { return a.has_value() == b.has_value() && (!a || sameVertexInfo(*a, *b)); }; const auto forwardRecordWords = [&](std::size_t programIndex, ShaderRecompiler::RecompileResult& result, const std::optional& previousInfo) { std::uint64_t walked = 0; - if (stageCaptures[programIndex].capture != nullptr) walked = stageCaptures[programIndex].userDataUse.asBase | stageCaptures[programIndex].userDataUse.asValue; + if (stageCaptures[programIndex].capture != nullptr) walked = stageCaptures[programIndex].UserDataUse().asBase | stageCaptures[programIndex].UserDataUse().asValue; else if (matched[programIndex] != nullptr) walked = matched[programIndex]->userWordsWalked; else return false; if ((graphics.stages.mesh && programIndex == 0) || !sameInfo(previousInfo, vertexInfos[programIndex])) return false; @@ -1240,7 +1360,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const bool sameBindings = forwarded.bindings.size() == fresh.bindings.size() && std::equal(forwarded.bindings.begin(), forwarded.bindings.end(), fresh.bindings.begin(), [](const auto& a, const auto& b) { return a.kind == b.kind && a.role == b.role && a.binding == b.binding && a.count == b.count && a.guestDescriptor == b.guestDescriptor; }); std::uint64_t walked = 0; for (const auto& word : recordWords) { - if (word.program == programIndex && word.index < ShaderRecompiler::SrtUserDataUse::TrackedWords) walked |= (stageCaptures[programIndex].userDataUse.asBase | stageCaptures[programIndex].userDataUse.asValue) >> word.index & 1u; + if (word.program == programIndex && word.index < ShaderRecompiler::SrtUserDataUse::TrackedWords) walked |= (stageCaptures[programIndex].UserDataUse().asBase | stageCaptures[programIndex].UserDataUse().asValue) >> word.index & 1u; } const char* what = forwarded.variantId != fresh.variantId ? "variant" : forwarded.pushConstants != fresh.pushConstants ? "push constants" : !sameBindings ? "bindings" : forwarded.shaderDataUserWords != fresh.shaderDataUserWords ? "forwarded words" : walked != 0 ? "walked user word" : nullptr; ++wordsVerified; @@ -1296,20 +1416,22 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const auto pushBytes = result.pushConstants.size(); const auto previousInfo = vertexInfos[programIndex]; decodeVertexInfo(programIndex); - if (pushWord && forwardRecordWords(programIndex, result, previousInfo)) { + if (pushWord && !heapDraw && forwardRecordWords(programIndex, result, previousInfo)) { wordsForwarded += static_cast(std::count_if(recordWords.begin(), recordWords.end(), [&](const RecordWord& word) { return word.program == programIndex; })); if (!verifyPushWord) continue; - const auto fresh = materializeDrawStage(programIndex, pushOffsets[programIndex], queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics); + const auto fresh = materializeDrawStage(stageContext, programIndex, pushOffsets[programIndex], drawParameters, heapDraw); for (auto& stage : stages) if (stage.program == &result) stage.registeredImageViews = stageCaptures[programIndex].registeredViews.get(); - if (!rejected.empty()) return DrawVerdict::Rejected; verifyForwardedWords(programIndex, result, *fresh); continue; } if (pushWord) wordsRefused += static_cast(std::count_if(recordWords.begin(), recordWords.end(), [&](const RecordWord& word) { return word.program == programIndex; })); - result = *materializeDrawStage(programIndex, pushOffsets[programIndex], queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, programs[programIndex].binary.stage == Stage::TessellationControl || programs[programIndex].binary.stage == Stage::TessellationEvaluation ? direct : drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics); + result = *materializeDrawStage(stageContext, programIndex, pushOffsets[programIndex], programs[programIndex].binary.stage == Stage::TessellationControl || programs[programIndex].binary.stage == Stage::TessellationEvaluation ? direct : drawParameters, heapDraw); for (auto& stage : stages) if (stage.program == &result) stage.registeredImageViews = stageCaptures[programIndex].registeredViews.get(); - if (!rejected.empty()) return DrawVerdict::Rejected; require(result.pushConstants.size() == pushBytes, "patched program changed its push constant layout"); + require(fitsDraw(result), "a patched program left the GPU heap mode of its draw"); + for (auto& stage : stages) { + if (stage.program == &result) stage.heap = stageCaptures[programIndex].heapWords.get(); + } ++stagesRecompiled; } fold(*programResults[0], direct); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp index fefe24878661..9c8e6e5eab23 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "HeapCacheSwitch.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp" #include #include @@ -23,17 +24,17 @@ bool DrawRecipeRecord::Expired() const { } bool Driver::drawEntries() { - static const bool entries = std::getenv("APS5_NO_DRAW_SRT_ENTRIES") == nullptr && !stampValidate(); + static const bool entries = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::DrawSrtEntries) && !stampValidate(); return entries; } bool Driver::drawDataHits() { - static const bool hits = std::getenv("APS5_NO_DRAW_DATA_HITS") == nullptr; + static const bool hits = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::DrawDataHits); return hits; } bool Driver::drawStageDataHits() { - static const bool hits = std::getenv("APS5_NO_DRAW_STAGE_DATA_HITS") == nullptr && !stampValidate(); + static const bool hits = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::DrawStageDataHits) && !stampValidate(); return hits; } @@ -48,7 +49,7 @@ bool Driver::verifyDrawEntries() { } bool Driver::registerKeyEnabled() { - static const bool registerKey = std::getenv("APS5_NO_DRAW_KEY") == nullptr; + static const bool registerKey = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::DrawKey); return registerKey; } @@ -164,16 +165,26 @@ bool Driver::drawEntriesThisDraw() { return backoff.use(drawCacheUseful().load(std::memory_order_relaxed)); } +DrawKeySightings& Driver::drawKeySightingsTable() { + if (!drawKeySightings) drawKeySightings.emplace(drawCacheEntries() * DrawKeySightings::Ways); + return *drawKeySightings; +} + +DrawKeySightings& Driver::drawShapeSightingsTable() { + if (!drawShapeSightings) drawShapeSightings.emplace(drawCacheEntries() * DrawKeySightings::Ways); + return *drawShapeSightings; +} + bool Driver::admitDrawKey(std::uint64_t key, std::uint64_t shape) { std::lock_guard cacheLock(drawCacheMutex); if (drawCache.contains(key)) return true; - if (!drawKeySightings) drawKeySightings.emplace(drawCacheEntries() * DrawKeySightings::Ways); - bool seen = drawKeySightings->SeenBefore(key); + auto& keySightings = drawKeySightingsTable(); + bool seen = keySightings.SeenBefore(key); const auto& pending = drawRelocationPending; if (pending.key == key && pending.identity != 0) { if (pending.alias != 0) { const auto trial = drawRelocationTrials.find(pending.identity); - if (drawKeySightings->SeenBefore(pending.alias ^ 0x9e3779b97f4a7c15ull) && trial != drawRelocationTrials.end()) { + if (keySightings.SeenBefore(pending.alias ^ 0x9e3779b97f4a7c15ull) && trial != drawRelocationTrials.end()) { auto& state = trial->second; if (state.productive || state.hits != 0 || state.admissions < DrawRelocationTrial::ProbationAdmissions) { if (!state.productive && state.hits == 0) ++state.admissions; @@ -181,12 +192,11 @@ bool Driver::admitDrawKey(std::uint64_t key, std::uint64_t shape) { } } } else if (!drawRelocations.contains(pending.identity)) { - if (drawKeySightings->SeenBefore(pending.identity ^ 0xc2b2ae3d27d4eb4full)) seen = true; + if (keySightings.SeenBefore(pending.identity ^ 0xc2b2ae3d27d4eb4full)) seen = true; } } if (seen || shape == 0 || drawShapes.contains(shape)) return seen; - if (!drawShapeSightings) drawShapeSightings.emplace(drawCacheEntries() * DrawKeySightings::Ways); - return drawShapeSightings->SeenBefore(shape); + return drawShapeSightingsTable().SeenBefore(shape); } void Driver::insertDrawEntry(std::uint64_t key, std::vector>& fresh, std::shared_ptr decode, std::uint64_t shape, bool replaceShape) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 3658ba6a71ca..55d8f02a69ba 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -1,3 +1,14 @@ +#include +#include +#include +#include +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include +#include +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" @@ -10,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -20,6 +32,12 @@ namespace AgcDriver::DriverDetail { +const ShaderRecompiler::SrtUserDataUse& StageCapture::UserDataUse() const { + static const ShaderRecompiler::SrtUserDataUse none; + return capture != nullptr ? capture->userDataUse : none; +} + + namespace { void TraceMaterializationFailure(std::uint64_t token, const Submission& submission, std::size_t packetOffset, std::size_t stage, const char* phase, const std::exception_ptr& failure) { @@ -40,6 +58,24 @@ void TraceMaterializationFailure(std::uint64_t token, const Submission& submissi } } +std::uint64_t UserDataMask(const DrawProgram& program, const std::optional& vertexInfo, std::uint64_t walked, const ShaderRecompiler::RecompileResult& compiled) { + std::uint64_t mask = walked | compiled.userDataRegisterReads; + if (program.snapshot) { + const auto& tail = program.snapshot->userDataTailRegister; + if (tail && *tail >= program.firstUserSgpr) { + const auto index = *tail - program.firstUserSgpr; + mask |= index + 1u < 64u ? std::uint64_t{3} << index : ~std::uint64_t{0}; + } else if (tail) { + return ~std::uint64_t{0}; + } + if (StageLinksUserDataCallees(*program.snapshot, program.codeOffset)) return ~std::uint64_t{0}; + } + if (vertexInfo) { + for (const auto reg : {static_cast(vertexInfo->fetchAttribReg), static_cast(vertexInfo->fetchBufferReg)}) mask |= reg + 1u < 64u ? std::uint64_t{3} << reg : ~std::uint64_t{0}; + } + return mask; +} + void TraceShaderRequestFailure(std::uint64_t token, const Submission& submission, std::size_t packetOffset, const DrawProgram& program, const std::exception_ptr& failure) noexcept { if (token == 0) return; try { @@ -87,26 +123,32 @@ PendingMaterializes& pendingMaterializes() { } -std::shared_ptr MaterializeInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr& capture, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address) { - if (!AsyncDrawCompile()) return invocation.Materialize(*capture); - bool contended = false; - if (auto memoized = invocation.MaterializeIfMemoized(*capture, &contended)) return memoized; +namespace { + +using MaterializeWork = std::function()>; + +std::atomic heapTemplatesInBackground{0}; + +bool cheapAt(std::uint64_t address, bool contended) { auto& pending = pendingMaterializes(); - bool cheap = false; - { - std::lock_guard lock(pending.mutex); - const auto found = pending.lastMs.find(address); - cheap = !contended && found != pending.lastMs.end() && found->second < PendingMaterializes::CheapMs; - } - if (cheap) { - const auto started = std::chrono::steady_clock::now(); - auto result = invocation.Materialize(*capture); - const auto ms = ElapsedMs(started); - std::lock_guard lock(pending.mutex); - pending.lastMs[address] = ms; - return result; - } - const std::pair key{address, invocation.SnapshotKey(*capture)}; + std::lock_guard lock(pending.mutex); + const auto found = pending.lastMs.find(address); + return !contended && found != pending.lastMs.end() && found->second < PendingMaterializes::CheapMs; +} + +std::shared_ptr timedAt(std::uint64_t address, const MaterializeWork& work) { + const auto started = std::chrono::steady_clock::now(); + auto result = work(); + const auto ms = ElapsedMs(started); + auto& pending = pendingMaterializes(); + std::lock_guard lock(pending.mutex); + pending.lastMs[address] = ms; + return result; +} + +std::shared_ptr finishedInBackground(std::uint64_t address, std::uint64_t snapshotKey, const std::function& makeWork, bool* created = nullptr) { + auto& pending = pendingMaterializes(); + const std::pair key{address, snapshotKey}; std::shared_ptr job; bool started = false; { @@ -124,15 +166,14 @@ std::shared_ptr MaterializeInBackground } job = slot; } + if (created != nullptr) *created = started; if (started) { - const auto owned = OwnRecompileRequest(invocation.Request(), memory); - const auto rebound = std::make_shared(invocation.Rebound(owned->request)); - SubmitLibraryPrebuild([job, owned, rebound, capture, address] { + SubmitLibraryPrebuild([job, work = makeWork(), address] { std::shared_ptr result; std::exception_ptr failure; const auto started = std::chrono::steady_clock::now(); try { - result = rebound->Materialize(*capture); + result = work(); } catch (...) { failure = std::current_exception(); } @@ -162,152 +203,284 @@ std::shared_ptr MaterializeInBackground return job->result; } -std::shared_ptr Driver::materializeDrawStage(std::size_t i, std::uint32_t pushOffset, const QueueState& queue, const Submission& submission, std::size_t packetOffset, std::uint64_t traceToken, const std::vector& programs, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector>& vertexInfos, std::vector& memory, const std::vector& linked, const Pm4::DrawParameters& drawParameters, const std::shared_ptr& localDevice, ShaderMemory& shaderMemory, std::vector& stageCaptures, std::vector& recompiled, bool drawHit, const std::vector>& matched, const std::vector>& matchedRegions, bool profile, std::uint64_t dumpTarget, std::uint64_t dumpSlot1, std::uint64_t& captures, DrawPhaseTiming& phaseTiming, std::array& phaseMs, std::string& rejected, const std::optional& meshBarycentrics) try { - PerformanceTimer timing("Shader.DrawStage"); +template +std::function reboundWork(const ShaderRecompiler::PreparedShaderInvocation& invocation, ShaderRecompiler::MemoryRegionView memory, Run run) { + return [&invocation, memory, run] { + std::shared_ptr owned = OwnRecompileRequest(invocation.Request(), memory); + auto rebound = std::make_shared(invocation.Rebound(owned->request)); + return MaterializeWork([owned, rebound, run] { return run(*rebound); }); + }; +} + +void dropHeapReadRegions(std::vector& memory, const StageCapture& stage) { + if (stage.heapReadWords == nullptr || stage.heapReadWords->empty()) return; + const auto* first = reinterpret_cast(stage.heapReadWords->data()); + const auto* last = first + stage.heapReadWords->size() * sizeof(std::uint32_t); + std::erase_if(memory, [&](const ShaderRecompiler::MemoryRegion& region) { return region.bytes.data() >= first && region.bytes.data() < last; }); +} + +constexpr std::uint64_t HeapTemplateJob = std::uint64_t{1} << 63u; + +} + +std::shared_ptr MaterializeInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr& capture, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address) { + if (!AsyncDrawCompile()) return invocation.Materialize(*capture); + bool contended = false; + if (auto memoized = invocation.MaterializeIfMemoized(*capture, &contended)) return memoized; + if (cheapAt(address, contended)) return timedAt(address, [&] { return invocation.Materialize(*capture); }); + return finishedInBackground(address, invocation.SnapshotKey(*capture), reboundWork(invocation, memory, [capture](const ShaderRecompiler::PreparedShaderInvocation& rebound) { return rebound.Materialize(*capture); })); +} + +std::uint64_t HeapTemplatesBuiltInBackground() { + return heapTemplatesInBackground.load(std::memory_order_relaxed); +} + +std::shared_ptr MaterializeHeapInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr& capture, ShaderRecompiler::HeapStageWords& words, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address) { + if (!AsyncDrawCompile()) return invocation.MaterializeHeap(*capture, words); + ShaderRecompiler::HeapTemplateMiss miss; + if (auto hit = invocation.MaterializeHeap(*capture, words, &miss); hit != nullptr || !miss.missing) return hit; + const auto job = address | HeapTemplateJob; + if (cheapAt(job, false)) return timedAt(job, [&] { return invocation.MaterializeHeap(*capture, words); }); + bool created = false; + try { + static_cast(finishedInBackground(job, miss.key, reboundWork(invocation, memory, [capture](const ShaderRecompiler::PreparedShaderInvocation& rebound) { + ShaderRecompiler::HeapStageWords built; + return rebound.MaterializeHeap(*capture, built); + }), &created)); + } catch (const DrawCompilePending&) { + if (created) heapTemplatesInBackground.fetch_add(1, std::memory_order_relaxed); + throw; + } + return invocation.MaterializeHeap(*capture, words); +} + +bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t i, const ShaderRecompiler::PreparedShaderInvocation& invocation, const ShaderRecompiler::RecompileRequest& request, PerformanceTimer& timing) { + const auto& program = context.programs[i]; + auto& stageCapture = context.stageCaptures[i]; + HeapStageMaterialized materialized; + try { + materialized = MaterializeHeapStage(invocation, program.userData, request.context.memory, program.binary.codeAddress); + } catch (const DrawCompilePending&) { + throw; + } catch (const std::exception& error) { + throw stageFailure(program, request, error, request.context.memory); + } + if (materialized.result == nullptr) return false; + RequireHeapStageMappable(*materialized.result); + NoteHeapDirect(); + stageCapture.compiled = std::move(materialized.result); + stageCapture.heapWords = stageCapture.compiled->heapTemplateId != 0 ? std::move(materialized.words) : nullptr; + if (SampleHeapStageVerify()) { + const auto fullCapture = context.shaderMemory.Capture(invocation); + const auto expected = invocation.Materialize(*fullCapture); + static_cast(context.shaderMemory.TakeRecentRegions()); + NoteHeapDirectVerify(stageCapture.heapWords != nullptr ? *PatchedHeapResult(*stageCapture.compiled, *stageCapture.heapWords) : *stageCapture.compiled, *expected, fullCapture.get()); + } + stageCapture.regions.clear(); + stageCapture.origin = StageOrigin::HeapUnread; + auto& reads = materialized.reads; + if (reads.complete) { + auto owned = std::move(reads.values); + std::size_t cursor = 0; + for (const auto& [begin, end] : *reads.ranges) { + const auto count = static_cast((end - begin) / sizeof(std::uint32_t)); + stageCapture.regions.push_back({begin, std::as_bytes(std::span(owned->data() + cursor, count))}); + cursor += count; + } + stageCapture.heapReadWords = std::move(owned); + const auto& use = reads.capture->userDataUse; + stageCapture.userDataMask = UserDataMask(program, context.vertexInfos[i], use.asValue | use.asBase, *stageCapture.compiled); + stageCapture.capture = std::move(reads.capture); + stageCapture.origin = StageOrigin::HeapRead; + context.memory.insert(context.memory.end(), stageCapture.regions.begin(), stageCapture.regions.end()); + } + context.recompiled[i] = true; + timing.Mark("heap_direct"); + context.phaseTiming.Phase(DrawRowRecompile); + return true; +} + +std::runtime_error Driver::stageFailure(const DrawProgram& program, const ShaderRecompiler::RecompileRequest& request, const std::exception& error, std::span regions) { + static const bool dumpShaders = std::getenv("APS5_DUMP_SHADERS") != nullptr; + std::string dump; + if (dumpShaders) { + try { + auto failed = request; + failed.context.memory = regions; + dump = dumpRequest(program.binary.codeAddress, failed, "_failed"); + } catch (...) {} + } + std::ostringstream where; + where << "shader 0x" << std::hex << program.binary.codeAddress << " stage " << std::dec << static_cast(program.binary.stage); + if (!dump.empty()) where << " (" << dump << ")"; + where << ": "; + return std::runtime_error(where.str() + error.what()); +} + +ShaderRecompiler::RecompileRequest Driver::drawStageRequest(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters) { using Stage = ShaderRecompiler::ShaderStage; - phaseTiming.Phase(DrawRowVectors); - const auto& program = programs[i]; - const auto waveSize = Graphics::StageWaveSize(graphics.stages, program.binary.stage); - const bool fixedSlots = localDevice->GraphicsPipelineLibraries(); + const auto& program = context.programs[i]; + const auto waveSize = Graphics::StageWaveSize(context.graphics.stages, program.binary.stage); + const bool fixedSlots = context.localDevice->GraphicsPipelineLibraries(); require(pushOffset <= Graphics::PushBlockBytes(fixedSlots), "stage push constant offset exceeds the pipeline push constant block"); - const bool hasFragment = std::ranges::any_of(programs, [](const DrawProgram& value) { return value.binary.stage == Stage::Fragment; }); - const auto pushBytes = Graphics::StagePushBudget(Graphics::StagePushLimit(graphics.stages, pushOffset, graphics.depthRemap.mode != 0u), pushOffset, program.binary.stage, fixedSlots, hasFragment); + const bool hasFragment = std::ranges::any_of(context.programs, [](const DrawProgram& value) { return value.binary.stage == Stage::Fragment; }); + const auto pushBytes = Graphics::StagePushBudget(Graphics::StagePushLimit(context.graphics.stages, pushOffset, context.graphics.depthRemap.mode != 0u), pushOffset, program.binary.stage, fixedSlots, hasFragment); ShaderRecompiler::RecompileRequest request{ program.binary, - {waveSize, program.firstUserSgpr, program.userData, std::nullopt, program.binary.stage == Stage::Fragment ? std::optional(pixel) : std::nullopt, vertexInfos[i], memory, RegisteredFloatMode(*program.snapshot)}, - localDevice->Target(), + {waveSize, program.firstUserSgpr, program.userData, std::nullopt, program.binary.stage == Stage::Fragment ? std::optional(context.pixel) : std::nullopt, context.vertexInfos[i], context.memory, RegisteredFloatMode(*program.snapshot)}, + context.localDevice->Target(), {0, 0, pushOffset, pushBytes}, - ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, Graphics::StageMeshConfiguration(graphics.stages, program.binary.stage), graphics.stages.tessellation, {drawParameters.indexAddress, drawParameters.indexCount, drawParameters.indexSize, drawParameters.instanceCount}, program.binary.stage == Stage::Mesh ? meshBarycentrics : std::nullopt} + ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, context.linked, Graphics::StageMeshConfiguration(context.graphics.stages, program.binary.stage), context.graphics.stages.tessellation, {drawParameters.indexAddress, drawParameters.indexCount, drawParameters.indexSize, drawParameters.instanceCount}, program.binary.stage == Stage::Mesh ? context.meshBarycentrics : std::nullopt} }; - const auto waitedBefore = traceCapSync() || profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; - auto invocation = [&] { + return request; +} + +bool Driver::drawStageExcluded(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters) { + const auto& program = context.programs[i]; + auto request = drawStageRequest(context, i, pushOffset, drawParameters); + request.target.gpuResolvedImages = true; + const auto invocation = InvocationFor(*program.snapshot, program.codeOffset, request); + return HeapExcludedFor(invocation); +} + +std::shared_ptr Driver::materializeDrawStage(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters, bool heapDraw) try { + PerformanceTimer timing("Shader.DrawStage"); + using Stage = ShaderRecompiler::ShaderStage; + context.phaseTiming.Phase(DrawRowVectors); + dropHeapReadRegions(context.memory, context.stageCaptures[i]); + const auto& program = context.programs[i]; + auto request = drawStageRequest(context, i, pushOffset, drawParameters); + + const auto waitedBefore = traceCapSync() || context.profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; + if (heapDraw) request.target.gpuResolvedImages = true; + const auto invocationFor = [&] { try { return InvocationFor(*program.snapshot, program.codeOffset, request, AsyncDrawCompile()); } catch (const DrawCompilePending&) { throw; } catch (...) { - TraceShaderRequestFailure(traceToken, submission, packetOffset, program, std::current_exception()); + TraceShaderRequestFailure(context.traceToken, context.submission, context.packetOffset, program, std::current_exception()); throw; } - }(); + }; + auto invocation = invocationFor(); + using StageReason = Graphics::HeapStageReason; + const StageReason stageReason = heapDraw ? StageReason::Heap : !Graphics::DescriptorHeapEnabled() ? StageReason::Disabled : StageReason::Excluded; + if (heapDraw) { + const auto plan = invocation.PlanOrLoad(); + if (const auto* ineligible = HeapStageIneligibility(program.binary.stage, plan.get())) + throw std::runtime_error(std::string("AGC graphics: a GPU heap stage cannot take the heap: ") + ineligible); + } + Graphics::NoteHeapStageReason(stageReason); timing.Mark("prepared_invocation"); - auto& stageCapture = stageCaptures[i]; + auto& stageCapture = context.stageCaptures[i]; + stageCapture.origin = StageOrigin::Captured; + stageCapture.heapReadWords.reset(); + stageCapture.capture.reset(); + stageCapture.registeredViews.reset(); + stageCapture.supplied.clear(); stageCapture.forgetSerial = GuestMemory::ForgetSerial(); stageCapture.pushOffset = pushOffset; - const auto named = [&](const std::exception& error, std::span regions) { - static const bool dumpShaders = std::getenv("APS5_DUMP_SHADERS") != nullptr; - std::string dump; - if (dumpShaders) { - try { - auto failed = request; - failed.context.memory = regions; - dump = dumpRequest(program.binary.codeAddress, failed, "_failed"); - } catch (...) {} - } - std::ostringstream where; - where << "shader 0x" << std::hex << program.binary.codeAddress << " stage " << std::dec << static_cast(program.binary.stage); - if (!dump.empty()) where << " (" << dump << ")"; - where << ": "; - return std::runtime_error(where.str() + error.what()); - }; + static const bool dumpGraphics = std::getenv("APS5_DUMP_GRAPHICS_SHADERS") != nullptr; + const bool captured = dumpGraphics || traceCapSync() || context.dumpTarget != 0 || context.dumpSlot1 != 0; + if (request.target.gpuResolvedImages && !captured) { + if (materializeHeapDirect(context, i, invocation, request, timing)) return stageCapture.compiled; + } const auto capture = [&] { const SampledReadScope sampling(evidenceReads); try { - return CaptureInvocation(shaderMemory, *program.snapshot, program.codeOffset, request, invocation); + return CaptureInvocation(context.shaderMemory, *program.snapshot, program.codeOffset, request, invocation); } catch (const std::exception& error) { - throw named(error, shaderMemory.Regions()); + throw stageFailure(program, request, error, context.shaderMemory.Regions()); } }(); - stageCapture.regions = shaderMemory.TakeRecentRegions(); - stageCapture.supplied = shaderMemory.SuppliedBlocks(); - stageCapture.userDataUse = capture->userDataUse; + stageCapture.regions = context.shaderMemory.TakeRecentRegions(); + stageCapture.supplied = context.shaderMemory.SuppliedBlocks(); stageCapture.registeredViews = std::make_shared>(capture->snapshot.registeredImages); - recompiled[i] = true; - memory = shaderMemory.Regions(); + context.recompiled[i] = true; + context.memory = context.shaderMemory.Regions(); - for (std::size_t j = 0; j < programs.size(); ++j) { - if (matched[j] != nullptr && !recompiled[j] && (drawHit || j < i)) memory.insert(memory.end(), matchedRegions[j].begin(), matchedRegions[j].end()); + for (std::size_t j = 0; j < context.programs.size(); ++j) { + if (context.matched[j] != nullptr && !context.recompiled[j] && (context.drawHit || j < i)) context.memory.insert(context.memory.end(), context.matchedRegions[j].begin(), context.matchedRegions[j].end()); + if (j != i && context.recompiled[j] && context.stageCaptures[j].Direct()) context.memory.insert(context.memory.end(), context.stageCaptures[j].regions.begin(), context.stageCaptures[j].regions.end()); } - request.context.memory = memory; - static const bool dumpGraphics = std::getenv("APS5_DUMP_GRAPHICS_SHADERS") != nullptr; + request.context.memory = context.memory; if (dumpGraphics) static_cast(dumpRequest(program.binary.codeAddress, request)); - if (traceCapSync()) traceCapture("draw-capture", program.binary.codeAddress, submission.queue, memory, Graphics::Recorder::ThreadWaitedMs() - waitedBefore); - if (profile) { - ++captures; - phaseTiming.Phase(DrawRowCapture); - - const auto waited = std::min(Graphics::Recorder::ThreadWaitedMs() - waitedBefore, phaseMs[DrawRowCapture]); - phaseMs[DrawRowCapture] -= waited; - phaseMs[DrawRowCaptureHookWaits] += waited; + if (traceCapSync()) traceCapture("draw-capture", program.binary.codeAddress, context.submission.queue, context.memory, Graphics::Recorder::ThreadWaitedMs() - waitedBefore); + if (context.profile) { + ++context.captures; + context.phaseTiming.Phase(DrawRowCapture); + + const auto waited = std::min(Graphics::Recorder::ThreadWaitedMs() - waitedBefore, context.phaseMs[DrawRowCapture]); + context.phaseMs[DrawRowCapture] -= waited; + context.phaseMs[DrawRowCaptureHookWaits] += waited; } - if (dumpTarget != 0) { + if (context.dumpTarget != 0) { - const auto slot0 = (static_cast(readRegister(queue.context, 0x390)) << 40u) | (static_cast(readRegister(queue.context, 0x318)) << 8u); - if ((graphics.hasColorTarget && graphics.color.address == dumpTarget) || slot0 == dumpTarget || program.binary.codeAddress == dumpTarget) static_cast(dumpRequest(program.binary.codeAddress, request)); + const auto slot0 = (static_cast(readRegister(context.queue.context, 0x390)) << 40u) | (static_cast(readRegister(context.queue.context, 0x318)) << 8u); + if ((context.graphics.hasColorTarget && context.graphics.color.address == context.dumpTarget) || slot0 == context.dumpTarget || program.binary.codeAddress == context.dumpTarget) static_cast(dumpRequest(program.binary.codeAddress, request)); } - if (dumpSlot1 != 0) { - const auto value = [&](std::uint32_t offset) -> std::uint64_t { const auto it = queue.context.find(offset); return it == queue.context.end() ? 0u : it->second; }; + if (context.dumpSlot1 != 0) { + const auto value = [&](std::uint32_t offset) -> std::uint64_t { const auto it = context.queue.context.find(offset); return it == context.queue.context.end() ? 0u : it->second; }; const auto slot1 = (value(0x391) << 40u) | (value(0x327) << 8u); - if (slot1 == dumpSlot1) { + if (slot1 == context.dumpSlot1) { static_cast(dumpRequest(program.binary.codeAddress, request)); if (std::FILE* file = std::fopen("draw_slot1.regs", "w")) { - for (const auto& [offset, value] : queue.context) std::fprintf(file, "context %x %08x\n", offset, value); - for (const auto& [offset, value] : queue.userConfig) std::fprintf(file, "uconfig %x %08x\n", offset, value); - for (const auto& [offset, value] : queue.shader) std::fprintf(file, "shader %x %08x\n", offset, value); + for (const auto& [offset, value] : context.queue.context) std::fprintf(file, "context %x %08x\n", offset, value); + for (const auto& [offset, value] : context.queue.userConfig) std::fprintf(file, "uconfig %x %08x\n", offset, value); + for (const auto& [offset, value] : context.queue.shader) std::fprintf(file, "shader %x %08x\n", offset, value); std::fclose(file); } } } - phaseTiming.Phase(DrawRowCapture); + context.phaseTiming.Phase(DrawRowCapture); timing.Mark("capture_resources"); - try { - stageCapture.compiled = MaterializeInBackground(invocation, capture, request.context.memory, program.binary.codeAddress); - stageCapture.capture = capture; - } catch (const DrawCompilePending&) { - throw; - } catch (const std::exception& error) { - TraceMaterializationFailure(traceToken, submission, packetOffset, i, "capture-or-materialize", std::current_exception()); - throw named(error, request.context.memory); - } - timing.Mark("materialize"); - const auto walked = capture->userDataUse.asValue | capture->userDataUse.asBase; - auto mask = capture->plan != nullptr && capture->plan->srtPlanComplete ? walked | stageCapture.compiled->userDataRegisterReads : ~std::uint64_t{0}; - if (vertexInfos[i]) { - for (const auto reg : {static_cast(vertexInfos[i]->fetchAttribReg), static_cast(vertexInfos[i]->fetchBufferReg)}) { - mask |= reg + 1u < 64u ? std::uint64_t{3} << reg : ~std::uint64_t{0}; + stageCapture.heapWords.reset(); + if (request.target.gpuResolvedImages) { + auto words = std::make_shared(); + if (auto shared = MaterializeHeapInBackground(invocation, capture, *words, request.context.memory, program.binary.codeAddress)) { + words->dataOrigin = NextHeapDataOrigin(); + stageCapture.compiled = std::move(shared); + stageCapture.heapWords = std::move(words); + stageCapture.origin = StageOrigin::HeapRead; + if (SampleHeapStageVerify()) NoteHeapDirectVerify(*PatchedHeapResult(*stageCapture.compiled, *stageCapture.heapWords), *invocation.Materialize(*capture)); } } - if (program.snapshot && program.snapshot->userDataTailRegister) { - const auto reg = *program.snapshot->userDataTailRegister; - if (reg >= program.firstUserSgpr) { - const auto slot = reg - program.firstUserSgpr; - mask |= slot + 1u < 64u ? std::uint64_t{3} << slot : ~std::uint64_t{0}; - } else { - mask = ~std::uint64_t{0}; + if (stageCapture.heapWords == nullptr) { + try { + stageCapture.compiled = MaterializeInBackground(invocation, capture, request.context.memory, program.binary.codeAddress); + } catch (const DrawCompilePending&) { + throw; + } catch (const std::exception& error) { + TraceMaterializationFailure(context.traceToken, context.submission, context.packetOffset, i, "capture-or-materialize", std::current_exception()); + throw stageFailure(program, request, error, request.context.memory); } } - if (program.snapshot && StageLinksUserDataCallees(*program.snapshot, program.codeOffset)) { - mask = ~std::uint64_t{0}; - } - stageCapture.userDataMask = mask; - phaseTiming.Phase(DrawRowRecompile); + if (stageCapture.compiled->gpuResolvedImages) RequireHeapStageMappable(*stageCapture.compiled); + stageCapture.capture = capture; + timing.Mark("materialize"); + const auto walked = capture->userDataUse.asValue | capture->userDataUse.asBase; + stageCapture.userDataMask = capture->plan == nullptr || !capture->plan->srtPlanComplete ? ~std::uint64_t{0} : UserDataMask(program, context.vertexInfos[i], walked, *stageCapture.compiled); + context.phaseTiming.Phase(DrawRowRecompile); return stageCapture.compiled; } catch (const DrawCompilePending&) { throw; } catch (const std::exception& error) { if (!SkipRefusedDraws()) throw; - throw RefusedDraw(programs[i].binary.codeAddress, error.what()); + throw RefusedDraw(context.programs[i].binary.codeAddress, error.what()); } + + void Driver::recordStageDataPositions(DispatchVariant& variant, const ShaderRecompiler::ResourceCapture& capture, const std::vector& decodeReads) { const auto& compiled = *variant.compiled; for (std::size_t b = 0; b < compiled.bindings.size(); ++b) { if (compiled.bindings[b].role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; variant.flatBinding = static_cast(b); - static_cast(DataWordPositions(variant.runs, capture.readTrace.leaves, capture.readTrace.otherReads, variant.words, compiled.bindings[b].guestDescriptor, variant.dataPositions, variant.dataSlots)); + static_cast(DataWordPositions(variant.runs, capture.readTrace.leaves, capture.readTrace.otherReads, variant.words, variant.ringTemplate != nullptr && !variant.ringTemplate->flattenedSrt.empty() ? variant.ringTemplate->flattenedSrt : compiled.bindings[b].guestDescriptor, variant.dataPositions, variant.dataSlots)); break; } if (variant.dataPositions.empty() || decodeReads.empty()) return; @@ -346,7 +519,7 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP fresh[i] = matched[i]; continue; } - if (stageCapture.compiled == nullptr || !CacheableResult(*stageCapture.compiled)) continue; + if (stageCapture.compiled == nullptr || !stageCapture.Cacheable() || !CacheableResult(*stageCapture.compiled)) continue; auto variant = std::make_shared(); variant->compiled = stageCapture.compiled; variant->registeredViews = stageCapture.registeredViews; @@ -357,14 +530,30 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP variant->forgetSerial = stageCapture.forgetSerial; variant->pushOffset = stageCapture.pushOffset; variant->userDataMask = stageCapture.userDataMask; + if (stageCapture.origin == StageOrigin::HeapRead && stageCapture.heapWords != nullptr) { + auto ringTemplate = std::make_shared(); + ringTemplate->vertexAttributes = stageCapture.heapWords->vertexAttributes; + ringTemplate->flattenedSrt = stageCapture.heapWords->flattenedSrt; + ringTemplate->bindings = stageCapture.heapWords->bindings; + if (const auto& base = stageCapture.heapWords->base; base != nullptr && !base->bindings.empty()) { + const auto& program = stageCapture.compiled->bindings; + ringTemplate->bindings.resize(program.size()); + for (std::size_t index = 0; index < program.size(); ++index) { + if (ringTemplate->bindings[index].empty()) ringTemplate->bindings[index] = Graphics::DrawGuestWords(*stageCapture.compiled, stageCapture.heapWords.get(), program[index]); + if (ringTemplate->bindings[index] == program[index].guestDescriptor) ringTemplate->bindings[index].clear(); + } + } + ringTemplate->dataOrigin = NextHeapDataOrigin(); + variant->ringTemplate = std::move(ringTemplate); + } if (vertexInfos[i]) variant->vertexInfo = std::make_shared(*vertexInfos[i]); std::vector regions(stageCapture.regions.begin(), stageCapture.regions.end()); for (const auto& read : decodeReads[i]) regions.push_back({read.address, read.Bytes()}); std::stable_sort(regions.begin(), regions.end(), [](const ShaderRecompiler::MemoryRegion& a, const ShaderRecompiler::MemoryRegion& b) { return a.guestAddress < b.guestAddress; }); const bool relocatable = decodeReads[i].empty() && (!vertexInfos[i] || vertexInfos[i]->resourcesNum == 0); - tagVariantRuns(*variant, regions, stageCapture.userDataUse, relocatable, programs[i].hiddenUserWords, stageCapture.supplied); - if (relocatable) tagUserValueWords(*variant, programs[i]); + tagVariantRuns(*variant, regions, stageCapture.UserDataUse(), relocatable, programs[i].hiddenUserWords, stageCapture.supplied); + if (relocatable && (stageCapture.heapWords == nullptr || variant->ringTemplate != nullptr)) tagUserValueWords(*variant, programs[i], stageCapture.heapWords.get()); if (drawStageDataHits() && stageCapture.capture != nullptr && !stageCapture.capture->readTrace.leaves.empty()) recordStageDataPositions(*variant, *stageCapture.capture, decodeReads[i]); if (traceDrawCache() && entry != nullptr && matched[i] == nullptr && i < entry->stages.size()) { const auto& variants = entry->stages[i]; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp index 57b3eceb4f0b..6bb258cc2bb9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "Optimization/ResourceProgram.hpp" #include @@ -137,6 +138,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptrstages.size() != programs.size()) miss = DrawMiss::Stages; std::uint32_t cursor = 0; + std::optional heapMode; { const GuestMemory::ReadSiteScope site(GuestMemory::ReadSite::DrawCache); @@ -153,7 +155,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptrregisteredViews != nullptr && !CaptureRegisteredViewsCurrent(*variant->registeredViews)) continue; - if (variant->pushOffset != cursor || variant->compiled->pushConstants.size() > pushBudget) continue; + if (variant->pushOffset != cursor || variant->compiled->pushConstants.size() > pushBudget || (heapMode && variant->compiled->gpuResolvedImages != *heapMode)) continue; if (programs[i].binary.stage == ShaderRecompiler::ShaderStage::Mesh && !std::equal(variant->meshIndexDescriptor.begin(), variant->meshIndexDescriptor.end(), programs[i].userData.begin() + ShaderRecompiler::MeshIndexBufferUserWord)) { if (!anyLayout) outcome = EntryOutcome::Differing; anyLayout = true; @@ -180,6 +182,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptrcompiled->gpuResolvedImages; ++stageEqual; cursor += static_cast(variant->compiled->pushConstants.size()); break; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp index 8b664b430ca7..2149866214e9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -8,6 +8,7 @@ #include "prx/libSceAgcDriver/Execution/include/ProfileCounter.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/WorkerSampler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include @@ -130,7 +131,7 @@ bool DrawFinisher::PendingOverlapsAny(std::span ranges) { bool DrawFinisher::PendingKey(std::uint64_t key, std::uint64_t shape) { if (!Busy() || !finisherProducer) return false; std::lock_guard lock(mutex); - return std::any_of(pending.begin(), pending.end(), [&](const Pending& held) { return held.key == key || (shape != 0 && held.shape == shape); }); + return std::any_of(pending.begin(), pending.end(), [&](const Pending& held) { return (held.key != 0 && held.key == key) || (shape != 0 && held.shape == shape); }); } namespace { @@ -151,7 +152,7 @@ void DrawFinisher::NoteDrainedOpcode(std::uint32_t opcode, bool besideCommits) { } std::string DrawFinisher::DrainText() { - constexpr std::array(DrainSite::Count)> names{"lookup", "reads", "packet", "kept draw"}; + constexpr std::array(DrainSite::Count)> names{"lookup", "reads", "packet", "kept draw", "dispatch"}; std::string text = "; worker drains of the finisher (drained/skipped):"; for (std::size_t i = 0; i < names.size(); ++i) { char item[64]; @@ -181,6 +182,15 @@ void DrawFinisher::Enqueue(Job job) { Enqueue(std::move(job), Pending{}); } +void DrawFinisher::EnqueueBeside(Job job, std::vector writes, std::uint64_t labelAddress, std::vector labelBytes) { + Pending held; + held.unknown = false; + held.writes = std::move(writes); + held.labelAddress = labelAddress; + held.labelBytes = std::move(labelBytes); + Enqueue(std::move(job), std::move(held)); +} + void DrawFinisher::Enqueue(Job job, Pending held) { finisherProducer = true; constexpr std::size_t depth = 16; @@ -308,6 +318,11 @@ void DrawPipeline::rethrowFailure() { std::rethrow_exception(error); } +std::uint32_t DrawPipeline::FullWaiters() { + std::lock_guard lock(mutex); + return fullWaiters; +} + void DrawPipeline::Enqueue(Commit commit, std::vector writes, std::uint64_t labelAddress, std::vector labelBytes, std::vector reads, bool draw) { enqueue({std::move(commit), std::move(writes), labelAddress, std::move(labelBytes), std::move(reads), draw}); } @@ -359,13 +374,24 @@ void DrawPipeline::enqueue(Item item) { if (items.size() >= Depth()) { if (GuestMemory::GpuMutex().HeldByThisThread()) throw std::runtime_error("draw pipeline full while the enqueuing thread holds the GPU lock"); const auto start = std::chrono::steady_clock::now(); - resumeAt = Depth() - 1; - ++idleWaiters; - idle.wait(lock, [&] { return items.size() <= resumeAt; }); - --idleWaiters; - resumeAt = 0; + lock.unlock(); + static_cast(SpinUntil(HandoffSpinWindow(), [&] { return outstanding.load(std::memory_order_acquire) < Depth(); })); + lock.lock(); + if (items.size() >= Depth() && !closing) { + resumeAt = Depth() / 2; + ++idleWaiters; + ++fullWaiters; + idle.wait(lock, [&] { return items.size() <= resumeAt || closing; }); + --idleWaiters; + if (--fullWaiters == 0) resumeAt = 0; + } fullWaitNs += elapsedNs(start); rethrowFailure(); + if (closing) { + lock.unlock(); + item.commit(); + return; + } } depthSum += items.size(); ++enqueued; @@ -499,6 +525,7 @@ void DrawPipeline::Stop() { committer = std::move(thread); } wake.notify_all(); + idle.notify_all(); if (!committer.joinable()) return; if (committer.get_id() == std::this_thread::get_id()) committer.detach(); else committer.join(); @@ -626,9 +653,15 @@ DrawPipeline::Watch DrawPipeline::WatchWrites() { } bool DrawPipeline::WrittenSince(const Watch& watch, const std::vector& reads) { - const auto overlaps = [&reads](const std::vector& writes) { - return std::any_of(reads.begin(), reads.end(), [&writes](const Range& read) { - return std::any_of(writes.begin(), writes.end(), [&read](const Range& write) { return read.first < write.second && write.first < read.second; }); + Range hull{~std::uint64_t{0}, 0}; + for (const auto& read : reads) { + hull.first = std::min(hull.first, read.first); + hull.second = std::max(hull.second, read.second); + } + const auto overlaps = [&reads, &hull](const std::vector& writes) { + return std::any_of(writes.begin(), writes.end(), [&](const Range& write) { + if (!(hull.first < write.second && write.first < hull.second)) return false; + return std::any_of(reads.begin(), reads.end(), [&write](const Range& read) { return read.first < write.second && write.first < read.second; }); }); }; if (DrawFinisher::Overlap() && DrawFinisher::Get().PendingOverlapsAny(reads)) return true; @@ -646,7 +679,14 @@ bool DrawPipeline::Busy() const { bool DrawPipeline::OverlapsAny(std::span> ranges) { if (DrawFinisher::Overlap() && DrawFinisher::Get().PendingOverlapsAny(ranges)) return true; std::lock_guard lock(mutex); + if (queuedWrites.empty() || ranges.empty()) return false; + std::pair hull{~std::uint64_t{0}, 0}; + for (const auto& [address, end] : ranges) { + hull.first = std::min(hull.first, address); + hull.second = std::max(hull.second, end); + } for (const auto& [range, count] : queuedWrites) { + if (!(hull.first < range.second && range.first < hull.second)) continue; for (const auto& [address, end] : ranges) { if (address < range.second && range.first < end) return true; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp index 0cb69b035e4b..ba2b3e8d4327 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include #include #include @@ -61,14 +62,18 @@ std::uint64_t Driver::relocatedContentKey(const RelocatableUserWord& word, std:: return hash; } -void Driver::tagUserValueWords(DispatchVariant& variant, const DrawProgram& program) { +void Driver::tagUserValueWords(DispatchVariant& variant, const DrawProgram& program, const ShaderRecompiler::HeapStageWords* heap) { if (!drawRelocationEnabled() || variant.compiled == nullptr) return; const auto& compiled = *variant.compiled; const auto& forwarded = compiled.shaderDataUserWords; const auto users = std::min(program.userData.size(), 64); const auto bound = [&](std::uint32_t value) { std::size_t count = 0; - for (const auto& binding : compiled.bindings) count += static_cast(std::count(binding.guestDescriptor.begin(), binding.guestDescriptor.end(), value)); + for (const auto& binding : compiled.bindings) { + if (heap != nullptr && binding.role == ShaderRecompiler::DescriptorRole::ShaderData) continue; + const auto& words = Graphics::DrawGuestWords(compiled, heap, binding); + count += static_cast(std::count(words.begin(), words.end(), value)); + } return count; }; const auto elsewhere = [&](std::uint32_t index, std::uint32_t value) { @@ -115,16 +120,18 @@ void Driver::tagUserValueWords(DispatchVariant& variant, const DrawProgram& prog if (base == 0 || taken(index) || bound(base) != 1 || elsewhere(index, base)) continue; std::uint32_t binding = 0, word = 0; for (std::size_t b = 0; b < compiled.bindings.size(); ++b) { - const auto& descriptor = compiled.bindings[b].guestDescriptor; + if (heap != nullptr && compiled.bindings[b].role == ShaderRecompiler::DescriptorRole::ShaderData) continue; + const auto& descriptor = Graphics::DrawGuestWords(compiled, heap, compiled.bindings[b]); const auto found = std::find(descriptor.begin(), descriptor.end(), base); if (found == descriptor.end()) continue; binding = static_cast(b); word = static_cast(found - descriptor.begin()); } const auto& target = compiled.bindings[binding]; + const auto& targetWords = Graphics::DrawGuestWords(compiled, heap, target); const auto element = word / 4u; - const bool readOnly = target.role == ShaderRecompiler::DescriptorRole::GuestBuffers && target.guestDescriptor.size() == static_cast(target.count) * 4u && word % 4u == 0 && element < target.bufferWritten.size() && !target.bufferWritten[element] && (element >= target.bufferAtomic.size() || !target.bufferAtomic[element]); - if (!readOnly || target.guestDescriptor[word + 1] != program.userData[index + 1] || target.guestDescriptor[word + 2] != program.userData[index + 2] || readThrough(target.guestDescriptor.data() + word)) continue; + const bool readOnly = target.role == ShaderRecompiler::DescriptorRole::GuestBuffers && targetWords.size() == static_cast(target.count) * 4u && word % 4u == 0 && element < target.bufferWritten.size() && !target.bufferWritten[element] && (element >= target.bufferAtomic.size() || !target.bufferAtomic[element]); + if (!readOnly || targetWords[word + 1] != program.userData[index + 1] || targetWords[word + 2] != program.userData[index + 2] || readThrough(targetWords.data() + word)) continue; variant.valueWords |= std::uint64_t {1} << index; variant.valueSlots.push_back({index, binding, word}); const auto records = program.userData[index + 2]; @@ -136,6 +143,7 @@ void Driver::tagUserValueWords(DispatchVariant& variant, const DrawProgram& prog } void Driver::tagVariantRuns(DispatchVariant& variant, std::span regions, const ShaderRecompiler::SrtUserDataUse& use, bool eligible, std::uint32_t hiddenWords, std::span> supplied) { + variant.cleanPendingSerial.store(~0ull, std::memory_order_relaxed); variant.userWordsWalked = use.asBase | use.asValue; std::uint64_t relocatable = eligible && drawRelocationEnabled() ? use.asBase & ~use.asValue : 0; if (hiddenWords != 0) relocatable &= hiddenWords >= 64 ? 0 : ~((std::uint64_t {1} << hiddenWords) - 1); @@ -328,6 +336,9 @@ void Driver::relocateDrawEntry(const QueueState& queue, std::uint64_t alias, std copy->flatBinding = variant->flatBinding; copy->pushOffset = variant->pushOffset; copy->vertexInfo = variant->vertexInfo; + copy->ringTemplate = variant->ringTemplate; + copy->ringDescriptorPatches = variant->ringDescriptorPatches; + copy->ringDataPatches = variant->ringDataPatches; for (const auto& move : moves) { if (move.program != i) continue; const auto delta = AlignedWord(move.to) - AlignedWord(move.from); @@ -355,7 +366,25 @@ void Driver::relocateDrawEntry(const QueueState& queue, std::uint64_t alias, std void Driver::applyShaderDataPatches(DispatchVariant& variant) { if (variant.shaderDataPatches.empty() && variant.descriptorPatches.empty()) return; - auto rebased = std::make_shared(*variant.compiled); + const auto& compiled = *variant.compiled; + if (variant.ringTemplate != nullptr) { + const bool templateSrt = !variant.ringTemplate->flattenedSrt.empty(); + bool programWords = false; + for (const auto& patch : variant.descriptorPatches) { + if (!templateSrt && patch[0] < compiled.bindings.size() && compiled.bindings[patch[0]].role == ShaderRecompiler::DescriptorRole::FlattenedSrt) programWords = true; + else variant.ringDescriptorPatches.push_back(patch); + } + for (const auto& patch : variant.shaderDataPatches) { + variant.ringDataPatches.push_back(patch); + if (!compiled.dataAddressPush && static_cast(patch.first) * sizeof(std::uint32_t) + sizeof(std::uint32_t) <= compiled.pushConstants.size()) programWords = true; + } + if (!programWords) { + variant.shaderDataPatches.clear(); + variant.descriptorPatches.clear(); + return; + } + } + auto rebased = std::make_shared(compiled); for (const auto& [slot, value] : variant.shaderDataPatches) patchForwardedWord(*rebased, slot, value); for (const auto& [binding, word, value] : variant.descriptorPatches) { if (binding < rebased->bindings.size() && word < rebased->bindings[binding].guestDescriptor.size()) rebased->bindings[binding].guestDescriptor[word] = value; @@ -367,7 +396,7 @@ void Driver::applyShaderDataPatches(DispatchVariant& variant) { void Driver::patchForwardedWord(ShaderRecompiler::RecompileResult& result, std::uint32_t slot, std::uint32_t value) { const auto at = static_cast(slot) * sizeof(std::uint32_t); - if (at + sizeof(std::uint32_t) <= result.pushConstants.size()) std::memcpy(result.pushConstants.data() + at, &value, sizeof(value)); + if (!result.dataAddressPush && at + sizeof(std::uint32_t) <= result.pushConstants.size()) std::memcpy(result.pushConstants.data() + at, &value, sizeof(value)); for (auto& binding : result.bindings) { if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData && slot < binding.guestDescriptor.size()) binding.guestDescriptor[slot] = value; } @@ -375,7 +404,7 @@ void Driver::patchForwardedWord(ShaderRecompiler::RecompileResult& result, std:: void Driver::reportDrawRelocation() { auto& counters = drawRelocationCounters; - AgcDriver::ProfilePrint_nid_no_patch("[draw-relocate] %llu alias lookups: %llu donors with moved user words, %llu refusals, %llu hits through a relocated entry; %zu shader sets learned, %zu aliases held (%llu dropped at the limit)\n", static_cast(counters.lookups), static_cast(counters.donors), static_cast(counters.refused), static_cast(counters.hits), drawRelocations.size(), drawAliases.size(), static_cast(counters.evicted)); + AgcDriver::ProfilePrint_nid_no_patch("[draw-relocate] %llu alias lookups: %llu donors with moved user words, %llu refusals, %llu hits through a relocated entry (%llu cached under their own key); %zu shader sets learned, %zu aliases held (%llu dropped at the limit)\n", static_cast(counters.lookups), static_cast(counters.donors), static_cast(counters.refused), static_cast(counters.hits), static_cast(counters.admitted), drawRelocations.size(), drawAliases.size(), static_cast(counters.evicted)); counters = {}; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp new file mode 100644 index 000000000000..3b1f214b3074 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -0,0 +1,812 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "HeapCacheSwitch.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/HostThreadLocal.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::DriverDetail { + +namespace { + +constexpr std::uint64_t WalkPageBytes = 0x1000u; +constexpr std::uint64_t WordBytes = sizeof(std::uint32_t); + +std::atomic& heapStages() { + static std::atomic count{0}; + return count; +} + +const char* resultDifference(const ShaderRecompiler::RecompileResult& left, const ShaderRecompiler::RecompileResult& right, + std::size_t& index) { + index = 0; + if (left.PipelineVariantId() != right.PipelineVariantId()) return "variant"; + if (left.pushConstants != right.pushConstants) return "push constants"; + if (left.bindings.size() != right.bindings.size()) return "binding count"; + if (left.specialization.size() != right.specialization.size()) return "specialization count"; + for (index = 0; index < left.bindings.size(); ++index) { + const auto& a = left.bindings[index]; + const auto& b = right.bindings[index]; + if (a.role != b.role || a.kind != b.kind || a.binding != b.binding || a.count != b.count) return "binding layout"; + if (a.guestDescriptor != b.guestDescriptor) return "binding words"; + } + for (index = 0; index < left.specialization.size(); ++index) { + if (left.specialization[index].id != right.specialization[index].id || + left.specialization[index].value != right.specialization[index].value) + return "specialization"; + } + index = 0; + if (left.vertexAttributes.size() != right.vertexAttributes.size()) return "attribute count"; + for (index = 0; index < left.vertexAttributes.size(); ++index) { + const auto& a = left.vertexAttributes[index]; + const auto& b = right.vertexAttributes[index]; + const bool sameAttribute = a.location == b.location && a.components == b.components && a.resource.fields == b.resource.fields && + a.fetchIndex == b.fetchIndex && a.formatComponents == b.formatComponents; + if (!sameAttribute) return "attribute"; + } + return nullptr; +} + +void reportHeapMismatch(const char* check, const char* what, const ShaderRecompiler::RecompileResult& result, std::size_t index) { + static std::atomic printed{0}; + if (printed.fetch_add(1, std::memory_order_relaxed) >= 64u) return; + const int role = index < result.bindings.size() ? static_cast(result.bindings[index].role) : -1; + const int kind = index < result.bindings.size() ? static_cast(result.bindings[index].kind) : -1; + std::fprintf(stderr, "[heap-verify] %s: %s differ at %zu (role %d kind %d, template %llu, variant 0x%llx)\n", check, what, index, role, + kind, static_cast(result.heapTemplateId), static_cast(result.PipelineVariantId())); + std::fflush(stderr); +} + +struct VerifyCounts { + std::atomic verified{0}; + std::atomic differ{0}; + std::atomic notComparable{0}; + std::atomic accessor{0}; + std::atomic accessorDiffer{0}; + std::atomic ring{0}; + std::atomic ringDiffer{0}; +}; + +unsigned long long loaded(const std::atomic& counter) { + return static_cast(counter.load()); +} + +void reportVerifyCounts(const VerifyCounts& c) { + if (c.verified.load() != 0u || c.notComparable.load() != 0u) { + std::fprintf( + stderr, + "[heap-verify] %llu heap stages compared with a full capture, %llu differed, %llu not comparable (the full capture could not read every descriptor)\n", + loaded(c.verified), loaded(c.differ), loaded(c.notComparable)); + } + if (c.accessor.load() != 0u || c.ring.load() != 0u) { + std::fprintf(stderr, "[heap-verify] %llu accessor checks, %llu differed; %llu ring hits checked, %llu differed\n", + loaded(c.accessor), loaded(c.accessorDiffer), loaded(c.ring), loaded(c.ringDiffer)); + } +} + +VerifyCounts& verifyCounts() { + static VerifyCounts counts; + static std::once_flag registered; + std::call_once(registered, [] { std::atexit([] { reportVerifyCounts(verifyCounts()); }); }); + return counts; +} + +} + +bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage) { + using Stage = ShaderRecompiler::ShaderStage; + return stage == Stage::Vertex || stage == Stage::Local || stage == Stage::TessellationControl || + stage == Stage::TessellationEvaluation || stage == Stage::Mesh; +} + +const char* HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan) { + if (stage != ShaderRecompiler::ShaderStage::Fragment && !HeapPreRasterStage(stage)) return "its stage kind does not take the heap"; + if (plan == nullptr) return "it has no resource plan"; + if (plan->stage == ShaderRecompiler::IrShaderStage::Unknown || plan->stage == ShaderRecompiler::IrShaderStage::Fetch) + return "its resource plan has a fetch or unknown stage"; + return nullptr; +} + +bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan) { + return HeapStageIneligibility(stage, plan) == nullptr; +} + +namespace { + +struct HeapExclusions { + std::uint32_t stages = 0; + bool tables = false; + bool storage = false; + bool sampled = false; +}; + +using ExcludableStage = std::pair; + +constexpr ExcludableStage ExcludableStages[] = { + {"compute", ShaderRecompiler::ShaderStage::Compute}, + {"vertex", ShaderRecompiler::ShaderStage::Vertex}, + {"hull", ShaderRecompiler::ShaderStage::TessellationControl}, + {"domain", ShaderRecompiler::ShaderStage::TessellationEvaluation}, + {"geometry", ShaderRecompiler::ShaderStage::Geometry}, + {"pixel", ShaderRecompiler::ShaderStage::Fragment}, + {"local", ShaderRecompiler::ShaderStage::Local}, + {"mesh", ShaderRecompiler::ShaderStage::Mesh}}; + +bool applyExclusion(HeapExclusions& exclusions, std::string_view item) { + if (item == "tables") { + exclusions.tables = true; + return true; + } + if (item == "storage") { + exclusions.storage = true; + return true; + } + if (item == "sampled") { + exclusions.sampled = true; + return true; + } + const auto stage = std::find_if(std::begin(ExcludableStages), std::end(ExcludableStages), [&](const auto& entry) { return entry.first == item; }); + if (stage == std::end(ExcludableStages)) return false; + exclusions.stages |= 1u << static_cast(stage->second); + return true; +} + +const HeapExclusions& heapExclusions() { + static const HeapExclusions exclusions = [] { + HeapExclusions result; + const char* value = std::getenv("APS5_GPU_HEAP_EXCLUDE"); + std::string_view list = value != nullptr ? value : ""; + while (!list.empty()) { + const auto comma = list.find(','); + const auto item = list.substr(0, comma); + if (!applyExclusion(result, item)) throw std::runtime_error("APS5_GPU_HEAP_EXCLUDE: unknown class '" + std::string(item) + "'; use compute, vertex, hull, domain, geometry, pixel, local, mesh, tables, storage or sampled"); + if (comma == std::string_view::npos) break; + list.remove_prefix(comma + 1u); + } + return result; + }(); + return exclusions; +} + +std::string heapClassesFailure(const ShaderRecompiler::RecompileResult& result) { + using Role = ShaderRecompiler::DescriptorRole; + using Kind = ShaderRecompiler::DescriptorKind; + const auto& exclusions = heapExclusions(); + std::uint64_t demand = 0; + for (const auto& binding : result.bindings) { + const bool table = binding.role == Role::ImageTable || binding.role == Role::ImageStorageTable; + const bool image = binding.role == Role::GuestImages && (binding.kind == Kind::SampledImage || binding.kind == Kind::StorageImage); + if (table || image) demand += binding.count; + if ((table && exclusions.tables) || (image && binding.kind == Kind::StorageImage && exclusions.storage) || + (image && binding.kind == Kind::SampledImage && exclusions.sampled)) + return "AGC graphics: a GPU heap stage uses an image class APS5_GPU_HEAP_EXCLUDE names, which its resource plan did not show"; + } + const auto capacity = Graphics::BindlessHeap::ImageSlotCapacity(); + if (demand > capacity) + return "AGC graphics: a GPU heap stage needs " + std::to_string(demand) + " image slots, more than the heap's " + std::to_string(capacity); + return {}; +} + +constexpr std::size_t ThreadCacheLimit = 65536u; + +std::string heapStageFailure(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { + if (auto failure = heapClassesFailure(result); !failure.empty()) return failure; + std::pair refused{}; + if (!Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), {.workgroupAddress = workgroupAddress, .gdsAddress = result.dataAddressPush, .pixelLds = result.functionLdsBuffer, .meshWindow = result.meshWindowBuffer, .scratchPool = result.scratchPoolSlotDwords != 0u}, &refused)) + return "AGC graphics: a GPU heap stage uses descriptor set " + std::to_string(refused.first) + " binding " + std::to_string(refused.second) + + ", which the heap cannot map"; + return {}; +} + +const std::string& knownHeapStageFailure(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { + struct MappableStorage {}; + struct RecentStorage {}; + struct Recent { + std::uint64_t key = 0; + const std::string* failure = nullptr; + }; + constexpr std::size_t RecentSlots = 64; + auto& known = HostThreadLocal, MappableStorage>(); + auto& recent = HostThreadLocal, RecentStorage>(); + const auto key = result.variantId * 2u + (workgroupAddress ? 1u : 0u); + auto& slot = recent[(key ^ (key >> 17u)) % RecentSlots]; + if (slot.failure != nullptr && slot.key == key) return *slot.failure; + auto found = known.find(key); + if (found == known.end()) { + if (known.size() >= ThreadCacheLimit) { + known.clear(); + recent.fill({}); + } + found = known.emplace(key, heapStageFailure(result, workgroupAddress)).first; + } + slot = {key, &found->second}; + return found->second; +} + +} + +void RequireHeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { + if (const auto& failure = knownHeapStageFailure(result, workgroupAddress); !failure.empty()) throw std::runtime_error(failure); +} + +bool HeapStageFits(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { + return knownHeapStageFailure(result, workgroupAddress).empty(); +} + +bool HeapStageExcluded(ShaderRecompiler::ShaderStage stage) { + return (heapExclusions().stages >> static_cast(stage) & 1u) != 0u; +} + +namespace { + +bool heapPlanExcluded(const ShaderRecompiler::IrResourcePlan& plan) { + using Class = ShaderRecompiler::ImageResourceClass; + const auto& exclusions = heapExclusions(); + if (exclusions.tables && std::ranges::any_of(plan.descriptorSources, [](const ShaderRecompiler::DescriptorSource& source) { return source.tableColumn.has_value(); })) + return true; + const auto excludedImage = [&](const ShaderRecompiler::ImageResource& image) { + return (exclusions.storage && image.resourceClass == Class::Storage) || (exclusions.sampled && image.resourceClass == Class::Sampled); + }; + if (std::ranges::any_of(plan.info.images, excludedImage)) return true; + return std::ranges::any_of(plan.info.runtimeImageModes, [&](const std::vector& modes) { return std::ranges::any_of(modes, excludedImage); }); +} + +} + +bool HeapExcludedFor(const ShaderRecompiler::PreparedShaderInvocation& invocation) { + const auto plan = invocation.PlanOrLoad(); + if (plan == nullptr) throw std::runtime_error("AGC graphics: a GPU heap stage has no resource plan to apply APS5_GPU_HEAP_EXCLUDE to"); + return heapPlanExcluded(*plan); +} + +bool HeapClassesExcluded() { + const auto& exclusions = heapExclusions(); + return exclusions.tables || exclusions.storage || exclusions.sampled; +} + +bool SampleHeapStageVerify() { + const auto every = ShaderRecompiler::HeapVerifyEvery(); + if (every == 0) return false; + thread_local std::uint64_t calls = 0; + return calls++ % every == 0; +} + +void AppendWalkRead(std::vector>& runs, std::uint64_t address) { + if (!runs.empty() && address >= runs.back().first && address <= runs.back().second) { + runs.back().second = std::max(runs.back().second, address + WordBytes); + return; + } + runs.emplace_back(address, address + WordBytes); +} + +void CoalesceWalkReads(std::vector>& runs, std::vector>& ranges) { + if (!std::is_sorted(runs.begin(), runs.end())) std::sort(runs.begin(), runs.end()); + ranges.clear(); + for (const auto& [begin, end] : runs) { + if (!ranges.empty() && begin <= ranges.back().second) { + ranges.back().second = std::max(ranges.back().second, end); + continue; + } + ranges.emplace_back(begin, end); + } +} + +namespace { + +using AddressRanges = std::vector>; + +constexpr std::size_t WalkVerifiedSpans = 8; + +struct WalkReads { + AddressRanges runs; + const Graphics::Recorder::WriteRanges* before = nullptr; + std::vector> supplied; + bool collected = false; + std::array, WalkVerifiedSpans> verified{}; + std::size_t verifiedCount = 0; + std::size_t verifiedNext = 0; + bool failed = false; + + void Reset() { + runs.clear(); + supplied.clear(); + collected = false; + failed = false; + verifiedCount = 0; + verifiedNext = 0; + } + + bool Verified(std::uint64_t address, std::uint64_t bytes) const { + for (std::size_t i = 0; i < verifiedCount; ++i) { + if (address >= verified[i].first && address <= verified[i].second && bytes <= verified[i].second - address) return true; + } + return false; + } + + void Verify(std::uint64_t address, std::uint64_t bytes) { + verified[verifiedNext] = {address, address + bytes}; + verifiedNext = (verifiedNext + 1) % WalkVerifiedSpans; + verifiedCount = std::min(verifiedCount + 1, WalkVerifiedSpans); + } +}; + +bool readWalkWord(void* context, std::uint64_t address, std::uint32_t* value) { + auto& reads = *static_cast(context); + if (address % WordBytes != 0u) { + reads.failed = true; + return false; + } + if (!reads.Verified(address, sizeof(*value))) { + const auto page = address & ~(WalkPageBytes - 1u); + const bool crossesPage = (address & (WalkPageBytes - 1u)) > WalkPageBytes - sizeof(*value); + if (!crossesPage && GuestMemory::Accessible(reinterpret_cast(page), WalkPageBytes)) reads.Verify(page, WalkPageBytes); + else if (!GuestMemory::Accessible(reinterpret_cast(address), sizeof(*value))) { + reads.failed = true; + return false; + } + } + std::memcpy(value, reinterpret_cast(address), sizeof(*value)); + AppendWalkRead(reads.runs, address); + return true; +} + +bool readWalkWords(void* context, std::uint64_t address, std::uint32_t* values, std::uint64_t count) { + auto& reads = *static_cast(context); + if (address % WordBytes != 0u || count > (std::numeric_limits::max() - address) / WordBytes) { + reads.failed = true; + return false; + } + const auto first = address & ~(WalkPageBytes - 1u); + const auto past = (address + count * WordBytes + WalkPageBytes - 1u) & ~(WalkPageBytes - 1u); + if (count != 0u && past > first && !reads.Verified(address, count * WordBytes) && GuestMemory::Accessible(reinterpret_cast(first), static_cast(past - first))) reads.Verify(first, past - first); + while (count != 0u) { + const auto page = address & ~(WalkPageBytes - 1u); + const auto words = std::min(count, (page + WalkPageBytes - address) / WordBytes); + const auto bytes = words * WordBytes; + if (!reads.Verified(address, bytes)) { + if (GuestMemory::Accessible(reinterpret_cast(page), WalkPageBytes)) reads.Verify(page, WalkPageBytes); + else if (!GuestMemory::Accessible(reinterpret_cast(address), static_cast(bytes))) { + reads.failed = true; + return false; + } + } + std::memcpy(values, reinterpret_cast(address), static_cast(bytes)); + if (!reads.runs.empty() && address >= reads.runs.back().first && address <= reads.runs.back().second) reads.runs.back().second = std::max(reads.runs.back().second, address + bytes); + else reads.runs.emplace_back(address, address + bytes); + address += bytes; + values += words; + count -= words; + } + return true; +} + +bool queuedWriteOverlaps(std::span> ranges) { + if (!DrawPipeline::Active() && !DrawFinisher::OnFinisherThread()) return false; + auto& queue = DrawPipeline::Queue0(); + return queue.Busy() && queue.OverlapsAny(ranges); +} + +bool walkPending(const WalkReads& reads, std::uint64_t address, std::uint64_t bytes) { + const std::array range{std::pair{address, address + bytes}}; + const bool queuedWrite = queuedWriteOverlaps(range); + return queuedWrite || !Graphics::Recorder::ReadsSettled(range, reads.before); +} + +ShaderRecompiler::SrtWriteStamp stampWalkWrites(void* context, std::uint64_t address, std::uint64_t bytes) { + auto& reads = *static_cast(context); + if (bytes == 0u || address > std::numeric_limits::max() - bytes || walkPending(reads, address, bytes)) return {}; + reads.collected = true; + GuestMemory::FlushGpuWrites(address, static_cast(bytes)); + const auto layout = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); + const auto generation = GuestMemory::CollectWrites(address, static_cast(bytes)); + if (generation == 0u) return {}; + return {generation, layout}; +} + +bool walkUnchangedSince(void* context, std::uint64_t address, std::uint64_t bytes, const ShaderRecompiler::SrtWriteStamp& stamp) { + auto& reads = *static_cast(context); + if (bytes == 0u || address > std::numeric_limits::max() - bytes || walkPending(reads, address, bytes)) return false; + reads.collected = true; + return ShaderMemory::Vouched(nullptr, address, bytes, stamp); +} + +bool supplyWalkWords(void* context, const std::shared_ptr& words) { + auto& reads = *static_cast(context); + if (words == nullptr || words->runs.empty()) return false; + std::uint64_t total = 0; + for (const auto& [address, count] : words->runs) { + const auto bytes = static_cast(count) * WordBytes; + if (count == 0u || address % WordBytes != 0u || address > std::numeric_limits::max() - bytes) return false; + total += count; + } + if (total != words->words.size()) return false; + for (const auto& [address, count] : words->runs) { + const auto bytes = static_cast(count) * WordBytes; + const auto first = address & ~(WalkPageBytes - 1u); + const auto past = (address + bytes + WalkPageBytes - 1u) & ~(WalkPageBytes - 1u); + if (!reads.Verified(address, bytes)) { + if (!GuestMemory::Accessible(reinterpret_cast(first), static_cast(past - first))) return false; + reads.Verify(first, past - first); + } + } + for (const auto& [address, count] : words->runs) reads.runs.emplace_back(address, address + static_cast(count) * WordBytes); + reads.supplied.push_back(words); + return true; +} + +bool walkAccessible(void* context, std::uint64_t address, std::uint64_t bytes) { + auto& reads = *static_cast(context); + if (bytes != 0 && reads.Verified(address, bytes)) return true; + const bool accessible = GuestMemory::Accessible(reinterpret_cast(address), static_cast(bytes)); + if (!accessible) reads.failed = true; + else if (bytes != 0) reads.Verify(address, bytes); + return accessible; +} + + + +void copyRangeValues(const AddressRanges& ranges, std::span> supplied, std::vector& values) { + struct Reused { + std::uint64_t address; + std::uint64_t past; + const std::uint32_t* words; + }; + std::vector reused; + for (const auto& block : supplied) { + std::size_t at = 0; + for (const auto& [address, count] : block->runs) { + reused.push_back({address, address + static_cast(count) * WordBytes, block->words.data() + at}); + at += count; + } + } + std::sort(reused.begin(), reused.end(), [](const Reused& left, const Reused& right) { return left.address < right.address; }); + values.clear(); + auto next = reused.begin(); + for (const auto& [begin, end] : ranges) { + const auto offset = values.size(); + values.resize(offset + static_cast((end - begin) / WordBytes)); + auto* const out = values.data() + offset; + auto cursor = begin; + const auto live = [&](std::uint64_t past) { + if (past > cursor) std::memcpy(out + (cursor - begin) / WordBytes, reinterpret_cast(cursor), static_cast(past - cursor)); + cursor = std::max(cursor, past); + }; + for (; next != reused.end() && next->address < end; ++next) { + if (next->address < begin || next->past > end) throw std::runtime_error("a heap walk's reused table words lie outside its read ranges"); + live(next->address); + const auto first = std::max(next->address, cursor); + if (next->past > first) std::memcpy(out + (first - begin) / WordBytes, next->words + (first - next->address) / WordBytes, static_cast(next->past - first)); + cursor = std::max(cursor, next->past); + } + live(end); + } +} + +enum class Settle { Settled, Pending, Stamped }; + +Settle rangesSettled(const AddressRanges& ranges, const Graphics::Recorder::WriteRanges* before, std::uint64_t generation) { + const bool queuedWrite = queuedWriteOverlaps(ranges); + if (queuedWrite || !Graphics::Recorder::ReadsSettled(ranges, before)) return Settle::Pending; + return GuestMemory::NoStampAfter(ranges, generation) ? Settle::Settled : Settle::Stamped; +} + +void guardRanges(const AddressRanges& ranges) { + for (const auto& [begin, end] : ranges) GuestMemory::GuardRead(begin, static_cast(end - begin)); +} + +std::shared_ptr +captureWalk(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase, + WalkReads& reads) { + ShaderRecompiler::SrtRuntime runtime; + runtime.userData = userData; + runtime.shaderBase = shaderBase; + runtime.userContext = &reads; + runtime.readMemory = readWalkWord; + runtime.readWords = readWalkWords; + runtime.stampWrites = stampWalkWrites; + runtime.unchangedSince = walkUnchangedSince; + runtime.supplyWords = supplyWalkWords; + runtime.accessible = walkAccessible; + return invocation.Capture(runtime); +} + +} + +namespace { + +constexpr std::size_t RecycledKeptBytes = 16u << 10u; + +template +void clearRecycled(TVector& vector) { + if (vector.capacity() * sizeof(typename TVector::value_type) > RecycledKeptBytes) TVector().swap(vector); + else vector.clear(); +} + +} + +void ResetHeapStageWords(ShaderRecompiler::HeapStageWords& words) { + clearRecycled(words.userData); + clearRecycled(words.flattenedSrt); + clearRecycled(words.vertexAttributes); + clearRecycled(words.bindings); + words.base.reset(); + words.dataOrigin = 0; + words.drawKeyMemo.words.store(nullptr, std::memory_order_relaxed); + words.memoizeKey = true; +} + +namespace { + +constexpr std::size_t RecycledStageRecords = 1024, RecycledStageProbes = 8; + +template +struct RecycledStagePool : RecycledShared { + RecycledStagePool() : RecycledShared(RecycledStageRecords, RecycledStageProbes) {} +}; + +struct RecycledWordsStorage {}; +struct RecycledValuesStorage {}; +struct RecycledRangesStorage {}; + +std::shared_ptr recycledStageWords() { + return HostThreadLocal, RecycledWordsStorage>().Take(ResetHeapStageWords); +} + +std::shared_ptr> takeRecycledValues() { + return HostThreadLocal>, RecycledValuesStorage>().Take(clearRecycled>); +} + +std::shared_ptr takeRecycledRanges() { + return HostThreadLocal, RecycledRangesStorage>().Take(clearRecycled); +} + +} + +HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + ShaderRecompiler::MemoryRegionView memory, std::uint64_t shaderBase) { + struct ReadsStorage {}; + auto& reads = HostThreadLocal(); + auto sharedRanges = takeRecycledRanges(); + auto& ranges = *sharedRanges; + auto sharedValues = takeRecycledValues(); + auto& values = *sharedValues; + std::shared_ptr capture; + for (std::uint32_t attempt = 0;; ++attempt) { + reads.Reset(); + const auto before = Graphics::Recorder::PendingWriteSnapshot(); + reads.before = before.get(); + const auto generation = GuestMemory::StableTrackerGeneration(); + try { + capture = captureWalk(invocation, userData, shaderBase, reads); + } catch (const std::exception&) { + return {}; + } + CoalesceWalkReads(reads.runs, ranges); + if (!reads.failed) copyRangeValues(ranges, reads.supplied, values); + reads.supplied.clear(); + const auto settle = rangesSettled(ranges, before.get(), generation); + if (settle == Settle::Settled) break; + if (settle != Settle::Stamped || attempt != 0u || !reads.collected) return {}; + } + + guardRanges(ranges); + auto words = recycledStageWords(); + auto result = MaterializeHeapInBackground(invocation, capture, *words, memory, shaderBase); + if (result == nullptr) result = MaterializeInBackground(invocation, capture, memory, shaderBase); + words->dataOrigin = NextHeapDataOrigin(); + const bool complete = !reads.failed && result != nullptr; + HeapStageMaterialized materialized; + if (complete) materialized.reads = {std::move(sharedRanges), std::move(sharedValues), capture, true}; + materialized.result = std::move(result); + materialized.words = std::move(words); + return materialized; +} + + +std::uint64_t NextHeapDataOrigin() { + static std::atomic next{0}; + return next.fetch_add(1, std::memory_order_relaxed) + 1u; +} + +std::uint64_t HeapStagesTaken() { + return heapStages().load(); +} + +std::uint64_t HeapRingHitsVerified() { + return verifyCounts().ring.load(); +} + +std::uint64_t HeapRingHitsDiffering() { + return verifyCounts().ringDiffer.load(); +} + +std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, + const ShaderRecompiler::HeapStageWords& words) { + auto result = std::make_shared(shared); + for (auto& binding : result->bindings) { + if (binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && !words.flattenedSrt.empty()) + binding.guestDescriptor = words.flattenedSrt; + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) + ShaderRecompiler::OverlayUserWords(binding.guestDescriptor, words.userData); + } + if (words.base != nullptr && !words.base->bindings.empty()) { + if (words.base->bindings.size() != result->bindings.size()) + throw std::runtime_error("a heap stage's ring template bindings differ in number from its program"); + for (std::size_t index = 0; index < words.base->bindings.size(); ++index) { + const auto role = result->bindings[index].role; + if (role == ShaderRecompiler::DescriptorRole::ShaderData || role == ShaderRecompiler::DescriptorRole::FlattenedSrt || words.base->bindings[index].empty()) continue; + if (words.base->bindings[index].size() != result->bindings[index].guestDescriptor.size()) + throw std::runtime_error("a heap stage's ring template descriptor words differ in size from its program"); + result->bindings[index].guestDescriptor = words.base->bindings[index]; + } + } + if (!words.bindings.empty()) { + if (words.bindings.size() != result->bindings.size()) + throw std::runtime_error("a heap stage's per-draw bindings differ in number from its template"); + for (std::size_t index = 0; index < words.bindings.size(); ++index) { + if (words.bindings[index].empty()) continue; + if (result->bindings[index].role != ShaderRecompiler::DescriptorRole::FlattenedSrt && + words.bindings[index].size() != result->bindings[index].guestDescriptor.size()) + throw std::runtime_error("a heap stage's per-draw descriptor words differ in size from its template"); + result->bindings[index].guestDescriptor = words.bindings[index]; + } + } + if (!words.vertexAttributes.empty()) result->vertexAttributes = words.vertexAttributes; + return result; +} + +void BuildRingWords(const DispatchVariant& variant, std::span user, const std::vector* refreshedData, ShaderRecompiler::HeapStageWords& words) { + for (const auto index : variant.compiled->heapUserWords) { + if (index >= user.size()) throw std::runtime_error("a ring vertex template reads a user word the draw does not have"); + words.userData.push_back(user[index]); + } + const auto& ringTemplate = *variant.ringTemplate; + words.vertexAttributes = ringTemplate.vertexAttributes; + words.flattenedSrt.clear(); + for (auto& descriptor : words.bindings) descriptor.clear(); + words.base = nullptr; + words.dataOrigin = ringTemplate.dataOrigin; + if (!ringTemplate.flattenedSrt.empty()) { + words.flattenedSrt = ringTemplate.flattenedSrt; + if (refreshedData != nullptr) { + for (std::size_t k = 0; k < variant.dataPositions.size(); ++k) { + if (variant.dataSlots[k] < words.flattenedSrt.size()) words.flattenedSrt[variant.dataSlots[k]] = (*refreshedData)[variant.dataPositions[k]]; + } + } + } + if (!ringTemplate.bindings.empty()) { + const auto& program = variant.compiled->bindings; + if (ringTemplate.bindings.size() != program.size()) throw std::runtime_error("a ring vertex hit's bindings differ in number from its template"); + words.base = variant.ringTemplate; + words.bindings.resize(program.size()); + for (std::size_t index = 0; index < program.size(); ++index) { + const auto& shared = ringTemplate.bindings[index]; + if (program[index].role != ShaderRecompiler::DescriptorRole::ShaderData || shared.empty()) continue; + auto& descriptor = words.bindings[index]; + descriptor.assign(shared.begin(), shared.end()); + ShaderRecompiler::OverlayUserWords(descriptor, words.userData); + if (descriptor == program[index].guestDescriptor) descriptor.clear(); + } + } else { + words.bindings.clear(); + } + ShaderRecompiler::CompleteHeapDataWords(*variant.compiled, words); + if (variant.ringDescriptorPatches.empty() && variant.ringDataPatches.empty()) return; + const auto& program = variant.compiled->bindings; + if (words.bindings.empty()) words.bindings.resize(program.size()); + const auto own = [&](std::size_t index) -> std::vector& { + auto& descriptor = words.bindings[index]; + if (descriptor.empty()) { + const auto& source = Graphics::DrawGuestWords(*variant.compiled, &words, program[index]); + descriptor.assign(source.begin(), source.end()); + } + return descriptor; + }; + for (const auto& [binding, word, value] : variant.ringDescriptorPatches) { + if (binding >= program.size() || word >= program[binding].guestDescriptor.size()) continue; + if (program[binding].role == ShaderRecompiler::DescriptorRole::ShaderData && word >= words.userData.size()) words.dataOrigin = 0; + auto& descriptor = own(binding); + if (word < descriptor.size()) descriptor[word] = value; + } + for (const auto& [slot, value] : variant.ringDataPatches) { + if (slot >= words.userData.size()) words.dataOrigin = 0; + for (std::size_t index = 0; index < program.size(); ++index) { + if (program[index].role != ShaderRecompiler::DescriptorRole::ShaderData || slot >= program[index].guestDescriptor.size()) continue; + auto& descriptor = own(index); + if (slot < descriptor.size()) descriptor[slot] = value; + } + } +} + +void NoteHeapDirect() { + heapStages().fetch_add(1, std::memory_order_relaxed); +} + +void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, + const ShaderRecompiler::ResourceCapture* expectedCapture) { + auto& counts = verifyCounts(); + if (expectedCapture != nullptr) { + const auto partial = [](const std::vector& values) { + return std::ranges::any_of(values, [](const ShaderRecompiler::DescriptorValue& value) { + return value.availableDwordMask != static_cast((1u << value.dwordCount) - 1u); + }); + }; + const auto& snapshot = expectedCapture->snapshot; + if (partial(snapshot.buffers) || partial(snapshot.images) || partial(snapshot.samplers)) { + counts.notComparable.fetch_add(1, std::memory_order_relaxed); + return; + } + } + counts.verified.fetch_add(1, std::memory_order_relaxed); + std::size_t index = 0; + if (const auto* what = resultDifference(direct, expected, index)) { + counts.differ.fetch_add(1, std::memory_order_relaxed); + reportHeapMismatch("heap stage vs full capture", what, expected, index); + throw std::runtime_error(std::string("APS5_VERIFY_GPU_HEAP: a heap stage differs from its full capture in its ") + what); + } +} + +void VerifyHeapAccessor(const Graphics::CompiledShader& stage) { + if (stage.heap == nullptr || stage.program == nullptr) return; + const auto patched = PatchedHeapResult(*stage.program, *stage.heap); + auto& counts = verifyCounts(); + counts.accessor.fetch_add(1, std::memory_order_relaxed); + for (std::size_t index = 0; index < stage.program->bindings.size(); ++index) { + if (Graphics::DrawGuestWords(stage, stage.program->bindings[index]) == patched->bindings[index].guestDescriptor) continue; + counts.accessorDiffer.fetch_add(1, std::memory_order_relaxed); + reportHeapMismatch("accessor vs patched result", "binding words", *patched, index); + throw std::runtime_error("APS5_VERIFY_GPU_HEAP: a heap stage's binding words differ from its patched result"); + } + const auto& attributes = Graphics::DrawVertexAttributes(stage); + bool sameAttributes = attributes.size() == patched->vertexAttributes.size(); + for (std::size_t index = 0; sameAttributes && index < attributes.size(); ++index) + sameAttributes = attributes[index].resource.fields == patched->vertexAttributes[index].resource.fields && + attributes[index].fetchIndex == patched->vertexAttributes[index].fetchIndex; + if (!sameAttributes) { + counts.accessorDiffer.fetch_add(1, std::memory_order_relaxed); + reportHeapMismatch("accessor vs patched result", "vertex attributes", *patched, 0); + throw std::runtime_error("APS5_VERIFY_GPU_HEAP: a heap stage's vertex attributes differ from its patched result"); + } +} + +void VerifyRingWords(const ShaderRecompiler::RecompileResult& kept, const ShaderRecompiler::HeapStageWords& ring, + const ShaderRecompiler::RecompileResult& fresh, const ShaderRecompiler::HeapStageWords* freshWords) { + const auto reused = PatchedHeapResult(kept, ring); + const auto expected = + freshWords != nullptr ? PatchedHeapResult(fresh, *freshWords) : std::make_shared(fresh); + auto& counts = verifyCounts(); + counts.ring.fetch_add(1, std::memory_order_relaxed); + std::size_t index = 0; + if (const auto* what = resultDifference(*reused, *expected, index)) { + counts.ringDiffer.fetch_add(1, std::memory_order_relaxed); + reportHeapMismatch("ring hit vs fresh build", what, *expected, index); + throw std::runtime_error(std::string("a ring hit's rebuilt words differ from a fresh build in its ") + what); + } +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp index 834a673aacf1..e5760367f819 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp @@ -22,7 +22,7 @@ void Driver::FoldDrawOffsets(const ShaderRecompiler::RecompileResult& result, co if (result.instanceOffsetSgpr >= 0) parameters.firstInstance = drawUserWord(program, result.instanceOffsetSgpr); } -std::optional Driver::ClassifyIndirectDraw(const ShaderRecompiler::RecompileResult& result, const Graphics::State& graphics, const DrawProgram& frontProgram, const std::shared_ptr& localDevice, Pm4::DrawParameters& drawParameters, bool traceIndirect) { +std::optional Driver::ClassifyIndirectDraw(const ShaderRecompiler::RecompileResult& result, const Graphics::State& graphics, const DrawProgram& frontProgram, const std::shared_ptr& localDevice, Pm4::DrawParameters& drawParameters, bool traceIndirect, const ShaderRecompiler::HeapStageWords* heap) { std::optional indirectCpu; auto& indirect = *drawParameters.indirect; using Rule = Pm4::DrawParameters::IndirectDraw::Rule; @@ -66,7 +66,7 @@ std::optional Driver::ClassifyIndirectDraw(const Sha if ((indirect.vertexRule == Rule::Constant || indirect.instanceRule == Rule::Constant) && indirect.count > 1024) fail(Path::FeatureGap); static const std::uint64_t vertexCap = [] { const char* text = std::getenv("APS5_INDIRECT_VERTEX_MIB"); return (text ? std::strtoull(text, nullptr, 10) : 64ull) << 20u; }(); - for (const auto& attribute : result.vertexAttributes) { + for (const auto& attribute : heap != nullptr && !heap->vertexAttributes.empty() ? heap->vertexAttributes : result.vertexAttributes) { const auto stride = (attribute.resource.fields[1] >> 16u) & 0x3fffu; const auto extent = stride == 0 ? static_cast(attribute.resource.fields[2]) : static_cast(attribute.resource.fields[2]) * stride; if (extent > vertexCap) fail(Path::VertexRange); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp index e682efaff18b..a51a8101f41b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" @@ -17,13 +18,15 @@ namespace AgcDriver::DriverDetail { namespace { template -void visitWrittenBuffers(const ShaderRecompiler::RecompileResult& compiled, TVisit&& visit) { +void visitWrittenBuffers(const ShaderRecompiler::RecompileResult& compiled, TVisit&& visit, const ShaderRecompiler::HeapStageWords* heap = nullptr) { for (const auto& binding : compiled.bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; - for (std::uint32_t element = 0; element < binding.count; ++element) { + const auto& guestWords = Graphics::DrawGuestWords(compiled, heap, binding); + const auto elements = std::min(binding.count, guestWords.size() / 4); + for (std::uint32_t element = 0; element < elements; ++element) { const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; - if (!written || binding.guestDescriptor.size() < (static_cast(element) + 1) * 4) continue; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 4, 4); + if (!written) continue; + const auto words = std::span(guestWords).subspan(static_cast(element) * 4, 4); const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; const auto base = descriptor.Base48(); const auto size = descriptor.GetSize(); @@ -86,7 +89,7 @@ void Driver::noteForeignWriter(std::uint64_t begin, std::uint64_t end, std::uint void Driver::noteDrawWriters(std::span stages, std::uint32_t queue) { for (const auto& stage : stages) { - forEachWrittenBuffer(*stage.program, [&](std::uint32_t, std::uint64_t begin, std::uint64_t end, bool) { noteForeignWriter(begin, end, queue); }); + visitWrittenBuffers(*stage.program, [&](std::uint32_t, std::uint64_t begin, std::uint64_t end, bool) { noteForeignWriter(begin, end, queue); }, stage.heap); } } @@ -104,13 +107,14 @@ std::vector> DrawWriteRanges(const Graph }; for (const auto& stage : stages) { if (stage.program == nullptr) continue; - visitWrittenBuffers(*stage.program, [&](std::uint32_t, std::uint64_t begin, std::uint64_t end, bool) { ranges.emplace_back(begin, end); }); + visitWrittenBuffers(*stage.program, [&](std::uint32_t, std::uint64_t begin, std::uint64_t end, bool) { ranges.emplace_back(begin, end); }, stage.heap); for (const auto& binding : stage.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages || binding.kind != ShaderRecompiler::DescriptorKind::StorageImage) continue; for (std::uint32_t element = 0; element < binding.count; ++element) { const bool written = element >= binding.imageWritten.size() || binding.imageWritten[element]; - if (!written || binding.guestDescriptor.size() < (static_cast(element) + 1) * 8) continue; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8, 8); + const auto& guestWords = Graphics::DrawGuestWords(stage, binding); + if (!written || guestWords.size() < (static_cast(element) + 1) * 8) continue; + const auto words = std::span(guestWords).subspan(static_cast(element) * 8, 8); if (Graphics::IsNullTextureResource(words)) continue; const auto resource = Graphics::DecodeTextureResource(words); if (resource.baseAddress == 0) continue; @@ -173,16 +177,18 @@ std::vector> QueuedDrawReadRanges(const for (const auto& stage : stages) { if (stage.program == nullptr) continue; for (const auto& binding : stage.program->bindings) { - if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers || binding.guestDescriptor.size() < static_cast(binding.count) * 4u) continue; + if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; + const auto& guest = Graphics::DrawGuestWords(stage, binding); + if (guest.size() < static_cast(binding.count) * 4u) continue; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; + const auto* words = guest.data() + static_cast(element) * 4u; const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; add(descriptor.Base48(), descriptor.GetSize()); } } } if (stages.empty() || stages.front().program == nullptr) return ranges; - for (const auto& attribute : stages.front().program->vertexAttributes) { + for (const auto& attribute : Graphics::DrawVertexAttributes(stages.front())) { if (Graphics::NullVertexDescriptor(attribute)) continue; const auto address = attribute.resource.fields[0] | (static_cast(attribute.resource.fields[1] & 0xffffu) << 32u); std::uint64_t bytes = 0; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp index cef1899933f0..07eb9f8d2775 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp @@ -305,9 +305,12 @@ void Driver::execute(Submission& submission) { auto nextCursor = cursor + count; const bool predicated = Pm4::Predicated(header) && queue.predication.operation != 0; if (submission.queue == 0 && DrawFinisher::Busy() && !keepsDrawFinisher(header, opcode)) { - const bool queuesLabel = pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor) && labelPacketQueues(packet, opcode); + const bool queueable = pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor); + const bool queuesLabel = queueable && labelPacketQueues(packet, opcode); const bool heldLabelWait = pipelined && !predicated && orderedWaits && (opcode == 0x3c || opcode == 0x93) && header != RenderingWaitPacketHeader && waitTakesPendingLabel(packet); - const bool beside = DrawFinisher::Overlap() && opcode != 0x15 && (queuesLabel || heldLabelWait || keepsDrawPipeline(packet, header, opcode)); + const bool queuesSampleDump = queueable && sampleDumpQueues(packet, opcode, submission.queue); + const bool queuesDispatch = opcode == 0x15 && pipelined && pipelineDispatch() && !predicated; + const bool beside = DrawFinisher::Overlap() && (queuesDispatch || (opcode != 0x15 && (queuesLabel || heldLabelWait || queuesSampleDump || keepsDrawPipeline(packet, header, opcode)))); if (!beside) DrawFinisher::Get().Drain(); if (DrawFinisher::Overlap()) { DrawFinisher::NoteDrain(DrawFinisher::DrainSite::Packet, !beside); 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 30c8c52adadc..4086c85b2277 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp @@ -340,25 +340,37 @@ void Driver::dumpSampleCounters(std::uint64_t address) { } } -bool Driver::enqueueSampleDumpPacket(std::span packet, std::uint32_t opcode, std::uint32_t queue) { +bool Driver::sampleDumpQueues(std::span packet, std::uint32_t opcode, std::uint32_t queue) { static const bool ordered = std::getenv("APS5_PIPELINE_DRAIN_SAMPLE_DUMPS") == nullptr; if (!ordered || opcode != 0x46 || queue != 0 || packet.size() < 4 || !Pm4::SampleDump(packet) || !DrawPipeline::Active() || !deferredLabels().labels.empty()) return false; const auto address = Pm4::SampleDumpAddress(packet); - if (address == 0 || !GuestMemory::Accessible(reinterpret_cast(address), Pm4::SampleDumpBytes, true)) return false; - DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::SampleDump, [this, queue, address] { - GuestMemory::SetCurrentPacket(0x46, queue); - bool wrote = false; - { - GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Label); - std::lock_guard gpuLock(GuestMemory::GpuMutex()); - if (const auto localDevice = device.Load()) { - recordDeferredLabels(localDevice.get(), queue); - wrote = localDevice->DumpSamplesOnGpu(address); - if (!wrote) localDevice->WaitIdle(); + return address != 0 && GuestMemory::Accessible(reinterpret_cast(address), Pm4::SampleDumpBytes, true); +} + +bool Driver::enqueueSampleDumpPacket(std::span packet, std::uint32_t opcode, std::uint32_t queue) { + if (!sampleDumpQueues(packet, opcode, queue)) return false; + const auto address = Pm4::SampleDumpAddress(packet); + auto enqueue = [this, queue, address] { + DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::SampleDump, [this, queue, address] { + GuestMemory::SetCurrentPacket(0x46, queue); + bool wrote = false; + { + GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Label); + std::lock_guard gpuLock(GuestMemory::GpuMutex()); + if (const auto localDevice = device.Load()) { + recordDeferredLabels(localDevice.get(), queue); + wrote = localDevice->DumpSamplesOnGpu(address); + if (!wrote) localDevice->WaitIdle(); + } } - } - if (!wrote) dumpSampleCounters(address); - }, {{address, address + Pm4::SampleDumpBytes}}); + if (!wrote) dumpSampleCounters(address); + }, {{address, address + Pm4::SampleDumpBytes}}); + }; + if (DrawFinisher::Overlap() && DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread()) { + DrawFinisher::Get().EnqueueBeside(std::move(enqueue), {{address, address + Pm4::SampleDumpBytes}}); + } else { + enqueue(); + } ++sampleDumpsQueued; Graphics::Recorder::CountRecordedWork(); return true; @@ -524,12 +536,7 @@ bool Driver::enqueueLabelPacket(std::span packet, std::uint }, std::move(writes), address, std::move(stored)); }; if (queue == 0 && DrawFinisher::Overlap() && DrawFinisher::Busy()) { - DrawFinisher::Pending held; - held.unknown = false; - held.writes = std::move(writes); - held.labelAddress = address; - held.labelBytes = std::move(labelBytes); - DrawFinisher::Get().Enqueue(std::move(enqueue), std::move(held)); + DrawFinisher::Get().EnqueueBeside(std::move(enqueue), std::move(writes), address, std::move(labelBytes)); return true; } enqueue(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp index 91d3c56328e1..3a356c57ef47 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp @@ -7,6 +7,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libc/include/HostThreadLocal.hpp" @@ -1390,7 +1391,7 @@ ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& s if (entry.codeOffset != codeOffset) continue; invocationRequest.shader.code = ShaderRecompiler::GetPreparedCode(*entry.handle); if (!linked.code.empty() && !std::ranges::equal(invocationRequest.shader.code, linked.code)) continue; - if (auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(invocationRequest, entry.handle, key)) { + if (auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(std::move(invocationRequest), entry.handle, key)) { NoteMatchedEntry(entry, preparedAtUse); return std::move(*invocation); } @@ -1400,11 +1401,12 @@ ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& s std::shared_ptr handle = deferPreparation ? PrepareInBackground(snapshot, codeOffset, source, key) : PrepareShaderWithDiagnostics(source); invocationRequest = source; invocationRequest.shader.code = ShaderRecompiler::GetPreparedCode(*handle); - auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(invocationRequest, handle, key); + auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(std::move(invocationRequest), handle, key); if (!invocation.has_value() && deferPreparation) { handle = PrepareShaderWithDiagnostics(source); + invocationRequest = source; invocationRequest.shader.code = ShaderRecompiler::GetPreparedCode(*handle); - invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(invocationRequest, handle, key); + invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(std::move(invocationRequest), handle, key); } if (!invocation.has_value()) throw std::runtime_error("AGC driver: an artifact prepared at use does not match its invocation"); snapshot.prepared->entries.push_back({codeOffset, std::move(handle)}); @@ -1657,6 +1659,7 @@ bool LibraryPrebuildDisabled() { void PrebuildStageLibrary(const std::shared_ptr& device, const Graphics::ShaderStages& stages, ShaderRecompiler::ShaderStage stage, std::shared_ptr result, std::uint32_t pushOffset, std::uint64_t program) { if (LibraryPrebuildDisabled() || result == nullptr || (stage != ShaderRecompiler::ShaderStage::Vertex && stage != ShaderRecompiler::ShaderStage::Fragment)) return; + if (result->gpuResolvedImages && !HeapStageFits(*result)) return; SubmitLibraryPrebuild([device, stages, stage, result = std::move(result), pushOffset] { const std::array shaders{{{stage, result.get(), pushOffset}}}; try { @@ -1676,13 +1679,35 @@ std::vector PrepareRegistered(RegisteredPreparation& pla entries.push_back({plan.codeOffset, PrepareShaderWithDiagnostics(request, &preparation)}); }; append(); - if (plan.prebuildDevice != nullptr && request.target.registrationModules && request.shader.stage == ShaderRecompiler::ShaderStage::Fragment && !LibraryPrebuildDisabled()) { + const bool fragment = request.shader.stage == ShaderRecompiler::ShaderStage::Fragment; + const bool heapVertex = HeapPreRasterStage(request.shader.stage) && request.target.descriptorMemory; + const bool vertex = request.shader.stage == ShaderRecompiler::ShaderStage::Vertex; + const auto prebuild = [&](const ShaderRecompiler::RecompileRequest& stageRequest, const ShaderRecompiler::SourceHandle& handle) { + if (plan.prebuildDevice == nullptr || !stageRequest.target.registrationModules || !(fragment || (vertex && heapVertex && stageRequest.target.gpuResolvedImages)) || LibraryPrebuildDisabled()) return; try { - PrebuildStageLibrary(plan.prebuildDevice, {Graphics::ShaderPath::Vertex, 0u, 32u, request.context.waveSize, {}, {}}, request.shader.stage, ShaderRecompiler::RegistrationResult(request, *entries.front().handle), request.layout.pushConstantOffsetBytes, plan.program); + PrebuildStageLibrary(plan.prebuildDevice, {Graphics::ShaderPath::Vertex, 0u, 32u, stageRequest.context.waveSize, {}, {}}, stageRequest.shader.stage, ShaderRecompiler::RegistrationResult(stageRequest, handle), stageRequest.layout.pushConstantOffsetBytes, plan.program); } catch (const std::exception& error) { APS5_LOG_OUT("shader library prebuild skipped: %s", error.what()); } + }; + bool heapPrebuilt = false; + if ((fragment || heapVertex) && !HeapStageExcluded(request.shader.stage) && Graphics::DescriptorHeapEnabled()) { + const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, entries.front().handle); + if (invocation && HeapStageEligible(request.shader.stage, invocation->Plan().get())) { + auto heapRequest = request; + heapRequest.target.gpuResolvedImages = true; + PerformanceTimer timing("Shader.PrepareArtifact"); + try { + auto heapHandle = PrepareShaderWithDiagnostics(heapRequest, &preparation); + entries.push_back({plan.codeOffset, std::move(heapHandle)}); + prebuild(heapRequest, *entries.back().handle); + heapPrebuilt = request.target.descriptorMemory; + } catch (const std::exception& error) { + APS5_LOG_OUT("heap shader preparation skipped: %s", error.what()); + } + } } + if (!heapPrebuilt) prebuild(request, *entries.front().handle); if (request.context.compute) { request.context.compute->partialThreads = {1, 1, 1}; append(); @@ -2279,6 +2304,24 @@ std::optional RegistrationPreparationsPending() { std::vector PrepareGraphicsStages(const DrawDecode& decoded, const ShaderRecompiler::SpirvTarget& target, bool deferUnprepared) { ShaderPreparationTransaction transaction; + const auto preparedHandle = [&](const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request) { + std::vector key; + ShaderRecompiler::BuildPreparedShaderKey(request, key); + for (const auto& entry : transaction.Read(snapshot).entries) { + if (entry.codeOffset == codeOffset && ShaderRecompiler::MatchesPreparedShader(request, *entry.handle, key)) return entry.handle; + } + PerformanceTimer timing("Shader.PrepareArtifact"); + return PrepareShaderWithDiagnostics(request); + }; + const auto registrationFor = [&](const ShaderRecompiler::RecompileRequest& request, const ShaderRecompiler::SourceHandle& handle) -> std::shared_ptr { + if (!target.registrationModules || LibraryPrebuildDisabled()) return nullptr; + try { + return ShaderRecompiler::RegistrationResult(request, handle); + } catch (const std::exception& error) { + APS5_LOG_OUT("shader library prebuild skipped: %s", error.what()); + return nullptr; + } + }; require(decoded.programs.size() == decoded.roles.size(), "graphics ABI program roles are incomplete"); for (const auto& program : decoded.programs) require(program.snapshot != nullptr, "graphics ABI has no registered shader snapshot"); std::vector expected; @@ -2303,6 +2346,7 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod linked.push_back({decoded.roles[index], program.binary, program.userDataBase, program.firstUserSgpr, program.userData}); } std::vector prepared; + std::vector> requests; std::uint32_t pushOffset = 0; const bool fixedSlots = target.fixedPushSlots; const bool hasFragment = !decoded.roles.empty() && decoded.roles.back() == ShaderRecompiler::ProgramRole::Fragment; @@ -2317,6 +2361,7 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod const auto room = Graphics::StagePushBudget(Graphics::StagePushLimit(decoded.state.stages, pushOffset, decoded.state.depthRemap.mode != 0u), pushOffset, program.binary.stage, fixedSlots, hasFragment); if (deferUnprepared && DeferFailedRegistration(*program.snapshot)) { prepared.push_back({program.snapshot, {program.codeOffset, nullptr}, program.binary.stage, offset, nullptr}); + requests.emplace_back(); continue; } std::optional vertex; @@ -2326,6 +2371,7 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod if (!deferUnprepared) throw; DeferPipelineStage(transaction.Edit(*program.snapshot), *program.snapshot, error.what()); prepared.push_back({program.snapshot, {program.codeOffset, nullptr}, program.binary.stage, offset, nullptr}); + requests.emplace_back(); continue; } if (vertex) { @@ -2337,35 +2383,49 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod std::vector key; ShaderRecompiler::BuildPreparedShaderKey(request, key); std::shared_ptr handle; - for (const auto& entry : transaction.Read(*program.snapshot).entries) { - if (entry.codeOffset == program.codeOffset && ShaderRecompiler::MatchesPreparedShader(request, *entry.handle, key)) { - handle = entry.handle; - break; - } - } - if (handle == nullptr) { - PerformanceTimer timing("Shader.PrepareArtifact"); - try { - handle = PrepareShaderWithDiagnostics(request); - } catch (const std::exception& error) { - if (!deferUnprepared) throw; - DeferPipelineStage(transaction.Edit(*program.snapshot), *program.snapshot, error.what()); - prepared.push_back({program.snapshot, {program.codeOffset, nullptr}, program.binary.stage, offset, nullptr}); - continue; - } + try { + handle = preparedHandle(*program.snapshot, program.codeOffset, request); + } catch (const std::exception& error) { + if (!deferUnprepared) throw; + DeferPipelineStage(transaction.Edit(*program.snapshot), *program.snapshot, error.what()); + prepared.push_back({program.snapshot, {program.codeOffset, nullptr}, program.binary.stage, offset, nullptr}); + requests.emplace_back(); + continue; } const auto bytes = handle->artifact->bindings.pushConstantSizeBytes; require(bytes <= room, "prepared graphics stages exceed the push constant block"); - std::shared_ptr registration; - if (target.registrationModules && !LibraryPrebuildDisabled()) { + prepared.push_back({program.snapshot, {program.codeOffset, handle}, program.binary.stage, offset, registrationFor(request, *handle)}); + requests.push_back(std::move(request)); + pushOffset += bytes; + } + if (Graphics::DescriptorHeapEnabled()) { + std::vector heap; + const auto addHeap = [&](std::size_t index, bool heapVertex) { + const auto& stage = prepared[index]; + if (stage.entry.handle == nullptr || !requests[index] || HeapStageExcluded(stage.stage)) return false; + const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(*requests[index], stage.entry.handle); + if (!invocation || !HeapStageEligible(stage.stage, invocation->Plan().get()) || (HeapPreRasterStage(stage.stage) && !heapVertex)) return false; + auto request = *requests[index]; + request.target.gpuResolvedImages = true; + std::shared_ptr handle; try { - registration = ShaderRecompiler::RegistrationResult(request, *handle); + handle = preparedHandle(*stage.snapshot, stage.entry.codeOffset, request); } catch (const std::exception& error) { - APS5_LOG_OUT("shader library prebuild skipped: %s", error.what()); + if (!deferUnprepared) throw; + APS5_LOG_OUT("heap graphics stage preparation skipped: %s", error.what()); + return false; } + heap.push_back({stage.snapshot, {stage.entry.codeOffset, handle}, stage.stage, stage.pushOffset, registrationFor(request, *handle), true}); + return true; + }; + bool fragmentOnHeap = true; + for (std::size_t index = 0; index < prepared.size(); ++index) { + if (prepared[index].stage == ShaderRecompiler::ShaderStage::Fragment) fragmentOnHeap = addHeap(index, false); } - prepared.push_back({program.snapshot, {program.codeOffset, handle}, program.binary.stage, offset, std::move(registration)}); - pushOffset += bytes; + for (std::size_t index = 0; index < prepared.size(); ++index) { + if (HeapPreRasterStage(prepared[index].stage)) static_cast(addHeap(index, target.descriptorMemory && fragmentOnHeap)); + } + prepared.insert(prepared.begin(), std::make_move_iterator(heap.begin()), std::make_move_iterator(heap.end())); } transaction.Commit(); return prepared; @@ -2469,11 +2529,13 @@ void Driver::ResolveGraphicsStagesAbi(std::span stages, std if (!duplicate) transaction.Edit(*stage.snapshot).entries.push_back(std::move(stage.entry)); } for (const auto& stage : prepared) { - if (stage.snapshot->type == 1) continue; + if (stage.snapshot->type == 1 || stage.heapVariant) continue; ResolvePreparedGraphics(*stage.snapshot, {}, primitiveType == state.userConfig.end() ? 0u : primitiveType->second, localDevice->Target(), true); } PreparedShaderState::GraphicsAbi abi{key, registry, {}}; - for (const auto& stage : prepared) abi.stages.push_back(stage.snapshot); + for (const auto& stage : prepared) { + if (!stage.heapVariant) abi.stages.push_back(stage.snapshot); + } auto& graphicsAbis = transaction.Edit(*owner).graphicsAbis; std::erase_if(graphicsAbis, [](const auto& entry) { return entry.registry.expired(); }); graphicsAbis.push_back(std::move(abi)); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp index 548eda8c3199..a4e38925307c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp @@ -2879,6 +2879,10 @@ std::uint64_t TrackerGeneration() { return tracker.generation; } +std::uint64_t StableTrackerGeneration() { + return Tracker().stable.load(std::memory_order_acquire); +} + void AdvanceTrackerGenerationForTest(std::uint64_t generation) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); @@ -2892,6 +2896,14 @@ std::uint64_t NewestStamp(std::uint64_t address, std::size_t bytes) { return bytes == 0 ? 0 : tracker.newestStamp(address, address + bytes); } +bool NoStampAfter(std::span> ranges, std::uint64_t generation) { + if (ranges.empty()) return true; + auto& tracker = Tracker(); + const auto lock = lockTracker(tracker); + tracker.initialize(); + return std::none_of(ranges.begin(), ranges.end(), [&](const auto& range) { return range.second > range.first && tracker.newestStamp(range.first, range.second) > generation; }); +} + #ifdef _WIN32 namespace { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceOverlay.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceOverlay.cpp index c3ba758f6070..2129699536d5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceOverlay.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceOverlay.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceOverlay.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" @@ -1191,7 +1192,7 @@ OverlayRect PerformanceOverlay::RecordRects(VkCommandBuffer commands, std::size_ state.SetViewport(context, {0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f}); state.SetScissor(context, area); const OverlayParameters parameters{OverlayPalette(format, colorSpace), {static_cast(extent.width), static_cast(extent.height)}}; - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), ¶meters); + Graphics::CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), ¶meters); const VkBuffer buffer = slot.rects->Handle(); const VkDeviceSize offset = 0; context.Function("vkCmdBindVertexBuffers")(commands, 0, 1, &buffer, &offset); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index da7eedc7fa2a..b6a6d80bfadd 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" #include "prx/libSceAgcDriver/Execution/include/PresentationPass.hpp" #include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp" @@ -9,8 +10,11 @@ #include "prx/libSceAgcDriver/Graphics/shaders/PresentationPassVert_spv.h" #include #include +#include #include +#include #include +#include namespace AgcDriver { namespace { @@ -20,13 +24,24 @@ constexpr std::uint32_t ModeRedLow = 2; constexpr std::uint32_t ModeKeepTenBit = 4; constexpr std::uint32_t ModeSubsample = 8; constexpr std::uint32_t ModePq = 16; +constexpr std::uint32_t PresentHeapKind = ShaderRecompiler::RuntimeAbi::FirstImageBinding + 9u; + +struct HeapPush { + std::int32_t parameters[9]; + std::uint32_t pad; + std::uint64_t pqNits; + std::uint32_t slot; + std::uint32_t pad2; +}; + +static_assert(offsetof(HeapPush, pqNits) == 40 && offsetof(HeapPush, slot) == 48); } PresentationPass::PresentationPass(const Graphics::Context& context, std::size_t slotCount) : context(context), slots(slotCount) { Graphics::Require(slotCount != 0, "presentation pass needs at least one slot"); try { - VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + heap = Graphics::DescriptorHeapEnabled() && Graphics::BindlessHeap::For(context).DescriptorHeapMode(); samplerInfo.magFilter = VK_FILTER_NEAREST; samplerInfo.minFilter = VK_FILTER_NEAREST; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; @@ -60,7 +75,7 @@ PresentationPass::PresentationPass(const Graphics::Context& context, std::size_t Graphics::Check(context.Function("vkAllocateDescriptorSets")(context.device, &allocation, &slot.set), "vkAllocateDescriptorSets presentation pass"); } const auto& luminance = PqEotfNits(); - pqNits = std::make_unique(context, sizeof(luminance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + pqNits = std::make_unique(context, sizeof(luminance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (heap ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u)); std::memcpy(pqNits->Bytes().data(), luminance.data(), sizeof(luminance)); const VkDescriptorBufferInfo tableInfo{pqNits->Handle(), 0, sizeof(luminance)}; std::vector tableWrites(slots.size(), VkWriteDescriptorSet{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}); @@ -92,6 +107,7 @@ void PresentationPass::release() noexcept { } for (const auto& [key, entry] : targets) { if (entry.pipeline) context.Function("vkDestroyPipeline")(context.device, entry.pipeline, nullptr); + if (entry.heapPipeline) context.Function("vkDestroyPipeline")(context.device, entry.heapPipeline, nullptr); if (entry.renderPass) context.Function("vkDestroyRenderPass")(context.device, entry.renderPass, nullptr); } targets.clear(); @@ -138,6 +154,7 @@ void PresentationPass::Release(std::size_t index) noexcept { if (view) context.Function("vkDestroyImageView")(context.device, view, nullptr); } slot.transient.clear(); + if (slot.source && heap) slot.ReleaseHeapSlots(context); if (slot.source) context.Function("vkDestroyImageView")(context.device, slot.source, nullptr); slot.source = VK_NULL_HANDLE; } @@ -258,7 +275,14 @@ const PresentationPass::Target& PresentationPass::target(VkFormat format, VkImag pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = created.renderPass; Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.pipeline), "vkCreateGraphicsPipelines presentation pass"); + if (heap) { + const std::array mappings{ + Graphics::HeapPushSampledImageMapping(Graphics::BindlessHeap::For(context), 0, 0, offsetof(HeapPush, slot), samplerInfo), + Graphics::HeapPushAddressMapping(0, 1, offsetof(HeapPush, pqNits))}; + created.heapPipeline = Graphics::CreateHeapStagePipeline(context, pipelineInfo, 1, mappings, "vkCreateGraphicsPipelines presentation pass heap"); + } } catch (...) { + if (created.pipeline) context.Function("vkDestroyPipeline")(context.device, created.pipeline, nullptr); if (created.renderPass) context.Function("vkDestroyRenderPass")(context.device, created.renderPass, nullptr); throw; } @@ -355,19 +379,26 @@ void PresentationPass::BindTexels(std::size_t index, VkCommandBuffer commands, s Bind(index, slot.uploadImage, width, height, pixelFormat, whiteNits); } -void PresentationPass::draw(VkCommandBuffer commands, const Slot& slot, const Target& entry, VkFramebuffer framebuffer, VkExtent2D extent, VkRect2D scissor, const std::int32_t (¶meters)[9]) const { +void PresentationPass::draw(VkCommandBuffer commands, Slot& slot, const Target& entry, VkFramebuffer framebuffer, VkExtent2D extent, VkRect2D scissor, const std::int32_t (¶meters)[9]) const { VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; begin.renderPass = entry.renderPass; begin.framebuffer = framebuffer; begin.renderArea = {{0, 0}, extent}; context.Function("vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE); + const auto heapSlot = entry.heapPipeline != VK_NULL_HANDLE ? Graphics::BindlessHeap::For(context).ViewSlot(PresentHeapKind, &slot, slot.source) : std::nullopt; Graphics::CommandState state; state.Begin(commands, false); - state.BindPipeline(context, entry.pipeline, 0); + state.BindPipeline(context, heapSlot ? entry.heapPipeline : entry.pipeline, 0); state.SetViewport(context, {0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f}); state.SetScissor(context, scissor); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set, 0, nullptr); - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters); + if (heapSlot) { + HeapPush pushed{{}, 0u, pqNits->DeviceAddress(), *heapSlot, 0u}; + std::copy(std::begin(parameters), std::end(parameters), pushed.parameters); + Graphics::CmdPushHeapData(context, commands, sizeof(pushed), &pushed); + } else { + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set, Graphics::SetBindSite::Presentation); + Graphics::CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters); + } context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); context.Function("vkCmdEndRenderPass")(commands); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp index ac2f0e4eee2e..fada79f48e68 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp @@ -1,6 +1,7 @@ #include "prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp" #include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp" #include "prx/libSceAgcDriver/Execution/include/PresentationPass.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/FsrEasuFrag_spv.h" @@ -8,6 +9,8 @@ #include "prx/libSceAgcDriver/Graphics/shaders/PresentationPassVert_spv.h" #include #include +#include +#include namespace AgcDriver { namespace { @@ -30,13 +33,20 @@ struct RcasParameters { constexpr std::uint32_t ParameterBytes = sizeof(RcasParameters); static_assert(sizeof(EasuParameters) <= ParameterBytes); +struct HeapPush { + std::uint8_t parameters[ParameterBytes]; + std::uint32_t slot; +}; + +static_assert(offsetof(HeapPush, slot) == 20 && sizeof(HeapPush) == 24); + } PresentationUpscaler::PresentationUpscaler(const Graphics::Context& context, std::size_t slotCount, float sharpness) : context(context), sharpness(sharpness), slots(slotCount) { Graphics::Require(slotCount != 0, "presentation upscaler needs at least one slot"); Graphics::Require(std::isfinite(sharpness) && sharpness >= 0.0f && sharpness <= 2.0f, "FSR sharpness must be from 0.0 to 2.0 stops"); try { - VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + heap = Graphics::DescriptorHeapEnabled() && Graphics::BindlessHeap::For(context).DescriptorHeapMode(); samplerInfo.magFilter = VK_FILTER_NEAREST; samplerInfo.minFilter = VK_FILTER_NEAREST; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; @@ -90,10 +100,11 @@ PresentationUpscaler::~PresentationUpscaler() { void PresentationUpscaler::release() noexcept { for (std::size_t i = 0; i < slots.size(); ++i) { Release(i); - releaseSurface(slots[i].stage); - releaseSurface(slots[i].upscaled); + releaseSurface(slots[i], slots[i].stage); + releaseSurface(slots[i], slots[i].upscaled); } for (const auto& [key, entry] : targets) { + if (entry.heapPipeline) context.Function("vkDestroyPipeline")(context.device, entry.heapPipeline, nullptr); if (entry.pipeline) context.Function("vkDestroyPipeline")(context.device, entry.pipeline, nullptr); if (entry.renderPass) context.Function("vkDestroyRenderPass")(context.device, entry.renderPass, nullptr); } @@ -132,16 +143,17 @@ void PresentationUpscaler::Release(std::size_t index) noexcept { slots[index].transient.clear(); } -void PresentationUpscaler::releaseSurface(Surface& surface) noexcept { +void PresentationUpscaler::releaseSurface(Slot& slot, Surface& surface) noexcept { + if (surface.sampled && heap) slot.ReleaseHeapSlots(context); if (surface.sampled) context.Function("vkDestroyImageView")(context.device, surface.sampled, nullptr); if (surface.image) context.Function("vkDestroyImage")(context.device, surface.image, nullptr); if (surface.memory) context.Function("vkFreeMemory")(context.device, surface.memory, nullptr); surface = Surface{}; } -void PresentationUpscaler::ensureSurface(Surface& surface, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage) { +void PresentationUpscaler::ensureSurface(Slot& slot, Surface& surface, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage) { if (surface.image != VK_NULL_HANDLE && surface.format == format && surface.extent.width == extent.width && surface.extent.height == extent.height) return; - releaseSurface(surface); + releaseSurface(slot, surface); VkFormatProperties properties{}; context.formatProperties(context.physical, format, &properties); VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT; @@ -171,7 +183,7 @@ void PresentationUpscaler::ensureSurface(Surface& surface, VkFormat format, VkEx surface.format = format; surface.extent = extent; } catch (...) { - releaseSurface(surface); + releaseSurface(slot, surface); throw; } } @@ -195,7 +207,7 @@ VkImage PresentationUpscaler::Stage(std::size_t index, VkFormat format, VkExtent Graphics::Require(index < slots.size(), "presentation upscaler slot is out of range"); Graphics::Require(extent.width != 0 && extent.height != 0, "presentation upscaler stage extent must be non-zero"); auto& slot = slots[index]; - ensureSurface(slot.stage, format, extent, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); + ensureSurface(slot, slot.stage, format, extent, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); return slot.stage.image; } @@ -302,9 +314,16 @@ const PresentationUpscaler::Target& PresentationUpscaler::target(VkFormat format pipelineInfo.pDynamicState = &dynamic; pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = created.renderPass; - const auto lock = context.LockPipelineCacheForUse(); - Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.pipeline), "vkCreateGraphicsPipelines presentation upscaler"); + { + const auto lock = context.LockPipelineCacheForUse(); + Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.pipeline), "vkCreateGraphicsPipelines presentation upscaler"); + } + if (heap) { + const auto mapping = Graphics::HeapPushSampledImageMapping(Graphics::BindlessHeap::For(context), 0, 0, offsetof(HeapPush, slot), samplerInfo); + created.heapPipeline = Graphics::CreateHeapStagePipeline(context, pipelineInfo, 1, std::span(&mapping, 1), "vkCreateGraphicsPipelines presentation upscaler heap"); + } } catch (...) { + if (created.pipeline) context.Function("vkDestroyPipeline")(context.device, created.pipeline, nullptr); if (created.renderPass) context.Function("vkDestroyRenderPass")(context.device, created.renderPass, nullptr); throw; } @@ -339,23 +358,33 @@ void PresentationUpscaler::bindSource(VkDescriptorSet set, VkImageView view) con context.Function("vkUpdateDescriptorSets")(context.device, 1, &write, 0, nullptr); } -void PresentationUpscaler::draw(VkCommandBuffer commands, const Target& entry, VkFramebuffer framebuffer, VkExtent2D extent, VkDescriptorSet set, const void* parameters, std::uint32_t size) const { +void PresentationUpscaler::draw(VkCommandBuffer commands, Slot& slot, const Target& entry, VkFramebuffer framebuffer, VkExtent2D extent, VkDescriptorSet set, VkImageView source, const void* parameters, std::uint32_t size) const { + Graphics::Require(size <= ParameterBytes, "presentation upscaler parameters exceed the push range"); VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; begin.renderPass = entry.renderPass; begin.framebuffer = framebuffer; begin.renderArea = {{0, 0}, extent}; context.Function("vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE); + const auto heapSlot = entry.heapPipeline != VK_NULL_HANDLE ? Graphics::BindlessHeap::For(context).ViewSlot(Graphics::HeapPassSampledKind, &slot, source, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) : std::nullopt; // Not tracked across passes: suppress = false makes the state emit every command, as before. Graphics::CommandState recording; recording.Begin(commands, false); const VkDynamicState dynamicStates[2] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - recording.BindPipeline(context, entry.pipeline, Graphics::CommandState::DynamicSlots(dynamicStates)); + recording.BindPipeline(context, heapSlot ? entry.heapPipeline : entry.pipeline, Graphics::CommandState::DynamicSlots(dynamicStates)); const VkViewport viewport{0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f}; const VkRect2D scissor{{0, 0}, extent}; recording.SetViewport(context, viewport); recording.SetScissor(context, scissor); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, 0, nullptr); - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, size, parameters); + if (heapSlot) { + HeapPush pushed{}; + std::memcpy(pushed.parameters, parameters, size); + pushed.slot = *heapSlot; + Graphics::CmdPushHeapData(context, commands, sizeof(pushed), &pushed); + } else { + bindSource(set, source); + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, Graphics::SetBindSite::Presentation); + Graphics::CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, size, parameters); + } context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); context.Function("vkCmdEndRenderPass")(commands); } @@ -366,9 +395,8 @@ void PresentationUpscaler::RecordUpscale(VkCommandBuffer commands, std::size_t i auto& slot = slots[index]; const auto& entry = target(slot.stage.format, finalLayout, Filter::Easu); const auto framebuffer = transientFramebuffer(slot, entry.renderPass, destination, slot.stage.format, extent, finalLayout); - bindSource(slot.easuSet, slot.stage.sampled); const EasuParameters parameters{static_cast(slot.stage.extent.width), static_cast(slot.stage.extent.height), static_cast(extent.width), static_cast(extent.height)}; - draw(commands, entry, framebuffer, extent, slot.easuSet, ¶meters, sizeof(parameters)); + draw(commands, slot, entry, framebuffer, extent, slot.easuSet, slot.stage.sampled, ¶meters, sizeof(parameters)); } void PresentationUpscaler::RecordPresent(VkCommandBuffer commands, std::size_t index, std::uint32_t width, std::uint32_t height, VkImage destination, VkExtent2D extent, VkImageLayout finalLayout) { @@ -381,15 +409,14 @@ void PresentationUpscaler::RecordPresent(VkCommandBuffer commands, std::size_t i VkImageView sharpened = slot.stage.sampled; if (Upscales(width, height, extent)) { const VkExtent2D upscaled{rect.width, rect.height}; - ensureSurface(slot.upscaled, slot.stage.format, upscaled, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); + ensureSurface(slot, slot.upscaled, slot.stage.format, upscaled, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); RecordUpscale(commands, index, slot.upscaled.image, upscaled, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); sharpened = slot.upscaled.sampled; } const auto& entry = target(slot.stage.format, finalLayout, Filter::Rcas); const auto framebuffer = transientFramebuffer(slot, entry.renderPass, destination, slot.stage.format, extent, finalLayout); - bindSource(slot.rcasSet, sharpened); const RcasParameters parameters{rect.x, rect.y, static_cast(rect.width), static_cast(rect.height), sharpness}; - draw(commands, entry, framebuffer, extent, slot.rcasSet, ¶meters, sizeof(parameters)); + draw(commands, slot, entry, framebuffer, extent, slot.rcasSet, sharpened, ¶meters, sizeof(parameters)); } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index c5a332eba2e3..96c2913d7a40 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libc/include/HostThread.hpp" +#include "HeapCacheSwitch.hpp" #include "prx/libSceAgcDriver/Execution/include/FrameDumpIo.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" @@ -16,6 +17,7 @@ #include "prx/libSceAgcDriver/Execution/include/Float16ConversionProbe.hpp" #include "prx/libSceAgcDriver/Execution/include/Float16NanProbe.hpp" #include "prx/libSceAgcDriver/Execution/include/FloatFlushProbe.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" @@ -230,6 +232,45 @@ APS5_RUN_REPORT_COMPONENT("libSceAgcDriver") namespace { +std::optional ActiveValidationLayerVersion(PFN_vkGetInstanceProcAddr instanceProc) { + const auto requested = [](const char* variable) { + const char* value = std::getenv(variable); + return value != nullptr && (std::strstr(value, "validation") != nullptr || std::strchr(value, '*') != nullptr); + }; + if (!requested("VK_INSTANCE_LAYERS") && !requested("VK_LOADER_LAYERS_ENABLE")) return std::nullopt; + const auto enumerate = reinterpret_cast(instanceProc(VK_NULL_HANDLE, "vkEnumerateInstanceLayerProperties")); + if (enumerate == nullptr) return std::nullopt; + std::uint32_t count = 0; + if (enumerate(&count, nullptr) != VK_SUCCESS) return std::nullopt; + std::vector layers(count); + if (enumerate(&count, layers.data()) != VK_SUCCESS) return std::nullopt; + for (const auto& layer : layers) { + if (std::strcmp(layer.layerName, "VK_LAYER_KHRONOS_validation") == 0) return layer.specVersion; + } + return std::nullopt; +} + +constexpr std::uint32_t MinHeapValidationLayerVersion = VK_MAKE_API_VERSION(0, 1, 4, 363); +constexpr std::uint32_t HeapDataUniformDwordCap = 16384u; + +bool DescriptorHeapAvailable(const std::vector& availableExtensions, PFN_vkGetInstanceProcAddr instanceProc) { + if (!Graphics::GpuHeapEnabled()) return false; + const auto heapExtension = std::find_if(availableExtensions.begin(), availableExtensions.end(), [](const auto& item) { return std::strcmp(item.extensionName, VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) == 0; }); + if (heapExtension == availableExtensions.end()) return false; + if (heapExtension->specVersion < VK_EXT_DESCRIPTOR_HEAP_SPEC_VERSION) { + std::fprintf(stderr, "[gpu-heap] the driver's VK_EXT_descriptor_heap is revision %u, older than the released revision %u, so the GPU heap stays off\n", + heapExtension->specVersion, static_cast(VK_EXT_DESCRIPTOR_HEAP_SPEC_VERSION)); + return false; + } + const auto validationVersion = ActiveValidationLayerVersion(instanceProc); + if (validationVersion.has_value() && *validationVersion < MinHeapValidationLayerVersion) { + std::fprintf(stderr, "[gpu-heap] VK_LAYER_KHRONOS_validation %u.%u.%u predates its descriptor heap rules (1.4.363 is the oldest layer that validates heap push data), so the GPU heap stays off\n", + VK_API_VERSION_MAJOR(*validationVersion), VK_API_VERSION_MINOR(*validationVersion), VK_API_VERSION_PATCH(*validationVersion)); + return false; + } + return true; +} + std::atomic descriptorUse[7 * 4]; void CountDescriptor(int type, int, int usage) { @@ -247,7 +288,6 @@ const ShaderRecompiler::DiagnosticSink runReportSink{ }; [[maybe_unused]] const bool runReportSinkInstalled = (LibcRunReportSetDescriptorCounters_nid_no_patch(descriptorUse), ShaderRecompiler::SetDiagnosticSink(&runReportSink), true); - std::uint64_t fillCompletionSyncs = 0; void check(VkResult result, const char* operation) { @@ -332,6 +372,31 @@ const wchar_t* ComputePipelineDumpDirectory() { return _wgetenv(L"APS5_DUMP_COMP const char* ComputePipelineDumpDirectory() { return std::getenv("APS5_DUMP_COMPUTE_PIPELINES"); } #endif +static_assert(Graphics::ComputePushConstantBytes + sizeof(VkDeviceAddress) == ShaderRecompiler::GpuScratchPoolAddressPushByte && + ShaderRecompiler::GpuScratchPoolAddressPushByte + sizeof(VkDeviceAddress) <= ShaderRecompiler::GpuScratchPoolDwordsPushByte && + (ShaderRecompiler::StagePushFeatures(ShaderRecompiler::ShaderStage::Compute, 0u) & ShaderRecompiler::PushBytesMask(Graphics::ComputePushConstantBytes, ShaderRecompiler::GpuScratchPoolDwordsPushByte + sizeof(std::uint32_t) - Graphics::ComputePushConstantBytes)) == ShaderRecompiler::PushBytesMask(Graphics::ComputePushConstantBytes, ShaderRecompiler::GpuScratchPoolDwordsPushByte + sizeof(std::uint32_t) - Graphics::ComputePushConstantBytes)); + +void CreateComputeHeapPipeline(VkDevice device, PFN_vkCreateComputePipelines create, VkPipelineCache cache, VkShaderModule module, VkPipelineCreateFlags flags, VkPipelineShaderStageCreateFlags stageFlags, const VkSpecializationInfo* specialization, std::uint32_t subgroupSize, std::span mappings, VkPipeline* pipeline, Graphics::PipelineCacheSynchronization* synchronization) { + auto flags2 = Graphics::DescriptorHeapFlags(static_cast(flags)); + VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, &flags2}; + info.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + info.stage.flags = stageFlags; + info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + info.stage.module = module; + info.stage.pName = "main"; + info.stage.pSpecializationInfo = specialization; + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + mappingInfo.mappingCount = static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT subgroup{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT}; + subgroup.requiredSubgroupSize = subgroupSize; + info.stage.pNext = &mappingInfo; + if (subgroupSize != 0) mappingInfo.pNext = &subgroup; + info.layout = VK_NULL_HANDLE; + auto cacheLock = synchronization != nullptr ? synchronization->LockForPipelineUse() : Graphics::PipelineCacheSynchronization::PipelineUseLock{}; + check(create(device, cache, 1, &info, nullptr, pipeline), "vkCreateComputePipelines (descriptor heap)"); +} + bool CaptureComputePipeline(std::size_t words) { const char* minimum = std::getenv("APS5_DUMP_COMPUTE_MIN_WORDS"); if (minimum == nullptr) return true; @@ -443,6 +508,9 @@ struct ComputePipelineObjects { VkDescriptorSetLayout resourcesLayout = VK_NULL_HANDLE; std::mutex splitMutex; std::map, VkPipeline> splitPipelines; + std::vector pushPlacements; + std::vector heapMappings; + bool descriptorHeap = false; ~ComputePipelineObjects() { for (const auto& [base, split] : splitPipelines) destroyPipeline(device, split, nullptr); if (pipeline != VK_NULL_HANDLE) destroyPipeline(device, pipeline, nullptr); @@ -469,6 +537,7 @@ struct WorkgroupMemory { std::unique_ptr buffer; VkDescriptorPool pool = VK_NULL_HANDLE; VkDescriptorSet set = VK_NULL_HANDLE; + VkDeviceAddress address = 0; ~WorkgroupMemory() { buffer.reset(); if (pool != VK_NULL_HANDLE) destroyPool(device, pool, nullptr); @@ -481,6 +550,7 @@ struct ScratchPool { std::unique_ptr buffer; VkDescriptorPool pool = VK_NULL_HANDLE; VkDescriptorSet set = VK_NULL_HANDLE; + VkDeviceAddress address = 0; std::uint64_t slots = 0; std::uint64_t headerBytes = 0; std::uint64_t bytes = 0; @@ -700,10 +770,15 @@ struct VulkanDevice::State { // built once after setup (see graphicsContext); the context's pool reference is dropped before // the pool at teardown. Graphics::DeviceFunctions deviceFunctions; + std::unique_ptr functionCache = std::make_unique(); bool functionsReady = false; Graphics::Context context; bool contextReady = false; std::unique_ptr detiler; + bool descriptorHeap = false; + VkPhysicalDeviceDescriptorHeapPropertiesEXT descriptorHeapProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT}; + std::uint32_t heapDataUniformDwords = 0; + bool uniformConstantBuffers = false; std::unique_ptr recorder; // Device-local buffers of a repeated 16-byte fill pattern (FillBuffer), most recently used // last; each is filled once by a doubling chain in device memory. @@ -731,6 +806,7 @@ struct VulkanDevice::State { std::shared_ptr journalReplay; std::atomic journalReplayPending{false}; std::atomic computePipelinesCreated{0}; + std::atomic descriptorHeapComputePipelines{0}; std::unique_ptr colorTransfer; std::shared_ptr bufferPool; std::unique_ptr emptyBuffer; @@ -834,12 +910,14 @@ struct VulkanDevice::State { template TFunction DeviceFunction(Graphics::FunctionName name) const { + if (const auto cached = functionCache->Find(name.Value(), deviceProc); cached != nullptr) return reinterpret_cast(cached); ++Graphics::DeviceProcLookups(); - auto function = reinterpret_cast(deviceProc(device, name.Value())); + const auto function = deviceProc(device, name.Value()); if (function == nullptr) { throw std::runtime_error(std::string("Vulkan device function missing: ") + name.Value()); } - return function; + functionCache->Keep(name.Value(), deviceProc, function); + return reinterpret_cast(function); } void CreateWorkgroupMemoryLayout() { @@ -866,7 +944,7 @@ struct VulkanDevice::State { auto memory = std::make_shared(); memory->device = device; memory->destroyPool = DeviceFunction("vkDestroyDescriptorPool"); - memory->buffer = std::make_unique(context, static_cast(size), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + memory->buffer = std::make_unique(context, static_cast(size), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (context.descriptorHeap ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u)); const VkDescriptorPoolSize poolSize{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; poolInfo.maxSets = 1; @@ -886,6 +964,7 @@ struct VulkanDevice::State { write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &described; DeviceFunction("vkUpdateDescriptorSets")(device, 1, &write, 0, nullptr); + if (context.descriptorHeap) memory->address = Graphics::BufferDeviceAddress(context, memory->buffer->Handle()); workgroupMemory = std::move(memory); return workgroupMemory; } @@ -913,7 +992,7 @@ struct VulkanDevice::State { created->headerBytes = wanted * 2u * 4u; created->bytes = size; created->lastUse = use; - created->buffer = std::make_unique(context, static_cast(size), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); + created->buffer = std::make_unique(context, static_cast(size), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | (context.descriptorHeap ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u)); const VkDescriptorPoolSize poolSize{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; poolInfo.maxSets = 1; @@ -933,6 +1012,7 @@ struct VulkanDevice::State { write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &described; DeviceFunction("vkUpdateDescriptorSets")(device, 1, &write, 0, nullptr); + if (context.descriptorHeap) created->address = Graphics::BufferDeviceAddress(context, created->buffer->Handle()); ZeroScratchPoolHeader(context, *created); scratchPools[identity] = created; return created; @@ -1212,6 +1292,7 @@ struct VulkanDevice::State { Graphics::ClearRetainedSpaces(device); Graphics::ClearCachedTextures(device); Graphics::ClearSnapshotCopies(device); + Graphics::BindlessHeap::Release(device); Graphics::ClearUploadCopies(device); Graphics::ClearImageMirrors(device); Graphics::ClearHostImports(device); @@ -1688,6 +1769,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : const std::array meshExtensions{VK_EXT_MESH_SHADER_EXTENSION_NAME, VK_KHR_SPIRV_1_4_EXTENSION_NAME}; const bool meshAvailable = std::all_of(meshExtensions.begin(), meshExtensions.end(), hasExtension); VkPhysicalDeviceMeshShaderFeaturesEXT meshFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; + VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR standardLayout{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR}; if (meshAvailable) { VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &meshFeatures}; state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &features); @@ -2271,6 +2353,34 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : state->InstanceFunction("vkGetPhysicalDeviceProperties2")(selected, &properties); } } + VkPhysicalDeviceDescriptorHeapFeaturesEXT descriptorHeapFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_FEATURES_EXT}; + if (DescriptorHeapAvailable(availableExtensions, state->instanceProc) && hasExtension(VK_KHR_MAINTENANCE_5_EXTENSION_NAME) && hasExtension(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) && hasExtension(VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME) && hasExtension(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) { + VkPhysicalDeviceMaintenance5FeaturesKHR heapMaintenance5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR, &descriptorHeapFeatures}; + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &heapMaintenance5}; + state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &features); + const bool heapSupported = descriptorHeapFeatures.descriptorHeap == VK_TRUE && heapMaintenance5.maintenance5 == VK_TRUE; + if (heapSupported) { + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &state->descriptorHeapProperties}; + state->InstanceFunction("vkGetPhysicalDeviceProperties2")(selected, &properties); + } + if (heapSupported && Graphics::BindlessHeap::Fits(state->descriptorHeapProperties)) { + state->descriptorHeap = true; + state->maintenance5 = true; + state->heapDataUniformDwords = std::min(HeapDataUniformDwordCap, state->properties.limits.maxUniformBufferRange / 4u); + if (hasExtension(VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME)) { + VkPhysicalDeviceFeatures2 layoutFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &standardLayout}; + state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &layoutFeatures); + } + state->uniformConstantBuffers = Graphics::ChooseUniformConstantBuffers(standardLayout.uniformBufferStandardLayout == VK_TRUE, state->properties.limits); + if (state->uniformConstantBuffers) deviceExtensions.push_back(VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME); + deviceExtensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); + for (const char* required : {VK_KHR_MAINTENANCE_5_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}) { + if (std::find_if(deviceExtensions.begin(), deviceExtensions.end(), [&](const char* name) { return std::strcmp(name, required) == 0; }) == deviceExtensions.end()) deviceExtensions.push_back(required); + } + } + descriptorHeapFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_FEATURES_EXT}; + descriptorHeapFeatures.descriptorHeap = state->descriptorHeap ? VK_TRUE : VK_FALSE; + } descriptorIndexingFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT}; if (state->descriptorIndexing || state->storageBufferUpdateAfterBind || state->sampledImageUpdateAfterBind || state->descriptorBindingPartiallyBound || state->descriptorBindingVariableDescriptorCount || state->runtimeDescriptorArray) deviceExtensions.push_back(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME); if (state->descriptorIndexing) { @@ -2301,6 +2411,14 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : meshFeatures.pNext = const_cast(deviceInfo.pNext); deviceInfo.pNext = &meshFeatures; } + if (state->uniformConstantBuffers) { + standardLayout = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR, const_cast(deviceInfo.pNext), VK_TRUE}; + deviceInfo.pNext = &standardLayout; + } + if (state->descriptorHeap) { + descriptorHeapFeatures.pNext = const_cast(deviceInfo.pNext); + deviceInfo.pNext = &descriptorHeapFeatures; + } if (state->depthClipControl) { depthClipFeatures.pNext = const_cast(deviceInfo.pNext); deviceInfo.pNext = &depthClipFeatures; @@ -2704,11 +2822,17 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : state->functionsReady = true; } Graphics::PrepareImportWatch(graphicsContext()); + const bool heapDevice = state->descriptorHeap && state->descriptorHeapProperties.maxPushDataSize >= Graphics::PipelinePushConstantBytes; + if (heapDevice && Graphics::GpuHeapEnabled() && !state->timelineSemaphores) + throw std::runtime_error("AGC graphics: the GPU heap needs timeline semaphores to evict slots; APS5_NO_TIMELINE cannot be used with APS5_GPU_HEAP"); + Graphics::SetDescriptorHeapDevice(heapDevice); + Graphics::BufferPool::SetForceAddresses(Graphics::DescriptorHeapEnabled()); state->bufferPool = std::make_shared(graphicsContext()); state->emptyBuffer = std::make_unique(graphicsContext(), Graphics::EmptyBufferBytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); std::ranges::fill(state->emptyBuffer->Bytes(), std::byte{0}); state->oversizedBuffer = std::make_unique(graphicsContext(), Graphics::EmptyBufferBytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); std::ranges::fill(state->oversizedBuffer->Bytes(), std::byte{0}); + if (state->descriptorHeap && Graphics::DescriptorHeapEnabled()) APS5_LOG_OUT("Vulkan descriptor heap: %s", "GPU-mode draws and dispatches bind from VK_EXT_descriptor_heap"); if (!compileOnly && Pm4::GdsImportable() && Graphics::HostImportFor(graphicsContext(), Pm4::GdsAddress(), Pm4::GdsBytes, Graphics::ImportRequester::Map) == nullptr) Pm4::RejectGdsImport(); if (!state->imageInt64Atomics || !state->bufferInt64Atomics) { state->atomicLockTable = std::make_unique(graphicsContext(), ShaderRecompiler::RuntimeAbi::AtomicLockCount * sizeof(std::uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); @@ -2897,6 +3021,10 @@ std::uint64_t VulkanDevice::ComputePipelinesCreated() const { return state->computePipelinesCreated.load(std::memory_order_relaxed); } +std::uint64_t VulkanDevice::DescriptorHeapComputePipelines() const { + return state->descriptorHeapComputePipelines.load(std::memory_order_relaxed); +} + bool VulkanDevice::ReplayComputePipeline(const ShaderRecompiler::RecompileResult& shader, bool pushConstants) { ShaderRecompiler::RuntimeAbi::RequireVersion(shader.runtimeAbiVersion); const auto key = ComputePipelineKey::Of(shader, pushConstants); @@ -4298,6 +4426,7 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu check(state->DeviceFunction("vkResetCommandBuffer")(commands, 0), "vkResetCommandBuffer"); VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + Graphics::NoteCommandBufferBegun(commands); check(state->DeviceFunction("vkBeginCommandBuffer")(commands, &begin), "vkBeginCommandBuffer"); APS5_LOG_OUT_DEBUG("Presentation command buffer begin commands=%p image=%p", reinterpret_cast(commands), reinterpret_cast(state->images[index])); using CommandClass = Graphics::Recorder::CommandClass; @@ -4650,6 +4779,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::ComputeTarget(std::uint32_t waveSize auto target = Target(); target.float32FlushToZero = state->float32FlushToZero; if (waveSize == 32u && state->computeWave32) target.subgroupSize = 32u; + target.gpuResolvedImages = Graphics::DescriptorHeapEnabled(); return target; } @@ -4719,6 +4849,9 @@ ShaderRecompiler::SpirvTarget VulkanDevice::Target() const { target.fusedExactArithmetic = state->fusedExactArithmetic; target.hostInterpolationFirst = state->hostInterpolationFirst; target.float32DenormPreserve = state->float32DenormPreserve; + target.descriptorMemory = Graphics::DescriptorHeapEnabled(); + target.heapDataUniformDwords = target.descriptorMemory ? state->heapDataUniformDwords : 0u; + target.uniformConstantBuffers = target.descriptorMemory && state->uniformConstantBuffers; target.float16WidenNans = state->float16WidenNans; target.float16NarrowNans = state->float16NarrowNans; return target; @@ -4814,10 +4947,19 @@ std::pair VulkanDevice::scratchPoolHeader(const ShaderR return {found->second->buffer->Handle(), found->second->headerBytes}; } -Graphics::Context VulkanDevice::graphicsContext() const { +const Graphics::Context& VulkanDevice::contextRef(std::optional& scratch) const { static const bool noCache = std::getenv("APS5_NO_CONTEXT_CACHE") != nullptr; if (state->contextReady && !noCache) return state->context; - return buildContext(); + return scratch.emplace(buildContext()); +} + +bool VulkanDevice::TimelineSemaphores() const { + return state->timelineSemaphores; +} + +Graphics::Context VulkanDevice::graphicsContext() const { + std::optional scratch; + return contextRef(scratch); } Graphics::Context VulkanDevice::buildContext() const { @@ -4869,6 +5011,8 @@ Graphics::Context VulkanDevice::buildContext() const { context.settleFamily = state->settleFamily; context.settleQueueMutex = &state->settleQueueMutex; context.recorder = state->recorder.get(); + context.descriptorHeap = state->descriptorHeap; + context.descriptorHeapProperties = state->descriptorHeapProperties; context.descriptorCache = state->descriptorCache.get(); context.vertexInputs = state->vertexInputs.get(); context.vertexFormats = &state->vertexFormats; @@ -4902,6 +5046,7 @@ Graphics::Context VulkanDevice::buildContext() const { context.exactRobustLoads = state->exactRobustLoads; context.copiedWriters = state->copiedWriters.get(); context.functions = state->functionsReady ? &state->deviceFunctions : nullptr; + context.functionCache = state->functionsReady ? state->functionCache.get() : nullptr; context.descriptorIndexing = state->descriptorIndexing; context.descriptorIndexingLimits = state->descriptorIndexingProperties; context.imageInt64Atomics = state->imageInt64Atomics; @@ -4960,7 +5105,8 @@ VulkanDevice::IndirectDrawSupport VulkanDevice::DrawIndirectSupport() const { } std::optional VulkanDevice::KnownDrawRejection(const Graphics::State& graphics, std::span shaders) const { - return Graphics::KnownValidationFailure(graphicsContext(), shaders, graphics); + std::optional scratch; + return Graphics::KnownValidationFailure(contextRef(scratch), shaders, graphics); } void VulkanDevice::ColorMetadataPass(const Graphics::ColorMetadataPass& pass) { @@ -5039,7 +5185,7 @@ namespace { // which needs the texture caches: without them every lookup makes a fresh object, so a hit could // never validate and would only upload everything twice. bool ResourceCacheEnabled() { - static const bool noResourceCache = std::getenv("APS5_NO_RESOURCE_CACHE") != nullptr; + static const bool noResourceCache = !ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::ResourceCache); static const bool noTextureCache = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr; return !noResourceCache && !noTextureCache; } @@ -5271,11 +5417,11 @@ DispatchCounters& Dispatches() { // The [recipe] line (APS5_PROFILE_DRAW, every 10 s), dispatch and indirect rows apart. The // pre-check runs without the mutex, so the counters are atomic. -enum RecipeMiss : std::size_t { MissNoRecipe, MissDevice, MissTemplateGone, MissObjectsGone, MissNotRecordable, RecipeMissCount }; -constexpr std::array RecipeMissNames{"no recipe", "device", "template gone", "objects gone", "not recordable"}; +enum RecipeMiss : std::size_t { MissNoRecipe, MissDevice, MissTemplateGone, MissObjectsGone, MissNotRecordable, MissMoved, RecipeMissCount }; +constexpr std::array RecipeMissNames{"no recipe", "device", "template gone", "objects gone", "not recordable", "moved buffers refused"}; // The draw rows name the miss reasons of DrawWithRecipe (a target or a pipeline gone is the // objects-gone slot). -constexpr std::array DrawRecipeMissNames{"no recipe", "device", "template gone", "targets gone", "not recordable"}; +constexpr std::array DrawRecipeMissNames{"no recipe", "device", "template gone", "targets gone", "not recordable", "moved buffers refused"}; constexpr std::array(Graphics::ShaderResources::ProofPath::Count)> ProofPathNames{"fast", "T1 refreshed", "full"}; constexpr std::array(Graphics::ShaderResources::ProofFailure::Count)> ProofFailureNames{"none", "imports", "evicted", "pending", "changed", "keys", "other"}; @@ -5579,6 +5725,10 @@ void VulkanDevice::NoteDrawRecipeMiss(DrawRecipePrecheck miss) { counters.precheckMisses[miss == DrawRecipePrecheck::NoRecipe ? MissNoRecipe : MissDevice].fetch_add(1, std::memory_order_relaxed); } +std::uint64_t VulkanDevice::DispatchRecipeTemplatesGone() { + return Recipes().kinds[static_cast(RecipeKind::Dispatch)].precheckMisses[MissTemplateGone].load(std::memory_order_relaxed); +} + std::uint64_t VulkanDevice::DrawRecipeHits() { return Recipes().kinds[static_cast(RecipeKind::Draw)].hits.load(std::memory_order_relaxed); } @@ -5601,6 +5751,7 @@ RecipeOutcome VulkanDevice::DrawFromRecipe(const Graphics::State& graphics, cons case Graphics::DrawRecipeMiss::TargetGone: case Graphics::DrawRecipeMiss::ObjectsGone: counters.precheckMisses[MissObjectsGone].fetch_add(1, std::memory_order_relaxed); break; case Graphics::DrawRecipeMiss::TemplateGone: counters.precheckMisses[MissTemplateGone].fetch_add(1, std::memory_order_relaxed); break; + case Graphics::DrawRecipeMiss::Buffers: counters.precheckMisses[MissMoved].fetch_add(1, std::memory_order_relaxed); break; case Graphics::DrawRecipeMiss::Proof: counters.rebuilds[static_cast(outcome.proof.failure)].fetch_add(1, std::memory_order_relaxed); break; default: break; } @@ -5738,7 +5889,7 @@ std::shared_ptr VulkanDevice::PrepareDispatch(const ShaderReco if (built.Layout() != VK_NULL_HANDLE) { const auto layouts = built.SetLayouts(); prepared->objects = computePipeline(context, shader, layouts.main, layouts.mainKey, pushStages, programAddress); - } else if (context.descriptorCache != nullptr) { + } else if (context.descriptorCache != nullptr && !shader.gpuResolvedImages) { const auto described = Graphics::DescribeSetLayouts(context, shaders); prepared->describedLayoutKey = described.mainKey; prepared->objects = computePipeline(context, shader, described.layouts.main, described.mainKey, pushStages, programAddress); @@ -5922,6 +6073,9 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { const bool overlapCapable = overlapQueue != 0 && Graphics::Recorder::DispatchOverlapEnabled() && arguments == 0 && argumentImport == nullptr && record.threadGroup == std::array{} && record.shader->program->workgroupMemoryDwords == 0 && state->checkpointMarker == nullptr && state->bufferMarker == nullptr && record.x <= groupLimit[0] && record.y <= groupLimit[1] && record.z <= groupLimit[2] && !resources.HasHostGpuCopies(); std::vector runAccesses; if (overlapCapable) resources.RunAccesses(runAccesses); + if (overlapCapable && record.bindings != nullptr) { + for (const auto& [begin, end] : record.bindings->movedReads) runAccesses.push_back({begin, end, 0u}); + } VkAccessFlags covered = 0; bool overlapped = false; const std::array runOwners{record.resources.get(), resources.MemoryOwner()}; @@ -5938,6 +6092,11 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { for (const auto& snapshot : record.bindings->snapshots) recorder.KeepBytes(snapshot.buffer.get(), snapshot.buffer->Bytes().size()); } recordStep(PhaseRecordKeeps); + if (resources.HeapStage()) { + if (record.threadGroup != std::array{}) resources.forgetShaderDataWords(*record.shader); + resources.RefreshHeapStage(std::span(record.shader, 1)); + if (record.bindings != nullptr) resources.RefreshMovedAddresses(*record.bindings); + } if (record.dataRefresh != RecordedDispatch::DataRefresh::None) { // The template's data buffers take this dispatch's words: a transfer write the pre-dispatch // barrier makes visible (so it is recorded whatever the previous command covered), ordered @@ -5957,10 +6116,10 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { } std::shared_ptr threadArguments; if (record.threadGroup != std::array{}) { - const auto data = resources.shaderDataBuffer(*record.shader); + const auto [data, dataOffset] = resources.shaderDataLocation(*record.shader, record.bindings.get()); const auto limitDword = record.shader->program->imageMetadataDword; Graphics::Require(data != VK_NULL_HANDLE && limitDword >= 3, "Vulkan dispatch: a thread-dimension dispatch has no ShaderData thread limit"); - const VkDeviceSize limitByte = static_cast(limitDword - 3) * sizeof(std::uint32_t); + const VkDeviceSize limitByte = dataOffset + static_cast(limitDword - 3) * sizeof(std::uint32_t); Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); if (argumentImport != nullptr) { threadArguments = std::make_shared(context, 24, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); @@ -5993,7 +6152,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { recorder.NotePendingRead(arguments, 12, Graphics::Recorder::ReadKind::Indirect); } // Results of earlier recorded work are visible to this dispatch, its own to everything after. - constexpr VkAccessFlags shaderAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + constexpr VkAccessFlags shaderAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_UNIFORM_READ_BIT; if (overlapped) { if (record.refreshed) { Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT); @@ -6005,7 +6164,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { } else { const auto timing = recorder.BeginGpuTiming(CommandClass::DispatchLeading); const VkPipelineStageFlags leadingStages = overlapCapable ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - const VkAccessFlags leadingAccess = overlapCapable ? VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + const VkAccessFlags leadingAccess = overlapCapable ? VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, leadingStages, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, leadingAccess); Graphics::Recorder::CountBarriers(CommandClass::DispatchLeading); recorder.EndGpuTiming(timing); @@ -6026,20 +6185,55 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { } } context.BindComputePipeline(commands, record.objects->pipeline); - if (record.bindings != nullptr) Graphics::Require(record.bindings->allocation.set != VK_NULL_HANDLE, "dispatch overlay has no descriptor set"); - if (record.bindings != nullptr) context.Resolved(&Graphics::DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, 0, 1, &record.bindings->allocation.set, 0, nullptr); - else resources.Bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout); + Graphics::NoteHeapRecord(true, record.objects->descriptorHeap); + if (record.objects->descriptorHeap) { + resources.BindDescriptorHeaps(commands); + } else if (record.bindings != nullptr) { + Graphics::Require(record.bindings->allocation.set != VK_NULL_HANDLE && !resources.HeapStage(), "dispatch overlay has no descriptor set"); + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, 0, 1, &record.bindings->allocation.set, Graphics::SetBindSite::Dispatch); + } else { + Graphics::Require(!resources.HeapStage(), "a GPU-mode dispatch needs a VK_EXT_descriptor_heap pipeline"); + resources.Bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout); + } + VkDeviceAddress workgroupAddress = 0; if (const auto dwords = record.shader->program->workgroupMemoryDwords; dwords != 0) { auto memory = state->WorkgroupMemoryFor(context, record.x, record.y, record.z, dwords); - context.Resolved(&Graphics::DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, ShaderRecompiler::WorkgroupMemoryDescriptorSet, 1, &memory->set, 0, nullptr); + if (record.objects->descriptorHeap) { + workgroupAddress = memory->address; + } else { + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, ShaderRecompiler::WorkgroupMemoryDescriptorSet, 1, &memory->set, Graphics::SetBindSite::Dispatch); + } recorder.Keep(std::move(memory)); } + std::array stageAddresses{}; + std::memcpy(stageAddresses.data(), &workgroupAddress, sizeof(workgroupAddress)); if (pool != nullptr) { - context.Resolved(&Graphics::DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, ShaderRecompiler::ScratchPoolDescriptorSet, 1, &pool->set, 0, nullptr); + if (record.objects->descriptorHeap) { + const auto dwords = static_cast(pool->bytes / sizeof(std::uint32_t)); + std::memcpy(stageAddresses.data() + (ShaderRecompiler::GpuScratchPoolAddressPushByte - Graphics::ComputePushConstantBytes), &pool->address, sizeof(pool->address)); + std::memcpy(stageAddresses.data() + (ShaderRecompiler::GpuScratchPoolDwordsPushByte - Graphics::ComputePushConstantBytes), &dwords, sizeof(dwords)); + } else { + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, ShaderRecompiler::ScratchPoolDescriptorSet, 1, &pool->set, Graphics::SetBindSite::Dispatch); + } recorder.Keep(std::move(pool)); } + if (record.objects->descriptorHeap && record.pushStages == 0 && (workgroupAddress != 0 || record.shader->program->scratchPoolSlotDwords != 0)) { + Graphics::CmdPushData(context, commands, static_cast(stageAddresses.size()), stageAddresses.data(), Graphics::ComputePushConstantBytes); + } if (record.pushStages != 0) { - context.Resolved(&Graphics::DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, record.objects->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes, record.pushBytes->data()); + std::array patchedBytes; + const std::byte* pushed = record.pushBytes->data(); + if (resources.HeapStage() || record.objects->descriptorHeap) { + patchedBytes = *record.pushBytes; + resources.PatchDataAddresses(patchedBytes, std::span(record.shader, 1), record.objects->pushPlacements, record.bindings.get()); + pushed = patchedBytes.data(); + } + if (record.objects->descriptorHeap) { + std::memcpy(patchedBytes.data() + Graphics::ComputePushConstantBytes, stageAddresses.data(), stageAddresses.size()); + Graphics::CmdPushData(context, commands, static_cast(patchedBytes.size()), patchedBytes.data()); + } else { + Graphics::CmdPushConstants(context, commands, record.objects->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes, pushed); + } } static const bool reportingDispatch = LibcRunReportEnabled_nid_no_patch(); if (reportingDispatch) recorder.NoteGuestWork(commands); @@ -6128,7 +6322,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { resources.CopyBacksAfterRun(record.resources); } else { const auto trailingTiming = recorder.BeginGpuTiming(CommandClass::DispatchTrailing); - constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; + constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, dispatchedAccess); Graphics::Recorder::CountBarriers(CommandClass::DispatchTrailing); recorder.EndGpuTiming(trailingTiming); @@ -6167,9 +6361,6 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { recordStep(PhaseRecordCompletion); } -// The module, pipeline layout and pipeline of a compute result over `setLayout` (the set layout -// its bindings describe): what a dispatch or its preparation builds at the first use of a module, -// and what the journal replay builds on its own threads before that use. std::shared_ptr VulkanDevice::createComputePipeline(const Graphics::Context& context, const ShaderRecompiler::RecompileResult& shader, VkDescriptorSetLayout setLayout, std::span layoutKey, VkShaderStageFlags pushStages, std::uint64_t programAddress) { PerformanceTimer timing("Vulkan.ComputePipeline"); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; @@ -6181,20 +6372,28 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons objects->destroyPipeline = state->DeviceFunction("vkDestroyPipeline"); objects->module = Graphics::CreateShaderModule(state->DeviceFunction("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, shader.spirv.data(), shader.spirv.size() * sizeof(std::uint32_t), "vkCreateShaderModule"); objects->resourcesLayout = setLayout; + const bool gpuMode = shader.gpuResolvedImages; + const bool heapDevice = gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled(); const bool scratchPool = shader.scratchPoolSlotDwords != 0; - const std::array setLayouts{setLayout, shader.workgroupMemoryDwords != 0 || scratchPool ? state->workgroupMemoryLayout : VK_NULL_HANDLE, scratchPool ? state->workgroupMemoryLayout : VK_NULL_HANDLE}; const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes}; - VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layoutInfo.setLayoutCount = scratchPool ? ShaderRecompiler::ScratchPoolDescriptorSet + 1 : shader.workgroupMemoryDwords != 0 ? ShaderRecompiler::WorkgroupMemoryDescriptorSet + 1 : 1; - layoutInfo.pSetLayouts = setLayouts.data(); - layoutInfo.pushConstantRangeCount = pushStages != 0 ? 1 : 0; - layoutInfo.pPushConstantRanges = pushStages != 0 ? &push : nullptr; - check(state->DeviceFunction("vkCreatePipelineLayout")(state->device, &layoutInfo, nullptr, &objects->layout), "vkCreatePipelineLayout"); + if (!gpuMode) { + const std::array setLayouts{setLayout, shader.workgroupMemoryDwords != 0 || scratchPool ? state->workgroupMemoryLayout : VK_NULL_HANDLE, scratchPool ? state->workgroupMemoryLayout : VK_NULL_HANDLE}; + VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layoutInfo.setLayoutCount = scratchPool ? ShaderRecompiler::ScratchPoolDescriptorSet + 1 : shader.workgroupMemoryDwords != 0 ? ShaderRecompiler::WorkgroupMemoryDescriptorSet + 1 : 1; + layoutInfo.pSetLayouts = setLayouts.data(); + layoutInfo.pushConstantRangeCount = pushStages != 0 ? 1 : 0; + layoutInfo.pPushConstantRanges = pushStages != 0 ? &push : nullptr; + check(state->DeviceFunction("vkCreatePipelineLayout")(state->device, &layoutInfo, nullptr, &objects->layout), "vkCreatePipelineLayout"); + } const VkPipelineCreateFlags pipelineFlags = computePipelineFlags(); - const Graphics::PipelineSpecialization specialization(shader, context.atomicLockTable); + const Graphics::CompiledShader placed{ShaderRecompiler::ShaderStage::Compute, &shader, 0u}; + objects->pushPlacements = Graphics::PushDataPlacements(std::span(&placed, 1)); + Graphics::PipelineSpecialization specialization(shader, context.atomicLockTable); + specialization.PlacePushData(objects->pushPlacements.front()); + if (heapDevice) specialization.PlaceHeapImageSlots(Graphics::BindlessHeap::For(context).ImageSlots()); const auto subgroupSize = computeSubgroupSize(shader); const auto stageFlags = computeStageFlags(shader); - if (const auto* directory = ComputePipelineDumpDirectory(); directory != nullptr && *directory != 0 && !state->probingFloatControls && ComputePipelineCapture::OptionalEnabled() && CaptureComputePipeline(shader.spirv.size())) { + if (const auto* directory = ComputePipelineDumpDirectory(); directory != nullptr && *directory != 0 && !gpuMode && !state->probingFloatControls && ComputePipelineCapture::OptionalEnabled() && CaptureComputePipeline(shader.spirv.size())) { ComputePipelineCapture capture; capture.spirv = shader.spirv.Copy(); ComputeDescriptorSetLayout resourcesLayout; @@ -6222,12 +6421,22 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons if (!path.empty()) std::fprintf(stderr, "[compute-capture] %s\n", path.string().c_str()); } if (profile && shader.spirv.size() > 100000) std::fprintf(stderr, "[dispatch] creating a pipeline for %zu SPIR-V words (program 0x%llx)\n", shader.spirv.size(), static_cast(programAddress)); - CreateComputePipeline(state->device, state->DeviceFunction("vkCreateComputePipelines"), context.pipelineCache, objects->module, objects->layout, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, &objects->pipeline, context.pipelineCacheSynchronization); + std::vector heapMappings; + const bool workgroupAddress = shader.workgroupMemoryDwords != 0; + const auto workgroupAddressOffset = workgroupAddress ? Graphics::ComputePushConstantBytes : ~0u; + const std::span spirv(shader.spirv.data(), shader.spirv.size()); + objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, {.workgroupAddress = workgroupAddress, .gdsAddress = shader.dataAddressPush, .scratchPool = scratchPool}, &objects->pushPlacements.front(), &shader.bindings, workgroupAddressOffset); + require(!gpuMode || objects->descriptorHeap, "a GPU-mode compute stage does not map onto VK_EXT_descriptor_heap"); + const auto createPipelines = state->DeviceFunction("vkCreateComputePipelines"); + if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, objects->module, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); + else CreateComputePipeline(state->device, createPipelines, context.pipelineCache, objects->module, objects->layout, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, &objects->pipeline, context.pipelineCacheSynchronization); + if (objects->descriptorHeap) objects->heapMappings = std::move(heapMappings); objects->destroyModule(objects->device, objects->module, nullptr); objects->module = VK_NULL_HANDLE; if (!state->probingFloatControls) { computePipelinesCreated.fetch_add(1, std::memory_order_relaxed); state->computePipelinesCreated.fetch_add(1, std::memory_order_relaxed); + if (objects->descriptorHeap) state->descriptorHeapComputePipelines.fetch_add(1, std::memory_order_relaxed); if (GuestMemory::GpuMutex().HeldByThisThread()) computePipelinesCreatedLocked.fetch_add(1, std::memory_order_relaxed); } Graphics::LogPipelineStatistics_nid_no_patch(context, objects->pipeline); @@ -6240,11 +6449,15 @@ VkPipeline VulkanDevice::splitComputePipeline(const Graphics::Context& context, if (const auto found = objects.splitPipelines.find(base); found != objects.splitPipelines.end()) return found->second; std::array offsets{}; for (std::uint32_t component = 0; component < offsets.size(); ++component) offsets[component] = {ShaderRecompiler::PipelineSpecialization::WorkgroupOffsetBase + component, base[component]}; - const Graphics::PipelineSpecialization specialization(shader, context.atomicLockTable, offsets); + Graphics::PipelineSpecialization specialization(shader, context.atomicLockTable, offsets); + specialization.PlacePushData(objects.pushPlacements.front()); + if (objects.descriptorHeap) specialization.PlaceHeapImageSlots(Graphics::BindlessHeap::For(context).ImageSlots()); VkShaderModule module = Graphics::CreateShaderModule(state->DeviceFunction("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, shader.spirv.data(), shader.spirv.size() * sizeof(std::uint32_t), "vkCreateShaderModule"); VkPipeline pipeline = VK_NULL_HANDLE; try { - CreateComputePipeline(state->device, state->DeviceFunction("vkCreateComputePipelines"), context.pipelineCache, module, objects.layout, computePipelineFlags(), computeStageFlags(shader), specialization.Info(), computeSubgroupSize(shader), &pipeline, context.pipelineCacheSynchronization); + const auto createPipelines = state->DeviceFunction("vkCreateComputePipelines"); + if (objects.descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, module, computePipelineFlags(), computeStageFlags(shader), specialization.Info(), computeSubgroupSize(shader), objects.heapMappings, &pipeline, context.pipelineCacheSynchronization); + else CreateComputePipeline(state->device, createPipelines, context.pipelineCache, module, objects.layout, computePipelineFlags(), computeStageFlags(shader), specialization.Info(), computeSubgroupSize(shader), &pipeline, context.pipelineCacheSynchronization); } catch (...) { objects.destroyModule(objects.device, module, nullptr); throw; @@ -6305,7 +6518,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec if (base != 0 && bytes != 0) static_cast(Graphics::FlushDepthPlanes(base, static_cast(bytes))); } } - state->recorder->BoundKeptBytes(); + state->recorder->BoundDrawBatch(); ShaderRecompiler::RuntimeAbi::RequireVersion(shader.runtimeAbiVersion); PerformanceTimer timing("Vulkan.Dispatch"); if (recipeOut != nullptr) *recipeOut = nullptr; @@ -6447,7 +6660,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec } if (moved.has_value() && !moved->empty()) { overlay = cached->PrepareDrawBindings(*state->recorder, *moved, true); - if (overlay != nullptr && overlay->allocation.set == VK_NULL_HANDLE) overlay.reset(); + if (overlay != nullptr && overlay->allocation.set == VK_NULL_HANDLE && !cached->HeapStage()) overlay.reset(); if (overlay == nullptr) { proof.refusal = Graphics::ShaderResources::MoveRefusal::Bindings; moved.reset(); @@ -6533,7 +6746,8 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec if (objects == nullptr) { if (verifySetLayouts && context.descriptorCache != nullptr) { const auto described = Graphics::DescribeSetLayouts(context, shaders); - require(described.layouts.main == resources->Layout() && !described.layouts.split, "the set layout described from the compute shader differs from the dispatch's"); + const auto live = resources->SetLayouts(); + require(described.layouts.main == resources->Layout() && described.layouts.split == live.split && described.layouts.fragment == live.fragment, "the set layout described from the compute shader differs from the dispatch's"); } const auto layouts = resources->SetLayouts(); objects = computePipeline(context, shader, layouts.main, layouts.mainKey, pushStages, programAddress); @@ -6544,6 +6758,47 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec return recordCompletedDispatch(shader, x, y, z, arguments, programAddress, recipeOut, threadGroup, htileClear, completion); } +namespace { + +enum class RecipeRefusal : std::size_t { NotCacheable, Overlay, NoObjects, NoContentKey, NeedsFaultChecks, NeedsCopiedWrites, Unreusable, Count }; +constexpr std::size_t UnreusableReasons = static_cast(Graphics::ShaderResources::Unreusable::Count); +std::array, static_cast(RecipeRefusal::Count)> recipeRefusals{}; +std::array, UnreusableReasons> unreusableRefusals{}; + +void noteRecipeRefusal(bool cacheable, bool overlay, bool objects, bool contentKey, const Graphics::ShaderResources& resources) { + const auto note = [](RecipeRefusal reason) { recipeRefusals[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); }; + if (!cacheable) return note(RecipeRefusal::NotCacheable); + if (overlay) return note(RecipeRefusal::Overlay); + if (!objects) return note(RecipeRefusal::NoObjects); + if (!contentKey) return note(RecipeRefusal::NoContentKey); + if (!resources.Reusable()) { + note(RecipeRefusal::Unreusable); + unreusableRefusals[std::min(static_cast(resources.UnreusableReason()), UnreusableReasons - 1)].fetch_add(1, std::memory_order_relaxed); + return; + } + if (resources.NeedsCompletion()) note(resources.HasCopiedWrites() ? RecipeRefusal::NeedsCopiedWrites : RecipeRefusal::NeedsFaultChecks); +} + +} + +std::string VulkanDevice::DispatchRecipeRefusalText() { + constexpr std::array(RecipeRefusal::Count)> names{"not cacheable", "binding overlay", "no objects", "no content key", "fault checks", "copied writes", "unreusable"}; + std::string text; + for (std::size_t index = 0; index < names.size(); ++index) { + const auto count = recipeRefusals[index].load(std::memory_order_relaxed); + if (count == 0) continue; + text += " " + std::string(names[index]) + " " + std::to_string(count); + } + std::string unreusable; + for (std::size_t index = 0; index < UnreusableReasons; ++index) { + const auto count = unreusableRefusals[index].load(std::memory_order_relaxed); + if (count == 0) continue; + unreusable += std::string(unreusable.empty() ? "" : ", ") + Graphics::ShaderResources::UnreusableReasonName(static_cast(index)) + " " + std::to_string(count); + } + if (!unreusable.empty()) text += " (unreusable: " + unreusable + ")"; + return text.empty() ? " none" : text; +} + VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t arguments, std::uint64_t programAddress, std::shared_ptr* recipeOut, const std::array& threadGroup, std::optional> htileClear, DispatchCompletion& completion) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; const auto& context = completion.context; @@ -6622,7 +6877,10 @@ VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const Shader // object the resource cache serves under this content key (reusable: no lease, no copied // writes, every direct region import- or mirror-served), so a hit's proof is the template's // Revalidate and nothing needs completion work. - if (recipeOut != nullptr && DispatchRecipes() && cacheable && overlay == nullptr && resources->Reusable() && !resources->NeedsCompletion() && objects != nullptr && !contentKey.empty()) { + const bool recipeWanted = recipeOut != nullptr && DispatchRecipes(); + const bool recipeable = recipeWanted && cacheable && overlay == nullptr && resources->Reusable() && !resources->NeedsCompletion() && objects != nullptr && !contentKey.empty(); + if (recipeWanted && profile && !recipeable) noteRecipeRefusal(cacheable, overlay != nullptr, objects != nullptr, !contentKey.empty(), *resources); + if (recipeable) { auto recipe = std::make_shared(); recipe->device = state->device; recipe->templateRef = resources; @@ -6644,7 +6902,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const Shader } RecipeOutcome VulkanDevice::DispatchRecipe(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t arguments, std::uint64_t programAddress, const std::shared_ptr& hit, IndirectOutcome& outcome, const std::shared_ptr& verify, bool refreshByWords, const std::array& threadGroup) { - state->recorder->BoundKeptBytes(); + state->recorder->BoundDrawBatch(); ShaderRecompiler::RuntimeAbi::RequireVersion(shader.runtimeAbiVersion); PerformanceTimer timing("Vulkan.DispatchRecipe"); outcome = {0, 0}; @@ -6699,7 +6957,8 @@ RecipeOutcome VulkanDevice::DispatchRecipe(const ShaderRecompiler::RecompileResu } // A data-only hit's words are the shader's, not the recipe's: its hash decision is // computed from the shader, as the record below decides by words. - const bool byHash = TemplateDataRefresh() && hit->resources->DataWordsHash() != (refreshByWords ? Graphics::ShaderResources::DataWordsHash(shaders[0]) : recipe.dataWordsHash); + const bool byHash = TemplateDataRefresh() && !hit->resources->HeapStage() && + hit->resources->DataWordsHash() != (refreshByWords ? Graphics::ShaderResources::DataWordsHash(shaders[0]) : recipe.dataWordsHash); const bool byWords = TemplateDataRefresh() && hit->resources->DataWordsDiffer(shaders[0]); const char* disagreement = mapped != hit->objects ? "the pipeline objects" : byHash != byWords ? "the RefreshData decision" : nullptr; if (disagreement != nullptr) { @@ -6731,7 +6990,7 @@ RecipeOutcome VulkanDevice::DispatchRecipe(const ShaderRecompiler::RecompileResu } counters.proofPaths[static_cast(report.path)].fetch_add(1, std::memory_order_relaxed); ++d.cacheHits; - state->resourceCache.Touch(recipe.key); + state->resourceCache.TouchAging(recipe.key, hit->resources->CacheTouchedAt()); // The recipe's hash names the words it was attached with, not a data-only hit's: that hit // refreshes by the per-word compare (RefreshData keeps the template's own hash exact, so a // later exact hit of a sibling variant compares correctly against it). diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp index 8a3cb853da14..cd010a921eaa 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp @@ -28,6 +28,8 @@ class BdaResources { std::span TableBytes() const; bool TableGuardCurrent(VkDevice device, std::span ranges); VkDescriptorBufferInfo Fault() const; + VkDeviceAddress TableAddress() const; + VkDeviceAddress FaultAddress() const; void CheckFault() const; void CheckUse(const BdaResources* record) const; void NoteUse(std::uint64_t serial); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp new file mode 100644 index 000000000000..979794b46453 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -0,0 +1,375 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_BINDLESSHEAP_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_BINDLESSHEAP_HPP + +#include "prx/libSceAgcDriver/Graphics/include/Context.hpp" +#include "RuntimeAbi.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ShaderRecompiler { +struct StagePushPlacement; +struct DescriptorBinding; +} + +namespace AgcDriver::Graphics { + +struct HeapBindingRoots { + bool workgroupAddress = false; + bool gdsAddress = false; + bool faultAddress = false; + bool pixelLds = false; + bool meshWindow = false; + bool scratchPool = false; +}; + +class Buffer; +class Recorder; +class HeapSlotOwner; +class Sampler; +class StorageTexture; +class Texture; + +class BindlessHeap { +public: + explicit BindlessHeap(const Context& context); + ~BindlessHeap(); + BindlessHeap(const BindlessHeap&) = delete; + BindlessHeap& operator=(const BindlessHeap&) = delete; + + static BindlessHeap& For(const Context& context); + static BindlessHeap* Existing(const Context& context); + static void Release(VkDevice device); + static bool Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties); + + bool DescriptorHeapMode() const { return resourceHeap != nullptr; } + VkDeviceSize ImageHeapStride() const { return imageHeapStride; } + void BindDescriptorHeaps(VkCommandBuffer commands) const; + bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, const HeapBindingRoots& roots, + const ShaderRecompiler::StagePushPlacement* placement = nullptr, + const std::vector* bindings = nullptr, std::uint32_t workgroupAddressOffset = 0u); + void WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes); + void WriteMeshWindowBuffer(VkDeviceAddress address, VkDeviceSize bytes); + std::pair DataLocation(VkDeviceAddress address) const; + std::span DataWords(VkDeviceAddress address, std::size_t words) const; + std::uint32_t EmbeddedSamplerCount() const; + + std::optional TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout); + std::optional StorageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view); + std::optional ViewSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout = VK_IMAGE_LAYOUT_GENERAL); + void ReleaseSlots(const HeapSlotOwner* owner); + std::uint32_t SlotGeneration(std::uint32_t slot) const; + const Texture* SlotTexture(std::uint32_t kind, std::uint32_t slot) const; + bool SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const HeapSlotOwner* owner, VkImageView view) const; + std::optional SamplerSlot(const std::shared_ptr& sampler); + std::optional PinnedSamplerSlot(const std::shared_ptr& sampler); + std::uint32_t SamplerGeneration(std::uint32_t slot) const; + std::uint64_t SlotSerial() const { return slotSerial.load(std::memory_order_acquire); } + bool GenerationsCurrent(std::span slots, std::span slotGenerations, + std::span samplerSlots, std::span samplerGenerations) const; + std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); + static bool NearlyFull(); + static std::uint32_t ImageSlotCapacity(); + std::uint32_t ImageSlots() const { return slotCap; } + std::uint32_t TouchSlots(std::span slots, std::span samplerSlots, std::uint32_t touched) const; + + struct DataSpan { + std::uint32_t offset = 0; + std::span words; + VkDeviceAddress address = 0; + }; + DataSpan Allocate(std::size_t words); + static void Write(const DataSpan& span, std::span words); + class SpanScope { + public: + explicit SpanScope(const BindlessHeap& heap); + ~SpanScope(); + SpanScope(const SpanScope&) = delete; + SpanScope& operator=(const SpanScope&) = delete; + + private: + friend class BindlessHeap; + const BindlessHeap& heap; + bool acquired; + }; + struct TableMark { + std::uint32_t block = 0; + std::uint32_t offset = 0; + std::uint32_t sizeClass = 0; + VkDeviceAddress address = 0; + }; + std::optional AllocateTable(const SpanScope& held, std::size_t words, TableMark& mark); + void RetireTable(const SpanScope& held, TableMark& mark); + void NoteTableKept(const SpanScope& held); + static constexpr std::size_t TableBlockBytes = 1u << 20u; + static constexpr std::uint32_t TableClasses = 16u; + + static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); + void Submitted(Recorder& recorder, std::uint64_t serial); + void RecorderDestroyed(Recorder& recorder); + bool TakeSlotPressure(); + + struct Counts { + std::uint64_t encodes = 0, encodedCopies = 0; + std::uint64_t slotsFreed = 0, slotsEvicted = 0, evictionWaits = 0; + std::uint64_t spanPeakBytes = 0, imageSlotsHeld = 0; + std::uint64_t spansWritten = 0, spansKept = 0; + std::uint64_t slotPressureSubmits = 0, samplersEvicted = 0; + std::uint64_t poolBytes = 0, poolBatchPeakBytes = 0, poolBlocksMade = 0, poolBlocksRecycled = 0, poolBlocksFreed = 0, poolBlocksHeld = 0, poolBlockBytes = 0; + Counts& operator+=(const Counts& other); + }; + Counts Statistics() const; + static Counts TotalStatistics(); + + static constexpr std::size_t PoolBlockBytes = 2u << 20u; + static constexpr std::size_t PoolIdleBytes = 32u << 20u; + +private: + Context context; + std::unique_ptr resourceHeap; + std::unique_ptr samplerHeap; + VkDeviceSize imageHeapStride = 0; + VkDeviceSize samplerHeapStride = 0; + VkDeviceSize resourceHeapUsed = 0; + VkDeviceSize pixelLdsHeapOffset = 0; + VkDeviceSize meshWindowHeapOffset = 0; + VkDeviceSize samplerHeapUsed = 0; + PFN_vkWriteResourceDescriptorsEXT writeResourceDescriptors = nullptr; + PFN_vkWriteSamplerDescriptorsEXT writeSamplerDescriptors = nullptr; + std::vector encodeScratch; + void writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImageView view, VkImageLayout layout); + void writeSamplerSlot(std::uint32_t slot, VkSampler sampler); + void writeBufferDescriptor(VkDeviceSize offset, VkDeviceAddress address, VkDeviceSize bytes, const char* what); + struct PoolBlock { + std::unique_ptr buffer; + std::byte* data = nullptr; + VkDeviceAddress address = 0; + std::size_t bytes = 0; + std::size_t cursor = 0; + Recorder* recorder = nullptr; + std::uint64_t serial = 0; + bool open = false; + }; + std::vector poolBlocks; + struct TableBlock { + std::unique_ptr buffer; + std::byte* data = nullptr; + VkDeviceAddress address = 0; + std::size_t bytes = 0; + std::size_t cursor = 0; + }; + std::vector tableBlocks; + std::array>, TableClasses> tableFree; + struct RetiredTable { + TableMark mark; + Recorder* recorder = nullptr; + std::uint64_t serial = 0; + bool submitted = false; + }; + std::deque retiredTables; + std::size_t tableShared = 0; + std::size_t makeTableBlockLocked(std::size_t bytes); + void reclaimTablesLocked(); + std::size_t poolCurrent = ~std::size_t{0}; + std::uint32_t poolAlignment = 256; + std::size_t poolBatchBytes = 0; + std::size_t takePoolBlockLocked(std::size_t bytes); + DataSpan allocateLocked(std::size_t words); + bool poolBlockDoneLocked(PoolBlock& block); + void trimPoolLocked(); + mutable std::mutex mutex; + mutable std::mutex spanMutex; + mutable std::atomic spanOwner{}; + struct EmbeddedSampler { + VkSamplerCreateInfo info{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + VkSamplerReductionModeCreateInfoEXT reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT}; + std::shared_ptr heapSampler; + std::uint32_t slot = ~0u; + }; + mutable std::mutex embeddedMutex; + std::map, EmbeddedSampler> embeddedSamplers; + std::uint32_t embeddedSamplerCount = 0; + std::optional embeddedSamplerMapping(const ShaderRecompiler::DescriptorBinding& binding, std::size_t element); + std::atomic slotSerial{1}; + struct ImageSlotKey { + std::uint32_t kind; + const HeapSlotOwner* owner; + VkImageView view; + VkImageLayout layout; + bool operator==(const ImageSlotKey&) const = default; + }; + struct ImageSlotKeyHash { + std::size_t operator()(const ImageSlotKey& key) const { + constexpr std::size_t HashSalt = 0x9e3779b97f4a7c15ull; + std::size_t seed = 0; + const auto mix = [&seed](std::size_t value) { seed ^= value + HashSalt + (seed << 6u) + (seed >> 2u); }; + mix(key.kind); + mix(static_cast(key.layout)); + mix(std::hash{}(key.owner)); + mix(std::hash{}(reinterpret_cast(key.view))); + return seed; + } + }; + std::unordered_map imageSlots; + std::unordered_map> ownerSlots; + struct SlotPool { + std::uint32_t next = 0; + std::uint32_t limit = 0; + std::vector free; + std::unique_ptr[]> generations; + void Configure(std::uint32_t first, std::uint32_t slots); + void Retire(std::uint32_t slot); + std::optional Take(); + void Free(std::uint32_t slot); + std::size_t Unused() const; + std::uint32_t Generation(std::uint32_t slot) const; + }; + struct SlotOwner { + const Texture* texture = nullptr; + ImageSlotKey key{}; + }; + std::vector owners; + SlotPool imagePool; + SlotPool samplerPool; + std::uint32_t slotCap = 0; + std::unique_ptr[]> slotUses; + std::atomic useEpoch{1}; + struct RetiringSlot { + std::uint32_t slot = 0; + std::uint64_t serial = 0; + bool sampler = false; + Recorder* recorder = nullptr; + }; + std::deque retiring; + std::size_t retiringAssigned = 0; + std::size_t retiringSamplers = 0; + std::size_t samplerRetiringAssigned = 0; + std::uint32_t evictScanEpoch = 0; + std::uint32_t samplerEvictScanEpoch = 0; + std::vector samplerOwners; + std::vector samplerPinned; + std::unique_ptr[]> samplerUses; + std::atomic pressured{false}; + Recorder* submitter = nullptr; + void touchLocked(std::uint32_t slot) const; + void touchSamplerLocked(std::uint32_t slot) const; + void evictLocked(std::uint32_t idleSubmissions); + void evictSamplersLocked(std::uint32_t idleSubmissions); + std::optional samplerSlot(const std::shared_ptr& sampler, bool pin); + std::size_t imageRetiring() const { return retiring.size() - retiringSamplers; } + bool reclaimLocked(bool wait); + std::optional imageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout, Texture* texture); + SlotOwner& claimSlotLocked(const ImageSlotKey& key, std::uint32_t slot); + void freeSlotLocked(std::uint32_t slot); + const SlotOwner* ownerLocked(std::uint32_t slot) const; + std::unordered_map samplerSlots; + std::unordered_set absentSlots; + bool refused = false; + void noteRefusedLocked(const char* what, std::uint32_t margin); + void noteTakenLocked(); + void noteSamplerTakenLocked(); + void noteReleasedLocked(); + std::uint32_t imageMargin() const; + bool roomLocked() const; + Counts counts; +}; + +class HeapSlotOwner { +public: + HeapSlotOwner(const HeapSlotOwner&) = delete; + HeapSlotOwner& operator=(const HeapSlotOwner&) = delete; + +protected: + HeapSlotOwner() = default; + ~HeapSlotOwner() = default; + void ReleaseHeapSlots(const Context& context) noexcept { + if (heapSlotted.exchange(false, std::memory_order_acq_rel)) { + if (auto* heap = BindlessHeap::Existing(context)) heap->ReleaseSlots(this); + } + } + +private: + friend class BindlessHeap; + mutable std::atomic heapSlotted{false}; +}; + +bool GpuHeapEnabled(); +void SetDescriptorHeapDevice(bool available); +bool DescriptorHeapEnabled(); +bool ChooseUniformConstantBuffers(bool standardLayout, const VkPhysicalDeviceLimits& limits); +bool UniformConstantBuffersEnabled(); +bool DescriptorHeapMappable(std::span spirv, const HeapBindingRoots& roots, std::pair* refused = nullptr); +void NoteHeapComputeStage(); +std::uint64_t HeapComputeStages(); +void NoteImageTableBuild(); +std::uint64_t ImageTableBuilds(); +void NoteDataAddressPush(); +void NotePushedUserDataKeep(); +void NoteUserWordsRewrite(std::size_t blockWords, std::size_t userWords); +std::uint64_t PushedUserDataKeeps(); +void NoteEmptyResourceSet(); +std::uint64_t EmptyResourceSets(); +std::uint64_t DataAddressPushes(); +std::uint64_t EmbeddedSamplerMappings(); +enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, DepthTransfer, StagedMerge, FirstSampleCopy, ChangedCopy, Count }; +enum class HeapExcluded : std::uint8_t { Draw, Dispatch, Count }; +enum class HeapStageReason : std::uint8_t { + Heap, + Disabled, + Excluded, + Count +}; +void NoteHeapStageReason(HeapStageReason reason); +void NoteHeapRecord(bool compute, bool heap); +void NoteHeapExcluded(HeapExcluded reason); +std::uint64_t HeapExcludedCount(HeapExcluded reason); +std::uint64_t HeapStageReasons(HeapStageReason reason); +void NoteCpuBufferCopy(std::uint64_t bytes); +void NoteCommandBufferBegun(VkCommandBuffer commands); +void CmdPushConstants(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, + std::uint32_t offset, std::uint32_t size, const void* values); +void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, + std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site); +void CmdPushDescriptorSet(PFN_vkCmdPushDescriptorSetKHR push, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t set, + std::uint32_t writeCount, const VkWriteDescriptorSet* writes, SetBindSite site); +std::uint64_t DescriptorHeapBinds(); +inline constexpr std::uint32_t HeapPassSampledKind = ShaderRecompiler::RuntimeAbi::FirstImageBinding; +inline constexpr std::uint32_t HeapPassStorageKind = ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding; +inline constexpr VkSpirvResourceTypeFlagsEXT HeapPassStorageBuffers = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT; +inline constexpr VkSpirvResourceTypeFlagsEXT HeapPassStorageImages = VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; +class HeapPassSlots : public HeapSlotOwner { +public: + explicit HeapPassSlots(const Context& context) : context(context) {} + ~HeapPassSlots() { ReleaseHeapSlots(context); } + void Release() noexcept { ReleaseHeapSlots(context); } + +private: + Context context; +}; +bool HeapPassesActive(const Context& context); +VkDescriptorSetAndBindingMappingEXT HeapPushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset, VkSpirvResourceTypeFlagsEXT resources = HeapPassStorageBuffers); +VkDescriptorSetAndBindingMappingEXT HeapPushIndexMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, + std::uint32_t pushOffset); +VkDescriptorSetAndBindingMappingEXT HeapPushSampledImageMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset, const VkSamplerCreateInfo& embeddedSampler); +VkPipeline CreateHeapStagePipeline(const Context& context, VkGraphicsPipelineCreateInfo info, std::uint32_t stage, std::span mappings, const char* what); +VkPipeline CreateHeapComputePipeline(const Context& context, VkComputePipelineCreateInfo info, std::span mappings); +VkPipeline CreateHeapGraphicsPipeline(const Context& context, VkGraphicsPipelineCreateInfo info, std::span mappings); +void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values, std::uint32_t offset = 0); +void CmdPushHeapData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values); +std::uint64_t NotePushDataWritten() noexcept; +std::uint64_t PushDataMark() noexcept; + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp index 14d870463dd7..5e0f81192529 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp @@ -66,6 +66,8 @@ class BufferPool { // The size a buffer for `bytes` is created with: its size class, or `bytes` itself when large. static std::size_t Capacity(std::size_t bytes); static VkBufferUsageFlags Usage(VkBufferUsageFlags usage, VkMemoryPropertyFlags properties); + static bool ForceAddresses(); + static void SetForceAddresses(bool force); VkDeviceMemory AllocateMemory(const VkMemoryAllocateInfo& allocation, const char* operation, std::optional hostType = std::nullopt, std::uint32_t* allocatedType = nullptr, bool newImage = false); ImageAllocation AllocateImage(const Context& context, VkImage image, const VkImageCreateInfo& imageInfo, const char* operation, bool newImage, bool budgeted); std::size_t ImageSlabBlocks(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index 96f07a98df42..a1c09bf7bd69 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -8,6 +8,7 @@ #include #include "prx/libc/include/PrimedSharedMutex.hpp" #include +#include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" #include #include #include @@ -53,8 +54,16 @@ class PipelineCacheSynchronization { mutable PrimedSharedMutex mutex; }; -inline void Require(bool condition, const std::string& reason) { - if (!condition) throw std::runtime_error("AGC graphics: " + reason); +[[noreturn, gnu::cold, gnu::noinline]] inline void RequireFailed(const std::string& reason) { + throw std::runtime_error("AGC graphics: " + reason); +} + +[[noreturn, gnu::cold, gnu::noinline]] inline void RequireFailed(const char* reason) { + throw std::runtime_error(std::string("AGC graphics: ") + reason); +} + +[[gnu::always_inline]] inline void Require(bool condition, const std::string& reason) { + if (!condition) [[unlikely]] RequireFailed(reason); } inline std::function& DeviceLostHook() { @@ -88,8 +97,8 @@ inline VkShaderModule CreateShaderModule(PFN_vkCreateShaderModule create, VkDevi return module; } -inline void Require(bool condition, const char* reason) { - if (!condition) throw std::runtime_error(std::string("AGC graphics: ") + reason); +[[gnu::always_inline]] inline void Require(bool condition, const char* reason) { + if (!condition) [[unlikely]] RequireFailed(reason); } struct DescriptorRejected : std::runtime_error { @@ -196,8 +205,52 @@ struct DeviceFunctions { // Per-thread count of vkGetDeviceProcAddr lookups made through Context::Function (the [vk] line). std::uint64_t& DeviceProcLookups(); +class DeviceFunctionCache { +public: + PFN_vkVoidFunction Find(const char* name, PFN_vkGetDeviceProcAddr proc) const { + for (std::size_t probe = 0, slot = slotOf(name); probe < MaxProbes; ++probe, slot = (slot + 1u) & (Slots - 1u)) { + const auto& entry = entries[slot]; + const auto* stored = entry.name.load(std::memory_order_acquire); + if (stored == nullptr) return nullptr; + if (stored != name) continue; + const auto function = entry.function.load(std::memory_order_acquire); + return function != nullptr && entry.proc.load(std::memory_order_relaxed) == proc ? function : nullptr; + } + return nullptr; + } + + void Keep(const char* name, PFN_vkGetDeviceProcAddr proc, PFN_vkVoidFunction function) { + for (std::size_t probe = 0, slot = slotOf(name); probe < MaxProbes; ++probe, slot = (slot + 1u) & (Slots - 1u)) { + auto& entry = entries[slot]; + const char* expected = nullptr; + if (!entry.name.compare_exchange_strong(expected, name, std::memory_order_acq_rel) && expected != name) continue; + if (expected == name) return; + entry.proc.store(proc, std::memory_order_relaxed); + entry.function.store(function, std::memory_order_release); + return; + } + } + +private: + static constexpr std::size_t Slots = 2048; + static constexpr std::size_t MaxProbes = 32; + struct Entry { + std::atomic name{nullptr}; + std::atomic proc{nullptr}; + std::atomic function{nullptr}; + }; + static std::size_t slotOf(const char* name) { + return static_cast((reinterpret_cast(name) >> 3u) * 0x9e3779b97f4a7c15ull >> 40u) & (Slots - 1u); + } + std::array entries{}; +}; + inline constexpr std::size_t EmptyBufferBytes = 16; +inline VkPipelineCreateFlags2CreateInfoKHR DescriptorHeapFlags(VkPipelineCreateFlags2KHR flags = 0, const void* next = nullptr) { + return {VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR, next, flags | VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT}; +} + struct Context { VkDevice device; VkPhysicalDevice physical; @@ -251,6 +304,8 @@ struct Context { GraphicsPipelineCache* graphicsPipelines = nullptr; // Batches GPU work across guest commands (see Recorder); null before the device finished setup. Recorder* recorder = nullptr; + bool descriptorHeap = false; + VkPhysicalDeviceDescriptorHeapPropertiesEXT descriptorHeapProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT}; // Per-device caches of the immutable descriptor objects a ShaderResources build needs (set // layouts, descriptor pools, samplers); null (tests) means every build makes and destroys its own. DescriptorCache* descriptorCache = nullptr; @@ -282,6 +337,7 @@ struct Context { const std::vector>* copiedWriters = nullptr; // The device's resolved entry points (see DeviceFunctions); null until the device set up. const DeviceFunctions* functions = nullptr; + DeviceFunctionCache* functionCache = nullptr; // VK_EXT_descriptor_indexing with non-uniform sampled/storage image array indexing enabled // (bindless image tables in graphics stages). bool descriptorIndexing = false; @@ -489,10 +545,21 @@ struct Context { template TFunction lookup(const char* name) const { Require(deviceProc != nullptr, "missing Vulkan device function resolver"); + const auto* cache = functions != nullptr ? functionCache : nullptr; + if (cache != nullptr) { + if (const auto cached = cache->Find(name, deviceProc); cached != nullptr) return reinterpret_cast(cached); + } + if (descriptorHeap) { + if (const auto hooked = DescriptorHeapObjectFunction(device, deviceProc, name); hooked != nullptr) { + if (cache != nullptr) functionCache->Keep(name, deviceProc, hooked); + return reinterpret_cast(hooked); + } + } ++DeviceProcLookups(); - const auto function = reinterpret_cast(deviceProc(device, name)); + const auto function = deviceProc(device, name); if (function == nullptr) throw std::runtime_error(std::string("AGC graphics: missing Vulkan function: ") + name); - return function; + if (cache != nullptr) functionCache->Keep(name, deviceProc, function); + return reinterpret_cast(function); } template diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp new file mode 100644 index 000000000000..a765f9356227 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp @@ -0,0 +1,38 @@ +#ifndef AGC_GRAPHICS_DESCRIPTOR_HEAP_OBJECTS_HPP +#define AGC_GRAPHICS_DESCRIPTOR_HEAP_OBJECTS_HPP + +#include + +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +struct ImageViewRecord { + VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + VkImageViewUsageCreateInfo usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; + VkImageViewMinLodCreateInfoEXT minLod{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT}; + bool hasUsage = false; + bool hasMinLod = false; + std::uint64_t generation = 0; + const VkImageViewCreateInfo* Chain(); +}; + +struct SamplerRecord { + VkSamplerCreateInfo info{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + VkSamplerReductionModeCreateInfo reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO}; + bool hasReduction = false; + const VkSamplerCreateInfo* Chain(); +}; + +PFN_vkVoidFunction DescriptorHeapObjectFunction(VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name); +std::optional FindImageView(VkDevice device, VkImageView view); +std::optional FindSampler(VkDevice device, VkSampler sampler); +bool CopyEncodedImageView(VkDevice device, VkImageView view, std::uint32_t key, std::span target); +void KeepEncodedImageView(VkDevice device, VkImageView view, std::uint64_t generation, std::uint32_t key, std::span bytes); + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp index 8f74ad5596c4..a58754ad4ece 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp @@ -132,6 +132,7 @@ struct DrawRecipeOutcome { DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, const DrawRecipe& recipe, const DrawTraceContext* trace = nullptr); // Whether recorded draws build recipes and draw-cache hits use them (APS5_NO_DRAW_RECIPE unset). bool DrawRecipes(); +std::uint64_t DrawContentKeysBuilt(); // How an indirect draw's records were read, for the [draws] line (APS5_PROFILE_DRAW): Gpu is // vkCmdDrawIndirect from the host import; every other value names why the CPU read them instead, diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp index 4f973ff75e27..ecf84eaeabd9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp @@ -6,6 +6,7 @@ namespace AgcDriver::Graphics { class Recorder; +class Texture; class FirstSampleCopy { public: @@ -14,6 +15,7 @@ class FirstSampleCopy { FirstSampleCopy(const FirstSampleCopy&) = delete; FirstSampleCopy& operator=(const FirstSampleCopy&) = delete; + void Record(Recorder& recorder, Texture& source); void Record(Recorder& recorder, VkImageView source, VkImageLayout layout); VkImage Image() const { return image; } @@ -33,6 +35,7 @@ class FirstSampleCopy { VkShaderModule vertex = VK_NULL_HANDLE; VkShaderModule fragment = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; }; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp index 672a39649356..69d20e25bce0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp @@ -32,6 +32,8 @@ class GpuColorTransfer { VkDescriptorSet descriptorSet = VK_NULL_HANDLE; VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; + VkBufferUsageFlags addressUsage = 0; // Guest bytes in host memory, and the device-local copies the conversion shader works on. std::unique_ptr tiled; std::unique_ptr tiledDevice; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index 79691576d59a..73b7cbefd7a4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -332,6 +332,8 @@ struct AddressCopy { }; std::string AddressCopyOverflow(std::vector copies, std::uint64_t limit); +VkDeviceSize GuestBufferViewAlignment(const VkPhysicalDeviceLimits& limits); + class AddressCopyCounters { public: struct Totals { @@ -397,7 +399,9 @@ class GuestBufferMemory { void Upload(bool addressable); void UploadPrepare(bool addressable); void UploadFinish(bool addressable, std::optional> htileClear = std::nullopt); - VkDescriptorBufferInfo Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const; + VkDescriptorBufferInfo Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, VkDeviceAddress* handleAddress = nullptr) const; + std::optional TryDescriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, std::string* failure = nullptr, VkDeviceAddress* handleAddress = nullptr) const; + std::optional ImportedView(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const; static std::uint64_t ViewBytes(std::uint64_t bytes, std::uint32_t adjustment); std::vector AddressRanges() const; // The BDA table of the cached address space when it serves this upload alone (an address-based @@ -599,6 +603,7 @@ class GuestBufferMemory { bool overlayCandidate(const Region& inside, bool readOnly) const; void resolveOverlays(); bool bindableInPlace(std::uint64_t offset, bool addressable) const; + VkDeviceSize viewAlignment() const; // Records the import-to-buffer copies of the given gpuCopy regions into the open batch, with // the barriers that order them after earlier recorded writes and before the shaders reading them. void recordGpuCopies(std::span copies, bool addressable); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp index 34ca9b1ddd4e..065b919bdb00 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp @@ -20,6 +20,14 @@ namespace AgcDriver::Graphics { +class HeapSlotOwner; + +struct MultisampleStorage { + VkImageView view = VK_NULL_HANDLE; + const HeapSlotOwner* owner = nullptr; + std::shared_ptr keep; +}; + class StorageTexture; class Texture; struct GuestTextureResource; @@ -112,7 +120,7 @@ VkImageView MultisampleTargetView(const Context& context, const ColorTarget& tar void PrepareMultisampleTargetForDraw_nid_no_patch(const Context& context, const ColorTarget& target); void KeepMultisampleTarget_nid_no_patch(const std::shared_ptr& owner); void MaterializeMultisampleTargetClear(const Context& context, const ColorTarget& target); -VkImageView MultisampleTargetStorageView(const Context& context, const GuestTextureResource& resource, bool uintStorage = false); +MultisampleStorage MultisampleTargetStorageView(const Context& context, const GuestTextureResource& resource, bool uintStorage = false); bool MultisampleTargetStorable(const Context& context, const ColorTarget& target); void ResolveMultisampleTarget(const Context& context, const ColorTarget& source, StorageTexture& destination, VkImageView destinationView); bool MultisampledColorFillAbsorbs(std::uint64_t address, std::size_t bytes, std::uint32_t pattern); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp new file mode 100644 index 000000000000..09f124c97ec0 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp @@ -0,0 +1,87 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +template +class PendingRangeIndex { +public: + struct Entry { + std::uint64_t begin = 0; + std::uint64_t end = 0; + Item item{}; + std::size_t position = 0; + }; + + void Insert(std::uint64_t begin, std::uint64_t end, Item item, std::size_t position) { + const auto at = std::upper_bound(entries.begin(), entries.end(), std::pair{begin, position}, [](const std::pair& key, const Entry& entry) { return key.first != entry.begin ? key.first < entry.begin : key.second < entry.position; }); + const auto index = static_cast(at - entries.begin()); + entries.insert(at, {begin, end, item, position}); + reach.insert(reach.begin() + static_cast(index), 0); + recompute(index); + } + + bool Erase(std::uint64_t begin, const Item& item) { + auto at = std::lower_bound(entries.begin(), entries.end(), begin, [](const Entry& entry, std::uint64_t value) { return entry.begin < value; }); + for (; at != entries.end() && at->begin == begin; ++at) { + if (!(at->item == item)) continue; + const auto index = static_cast(at - entries.begin()); + entries.erase(at); + reach.erase(reach.begin() + static_cast(index)); + recompute(index); + return true; + } + return false; + } + + const std::vector& Entries() const { return entries; } + + template + bool AnyOverlapping(std::uint64_t address, std::size_t bytes, Visit&& visit) const { + if (bytes == 0 || entries.empty()) return false; + const auto end = bytes > std::numeric_limits::max() - address ? std::numeric_limits::max() : address + bytes; + auto index = static_cast(std::lower_bound(entries.begin(), entries.end(), end, [](const Entry& entry, std::uint64_t value) { return entry.begin < value; }) - entries.begin()); + while (index != 0) { + --index; + if (reach[index] <= address) break; + const auto& entry = entries[index]; + if (entry.end > address && entry.begin < end && visit(entry.item)) return true; + } + return false; + } + + template + const Entry* FirstByPosition(std::uint64_t address, std::size_t bytes, Match&& match) const { + const Entry* first = nullptr; + if (bytes == 0 || entries.empty()) return nullptr; + const auto end = bytes > std::numeric_limits::max() - address ? std::numeric_limits::max() : address + bytes; + auto index = static_cast(std::lower_bound(entries.begin(), entries.end(), end, [](const Entry& entry, std::uint64_t value) { return entry.begin < value; }) - entries.begin()); + while (index != 0) { + --index; + if (reach[index] <= address) break; + const auto& entry = entries[index]; + if (entry.end > address && entry.begin < end && match(entry.item) && (first == nullptr || entry.position < first->position)) first = &entry; + } + return first; + } + +private: + void recompute(std::size_t from) { + std::uint64_t furthest = from == 0 ? 0 : reach[from - 1]; + for (std::size_t index = from; index < entries.size(); ++index) { + furthest = std::max(furthest, entries[index].end); + reach[index] = furthest; + } + } + + std::vector entries; + std::vector reach; +}; + +} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp index aba72c0e6263..214ecbc9e800 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp @@ -48,6 +48,7 @@ class Pipeline { Pipeline(const Pipeline&) = delete; Pipeline& operator=(const Pipeline&) = delete; VkPipelineLayout Layout() const; + bool DescriptorHeap() const { return descriptorHeap; } std::shared_ptr AcquireFramebuffer(std::span targets, std::span> owners, VkExtent2D extent, std::uint32_t layers = 1); // Begins the render pass on the framebuffer, binds the pipeline and sets its dynamic state. void Begin(CommandState& recording, const Framebuffer& framebuffer, VkExtent2D extent, const State& state, const State* masked = nullptr) const; @@ -64,6 +65,7 @@ class Pipeline { bool SampleLocationsEnabled() const { return sampleLocationsEnabled; } VkExtent2D HostSampleLocationGrid() const { return sampleLocationGrid; } void PushConstants(VkCommandBuffer commands, VkShaderStageFlags stages, std::span bytes) const; + std::span PushPlacements() const { return pushPlacements; } // Forgets the Vulkan objects without destroying them: for entries of a device that is already gone. void Abandon() noexcept; @@ -83,6 +85,7 @@ class Pipeline { void setViewports(CommandState& recording, const State& state) const; Context context; std::vector _modules; + std::vector pushPlacements; VkPipelineLayout layout = VK_NULL_HANDLE; VkRenderPass renderPass = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; @@ -98,6 +101,7 @@ class Pipeline { std::uint32_t dynamicSlots = 0; std::shared_ptr optimized; bool dynamicRendering = false; + bool descriptorHeap = false; VkFormat depthFormat = VK_FORMAT_UNDEFINED; VkImageLayout attachmentLayout = VK_IMAGE_LAYOUT_UNDEFINED; std::vector colorSlots; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp index fcd61045697d..18ff01097e70 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp @@ -42,7 +42,7 @@ struct OptimizedPipeline { void Schedule(); }; -VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPipelineCreateInfo& info, const VkPipelineRenderingCreateInfoKHR& rendering, const VkPipelineLayoutCreateInfo& layout, const PipelineLibraryKeys& keys, std::shared_ptr* optimized = nullptr, bool partsOnly = false, std::span modules = {}); +VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPipelineCreateInfo& info, const VkPipelineRenderingCreateInfoKHR& rendering, const VkPipelineLayoutCreateInfo& layout, const PipelineLibraryKeys& keys, bool descriptorHeap, std::shared_ptr* optimized = nullptr, bool partsOnly = false, std::span modules = {}); void WaitForOptimizedPipelines(VkDevice device); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp index 730ad1bf7730..7fc67370198a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp @@ -81,6 +81,27 @@ class PipelineSpecialization { [[nodiscard]] const VkSpecializationInfo* Info() const { return entries.empty() ? nullptr : &info; } + void PlaceHeapImageSlots(std::uint32_t slots) { + for (auto& constant : values) { + if (constant.id == ShaderRecompiler::PipelineSpecialization::HeapImageSlots) constant.value = slots; + } + } + + void PlacePushData(const ShaderRecompiler::StagePushPlacement& placement) { + namespace Ids = ShaderRecompiler::PipelineSpecialization; + for (auto& constant : values) { + if (constant.id == Ids::PushedDataBase) constant.value = placement.pushed.base; + if (constant.id == Ids::PushedDataCount) constant.value = placement.pushed.count; + if (constant.id >= Ids::BufferRootPosition && constant.id < Ids::BufferRootPosition + Ids::BufferRootCount) constant.value = placement.bufferRoots[constant.id - Ids::BufferRootPosition]; + if (constant.id == Ids::BufferOverflowPosition) constant.value = placement.bufferOverflow; + if (constant.id >= Ids::RootItemPositionBase && constant.id < Ids::RootItemPositionBase + ShaderRecompiler::RuntimeAbi::RootItemCount) { + const auto item = constant.id - Ids::RootItemPositionBase; + constant.value = placement.items[item]; + Require(item == static_cast(ShaderRecompiler::RuntimeAbi::RootItem::UserData) || constant.value != ShaderRecompiler::RuntimeAbi::NoPushPosition, "a stage reads a root item its pipeline's push layout does not hold"); + } + } + } + private: void describe(std::span constants) { entries.reserve(constants.size()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp new file mode 100644 index 000000000000..51232994333b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp @@ -0,0 +1,52 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_PUSHDATASHADOW_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_PUSHDATASHADOW_HPP + +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +template +class PushDataShadow { +public: + static constexpr std::size_t Unit = sizeof(VkDeviceAddress); + static_assert(Bytes % Unit == 0); + + std::pair Changed(VkCommandBuffer target, std::uint64_t currentMark, std::span next) { + if (target != commands || currentMark != mark) { + commands = target; + std::memcpy(bytes.data(), next.data(), Bytes); + return {0, Bytes}; + } + std::size_t first = Bytes; + std::size_t end = 0; + for (std::size_t offset = 0; offset < Bytes; offset += Unit) { + if (std::memcmp(next.data() + offset, bytes.data() + offset, Unit) == 0) continue; + first = std::min(first, offset); + end = offset + Unit; + } + if (first >= end) return {0, 0}; + std::memcpy(bytes.data() + first, next.data() + first, end - first); + return {first, end}; + } + + void Pushed(std::uint64_t newMark) { mark = newMark; } + +private: + VkCommandBuffer commands = VK_NULL_HANDLE; + std::uint64_t mark = 0; + std::array bytes{}; +}; + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index 93c0b2874552..e7a9ea6c31c9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -221,6 +221,7 @@ class Recorder { void FlushDeferredReleases(); static constexpr std::size_t KeptBytesBudget = std::size_t{512} << 20u; void BoundKeptBytes(); + void BoundDrawBatch(); std::size_t InFlightKeptBytes() const { return inFlightKeptBytes; } enum class SnapshotUse : std::uint8_t { Storage, Vertex, Index16, Index32, Index16Restart, Index32Restart, PaddedVertex }; static constexpr std::size_t DrawSnapshotBudget = std::size_t{1024} << 20u; @@ -539,6 +540,7 @@ class Recorder { // validation instead of one per run, and every test sees the same snapshot (design13 R1's p0). using WriteRanges = std::vector>; static std::shared_ptr PendingWriteSnapshot(); + static bool ReadsSettled(std::span> ranges, const WriteRanges* before); static bool SnapshotOverlaps(const WriteRanges* snapshot, std::uint64_t address, std::size_t bytes); // A label behind pending completions (CPU write-backs the label must not precede): stored to // guest memory by a completion action appended to the open batch, or to the newest in-flight @@ -925,9 +927,14 @@ class Recorder { int meshArgumentState = 0; VkPipelineLayout meshArgumentLayout = VK_NULL_HANDLE; VkPipeline meshArgumentPipeline = VK_NULL_HANDLE; + VkPipeline meshArgumentHeapPipeline = VK_NULL_HANDLE; int changedCopyState = 0; VkPipelineLayout changedCopyLayout = VK_NULL_HANDLE; VkPipeline changedCopyPipeline = VK_NULL_HANDLE; + VkPipeline changedCopyHeapPipeline = VK_NULL_HANDLE; + VkPipeline createPushOnlyHeapPipeline(const VkComputePipelineCreateInfo& info) const; + void bindPushOnlyPipeline(VkCommandBuffer commands, VkPipeline pipeline, VkPipeline heapPipeline) const; + void pushOnlyParameters(VkCommandBuffer commands, VkPipeline heapPipeline, VkPipelineLayout layout, std::uint32_t bytes, const void* values) const; int boundChangedCopyState = 0; VkDescriptorSetLayout boundChangedCopySetLayout = VK_NULL_HANDLE; VkPipelineLayout boundChangedCopyLayout = VK_NULL_HANDLE; @@ -944,6 +951,7 @@ class Recorder { int dispatchArgumentState = 0; VkPipelineLayout dispatchArgumentLayout = VK_NULL_HANDLE; VkPipeline dispatchArgumentPipeline = VK_NULL_HANDLE; + VkPipeline dispatchArgumentHeapPipeline = VK_NULL_HANDLE; // BeginGpuTiming on the open batch without Commands() (RecordStore times its own run, which // Commands() would close). std::uint32_t beginTiming(std::uint64_t key); @@ -963,7 +971,6 @@ class Recorder { PFN_vkCmdEndQuery cmdEndQuery = nullptr; PFN_vkCmdResetQueryPool cmdResetQueryPool = nullptr; PFN_vkCmdCopyQueryPoolResults cmdCopyQueryPoolResults = nullptr; - PFN_vkCmdPushConstants cmdPushConstants = nullptr; PFN_vkCmdDispatch cmdDispatch = nullptr; template TFunction function(TFunction resolved, FunctionName name) const { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ResidentMirror.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ResidentMirror.hpp index 87e0619b8ba3..76500a103ec7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ResidentMirror.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ResidentMirror.hpp @@ -34,6 +34,7 @@ class ResidentBuffer : public std::enable_shared_from_this { VkBuffer Handle() const { return buffer; } VkDeviceAddress DeviceAddress() const { return address + lead; } + VkDeviceAddress HandleAddress() const { return address; } std::uint64_t Origin() const { return origin; } std::uint64_t BoundBytes() const { return bound * BlockBytes; } std::uint32_t MemoryType() const { return type; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp index 2de6f3010068..87762d9fc4b8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp @@ -6,6 +6,8 @@ namespace AgcDriver::Graphics { +VkDeviceAddress BufferDeviceAddress(const Context& context, VkBuffer buffer); + class Buffer { public: Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp index a4af230b25b7..e5b6b47d48e7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp @@ -39,6 +39,8 @@ struct SampleOrderPass { bool located = false; }; +class HeapSlotOwner; + struct SampleOrderTarget { VkImage image = VK_NULL_HANDLE; VkImageView view = VK_NULL_HANDLE; @@ -47,6 +49,7 @@ struct SampleOrderTarget { std::uint32_t samples = 1; SampleOrderMethod method = SampleOrderMethod::Storage; std::shared_ptr keep; + const HeapSlotOwner* owner = nullptr; }; struct DepthSampleLocations { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp index 925fc854b1f4..f90bb7c57486 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp @@ -1,19 +1,22 @@ #ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_SAMPLER_HPP #define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_SAMPLER_HPP +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestSamplerResource.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" #include +#include #include #include #include #include +#include #include namespace AgcDriver::Graphics { -class Sampler { +class Sampler : public HeapSlotOwner { public: Sampler(const Context& context, const GuestSamplerResource& descriptor); ~Sampler(); @@ -27,8 +30,11 @@ class Sampler { bool ReadsOpaqueBlackBorder() const; bool RequiresNonSeamlessCube() const; static void Validate(const Context& context, const GuestSamplerResource& descriptor); + static VkSamplerCreateInfo CreateInfo(const Context& context, const GuestSamplerResource& descriptor, VkSamplerReductionModeCreateInfoEXT& reduction); static bool ShaderAppliesLodBias(const GuestSamplerResource& descriptor); static bool ReadsOpaqueBlackBorder(const GuestSamplerResource& descriptor); + const std::array* CacheKey() const { return cacheKey ? &*cacheKey : nullptr; } + void SetCacheKey(const std::array& key) { cacheKey = key; } private: void release() noexcept; @@ -40,6 +46,7 @@ class Sampler { bool requiresFilterMinmax = false; bool opaqueBlackBorder = false; bool requiresNonSeamlessCube = false; + std::optional> cacheKey; }; // One VkSampler per distinct S# (its 4 words plus the shader's depth-compare use and the diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 3f1bbf11ad79..dd43e4a026eb 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -3,6 +3,8 @@ #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" @@ -30,6 +32,7 @@ namespace AgcDriver::GuestMemory { struct WriteSubscription; } namespace AgcDriver::Graphics { + class Recorder; void FlushCachedTextures(VkDevice device); @@ -81,8 +84,8 @@ bool SampledTexturesShareEntry(std::span first, std::span words); +bool ProgramStoresThroughAddresses(const ShaderRecompiler::RecompileResult& program); bool SpirvFaultReportOnly(std::span words, std::uint32_t set, std::uint32_t binding); -bool ShaderStoresThroughAddresses(const ShaderRecompiler::SharedSpirv& spirv); void LastRecordIndices(std::span logged, std::span objects, std::vector& indices); // The cached storage image of a surface (render targets use it as their resident image); brought up @@ -99,6 +102,11 @@ std::shared_ptr RepeatStorageSurface(const Context& context, con // a storage image other than `except` has results pending in [address, address + bytes). bool PendingStorageOverlaps(std::uint64_t address, std::size_t bytes, const StorageTexture* except); +inline std::size_t HeapStageIndex(ShaderRecompiler::ShaderStage stage) { + using ShaderRecompiler::ShaderStage; + return static_cast(ShaderRecompiler::RuntimeAbi::StageGroup(stage == ShaderStage::Fragment, stage == ShaderStage::TessellationControl, stage == ShaderStage::TessellationEvaluation)); +} + struct PipelineSetLayouts { VkDescriptorSetLayout main = VK_NULL_HANDLE; VkDescriptorSetLayout fragment = VK_NULL_HANDLE; @@ -149,6 +157,7 @@ class DescriptorCache { std::uint64_t reusedSets = 0; }; Stats Counters() const; + static std::uint64_t RewrittenSets(); private: Context context; @@ -187,10 +196,16 @@ struct ImageTableReuseCounts { std::uint64_t arrayViewsShared = 0; }; ImageTableReuseCounts ImageTableReuses(); +struct HeapBufferPathCounts { + std::uint64_t pushedStages = 0; + std::uint64_t overflowStages = 0; +}; +HeapBufferPathCounts HeapBufferPaths(); std::uint64_t SampledTexturesCleared(); std::uint64_t SampledTexturesImported(); std::uint64_t SampledLookupKeyScans(); std::uint64_t SampledLookupKeyProofs(); +std::uint64_t DrawInputCopies(); struct PresyncSurface { std::uint64_t address; @@ -220,9 +235,13 @@ class ShaderResources { std::span LayoutBindingFlags() const { return layoutBindingFlags; } VkDescriptorSetLayout FragmentLayout() const { return fragment.layout; } bool SplitSets() const { return splitSets; } - PipelineSetLayouts SetLayouts() const { return {_layout, fragment.layout, splitSets, layoutKey, fragmentLayoutKey}; } + PipelineSetLayouts SetLayouts() const; + bool HeapStage() const { return heapStage; } + std::atomic& CacheTouchedAt() const { return cacheTouchedAt; } + void RefreshHeapStage(std::span shaders); void RequireGuestBuffers() const { requireGuestBuffers(); } void Bind(VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout) const; + void BindDescriptorHeaps(VkCommandBuffer commands, bool guestBuffersChecked = false) const; struct DrawBindings { DrawBindings() = default; DrawBindings(const DrawBindings&) = delete; @@ -241,8 +260,14 @@ class ShaderResources { DescriptorCache::SetAllocation fragmentAllocation; DescriptorCache::SetAllocation allocation; std::vector snapshots; + bool addressOffsets = false; + std::array heapOffsets{}; + std::vector> addressOverrides; + const VkDeviceAddressRangeEXT* AddressOverride(std::size_t allocation) const; + std::vector> movedReads; ~DrawBindings(); }; + void RefreshMovedAddresses(DrawBindings& rewritten) const; struct MovedBuffer { std::size_t allocation; std::uint64_t address; @@ -251,6 +276,8 @@ class ShaderResources { VkBuffer inPlace = VK_NULL_HANDLE; VkDeviceSize inPlaceOffset = 0; std::uint32_t adjustment = 0; + bool heapInPlace = false; + VkDeviceAddressRangeEXT view{}; }; struct DrawUse { DrawUse() = default; @@ -265,9 +292,9 @@ class ShaderResources { void CompleteDrawUse(const DrawUse& use) const; void BindDrawUse(VkCommandBuffer commands, VkPipelineLayout layout, const DrawUse* use) const; std::shared_ptr PrepareDrawBindings(Recorder& recorder, std::span moved = {}, bool movedOnly = false, const BdaResources* faultRecord = nullptr) const; - std::optional> MovedReadOnlyBuffers(std::span shaders, Recorder& recorder, const ColorTarget* target, bool* patchedData = nullptr) const; static std::uint64_t BytesUpToTarget(std::uint64_t address, std::uint64_t bytes, std::uint64_t stride, const ColorTarget* target); - enum class MoveRefusal : std::size_t { None, Shape, NotGuest, Written, Limit, Inaccessible, Overlap, Bindings, Count }; + enum class MoveRefusal : std::size_t { None, Shape, NotGuest, Written, Limit, Inaccessible, Overlap, Bindings, NotImported, Alignment, SharedBinding, Count }; + std::optional> MovedReadOnlyBuffers(std::span shaders, Recorder& recorder, const ColorTarget* target, bool* patchedData = nullptr, MoveRefusal* refusal = nullptr) const; struct MoveProof { MoveRefusal refusal = MoveRefusal::None; std::size_t buffers = 0; @@ -352,10 +379,14 @@ class ShaderResources { // ranges are fixed by the build), so a Revalidate's collects on the same worker are memo hits. void PrecollectSurfaces() const; bool Reusable() const { return reusable; } + enum class Unreusable : std::uint8_t { Unchecked, HtileClear, CopiedWrites, Lease, Bda, MultisampleSource, LoopGuard, TextureRefreshedPerUse, TemplateDataRefresh, NoDirectRegions, RegionNotServed, Count }; + Unreusable UnreusableReason() const { return unreusableReason; } + static const char* UnreusableReasonName(Unreusable reason); void KeepStorageImageBytes(Recorder& recorder) const; const std::vector& MultisampleSources() const { return multisampleSources; } static bool NeverReusable(std::span shaders); static std::uint64_t DepthGuardRefusals(); + static std::uint64_t MovedBehindGpuWrites(); const std::vector>& SampledTextures() const { return textures; } static std::size_t LookupLogCapacity(); bool ChecksFaults() const { return bda != nullptr; } @@ -385,6 +416,27 @@ class ShaderResources { void PatchPushConstants(std::span bytes) const { for (const auto& [position, adjustment] : pushPatches) bytes[position] = static_cast(adjustment); } + void PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const; + void writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const; + void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const DrawBindings* overrides, VkDeviceAddress empty) const; + bool pushImageMatches(std::span shaders, std::span placements) const; + void resetPushImage(std::span shaders, std::span placements) const; + void writeDataRoots(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten, bool cached) const; + struct PushImage { + std::array bytes{}; + std::uint64_t mask = 0; + std::vector placements; + std::array programs{}; + std::size_t count = 0; + struct Stage { + std::uint64_t version = ~std::uint64_t{0}; + std::array addresses{}; + bool live = true; + }; + std::array stages{}; + bool valid = false; + }; + mutable PushImage pushImage; bool PatchMovedPushConstants(std::span bytes, std::span moved) const { bool patched = false; for (const auto& entry : moved) { @@ -450,6 +502,7 @@ class ShaderResources { bool refreshData(VkCommandBuffer commands, const CompiledShader& shader, Recorder* recorder); std::optional shaderDataAllocation(const CompiledShader& shader) const; VkBuffer shaderDataBuffer(const CompiledShader& shader) const; + std::pair shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const; void forgetShaderDataWords(const CompiledShader& shader); struct DescribedRange { const char* kind; @@ -495,12 +548,19 @@ class ShaderResources { std::vector imageAllocations; VkDescriptorBindingFlags flags = 0; std::int32_t set = -1; + bool heap = false; + bool addressed = false; + std::uint32_t dataStage = 0; + std::uint32_t addressDword = 0; + ShaderRecompiler::DescriptorRole role = ShaderRecompiler::DescriptorRole::GuestBuffers; + std::vector embeddedSamplers; }; struct TableStage { ShaderRecompiler::ShaderStage stage = ShaderRecompiler::ShaderStage::Compute; const ShaderRecompiler::RecompileResult* program = nullptr; const ShaderRecompiler::DescriptorBinding* images = nullptr; + std::span imageWords; std::size_t mapAllocation = std::numeric_limits::max(); std::vector map; std::vector poison; @@ -514,15 +574,18 @@ class ShaderResources { std::vector elementTextures; std::vector representatives; std::vector> samplerRejections; + bool heap = false; + std::vector elementStorage; + std::vector tableSamplers; }; std::vector tableStages; std::array tableBindings{std::numeric_limits::max(), std::numeric_limits::max()}; std::array tableElements{}; std::array storageTableBindings{std::numeric_limits::max(), std::numeric_limits::max()}; TableStage& tableStage(const CompiledShader& shader); - static const ShaderRecompiler::DescriptorBinding* tableImages(std::span shaders, ShaderRecompiler::ShaderStage stage); + static const ShaderRecompiler::DescriptorBinding* tableImages(std::span shaders, ShaderRecompiler::ShaderStage stage, std::span& words); std::uint32_t rejectTableElement(TableStage& table, std::span words, const std::string& message); - void addSamplerTable(const ShaderRecompiler::DescriptorBinding& binding, VkShaderStageFlags flags, TableStage& table); + void addSamplerTable(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, VkShaderStageFlags flags, TableStage& table); void resolveImageTables(); void finishImageTables(); @@ -556,7 +619,7 @@ class ShaderResources { bool movedInPlace(Recorder& recorder, const Allocation& item, std::uint64_t address, std::uint64_t size, MovedBuffer& entry) const; // 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). - void addImageBinding(const ShaderRecompiler::DescriptorBinding& binding, VkShaderStageFlags flags); + void addImageBinding(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, VkShaderStageFlags flags); // Stage A: one record per planned image element (ImageRecord), in plan order: the decoded // descriptor and its surface size (computed once for the build), the write watch walked so stage // B's collects are memo hits (APS5_NO_PRECOLLECT=1 skips the pass entirely), and for a sampled @@ -599,12 +662,14 @@ class ShaderResources { // Stage B: the record's texture when the fastRevalidate predicate proves it current under the // lock and the cache still holds it; null sends the element to cachedTexture. std::shared_ptr fastTexture(ImageRecord& record); - void resolveImageBinding(const ShaderRecompiler::DescriptorBinding& binding, Binding& item, std::span> shaderSamplers); + void resolveImageBinding(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, Binding& item, std::span> shaderSamplers); void applySamplerVariants(); void forgetDeferredInputs(); void release() noexcept; + void completeBuild(std::span shaders); void prepareAddressBindings(std::span shaders, std::span snapshots); - VkDescriptorBufferInfo descriptor(Allocation& allocation); + VkDescriptorBufferInfo descriptor(Allocation& allocation) { return descriptor(allocation, allocation.adjustment); } + VkDescriptorBufferInfo descriptor(const Allocation& allocation, std::uint32_t& adjustment) const; VkDescriptorBufferInfo wholeDwordRange(VkDescriptorBufferInfo info) const; void noteReusable(); void reportDescriptorCaches() const; @@ -726,6 +791,120 @@ class ShaderResources { DescriptorCache::SetAllocation cacheAllocation; }; bool splitSets = false; + bool heapStage = false; + bool dataTableBound = false; + bool dataFaultBound = false; + mutable std::array heapOffsets{}; + void writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader); + struct HeapStageState { + struct SlotSet { + std::vector slots; + std::vector generations; + void CaptureImageGenerations(const BindlessHeap& heap) { + generations.clear(); + for (const auto slot : slots) generations.push_back(heap.SlotGeneration(slot)); + } + void CaptureSamplerGenerations(const BindlessHeap& heap) { + generations.clear(); + for (const auto slot : slots) generations.push_back(heap.SamplerGeneration(slot)); + } + static bool Current(const BindlessHeap& heap, const SlotSet& images, const SlotSet& samplers) { + return heap.GenerationsCurrent(images.slots, images.generations, samplers.slots, samplers.generations); + } + static std::uint32_t Touch(const BindlessHeap& heap, const SlotSet& images, const SlotSet& samplers, std::uint32_t touched) { + return heap.TouchSlots(images.slots, samplers.slots, touched); + } + }; + std::uint64_t slotSerial = 0; + std::uint64_t dataOrigin = 0; + std::uint64_t pushedUserWords = 0; + const void* dataProgram = nullptr; + VkShaderStageFlags laidOutFor = 0; + std::uint32_t touchedEpoch = 0; + std::uint32_t pushedPlaced = 0; + std::uint32_t userWords = 0; + bool splitUser = false; + bool keyTaken = false; + std::uint64_t pushVersion = 0; + bool mapBuilt = false; + std::uint32_t mapTouched = 0; + SlotSet mapImages; + SlotSet mapSamplers; + std::vector owned; + std::vector key; + struct KindRange { + std::uint32_t kind = 0; + std::uint32_t first = 0; + std::uint32_t count = 0; + }; + SlotSet images; + std::vector kindRanges; + SlotSet samplers; + std::vector> dataPatches; + struct KeptSpan { + std::vector words; + BindlessHeap::TableMark table; + }; + KeptSpan data, flat, map, user; + std::vector dataInput; + std::vector userInput; + const void* userProgram = nullptr; + struct PushRun { + std::uint32_t index = 0; + std::uint32_t dword = 0; + std::uint32_t count = 0; + bool user = false; + }; + std::uint32_t pushRunUserWords = 0; + std::vector splitPushRuns; + std::vector wholePushRuns; + std::span Slots(std::uint32_t kind) const { + for (const auto& range : kindRanges) { + if (range.kind == kind) return std::span(images.slots).subspan(range.first, range.count); + } + return {}; + } + }; + std::array heapStages; + std::uint64_t heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words); + std::uint64_t heapTable(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words); + bool keptTable(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept); + void retireHeapTables() noexcept; + bool ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const; + VkImageView heapPlaceholderView(std::uint32_t kind) const; + VkImageView heapSampledView(std::size_t index) const; + VkImageView heapStorageView(std::size_t index, std::uint32_t binding) const; + VkImageView heapMultisampleStorageView(std::size_t index) const; + const HeapSlotOwner* heapMultisampleStorageOwner(std::size_t index) const; + static void layOutStagePush(HeapStageState& state, const CompiledShader& shader, const ShaderRecompiler::StagePushPlacement& placement); + void collectAddressedElements(); + void layOutHeapStages(std::span shaders); + enum class HeapElementClass { Absent, SampledImage, StorageImage, MultisampleStorage, Sampler }; + static constexpr std::size_t heapElementKeyWords(HeapElementClass kind) { return kind == HeapElementClass::SampledImage || kind == HeapElementClass::StorageImage || kind == HeapElementClass::MultisampleStorage ? 3u : 1u; } + struct HeapElement { + HeapElementClass kind; + std::size_t index; + std::size_t element; + }; + HeapElementClass classifyHeapElement(const Binding& binding, std::size_t element) const; + template bool forEachHeapElement(const Binding& binding, Visit&& visit) const; + template void visitHeapSlotKey(std::span owned, Emit&& emit) const; + void appendHeapSlotKey(std::span owned, std::vector& key) const; + bool heapSlotKeySame(std::span owned, std::span key) const; + void takeHeapSlots(BindlessHeap& heap, HeapStageState& state, std::span owned, std::span key); + void verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const; + std::uint64_t commitStageData(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, std::span patched, std::span words, std::span userData); + std::uint64_t writeSplitUserData(BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, std::span words, std::span userData, std::size_t userWords, const std::vector& patched, bool current, std::uint64_t dataAddress); + bool refreshHeapStageSlots(BindlessHeap& heap, HeapStageState& stageState, VkShaderStageFlags stageBit); + void writeHeapDataBinding(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, const ShaderRecompiler::DescriptorBinding& binding, bool current); + void buildPatchedData(std::vector& patched, const CompiledShader& shader, const HeapStageState& stageState, std::span words, std::span userData, bool current) const; + void patchHeapSlotWords(const CompiledShader& shader, const HeapStageState& stageState, std::vector& patched, bool current, bool leading = false) const; + std::pair writeSplitHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, + std::span words, std::span userData, bool sameWalk, bool current); + static constexpr std::int64_t HeapRingDataFirst = -2; + static constexpr std::int64_t HeapRingData(std::size_t stage) { return HeapRingDataFirst - static_cast(stage); } + static constexpr bool IsHeapRingData(std::int64_t allocation) { return allocation <= HeapRingDataFirst && allocation > HeapRingDataFirst - static_cast(ShaderRecompiler::RuntimeAbi::StageCount); } + static constexpr std::size_t HeapRingStage(std::int64_t allocation) { return static_cast(HeapRingDataFirst - allocation); } std::vector fragmentLayoutKey; SetObjects fragment; struct TableWrites { @@ -743,6 +922,20 @@ class ShaderResources { mutable std::vector descriptorBuffers; std::vector descriptorImages; std::vector descriptorWrites; + bool addressedBuffers = false; + std::vector resolvedAddresses; + std::array, ShaderRecompiler::RuntimeAbi::StageCount> addressedElements; + std::vector addressedAllocations; + VkDeviceAddress emptyAddress = 0; + VkDeviceAddress resolvedGds = 0; + std::size_t gdsAllocation = std::numeric_limits::max(); + std::array heapTableMaps{}; + std::array heapTableMapSet{}; + void writeHeapTableMap(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, std::size_t stageIndex); + void buildHeapTableMap(std::vector& map, BindlessHeap& heap, const CompiledShader& shader, const TableStage& table, HeapStageState& stageState); + VkDeviceAddressRangeEXT bufferRange(std::uint32_t index, const DrawBindings* overrides) const; + VkDeviceAddressRangeEXT bufferAddress(const Allocation& allocation) const; + void resolveBufferAddresses(); struct FaultDescriptor { std::size_t write; std::size_t buffer; @@ -750,7 +943,8 @@ class ShaderResources { }; std::vector faultDescriptors; void prepareFaultSlot() const; - void writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord) const; + void writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace = {}) const; + void writeRewrittenSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord) const; std::shared_ptr> ownRecordBusy = std::make_shared>(false); mutable std::vector drawPoolSizes; // Guest buffer elements bound read-only: each use of this object skips that many pending-write @@ -768,7 +962,7 @@ class ShaderResources { std::vector textureBaseLevel; std::vector textureSrgb; std::vector> storageTextures; - std::vector multisampleStorageViews; + std::vector multisampleStorage; std::vector storageMips; std::vector storageKeys; std::vector storageFirstLayer; @@ -789,6 +983,7 @@ class ShaderResources { }; std::vector samplerSources; bool reusable = false; + Unreusable unreusableReason = Unreusable::Unchecked; std::vector directRegions; std::vector validatedTextures; std::vector registeredImageViews; @@ -807,6 +1002,7 @@ class ShaderResources { bool importsReconcilable = false; // FNV-1a offset basis: the hash of no data buffers (DataWordsHash). std::uint64_t dataWordsHash = 14695981039346656037ull; + mutable std::atomic cacheTouchedAt{0}; void rehashDataWords(); std::vector> pushPatches; std::vector dataPatches; @@ -820,6 +1016,7 @@ class ShaderResources { std::vector refreshResourceKey; struct DeferredImages { const ShaderRecompiler::DescriptorBinding* binding; + std::span words; std::size_t index; std::size_t firstSampler = 0; std::size_t samplerCount = 0; @@ -872,6 +1069,7 @@ class ResourceCache { // Moves the entry to the front of the LRU (a recipe hit uses its template without Find, and a // hot template must not age out under the recipes that depend on it); false when no entry. bool Touch(const Key& key); + void TouchAging(const Key& key, std::atomic& touchedAt); // Find and Touch calls so far (the [rescache] line: a recipe hit touches instead of finding). static std::uint64_t Finds(); static std::uint64_t Touches(); @@ -890,7 +1088,13 @@ class ResourceCache { void dropReleasedTextures(std::vector>* evicted); void noteEvicted(const Key& key); void noteReturn(const Key& key); - void noteUse(const Key& key); + struct Entry { + Key first; + std::shared_ptr second; + std::uint64_t usedWindow = 0; + }; + void noteUse(Entry& entry); + void resetUses(); void removeImage(const StorageTexture* image, std::vector>* evicted); struct KeyHash { std::size_t operator()(const Key& key) const noexcept { @@ -917,7 +1121,7 @@ class ResourceCache { } }; mutable AgcDriver::Mutex mutex; - std::list>> entries; + std::list entries; std::unordered_map index; std::size_t capacity = 0; bool fixedCapacity = false; @@ -925,11 +1129,16 @@ class ResourceCache { std::unordered_map evictedKeys; std::size_t evictionsSinceCheck = 0; std::size_t returnsSinceCheck = 0; - std::unordered_set usedKeys; + std::uint64_t useWindow = 1; + std::size_t usedEntries = 0; std::size_t usesSinceCheck = 0; static constexpr std::size_t InitialShrinkWindow = 8; static constexpr std::size_t MaximumShrinkWindow = 1024; std::size_t baseEntries = InitialEntries; + std::atomic operations{0}; + std::atomic usesWindowStart{0}; + std::atomic agingWindow{InitialEntries / 8u}; + void publishAgingWindow(); std::size_t baseShrinkWindow = InitialShrinkWindow; std::size_t shrinkWindow = InitialShrinkWindow; bool shrankLast = false; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp index 953db9bbf860..8cb4f40a84b5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include "IntermediateRepresentation/IrMetadata/ResourcePlan.hpp" #include "Recompiler.hpp" +#include "PushDataLayout.hpp" #include #include #include @@ -17,6 +18,10 @@ inline constexpr std::uint32_t PipelinePushConstantBytes = 256; inline constexpr std::uint32_t PipelinePushSlotBytes = 128; inline constexpr std::uint32_t ComputePushConstantBytes = 128; +inline constexpr std::uint32_t HeapLayoutKeyTag = 0x48454150u; +inline constexpr std::uint32_t MainSetBit = 1u; +inline constexpr std::uint32_t FragmentSetBit = 2u; + inline std::uint32_t PushBlockBytes(bool libraries) { return libraries ? PipelinePushConstantBytes : PipelinePushSlotBytes; } @@ -52,8 +57,95 @@ struct CompiledShader { const ShaderRecompiler::RecompileResult* program; std::uint32_t pushConstantOffset; const std::vector* registeredImageViews = nullptr; + const ShaderRecompiler::HeapStageWords* heap = nullptr; }; +inline bool HeapShader(const CompiledShader& shader) { + return shader.program != nullptr && shader.program->gpuResolvedImages; +} + +inline bool AnyHeapShader(std::span shaders) { + return std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return HeapShader(shader); }); +} + +inline bool RootedPushData(std::span shaders) { + return std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->dataAddressPush; }); +} + +inline bool PushesGeneratedFaultAddress(const CompiledShader& shader, bool rooted) { + if (!rooted || shader.program == nullptr || shader.program->dataAddressPush || HeapShader(shader)) return false; + return std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; }); +} + +std::uint32_t PushedBufferRecordCap(); + +inline std::vector PushDataPlacements(std::span shaders) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + std::vector stages(shaders.size()); + std::uint64_t occupied = 0; + const bool rooted = RootedPushData(shaders); + for (std::size_t index = 0; index < shaders.size(); ++index) { + const auto* program = shaders[index].program; + stages[index].part = ShaderRecompiler::PushPartOf(shaders[index].stage); + if (program == nullptr) continue; + occupied |= ShaderRecompiler::StagePushFeatures(shaders[index].stage, program->pushItems); + if (program->dataAddressPush) { + stages[index].items = program->pushItems & ShaderRecompiler::RootItemMask; + stages[index].pushedWanted = static_cast(program->pushedData.size()); + stages[index].pushedBuffers = program->pushedBufferCount; + continue; + } + if (!program->pushConstants.empty()) occupied |= ShaderRecompiler::PushBytesMask(shaders[index].pushConstantOffset, static_cast(program->pushConstants.size())); + if (PushesGeneratedFaultAddress(shaders[index], rooted)) stages[index].items = Abi::RootItemBit(Abi::RootItem::FaultAddress); + } + return ShaderRecompiler::PlacePushData(stages, occupied, PushedBufferRecordCap()); +} + +inline const std::vector& DrawGuestWords(const ShaderRecompiler::RecompileResult& program, const ShaderRecompiler::HeapStageWords* heap, const ShaderRecompiler::DescriptorBinding& binding) { + if (heap == nullptr) return binding.guestDescriptor; + const auto index = static_cast(&binding - program.bindings.data()); + if (index < heap->bindings.size() && !heap->bindings[index].empty()) return heap->bindings[index]; + if (binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && !heap->flattenedSrt.empty()) return heap->flattenedSrt; + const auto* base = heap->base.get(); + const bool shared = binding.role != ShaderRecompiler::DescriptorRole::ShaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt; + return shared && base != nullptr && index < base->bindings.size() && !base->bindings[index].empty() ? base->bindings[index] : binding.guestDescriptor; +} + +inline const std::vector& DrawGuestWords(const CompiledShader& shader, const ShaderRecompiler::DescriptorBinding& binding) { + return DrawGuestWords(*shader.program, shader.heap, binding); +} + +inline const std::vector& DrawVertexAttributes(const CompiledShader& shader) { + return shader.heap != nullptr && !shader.heap->vertexAttributes.empty() ? shader.heap->vertexAttributes : shader.program->vertexAttributes; +} + +enum class HeapBindingClass { SharedImage, StorageImage, ShaderData, PerDraw, Unsupported }; + +inline HeapBindingClass ClassifyHeapBinding(const ShaderRecompiler::DescriptorBinding& binding) { + using Role = ShaderRecompiler::DescriptorRole; + switch (binding.role) { + case Role::GuestImages: + if (binding.kind != ShaderRecompiler::DescriptorKind::StorageImage) return HeapBindingClass::SharedImage; + return binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet ? HeapBindingClass::StorageImage : HeapBindingClass::PerDraw; + case Role::GuestSamplers: + return HeapBindingClass::SharedImage; + case Role::BdaPagetable: + case Role::FaultBuffer: + case Role::Gds: + case Role::GuestBuffers: + return HeapBindingClass::PerDraw; + case Role::ShaderData: + case Role::FlattenedSrt: + return HeapBindingClass::ShaderData; + default: + return HeapBindingClass::Unsupported; + } +} + +inline bool BindsRole(std::span shaders, ShaderRecompiler::DescriptorRole role) { + return std::ranges::any_of(shaders, [&](const CompiledShader& shader) { return shader.program != nullptr && std::ranges::any_of(shader.program->bindings, [&](const auto& binding) { return binding.role == role; }); }); +} + inline std::uint32_t KeyedPushOffset(const CompiledShader& shader) { return shader.program->pushConstants.empty() ? 0u : shader.pushConstantOffset; } @@ -92,7 +184,7 @@ inline VkShaderStageFlags PushConstantStages(std::span sha VkShaderStageFlags result = 0; for (const auto& shader : shaders) { Require(shader.program != nullptr, "missing compiled shader"); - if (!shader.program->pushConstants.empty() || shader.program->readsDepthRemapPush || shader.stage == ShaderRecompiler::ShaderStage::Mesh || shader.stage == ShaderRecompiler::ShaderStage::TessellationControl) result |= VulkanStage(shader.stage); + if (!shader.program->pushConstants.empty() || shader.program->readsDepthRemapPush || shader.program->dataAddressPush || shader.stage == ShaderRecompiler::ShaderStage::Mesh || shader.stage == ShaderRecompiler::ShaderStage::TessellationControl) result |= VulkanStage(shader.stage); } return result; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/StagedMerge.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/StagedMerge.hpp index 60e2a764f7d2..3add8e5d57a7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/StagedMerge.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/StagedMerge.hpp @@ -15,7 +15,9 @@ struct StagedTemporary { std::shared_ptr AcquireStagedTemporary(const Context& context, VkExtent2D extent, std::uint32_t samples); void RecordStagedClear(const Context& context, VkCommandBuffer commands, StagedTemporary& temporary); -void RecordStagedMerge(const Context& context, VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area); +class HeapSlotOwner; +void RecordStagedMerge(const Context& context, VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area, + const HeapSlotOwner* targetOwner = nullptr); void ClearStagedMerges(VkDevice device); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp index e875a6d6c731..e6b2f7657bfb 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp @@ -1,6 +1,7 @@ #ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_TEXTURE_HPP #define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_TEXTURE_HPP +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestTextureResource.hpp" @@ -68,7 +69,7 @@ struct OwnedImage { ImageAllocation allocation; }; -class Texture { +class Texture : public HeapSlotOwner { public: Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span snapshot, bool depthCompare = false, bool layerRows = false, const VkClearColorValue* clear = nullptr, std::optional> packedSlabs = std::nullopt, const HostImport* source = nullptr); Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::shared_ptr staging, bool depthCompare = false, bool layerRows = false, std::optional> packedSlabs = std::nullopt); @@ -118,6 +119,7 @@ class Texture { ViewRange SampledViewRange(bool firstLayer) const { return firstLayer ? firstLayerRange : viewRange; } // The layout the image is kept in while sampled. VkImageLayout Layout() const { return layout; } + VkImage Image() const { return image; } VkDeviceSize AllocationBytes() const { return allocationBytes; } VkFormat ViewFormat() const { return viewFormat; } // Whether this texture is a view of a storage image (no snapshot of its own). @@ -280,7 +282,7 @@ class UnitFlags { // either at once (WriteBack) or deferred: MarkDirty keeps them on the GPU until something reads that // memory (FlushPending, through the GuestMemory flush hook), the image is refreshed after a CPU write, // or it leaves the cache. Dispatches reusing the image meanwhile skip the round trip entirely. -class StorageTexture : public std::enable_shared_from_this { +class StorageTexture : public std::enable_shared_from_this, public HeapSlotOwner { public: struct CreationHandOver { DccKeys keys = DccKeys::Uncompressed; @@ -305,6 +307,7 @@ class StorageTexture : public std::enable_shared_from_this { VkImageView View(std::uint32_t mip); VkImageView FirstLayerView(std::uint32_t mip); VkImageView StorageView(std::uint32_t mip, bool firstLayer, bool uintStorage = false); + VkImageView UintStorageViewOrDefault(std::uint32_t mip, bool firstLayer); VkImageView ElementView(); VkImageView AtomicView(std::uint32_t mip, bool firstLayer); VkImageView Atomic64View(std::uint32_t mip, bool firstLayer); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp index 5d037e2f05a5..39e3feea6eab 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp @@ -13,6 +13,8 @@ namespace AgcDriver::Graphics { +class HeapSlotOwner; + class Buffer; // The part of a mip one Dispatch moves: only elements whose tiled offset (relative to the mip's @@ -36,6 +38,8 @@ namespace AgcDriver::Graphics { std::uint32_t pipeBankXor = 0; }; + enum class DetileVariant : std::uint8_t { Classic, Addressed, Heap }; + class TextureDetiler { public: explicit TextureDetiler(const Context& context); @@ -48,20 +52,21 @@ namespace AgcDriver::Graphics { // restricts the move to part of the mip (a partial upload or write-back, StorageTexture), // leaving the other elements of both buffers alone. void Dispatch(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, bool thick = false, const DetileWindow& window = {}); - void DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, const DetileWindow& window = {}); + void DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, const DetileWindow& window = {}, const HeapSlotOwner* owner = nullptr); void DispatchRepack(VkCommandBuffer commands, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, std::uint64_t bytes, bool depthToFloat = false); static VkFormat ImageElementFormat(std::uint32_t elementBytes); // Recycles the descriptor sets of the previous batch; call before recording a new command batch. void BeginBatch(); - void DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write); + void DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write, const HeapSlotOwner* owner = nullptr); std::uint32_t CmaskErrors(); - void DispatchMultisampleReadback(VkCommandBuffer commands, VkFormat format, VkBuffer destination, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements); - void DispatchMultisampleImage(VkCommandBuffer commands, std::uint32_t elementBytes, VkBuffer source, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements); + void DispatchMultisampleReadback(VkCommandBuffer commands, VkFormat format, VkBuffer destination, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements, const HeapSlotOwner* owner = nullptr); + void DispatchMultisampleImage(VkCommandBuffer commands, std::uint32_t elementBytes, VkBuffer source, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements, const HeapSlotOwner* owner = nullptr); private: - VkPipeline multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth); - VkPipeline multisampleUploadPipeline(std::uint32_t elementBytes); - VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false); + VkPipeline multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth, bool heap); + VkPipeline multisampleUploadPipeline(std::uint32_t elementBytes, bool heap); + VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false, DetileVariant variant = DetileVariant::Classic); + VkDeviceAddress bufferAddress(VkBuffer buffer) const; void release() noexcept; struct DescriptorRing { std::vector pools; @@ -85,6 +90,7 @@ namespace AgcDriver::Graphics { VkDescriptorSetLayout cmaskDescriptorLayout = VK_NULL_HANDLE; VkPipelineLayout cmaskPipelineLayout = VK_NULL_HANDLE; VkPipeline cmaskPipeline = VK_NULL_HANDLE; + VkPipeline cmaskHeapPipeline = VK_NULL_HANDLE; DescriptorRing cmaskDescriptorSets; std::unique_ptr cmaskErrors; VkDescriptorSetLayout imageDescriptorLayout = VK_NULL_HANDLE; @@ -92,6 +98,12 @@ namespace AgcDriver::Graphics { VkShaderModule imageModule = VK_NULL_HANDLE; VkShaderModule repackModule = VK_NULL_HANDLE; VkPipeline repackPipeline = VK_NULL_HANDLE; + VkPipeline heapRepackPipeline = VK_NULL_HANDLE; + VkPipelineLayout addressedPipelineLayout = VK_NULL_HANDLE; + VkPipelineLayout addressedRepackLayout = VK_NULL_HANDLE; + VkShaderModule addressedModule = VK_NULL_HANDLE; + VkShaderModule addressedRepackModule = VK_NULL_HANDLE; + VkPipeline addressedRepackPipeline = VK_NULL_HANDLE; VkShaderModule imageWordModule = VK_NULL_HANDLE; VkShaderModule wordModule = VK_NULL_HANDLE; DescriptorRing imageDescriptorSets; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp b/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp index 6c8e6b6a7821..6a960b9b8b25 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp +++ b/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp @@ -39,6 +39,11 @@ layout(local_size_x = 8, local_size_y = 8) in; #ifdef LINEAR_IMAGE layout(set = 0, binding = 0, std430) buffer Tiled { uint data[]; } tiledBuffer; layout(set = 0, binding = 1) uniform uimage2D linearImage; +#elif defined(ADDRESSED) +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer Input { uint data[]; }; +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Output { uint data[]; }; #else layout(set = 0, binding = 0, std430) readonly buffer Input { uint data[]; } inputBuffer; layout(set = 0, binding = 1, std430) buffer Output { uint data[]; } outputBuffer; @@ -69,8 +74,17 @@ layout(push_constant) uniform Push { uint rowBegin; uint pipeBankXor; uint splitStride; +#ifdef ADDRESSED + uvec2 inputAddress; + uvec2 outputAddress; +#endif } params; +#ifdef ADDRESSED +#define inputBuffer Input(params.inputAddress) +#define outputBuffer Output(params.outputAddress) +#endif + uint equationBit(uint mask, uvec2 p) { uint selected = (p.x & (mask & 0xfffu)) ^ ((p.y << 12) & (mask & 0xfff000u)) ^ ((params.slice << 24) & (mask & 0xff000000u)); return bitCount(selected) & 1u; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureRepack.comp b/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureRepack.comp index 13eab0c8f4ae..89c9efcb36de 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureRepack.comp +++ b/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureRepack.comp @@ -2,8 +2,15 @@ layout(local_size_x = 64) in; +#ifdef ADDRESSED +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer Source { uint data[]; }; +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Destination { uint data[]; }; +#else layout(std430, set = 0, binding = 0) readonly buffer Source { uint source[]; }; layout(std430, set = 0, binding = 1) buffer Destination { uint destination[]; }; +#endif layout(push_constant) uniform Push { uint sourceBase; @@ -11,8 +18,17 @@ layout(push_constant) uniform Push { uint words; uint rowWords; uint depthToFloat; +#ifdef ADDRESSED + uvec2 sourceAddress; + uvec2 destinationAddress; +#endif } push; +#ifdef ADDRESSED +#define source Source(push.sourceAddress).data +#define destination Destination(push.destinationAddress).data +#endif + void main() { const uint index = gl_GlobalInvocationID.y * push.rowWords + gl_GlobalInvocationID.x; if (gl_GlobalInvocationID.x >= push.rowWords || index >= push.words) return; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp index 26e33d7c95a0..2167ffa7f2a2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -451,6 +452,15 @@ VkDescriptorBufferInfo BdaResources::Fault() const { return {faultChunk->buffer->Handle(), faultOffset, faultChunk->slotBytes}; } +VkDeviceAddress BdaResources::TableAddress() const { + Require(table != nullptr, "BDA page table was not requested"); + return table->DeviceAddress(); +} + +VkDeviceAddress BdaResources::FaultAddress() const { + return faultChunk->buffer->DeviceAddress() + faultOffset; +} + namespace { std::atomic loopGuardTripped{false}; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp new file mode 100644 index 000000000000..88fc2ddf000f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -0,0 +1,1718 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "PushDataLayout.hpp" +#include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "Recompiler.hpp" +#include "RuntimeAbi.hpp" +#include "SpirvBackend/SpirvAnalysis.hpp" +#include "prx/libc/include/HostThreadLocal.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__SSE2__) || defined(_M_X64) +#include +#endif + +namespace AgcDriver::Graphics { + + +namespace { + +namespace Abi = ShaderRecompiler::RuntimeAbi; + +constexpr std::size_t SpanAlignment = 16u; + +bool pipelineStats() { + static const bool enabled = std::getenv("APS5_PIPELINE_STATS") != nullptr; + return enabled; +} + +bool isSampledKind(std::uint32_t kind) { + return kind >= Abi::FirstImageBinding && kind < Abi::FirstStorageImageBinding; +} + +bool isImageKind(std::uint32_t kind) { + return kind >= Abi::FirstImageBinding && kind < BindlessHeap::SamplerKind; +} + + +std::atomic heapComputeStages{0}; +std::atomic descriptorHeapDevice{false}; +std::atomic imageTableBuilds{0}; +std::atomic dataAddressPushes{0}; +std::atomic pushedUserDataKeeps{0}; +std::atomic userWordsRewrites{0}; +std::atomic userWordsRewriteBlockWords{0}; +std::atomic userWordsRewriteUserWords{0}; +std::atomic embeddedSamplerMappings{0}; +std::atomic emptyResourceSets{0}; + +} + +namespace { + +std::uint32_t HeapEnvironmentNumber(const char* name, std::uint32_t fallback, std::uint32_t maximum) { + const char* text = std::getenv(name); + if (text == nullptr || *text == '\0') return fallback; + std::uint32_t value = 0; + const auto* end = text + std::strlen(text); + const auto parsed = std::from_chars(text, end, value); + if (parsed.ec != std::errc{} || parsed.ptr != end || value > maximum) throw std::runtime_error(std::string(name) + " must be an integer from 0 through " + std::to_string(maximum)); + return value; +} + +} + +bool GpuHeapEnabled() { + static const bool enabled = [] { + const char* value = std::getenv("APS5_GPU_HEAP"); + return value != nullptr && std::string_view(value) != "0"; + }(); + return enabled; +} + +void NoteImageTableBuild() { + imageTableBuilds.fetch_add(1, std::memory_order_relaxed); +} + +std::uint64_t ImageTableBuilds() { + return imageTableBuilds.load(std::memory_order_relaxed); +} + +namespace { + +template +void countOnRecordingThread(std::atomic& counter, std::type_identity_t amount) { + counter.store(counter.load(std::memory_order_relaxed) + amount, std::memory_order_relaxed); +} + +} + +void NoteDataAddressPush() { + countOnRecordingThread(dataAddressPushes, 1); +} + +std::uint64_t DataAddressPushes() { + return dataAddressPushes.load(std::memory_order_relaxed); +} + +void NotePushedUserDataKeep() { + countOnRecordingThread(pushedUserDataKeeps, 1); +} + +void NoteUserWordsRewrite(std::size_t blockWords, std::size_t userWords) { + countOnRecordingThread(userWordsRewrites, 1); + countOnRecordingThread(userWordsRewriteBlockWords, blockWords); + countOnRecordingThread(userWordsRewriteUserWords, userWords); +} + +std::uint64_t PushedUserDataKeeps() { + return pushedUserDataKeeps.load(std::memory_order_relaxed); +} + +std::uint64_t EmbeddedSamplerMappings() { + return embeddedSamplerMappings.load(std::memory_order_relaxed); +} + +void NoteEmptyResourceSet() { + countOnRecordingThread(emptyResourceSets, 1); +} + +std::uint64_t EmptyResourceSets() { + return emptyResourceSets.load(std::memory_order_relaxed); +} + +void NoteHeapComputeStage() { + heapComputeStages.fetch_add(1, std::memory_order_relaxed); +} + +std::uint64_t HeapComputeStages() { + return heapComputeStages.load(std::memory_order_relaxed); +} + +void SetDescriptorHeapDevice(bool available) { + descriptorHeapDevice.store(available, std::memory_order_relaxed); +} + +bool DescriptorHeapEnabled() { + return GpuHeapEnabled() && descriptorHeapDevice.load(std::memory_order_relaxed); +} + +std::uint32_t PushedBufferRecordCap() { + static const std::uint32_t cap = [] { + return HeapEnvironmentNumber("APS5_PUSHED_BUFFER_RECORDS", ShaderRecompiler::RuntimeAbi::PushedBufferLimit, ShaderRecompiler::RuntimeAbi::PushedBufferLimit); + }(); + return cap; +} + +namespace { + +std::atomic uniformConstantBuffers{false}; + +} + +bool ChooseUniformConstantBuffers(bool standardLayout, const VkPhysicalDeviceLimits& limits) { + const bool chosen = standardLayout && limits.maxUniformBufferRange >= ShaderRecompiler::RuntimeAbi::UniformConstantBufferBytes && + limits.minUniformBufferOffsetAlignment <= ShaderRecompiler::RuntimeAbi::UniformViewAdjustmentLimit + 1u; + uniformConstantBuffers.store(chosen, std::memory_order_relaxed); + return chosen; +} + +bool UniformConstantBuffersEnabled() { + return DescriptorHeapEnabled() && uniformConstantBuffers.load(std::memory_order_relaxed); +} + +namespace { + +struct HeapSizes { + std::uint32_t imageSlots = 0; + VkDeviceSize imageStride = 0; + VkDeviceSize samplerStride = 0; + VkDeviceSize pixelLdsOffset = 0; + VkDeviceSize meshWindowOffset = 0; + VkDeviceSize resourceUsed = 0; + VkDeviceSize samplerUsed = 0; +}; + +VkDeviceSize alignUp(VkDeviceSize value, VkDeviceSize alignment) { + return alignment == 0 ? value : (value + alignment - 1) / alignment * alignment; +} + +constexpr std::uint32_t MaximumImageSlots = 1u << 19u; + +HeapSizes heapLayout(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, std::uint32_t slots) { + HeapSizes sizes; + sizes.imageSlots = slots; + sizes.imageStride = alignUp(properties.imageDescriptorSize, properties.imageDescriptorAlignment); + sizes.samplerStride = alignUp(properties.samplerDescriptorSize, properties.samplerDescriptorAlignment); + const auto imageBytes = static_cast(slots) * sizes.imageStride; + sizes.pixelLdsOffset = alignUp(imageBytes, properties.bufferDescriptorAlignment); + sizes.meshWindowOffset = alignUp(sizes.pixelLdsOffset + properties.bufferDescriptorSize, properties.bufferDescriptorAlignment); + sizes.resourceUsed = alignUp(sizes.meshWindowOffset + properties.bufferDescriptorSize, properties.resourceHeapAlignment); + sizes.samplerUsed = alignUp(static_cast(Abi::GpuSamplerHeapSlots) * sizes.samplerStride, properties.samplerHeapAlignment); + return sizes; +} + +VkDeviceSize layoutEnd(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, const HeapSizes& sizes) { + return sizes.resourceUsed + properties.minResourceHeapReservedRange; +} + +HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { + const auto base = heapLayout(properties, Abi::GpuImageHeapSlots); + const auto end = layoutEnd(properties, base); + if (end >= properties.maxResourceHeapSize || base.imageStride == 0u) return base; + auto slots = static_cast(std::min(MaximumImageSlots, Abi::GpuImageHeapSlots + (properties.maxResourceHeapSize - end) / base.imageStride)); + while (slots > Abi::GpuImageHeapSlots) { + const auto grown = heapLayout(properties, slots); + const auto grownEnd = layoutEnd(properties, grown); + if (grownEnd <= properties.maxResourceHeapSize) return grown; + const auto over = grownEnd - properties.maxResourceHeapSize; + const auto step = static_cast(std::min(slots, over / base.imageStride + 1u)); + slots = slots - step > Abi::GpuImageHeapSlots ? slots - step : Abi::GpuImageHeapSlots; + } + return base; +} + +} + +bool BindlessHeap::Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { + const auto sizes = heapLayout(properties, Abi::GpuImageHeapSlots); + const bool resourcesFit = sizes.resourceUsed + properties.minResourceHeapReservedRange <= properties.maxResourceHeapSize; + const bool samplersFit = sizes.samplerUsed + properties.minSamplerHeapReservedRangeWithEmbedded <= properties.maxSamplerHeapSize; + return resourcesFit && samplersFit; +} + + +namespace { + +std::uint32_t configuredSlotCap(std::uint32_t slots) { + static const std::uint32_t requested = [] { + return HeapEnvironmentNumber("APS5_HEAP_SLOT_CAP", 0u, ~0u); + }(); + if (requested == 0u || slots <= BindlessHeap::SamplerKind) return slots; + return BindlessHeap::SamplerKind + std::min(requested, slots - BindlessHeap::SamplerKind); +} + +std::atomic deviceImageSlots{Abi::GpuImageHeapSlots}; + +constexpr VkBufferUsageFlags DataBlockUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + +std::unique_ptr makeHeapBuffer(const Context& context, std::size_t bytes, VkBufferUsageFlags usage) { + constexpr VkMemoryPropertyFlags deviceVisible = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + try { + return std::make_unique(context, bytes, usage, deviceVisible); + } catch (const std::exception&) { + } + return std::make_unique(context, bytes, usage); +} + +} + +BindlessHeap::BindlessHeap(const Context& context) : context(context) { + Require(context.descriptorHeap, "the GPU heap needs VK_EXT_descriptor_heap"); + const auto& heapProperties = context.descriptorHeapProperties; + const auto sizes = heapSizes(heapProperties); + imageHeapStride = sizes.imageStride; + samplerHeapStride = sizes.samplerStride; + resourceHeapUsed = sizes.resourceUsed; + pixelLdsHeapOffset = sizes.pixelLdsOffset; + meshWindowHeapOffset = sizes.meshWindowOffset; + samplerHeapUsed = sizes.samplerUsed; + Require(Fits(heapProperties), "the GPU heap's slots exceed the device's descriptor heap sizes"); + constexpr VkBufferUsageFlags heapUsage = VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + resourceHeap = makeHeapBuffer(context, static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange), heapUsage); + samplerHeap = makeHeapBuffer(context, static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); + std::fill(resourceHeap->Bytes().begin(), resourceHeap->Bytes().end(), std::byte{0}); + std::fill(samplerHeap->Bytes().begin(), samplerHeap->Bytes().end(), std::byte{0}); + writeResourceDescriptors = context.Function("vkWriteResourceDescriptorsEXT"); + poolAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, SpanAlignment})); + slotCap = configuredSlotCap(sizes.imageSlots); + deviceImageSlots.store(slotCap, std::memory_order_relaxed); + slotUses = std::make_unique[]>(slotCap); + imagePool.Configure(SamplerKind, slotCap); + samplerPool.Configure(0u, Abi::GpuSamplerHeapSlots); + samplerUses = std::make_unique[]>(Abi::GpuSamplerHeapSlots); +} + +namespace { + +constexpr std::uint32_t ImageSlotMargin = 1024u; +constexpr std::uint32_t EvictIdleSubmissions = 2u; +constexpr std::uint32_t SamplerSlotMargin = Abi::GpuSamplerHeapSlots / 4u; +std::atomic refusedHeaps{0}; + +} + +BindlessHeap::~BindlessHeap() { + if (refused) refusedHeaps.fetch_sub(1, std::memory_order_relaxed); +} + +namespace { + +std::mutex& heapsMutex() { + static auto& mutex = *new std::mutex(); + return mutex; +} + +std::unordered_map>& heaps() { + static auto& map = *new std::unordered_map>(); + return map; +} + +std::atomic heapsEpoch{0}; + +} + +namespace { + +struct CachedHeap { + VkDevice device = VK_NULL_HANDLE; + BindlessHeap* heap = nullptr; + std::uint64_t epoch = ~std::uint64_t{0}; +}; + +CachedHeap& ThreadCachedHeap() { + thread_local CachedHeap cached; + return cached; +} + +BindlessHeap* cachedHeap(VkDevice device) { + const auto& cached = ThreadCachedHeap(); + return cached.device == device && cached.epoch == heapsEpoch.load(std::memory_order_acquire) ? cached.heap : nullptr; +} + +} + +BindlessHeap& BindlessHeap::For(const Context& context) { + if (auto* cached = cachedHeap(context.device)) return *cached; + std::lock_guard lock(heapsMutex()); + auto& heap = heaps()[context.device]; + if (heap == nullptr) { + heap = std::make_unique(context); + heapsEpoch.fetch_add(1, std::memory_order_acq_rel); + } + ThreadCachedHeap() = {context.device, heap.get(), heapsEpoch.load(std::memory_order_acquire)}; + return *heap; +} + +void BindlessHeap::Release(VkDevice device) { + std::unique_ptr released; + { + std::lock_guard lock(heapsMutex()); + const auto found = heaps().find(device); + if (found == heaps().end()) return; + released = std::move(found->second); + heaps().erase(found); + heapsEpoch.fetch_add(1, std::memory_order_acq_rel); + } +} + +BindlessHeap* BindlessHeap::Existing(const Context& context) { + if (auto* cached = cachedHeap(context.device)) return cached; + std::lock_guard lock(heapsMutex()); + const auto found = heaps().find(context.device); + if (found == heaps().end()) return nullptr; + ThreadCachedHeap() = {context.device, found->second.get(), heapsEpoch.load(std::memory_order_acquire)}; + return found->second.get(); +} + +std::optional BindlessHeap::TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout) { + Require(isSampledKind(kind) && texture != nullptr && view != VK_NULL_HANDLE, "bindless heap: invalid texture slot request"); + const HeapSlotOwner* owner = texture; + return imageSlot(kind, owner, view, layout, texture); +} + +std::optional BindlessHeap::StorageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view) { + Require(Abi::GpuHeapStorageKind(kind) && owner != nullptr && view != VK_NULL_HANDLE, "bindless heap: invalid storage slot request"); + return imageSlot(kind, owner, view, VK_IMAGE_LAYOUT_GENERAL, nullptr); +} + +std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout) { + Require(isImageKind(kind) && owner != nullptr && view != VK_NULL_HANDLE, "bindless heap: invalid view slot request"); + return imageSlot(kind, owner, view, layout, nullptr); +} + +std::optional BindlessHeap::imageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout, Texture* texture) { + std::lock_guard lock(mutex); + const ImageSlotKey key{kind, owner, view, layout}; + if (const auto found = imageSlots.find(key); found != imageSlots.end()) { + touchLocked(found->second); + return found->second; + } + auto slot = imagePool.Take(); + if (!slot && reclaimLocked(true)) slot = imagePool.Take(); + if (!slot) return std::nullopt; + try { + writeImageSlot(kind, *slot, view, layout); + } catch (...) { + imagePool.Free(*slot); + throw; + } + claimSlotLocked(key, *slot).texture = texture; + touchLocked(*slot); + owner->heapSlotted.store(true, std::memory_order_release); + noteTakenLocked(); + return slot; +} + +void BindlessHeap::ReleaseSlots(const HeapSlotOwner* owner) { + std::lock_guard lock(mutex); + bool released = false; + if (const auto found = ownerSlots.find(owner); found != ownerSlots.end()) { + const auto slots = std::move(found->second); + ownerSlots.erase(found); + for (const auto slot : slots) freeSlotLocked(slot); + released = true; + } + if (const auto found = samplerSlots.find(owner); found != samplerSlots.end()) { + samplerOwners[found->second] = nullptr; + samplerPinned[found->second] = false; + samplerPool.Free(found->second); + samplerSlots.erase(found); + ++counts.slotsFreed; + released = true; + } + if (!released) return; + slotSerial.fetch_add(1, std::memory_order_release); + noteReleasedLocked(); +} + +BindlessHeap::SlotOwner& BindlessHeap::claimSlotLocked(const ImageSlotKey& key, std::uint32_t slot) { + imageSlots.emplace(key, slot); + ownerSlots[key.owner].push_back(slot); + if (owners.size() <= slot) owners.resize(slot + 1u); + owners[slot].key = key; + return owners[slot]; +} + +void BindlessHeap::freeSlotLocked(std::uint32_t slot) { + auto& owner = owners[slot]; + imageSlots.erase(owner.key); + owner.texture = nullptr; + owner.key = {}; + imagePool.Free(slot); + ++counts.slotsFreed; +} + +const BindlessHeap::SlotOwner* BindlessHeap::ownerLocked(std::uint32_t slot) const { + return slot < owners.size() ? &owners[slot] : nullptr; +} + +std::optional BindlessHeap::SlotPool::Take() { + if (!free.empty()) { + const auto slot = free.back(); + free.pop_back(); + return slot; + } + if (next >= limit) return std::nullopt; + return next++; +} + +void BindlessHeap::SlotPool::Configure(std::uint32_t first, std::uint32_t slots) { + next = first; + limit = slots; + generations = std::make_unique[]>(slots); +} + +void BindlessHeap::SlotPool::Retire(std::uint32_t slot) { + generations[slot].fetch_add(1u, std::memory_order_release); +} + +void BindlessHeap::SlotPool::Free(std::uint32_t slot) { + Retire(slot); + free.push_back(slot); +} + +std::size_t BindlessHeap::SlotPool::Unused() const { + return (next < limit ? limit - next : 0u) + free.size(); +} + +std::uint32_t BindlessHeap::SlotPool::Generation(std::uint32_t slot) const { + return slot < limit ? generations[slot].load(std::memory_order_acquire) : 0u; +} + +bool BindlessHeap::NearlyFull() { + return refusedHeaps.load(std::memory_order_relaxed) != 0u; +} + + + + +std::uint32_t BindlessHeap::ImageSlotCapacity() { + return deviceImageSlots.load(std::memory_order_relaxed) - SamplerKind; +} + +std::uint32_t BindlessHeap::imageMargin() const { + return std::max(1u, std::min(ImageSlotMargin, (slotCap - SamplerKind) / 4u)); +} + +bool BindlessHeap::roomLocked() const { + if (imagePool.Unused() + retiringAssigned < 2u * static_cast(imageMargin())) return false; + return samplerPool.Unused() + samplerRetiringAssigned >= 2u * SamplerSlotMargin; +} + +void BindlessHeap::noteRefusedLocked(const char* what, std::uint32_t margin) { + if (refused) return; + refused = true; + refusedHeaps.fetch_add(1, std::memory_order_relaxed); + pressured.store(true, std::memory_order_relaxed); + std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; the next draw or dispatch submits its batch so idle slots can be evicted\n", margin, what); +} + +void BindlessHeap::noteTakenLocked() { + const auto margin = imageMargin(); + if (imagePool.Unused() >= 2u * static_cast(margin)) return; + if (imagePool.Unused() + imageRetiring() < 2u * static_cast(margin)) evictLocked(EvictIdleSubmissions); + if (!refused && imagePool.Unused() + retiringAssigned < margin) noteRefusedLocked("image", margin); +} + +void BindlessHeap::touchLocked(std::uint32_t slot) const { + if (slot < slotCap) slotUses[slot].store(useEpoch.load(std::memory_order_relaxed), std::memory_order_relaxed); +} + +void BindlessHeap::touchSamplerLocked(std::uint32_t slot) const { + if (slot < Abi::GpuSamplerHeapSlots) samplerUses[slot].store(useEpoch.load(std::memory_order_relaxed), std::memory_order_relaxed); +} + +std::uint32_t BindlessHeap::TouchSlots(std::span slots, std::span samplerSlots, std::uint32_t touched) const { + const auto epoch = useEpoch.load(std::memory_order_relaxed); + if (touched == epoch) return epoch; + for (const auto slot : slots) { + if (slot < slotCap) slotUses[slot].store(epoch, std::memory_order_relaxed); + } + for (const auto slot : samplerSlots) { + if (slot < Abi::GpuSamplerHeapSlots) samplerUses[slot].store(epoch, std::memory_order_relaxed); + } + return epoch; +} + +void BindlessHeap::evictLocked(std::uint32_t idleSubmissions) { + const auto epoch = useEpoch.load(std::memory_order_relaxed); + if (submitter == nullptr || !GuestMemory::GpuMutex().HeldByThisThread()) return; + if (idleSubmissions != 0u && evictScanEpoch == epoch) return; + if (idleSubmissions != 0u) evictScanEpoch = epoch; + std::vector> idle; + for (std::uint32_t slot = SamplerKind; slot < imagePool.next && slot < owners.size(); ++slot) { + if (owners[slot].key.owner == nullptr) continue; + const auto use = slotUses[slot].load(std::memory_order_relaxed); + if (use + idleSubmissions <= epoch) idle.emplace_back(use, slot); + } + const auto wanted = std::min(idle.size(), 4u * static_cast(imageMargin())); + if (wanted == 0u) return; + std::nth_element(idle.begin(), idle.begin() + static_cast(wanted - 1u), idle.end()); + for (std::size_t index = 0; index < wanted; ++index) { + const auto slot = idle[index].second; + auto& owner = owners[slot]; + imageSlots.erase(owner.key); + if (const auto found = ownerSlots.find(owner.key.owner); found != ownerSlots.end()) { + auto& held = found->second; + held.erase(std::remove(held.begin(), held.end(), slot), held.end()); + if (held.empty()) ownerSlots.erase(found); + } + owner.texture = nullptr; + owner.key = {}; + imagePool.Retire(slot); + retiring.push_back({slot, 0u}); + ++counts.slotsEvicted; + } + slotSerial.fetch_add(1, std::memory_order_release); +} + +void BindlessHeap::evictSamplersLocked(std::uint32_t idleSubmissions) { + const auto epoch = useEpoch.load(std::memory_order_relaxed); + if (submitter == nullptr || !GuestMemory::GpuMutex().HeldByThisThread()) return; + if (idleSubmissions != 0u && samplerEvictScanEpoch == epoch) return; + if (idleSubmissions != 0u) samplerEvictScanEpoch = epoch; + std::vector> idle; + for (std::uint32_t slot = 0; slot < samplerPool.next && slot < samplerOwners.size(); ++slot) { + if (samplerOwners[slot] == nullptr || samplerPinned[slot]) continue; + const auto use = samplerUses[slot].load(std::memory_order_relaxed); + if (use + idleSubmissions <= epoch) idle.emplace_back(use, slot); + } + const auto wanted = std::min(idle.size(), 2u * static_cast(SamplerSlotMargin)); + if (wanted == 0u) return; + std::nth_element(idle.begin(), idle.begin() + static_cast(wanted - 1u), idle.end()); + for (std::size_t index = 0; index < wanted; ++index) { + const auto slot = idle[index].second; + samplerSlots.erase(samplerOwners[slot]); + samplerOwners[slot] = nullptr; + samplerPool.Retire(slot); + retiring.push_back({slot, 0u, true}); + ++retiringSamplers; + ++counts.samplersEvicted; + } + slotSerial.fetch_add(1, std::memory_order_release); +} + +bool BindlessHeap::reclaimLocked(bool wait) { + bool reclaimed = false; + while (!retiring.empty() && retiring.front().serial != 0u) { + const auto& front = retiring.front(); + if (front.recorder != nullptr && !front.recorder->WaitSerialFor(front.serial, 0u)) { + if (!wait || reclaimed || front.serial > front.recorder->Submissions()) break; + front.recorder->WaitSerial(front.serial); + ++counts.evictionWaits; + } + const auto entry = front; + retiring.pop_front(); + if (entry.sampler) { + samplerPool.free.push_back(entry.slot); + --retiringSamplers; + --samplerRetiringAssigned; + } else { + imagePool.free.push_back(entry.slot); + --retiringAssigned; + } + reclaimed = true; + } + if (reclaimed) noteReleasedLocked(); + return reclaimed; +} + +void BindlessHeap::noteSamplerTakenLocked() { + if (samplerPool.Unused() >= 2u * SamplerSlotMargin) return; + if (samplerPool.Unused() + retiringSamplers < 2u * SamplerSlotMargin) evictSamplersLocked(EvictIdleSubmissions); + if (!refused && samplerPool.Unused() + samplerRetiringAssigned < SamplerSlotMargin) noteRefusedLocked("sampler", SamplerSlotMargin); +} + +std::optional BindlessHeap::PinnedSamplerSlot(const std::shared_ptr& sampler) { + return samplerSlot(sampler, true); +} + +void BindlessHeap::noteReleasedLocked() { + if (!refused || !roomLocked()) return; + refused = false; + refusedHeaps.fetch_sub(1, std::memory_order_relaxed); + pressured.store(false, std::memory_order_relaxed); +} + +std::uint32_t BindlessHeap::SamplerGeneration(std::uint32_t slot) const { + if (slot == Abi::NoEmbeddedSampler) return 0u; + return samplerPool.Generation(slot); +} + +bool BindlessHeap::GenerationsCurrent(std::span slots, std::span slotGenerations, + std::span samplerSlots, + std::span samplerGenerations) const { + if (slots.size() != slotGenerations.size() || samplerSlots.size() != samplerGenerations.size()) return false; + for (std::size_t i = 0; i < slots.size(); ++i) { + if (imagePool.Generation(slots[i]) != slotGenerations[i]) return false; + } + for (std::size_t i = 0; i < samplerSlots.size(); ++i) { + if (samplerSlots[i] == Abi::NoEmbeddedSampler) continue; + if (samplerPool.Generation(samplerSlots[i]) != samplerGenerations[i]) return false; + } + return true; +} + +std::uint32_t BindlessHeap::SlotGeneration(std::uint32_t slot) const { + return imagePool.Generation(slot); +} + +const Texture* BindlessHeap::SlotTexture(std::uint32_t kind, std::uint32_t slot) const { + std::lock_guard lock(mutex); + const auto* owner = ownerLocked(slot); + return owner != nullptr && owner->key.kind == kind ? owner->texture : nullptr; +} + +bool BindlessHeap::SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const HeapSlotOwner* owner, VkImageView view) const { + std::lock_guard lock(mutex); + const auto* held = ownerLocked(slot); + return held != nullptr && held->key == ImageSlotKey{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; +} + +std::uint32_t BindlessHeap::AbsentSlot(std::uint32_t kind, VkImageView view) { + Require(isImageKind(kind), "bindless heap: invalid absent slot request"); + std::lock_guard lock(mutex); + if (absentSlots.contains(kind)) return kind; + writeImageSlot(kind, kind, view, VK_IMAGE_LAYOUT_GENERAL); + absentSlots.insert(kind); + return kind; +} + +std::optional BindlessHeap::SamplerSlot(const std::shared_ptr& sampler) { + return samplerSlot(sampler, false); +} + +std::optional BindlessHeap::samplerSlot(const std::shared_ptr& sampler, bool pin) { + Require(sampler != nullptr, "bindless heap: invalid sampler slot request"); + std::lock_guard lock(mutex); + if (const auto found = samplerSlots.find(static_cast(sampler.get())); found != samplerSlots.end()) { + touchSamplerLocked(found->second); + if (pin) samplerPinned[found->second] = true; + return found->second; + } + auto slot = samplerPool.Take(); + if (!slot && reclaimLocked(true)) slot = samplerPool.Take(); + if (!slot) return std::nullopt; + try { + writeSamplerSlot(*slot, sampler->Handle()); + } catch (...) { + samplerPool.Free(*slot); + throw; + } + const HeapSlotOwner* owner = sampler.get(); + samplerSlots.emplace(owner, *slot); + if (samplerOwners.size() <= *slot) { + samplerOwners.resize(*slot + 1u, nullptr); + samplerPinned.resize(*slot + 1u, false); + } + samplerOwners[*slot] = owner; + samplerPinned[*slot] = pin; + touchSamplerLocked(*slot); + owner->heapSlotted.store(true, std::memory_order_release); + noteSamplerTakenLocked(); + return slot; +} + +BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words) { + SpanScope scope(*this); + return allocateLocked(words); +} + +BindlessHeap::SpanScope::SpanScope(const BindlessHeap& heap) : heap(heap), acquired(heap.spanOwner.load(std::memory_order_relaxed) != std::this_thread::get_id()) { + if (!acquired) return; + heap.spanMutex.lock(); + heap.spanOwner.store(std::this_thread::get_id(), std::memory_order_relaxed); +} + +BindlessHeap::SpanScope::~SpanScope() { + if (!acquired) return; + heap.spanOwner.store(std::thread::id{}, std::memory_order_relaxed); + heap.spanMutex.unlock(); +} + +void BindlessHeap::Write(const DataSpan& span, std::span words) { + Require(words.size() <= span.words.size(), "the words written to a GPU heap span exceed it"); +#if defined(__SSE2__) || defined(_M_X64) + std::size_t index = 0; + for (; index + 4u <= words.size(); index += 4u) + _mm_storeu_si128(reinterpret_cast<__m128i*>(span.words.data() + index), _mm_loadu_si128(reinterpret_cast(words.data() + index))); + auto* tail = reinterpret_cast(span.words.data()); + for (; index < words.size(); ++index) tail[index] = words[index]; +#else + std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); +#endif +} + +std::size_t BindlessHeap::makeTableBlockLocked(std::size_t bytes) { + auto buffer = makeHeapBuffer(context, bytes, DataBlockUsage); + const auto vacant = std::find_if(tableBlocks.begin(), tableBlocks.end(), [](const TableBlock& block) { return block.buffer == nullptr; }); + auto& block = vacant != tableBlocks.end() ? *vacant : tableBlocks.emplace_back(); + block.data = buffer->Bytes().data(); + block.address = buffer->DeviceAddress(); + block.buffer = std::move(buffer); + block.bytes = bytes; + block.cursor = 0; + return static_cast(&block - tableBlocks.data()); +} + +std::optional BindlessHeap::AllocateTable(const SpanScope& held, std::size_t words, TableMark& mark) { + Require(&held.heap == this, "a heap table was allocated under another heap's lock"); + const auto bytes = std::max(words, 1u) * sizeof(std::uint32_t); + std::uint32_t sizeClass = 0; + while (sizeClass < TableClasses && (static_cast(poolAlignment) << sizeClass) < bytes) ++sizeClass; + const bool dedicated = sizeClass == TableClasses || (static_cast(poolAlignment) << sizeClass) > TableBlockBytes; + std::pair place{}; + std::size_t placedBytes = 0; + if (dedicated) { + placedBytes = static_cast(alignUp(bytes, poolAlignment)); + place = {static_cast(makeTableBlockLocked(placedBytes) + 1u), 0u}; + sizeClass = TableClasses; + } else { + placedBytes = static_cast(poolAlignment) << sizeClass; + auto& free = tableFree[sizeClass]; + if (!free.empty()) { + place = free.back(); + free.pop_back(); + } else { + if (tableShared == 0u || tableBlocks[tableShared - 1u].cursor + placedBytes > tableBlocks[tableShared - 1u].bytes) tableShared = makeTableBlockLocked(TableBlockBytes) + 1u; + auto& block = tableBlocks[tableShared - 1u]; + place = {static_cast(tableShared), static_cast(block.cursor)}; + block.cursor += placedBytes; + } + } + const auto& block = tableBlocks[place.first - 1u]; + mark = {place.first, place.second, sizeClass, block.address + place.second}; + ++counts.spansWritten; + counts.poolBytes += placedBytes; + return DataSpan{place.second, std::span(reinterpret_cast(block.data + place.second), words), mark.address}; +} + +void BindlessHeap::RetireTable(const SpanScope& held, TableMark& mark) { + Require(&held.heap == this, "a heap table was retired under another heap's lock"); + if (mark.address == 0u) return; + retiredTables.push_back({mark, nullptr, 0u, false}); + mark = {}; +} + +void BindlessHeap::NoteTableKept(const SpanScope& held) { + Require(&held.heap == this, "a heap table was kept under another heap's lock"); + ++counts.spansKept; +} + +void BindlessHeap::reclaimTablesLocked() { + while (!retiredTables.empty()) { + const auto& front = retiredTables.front(); + if (!front.submitted || (front.serial != 0u && !front.recorder->WaitSerialFor(front.serial, 0u))) return; + if (front.mark.sizeClass == TableClasses) { + auto& block = tableBlocks[front.mark.block - 1u]; + block.buffer.reset(); + block.data = nullptr; + block.address = 0; + block.bytes = 0; + } else { + tableFree[front.mark.sizeClass].emplace_back(front.mark.block, front.mark.offset); + } + retiredTables.pop_front(); + } +} + +BindlessHeap::DataSpan BindlessHeap::allocateLocked(std::size_t words) { + const auto bytes = alignUp(std::max(words, 1u) * sizeof(std::uint32_t), SpanAlignment); + if (poolCurrent >= poolBlocks.size() || alignUp(poolBlocks[poolCurrent].cursor, poolAlignment) + bytes > poolBlocks[poolCurrent].bytes) poolCurrent = takePoolBlockLocked(bytes); + auto& block = poolBlocks[poolCurrent]; + const auto offset = static_cast(alignUp(block.cursor, poolAlignment)); + block.cursor = offset + bytes; + block.open = true; + ++counts.spansWritten; + counts.poolBytes += bytes; + counts.spanPeakBytes = std::max(counts.spanPeakBytes, bytes); + poolBatchBytes += bytes; + return {static_cast(offset), std::span(reinterpret_cast(block.data + offset), words), block.address + offset}; +} + +bool BindlessHeap::poolBlockDoneLocked(PoolBlock& block) { + if (block.serial == 0u) return true; + if (block.recorder == nullptr || !block.recorder->WaitSerialFor(block.serial, 0u)) return false; + block.serial = 0u; + return true; +} + +std::size_t BindlessHeap::takePoolBlockLocked(std::size_t bytes) { + const auto need = std::max(bytes, PoolBlockBytes); + auto best = poolBlocks.size(); + std::size_t vacant = poolBlocks.size(); + for (std::size_t index = 0; index < poolBlocks.size(); ++index) { + auto& block = poolBlocks[index]; + if (block.buffer == nullptr) { + vacant = std::min(vacant, index); + continue; + } + if (index == poolCurrent || block.open || block.bytes < need) continue; + if (best < poolBlocks.size() && poolBlocks[best].bytes <= block.bytes) continue; + if (poolBlockDoneLocked(block)) best = index; + } + if (best < poolBlocks.size()) { + auto& block = poolBlocks[best]; + block.cursor = 0; + ++counts.poolBlocksRecycled; + return best; + } + const auto size = need == PoolBlockBytes ? PoolBlockBytes : static_cast(alignUp(need, PoolBlockBytes)); + auto buffer = makeHeapBuffer(context, size, DataBlockUsage); + if (vacant == poolBlocks.size()) poolBlocks.emplace_back(); + auto& block = poolBlocks[vacant]; + block.data = buffer->Bytes().data(); + block.address = buffer->DeviceAddress(); + block.buffer = std::move(buffer); + block.bytes = size; + block.cursor = 0; + block.recorder = nullptr; + block.serial = 0u; + block.open = false; + ++counts.poolBlocksMade; + return vacant; +} + +void BindlessHeap::trimPoolLocked() { + std::size_t idle = 0; + for (std::size_t index = 0; index < poolBlocks.size(); ++index) { + const auto& block = poolBlocks[index]; + if (block.buffer != nullptr && index != poolCurrent && !block.open) idle += block.bytes; + } + for (std::size_t index = poolBlocks.size(); index-- > 0u && idle > PoolIdleBytes;) { + auto& block = poolBlocks[index]; + if (block.buffer == nullptr || index == poolCurrent || block.open || !poolBlockDoneLocked(block)) continue; + idle -= block.bytes; + block.buffer.reset(); + block.data = nullptr; + block.address = 0; + block.bytes = 0; + ++counts.poolBlocksFreed; + } +} + +bool BindlessHeap::TakeSlotPressure() { + if (!pressured.load(std::memory_order_relaxed)) return false; + std::lock_guard lock(mutex); + if (!refused) return false; + if (imagePool.Unused() + imageRetiring() < 2u * static_cast(imageMargin())) evictLocked(0u); + if (samplerPool.Unused() + retiringSamplers < 2u * SamplerSlotMargin) evictSamplersLocked(0u); + ++counts.slotPressureSubmits; + return true; +} + +namespace { + +struct DataBlockHit { + Buffer* buffer = nullptr; + std::byte* data = nullptr; + VkDeviceAddress address = 0; +}; + +template +std::optional findIn(const std::vector& blocks, VkDeviceAddress address, std::size_t bytes) { + for (const auto& block : blocks) { + if (block.buffer != nullptr && address >= block.address && address + bytes <= block.address + block.bytes) return DataBlockHit{block.buffer.get(), block.data, block.address}; + } + return std::nullopt; +} + +template +DataBlockHit findBlock(const PoolBlocks& pool, const TableBlocks& tables, VkDeviceAddress address, std::size_t bytes, const char* outside) { + if (const auto hit = findIn(pool, address, bytes)) return *hit; + if (const auto hit = findIn(tables, address, bytes)) return *hit; + throw std::runtime_error(outside); +} + +} + +std::span BindlessHeap::DataWords(VkDeviceAddress address, std::size_t words) const { + SpanScope scope(*this); + const auto block = findBlock(poolBlocks, tableBlocks, address, words * sizeof(std::uint32_t), "AGC bindless heap: the words read lie outside every data block"); + return {reinterpret_cast(block.data + (address - block.address)), words}; +} + +std::pair BindlessHeap::DataLocation(VkDeviceAddress address) const { + SpanScope scope(*this); + const auto block = findBlock(poolBlocks, tableBlocks, address, 1u, "AGC bindless heap: shader data lies outside every data pool block"); + return {block.buffer->Handle(), address - block.address}; +} + +void BindlessHeap::writeSamplerSlot(std::uint32_t slot, VkSampler sampler) { + auto record = FindSampler(context.device, sampler); + Require(record.has_value(), "a GPU heap sampler has no recorded create info"); + const auto offset = static_cast(slot) * samplerHeapStride; + Require(offset + samplerHeapStride <= samplerHeapUsed, "a GPU heap sampler slot lies outside the sampler heap"); + const VkHostAddressRangeEXT target{samplerHeap->Bytes().data() + offset, static_cast(samplerHeapStride)}; + if (writeSamplerDescriptors == nullptr) writeSamplerDescriptors = context.Function("vkWriteSamplerDescriptorsEXT"); + Check(writeSamplerDescriptors(context.device, 1, record->Chain(), &target), "vkWriteSamplerDescriptorsEXT"); +} + +void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImageView view, VkImageLayout layout) { + const auto offset = static_cast(slot) * imageHeapStride; + Require(offset + imageHeapStride <= resourceHeapUsed, "a GPU heap image slot lies outside the resource heap"); + auto* target = resourceHeap->Bytes().data() + offset; + if (view == VK_NULL_HANDLE) { + std::memset(target, 0, static_cast(imageHeapStride)); + return; + } + const bool storage = Abi::GpuHeapStorageKind(kind); + const auto key = static_cast(layout) | (storage ? 0x80000000u : 0u); + const auto stride = static_cast(imageHeapStride); + if (CopyEncodedImageView(context.device, view, key, std::span(target, stride))) { + ++counts.encodedCopies; + return; + } + auto record = FindImageView(context.device, view); + Require(record.has_value(), "a GPU heap image view has no recorded create info"); + const VkImageDescriptorInfoEXT imageInfo{VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT, nullptr, record->Chain(), layout}; + VkResourceDescriptorInfoEXT resource{VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}; + resource.type = storage ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + resource.data.pImage = &imageInfo; + encodeScratch.resize(stride); + const VkHostAddressRangeEXT range{encodeScratch.data(), stride}; + Check(writeResourceDescriptors(context.device, 1, &resource, &range), "vkWriteResourceDescriptorsEXT"); + std::memcpy(target, encodeScratch.data(), stride); + KeepEncodedImageView(context.device, view, record->generation, key, encodeScratch); + ++counts.encodes; +} + +namespace { + +const std::uint32_t GeneratedFaultBinding = Abi::BindingNumber(Abi::Stage::TessellationControl, Abi::Binding::FaultBuffer); + +using SetAndBinding = std::pair; + +struct HeapBindingUse { + std::vector imageBindings; + bool workgroupMemory = false; + std::uint32_t gdsBinding = ~0u; + bool faultMemory = false; + bool pixelLdsMemory = false; + bool meshWindowMemory = false; + bool scratchPoolMemory = false; + std::vector dataUniforms; + std::vector embeddedSamplers; + std::vector pushedBuffers; + bool overflowRecords = false; + std::pair refused{~0u, ~0u}; +}; + +std::optional> decoratedVariables(std::span spirv) { + constexpr std::size_t HeaderWords = 5u; + constexpr std::uint32_t DecorateWords = 4u; + if (spirv.size() < HeaderWords) return std::nullopt; + std::unordered_map decorated; + for (std::size_t at = HeaderWords; at < spirv.size();) { + const auto count = spirv[at] >> 16u; + if (count == 0u || at + count > spirv.size()) return std::nullopt; + if ((spirv[at] & 0xffffu) == static_cast(spv::OpDecorate) && count >= DecorateWords) { + auto& entry = decorated.try_emplace(spirv[at + 1u], SetAndBinding{~0u, ~0u}).first->second; + if (spirv[at + 2u] == static_cast(spv::DecorationDescriptorSet)) entry.first = spirv[at + 3u]; + if (spirv[at + 2u] == static_cast(spv::DecorationBinding)) entry.second = spirv[at + 3u]; + } + at += count; + } + return decorated; +} + +bool heapBindings(std::span spirv, const HeapBindingRoots& roots, HeapBindingUse& use) { + use = {}; + const auto decorated = decoratedVariables(spirv); + if (!decorated) return false; + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + constexpr auto firstImage = bindingCount + Abi::FirstImageBinding; + constexpr auto samplers = bindingCount + BindlessHeap::SamplerKind; + for (const auto& [id, entry] : *decorated) { + const auto [set, binding] = entry; + if (set == ~0u && binding == ~0u) continue; + if (roots.workgroupAddress && set == ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet && binding == 0u) { + use.workgroupMemory = true; + continue; + } + if (roots.gdsAddress && set == Abi::GpuGdsSet && use.gdsBinding == ~0u) { + use.gdsBinding = binding; + continue; + } + if (roots.faultAddress && set == Abi::DescriptorSet && binding == GeneratedFaultBinding) { + use.faultMemory = true; + continue; + } + if (roots.pixelLds && !use.pixelLdsMemory && set == ShaderRecompiler::PixelFunctionLdsDescriptorSet && binding == 0u) { + use.pixelLdsMemory = true; + continue; + } + if (roots.meshWindow && !use.meshWindowMemory && set == ShaderRecompiler::MeshWindowDescriptorSet && binding == 0u) { + use.meshWindowMemory = true; + continue; + } + if (roots.scratchPool && set == ShaderRecompiler::GpuScratchPoolDescriptorSet && binding == 0u) { + use.scratchPoolMemory = true; + continue; + } + const auto dataKind = binding % bindingCount; + const bool dataBlock = dataKind == static_cast(Abi::Binding::ShaderData) || dataKind == static_cast(Abi::Binding::UserData) || + dataKind == static_cast(Abi::Binding::FlattenedSrt); + if (set == Abi::GpuDataSet && dataBlock && binding / bindingCount < Abi::StageCount) { + use.dataUniforms.push_back(binding); + continue; + } + if (set == Abi::EmbeddedSamplerSet) { + use.embeddedSamplers.push_back(binding); + continue; + } + if (set == Abi::PushedBufferSet && binding == Abi::PushedBufferOverflowBinding) { + use.overflowRecords = true; + continue; + } + if (set == Abi::PushedBufferSet) { + if (std::ranges::find(use.pushedBuffers, binding) == use.pushedBuffers.end()) use.pushedBuffers.push_back(binding); + continue; + } + const bool heapImageOrSampler = set == Abi::FragmentDescriptorSet && binding >= firstImage && binding <= samplers; + if (!heapImageOrSampler) { + use.refused = entry; + return false; + } + if (std::find(use.imageBindings.begin(), use.imageBindings.end(), binding) == use.imageBindings.end()) + use.imageBindings.push_back(binding); + } + return (!roots.workgroupAddress || use.workgroupMemory) && (!roots.faultAddress || use.faultMemory) && + (!roots.pixelLds || use.pixelLdsMemory) && (!roots.meshWindow || use.meshWindowMemory) && (!roots.scratchPool || use.scratchPoolMemory); +} + +VkDescriptorSetAndBindingMappingEXT baseMapping(std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, VkDescriptorMappingSourceEXT source) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = set; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = resources; + mapping.source = source; + return mapping; +} + +VkDescriptorSetAndBindingMappingEXT heapMapping(std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, + VkDeviceSize heapOffset, VkDeviceSize stride) { + auto mapping = baseMapping(set, binding, resources, VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT); + mapping.sourceData.constantOffset.heapOffset = static_cast(heapOffset); + mapping.sourceData.constantOffset.heapArrayStride = static_cast(stride); + return mapping; +} + +std::uint32_t rootItemOffset(const ShaderRecompiler::StagePushPlacement* placement, Abi::RootItem item) { + Require(placement != nullptr && placement->Item(item) != Abi::NoPushPosition, "a heap mapping reads a root item its pipeline's push layout does not hold"); + return placement->Item(item) * static_cast(sizeof(std::uint32_t)); +} + +VkDescriptorSetAndBindingMappingEXT pushedBufferMapping(std::uint32_t binding, const ShaderRecompiler::StagePushPlacement* placement) { + Require(placement != nullptr && binding < placement->pushedBuffers, "a heap mapping reads a pushed buffer its pipeline's push layout does not count"); + auto mapping = baseMapping(Abi::PushedBufferSet, binding, VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT, + VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT); + const auto root = binding < Abi::PushedBufferLimit ? placement->bufferRoots[binding] : Abi::NoPushPosition; + if (root != Abi::NoPushPosition) { + mapping.sourceData.pushAddressOffset = root * static_cast(sizeof(std::uint32_t)); + return mapping; + } + Require(placement->bufferOverflow != Abi::NoPushPosition, "a pushed buffer outside the push data has no overflow block"); + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_INDIRECT_ADDRESS_EXT; + mapping.sourceData.indirectAddress.pushOffset = placement->bufferOverflow * static_cast(sizeof(std::uint32_t)); + mapping.sourceData.indirectAddress.addressOffset = binding * Abi::OverflowRecordWords * static_cast(sizeof(std::uint32_t)); + return mapping; +} + +VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, const ShaderRecompiler::StagePushPlacement* placement) { + const auto kind = binding % static_cast(Abi::Binding::Count); + if (kind == static_cast(Abi::Binding::FlattenedSrt)) + return HeapPushAddressMapping(Abi::GpuDataSet, binding, rootItemOffset(placement, Abi::RootItem::SrtAddress), VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT); + const bool user = kind == static_cast(Abi::Binding::UserData); + const bool userPlaced = user && placement != nullptr && placement->Item(Abi::RootItem::UserData) != Abi::NoPushPosition; + return HeapPushAddressMapping(Abi::GpuDataSet, binding, rootItemOffset(placement, userPlaced ? Abi::RootItem::UserData : Abi::RootItem::ShaderData), VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT); +} + +VkDescriptorSetAndBindingMappingEXT overflowRecordsMapping(const ShaderRecompiler::StagePushPlacement* placement) { + Require(placement != nullptr, "a heap mapping reads buffer overflow records without a push layout"); + const auto offset = placement->bufferOverflow != Abi::NoPushPosition ? placement->bufferOverflow * static_cast(sizeof(std::uint32_t)) : rootItemOffset(placement, Abi::RootItem::ShaderData); + return HeapPushAddressMapping(Abi::PushedBufferSet, Abi::PushedBufferOverflowBinding, offset, VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT); +} + +} + +bool DescriptorHeapMappable(std::span spirv, const HeapBindingRoots& roots, std::pair* refused) { + HeapBindingUse use; + const bool mappable = heapBindings(spirv, roots, use); + if (!mappable && refused != nullptr) *refused = use.refused; + if (!mappable && pipelineStats()) { + static std::mutex causesMutex; + static std::map causes; + std::lock_guard lock(causesMutex); + const auto count = ++causes[use.refused]; + if (std::has_single_bit(count)) { + std::fprintf( + stderr, + "[gpu-heap] unmappable stage: descriptor set %d binding %d (workgroup address %d, gds address %d); %llu stage variants with this cause\n", + static_cast(use.refused.first), static_cast(use.refused.second), roots.workgroupAddress ? 1 : 0, roots.gdsAddress ? 1 : 0, + static_cast(count)); + } + } + return mappable; +} + +namespace { + +constexpr std::uint32_t InternalEmbeddedSamplers = 8u; + +std::uint32_t embeddedSamplerLimit(const Context& context) { + static const auto cap = [] { + return HeapEnvironmentNumber("APS5_EMBEDDED_SAMPLER_CAP", ~0u, ~0u); + }(); + const auto device = context.descriptorHeapProperties.maxDescriptorHeapEmbeddedSamplers; + return std::min(cap, device > InternalEmbeddedSamplers ? device - InternalEmbeddedSamplers : 0u); +} + +} + +std::uint32_t BindlessHeap::EmbeddedSamplerCount() const { + std::lock_guard lock(embeddedMutex); + return embeddedSamplerCount; +} + +std::optional BindlessHeap::embeddedSamplerMapping(const ShaderRecompiler::DescriptorBinding& binding, std::size_t element) { + if (binding.samplerEmbeddedWords.size() < (element + 1u) * 4u || element >= binding.samplerDepthCompare.size()) return std::nullopt; + std::array words{}; + std::copy_n(binding.samplerEmbeddedWords.begin() + static_cast(element * 4u), 4u, words.begin()); + if (element < binding.samplerCoordinatesIgnored.size() && binding.samplerCoordinatesIgnored[element]) words[0] &= ~(1u << 15u); + const bool compare = binding.samplerDepthCompare[element]; + const bool unnormalized = element < binding.samplerUnnormalized.size() && binding.samplerUnnormalized[element]; + const bool integerBorder = element < binding.samplerIntegerBorder.size() && binding.samplerIntegerBorder[element]; + const std::array key{words[0], words[1], words[2], words[3], (compare ? 1u : 0u) | (unnormalized ? 2u : 0u) | (integerBorder ? 4u : 0u)}; + auto mapping = baseMapping(Abi::EmbeddedSamplerSet, binding.samplerEmbedded[element], VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT, VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT); + std::lock_guard lock(embeddedMutex); + auto found = embeddedSamplers.find(key); + if (found == embeddedSamplers.end()) { + auto resource = DecodeSamplerResource(words, unnormalized, true, integerBorder); + resource.compareEnable = compare; + EmbeddedSampler made; + made.info = Sampler::CreateInfo(context, resource, made.reduction); + if (embeddedSamplerCount < embeddedSamplerLimit(context)) ++embeddedSamplerCount; + else made.heapSampler = std::make_shared(context, resource); + found = embeddedSamplers.emplace(key, std::move(made)).first; + if (found->second.info.pNext != nullptr) found->second.info.pNext = &found->second.reduction; + } + auto& entry = found->second; + if (entry.heapSampler == nullptr) { + mapping.sourceData.constantOffset.pEmbeddedSampler = &entry.info; + embeddedSamplerMappings.fetch_add(1, std::memory_order_relaxed); + return mapping; + } + if (entry.slot == ~0u) { + const auto slot = PinnedSamplerSlot(entry.heapSampler); + Require(slot.has_value(), "the global sampler heap is full"); + entry.slot = *slot; + } + mapping.sourceData.constantOffset.heapOffset = static_cast(entry.slot * samplerHeapStride); + return mapping; +} + +bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, const HeapBindingRoots& roots, + const ShaderRecompiler::StagePushPlacement* placement, const std::vector* bindings, + std::uint32_t workgroupAddressOffset) { + mappings.clear(); + if (resourceHeap == nullptr) return false; + HeapBindingUse use; + if (!heapBindings(spirv, roots, use)) return false; + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + constexpr VkSpirvResourceTypeFlagsEXT imageResources = VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT | + VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | + VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; + std::sort(use.imageBindings.begin(), use.imageBindings.end()); + for (const auto binding : use.imageBindings) { + const auto kind = binding - bindingCount; + if (kind == SamplerKind) + mappings.push_back( + heapMapping(Abi::FragmentDescriptorSet, binding, VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT, 0, samplerHeapStride)); + else mappings.push_back(heapMapping(Abi::FragmentDescriptorSet, binding, imageResources, 0, imageHeapStride)); + } + std::sort(use.embeddedSamplers.begin(), use.embeddedSamplers.end()); + for (const auto binding : use.embeddedSamplers) { + if (bindings == nullptr) return false; + std::optional mapping; + for (const auto& candidate : *bindings) { + if (candidate.role != ShaderRecompiler::DescriptorRole::GuestSamplers) continue; + const auto found = std::ranges::find(candidate.samplerEmbedded, binding); + if (found == candidate.samplerEmbedded.end()) continue; + mapping = embeddedSamplerMapping(candidate, static_cast(found - candidate.samplerEmbedded.begin())); + break; + } + if (!mapping) return false; + mappings.push_back(*mapping); + } + for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, placement)); + std::ranges::sort(use.pushedBuffers); + for (const auto binding : use.pushedBuffers) mappings.push_back(pushedBufferMapping(binding, placement)); + if (use.overflowRecords) mappings.push_back(overflowRecordsMapping(placement)); + if (use.workgroupMemory) + mappings.push_back(HeapPushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset, VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT)); + if (use.scratchPoolMemory) + mappings.push_back(HeapPushAddressMapping(ShaderRecompiler::GpuScratchPoolDescriptorSet, 0, ShaderRecompiler::GpuScratchPoolAddressPushByte, VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT)); + if (use.gdsBinding != ~0u) + mappings.push_back(HeapPushAddressMapping(Abi::GpuGdsSet, use.gdsBinding, rootItemOffset(placement, Abi::RootItem::GdsAddress), VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT)); + if (use.faultMemory) + mappings.push_back(HeapPushAddressMapping(Abi::DescriptorSet, GeneratedFaultBinding, rootItemOffset(placement, Abi::RootItem::FaultAddress), VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT)); + if (use.pixelLdsMemory) + mappings.push_back(heapMapping(ShaderRecompiler::PixelFunctionLdsDescriptorSet, 0, + VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT, pixelLdsHeapOffset, 0)); + if (use.meshWindowMemory) + mappings.push_back(heapMapping(ShaderRecompiler::MeshWindowDescriptorSet, 0, + VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT, meshWindowHeapOffset, 0)); + return true; +} + +void BindlessHeap::writeBufferDescriptor(VkDeviceSize offset, VkDeviceAddress address, VkDeviceSize bytes, const char* what) { + const auto& properties = context.descriptorHeapProperties; + Require(offset + properties.bufferDescriptorSize <= resourceHeapUsed, std::string("the ") + what + " descriptor lies outside the resource heap"); + const VkDeviceAddressRangeEXT buffer{address, bytes}; + VkResourceDescriptorInfoEXT resource{VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}; + resource.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + resource.data.pAddressRange = &buffer; + const VkHostAddressRangeEXT range{resourceHeap->Bytes().data() + offset, static_cast(properties.bufferDescriptorSize)}; + Check(writeResourceDescriptors(context.device, 1, &resource, &range), + (std::string("vkWriteResourceDescriptorsEXT ") + what).c_str()); +} + +void BindlessHeap::WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes) { + writeBufferDescriptor(pixelLdsHeapOffset, address, bytes, "pixel function LDS"); +} + +void BindlessHeap::WriteMeshWindowBuffer(VkDeviceAddress address, VkDeviceSize bytes) { + writeBufferDescriptor(meshWindowHeapOffset, address, bytes, "mesh window"); +} + +namespace { + +std::mutex boundHeapsMutex; +std::unordered_set boundHeaps; +std::atomic boundHeapsEpoch{0}; +std::atomic heapBinds{0}; +std::atomic commandBuffersBegun{0}; +std::atomic cpuBufferCopies{0}; +std::atomic cpuBufferCopyBytes{0}; +std::array, static_cast(SetBindSite::Count)> setBinds{}; +std::array, static_cast(HeapExcluded::Count)> heapExcludedCounts{}; +std::array, 4> heapRecords{}; + +std::size_t heapRecordIndex(bool compute, bool heap) { + return (compute ? 2u : 0u) + (heap ? 1u : 0u); +} +std::array, static_cast(HeapStageReason::Count)> heapStageReasons{}; +constexpr std::array(HeapStageReason::Count)> HeapStageReasonNames{"heap", "disabled", "excluded"}; +constexpr std::array(SetBindSite::Count)> SetBindSiteNames{"draw", "dispatch", "detiler", + "color transfer", "presentation", "depth transfer", "staged merge", "first-sample copy", "changed copy"}; +constexpr std::array(HeapExcluded::Count)> HeapExcludedNames{"draw excluded", "dispatch excluded"}; + +constexpr bool AllNamed(std::span names) { + return std::ranges::none_of(names, [](const char* name) { return name == nullptr; }); +} +static_assert(AllNamed(HeapStageReasonNames) && AllNamed(SetBindSiteNames) && AllNamed(HeapExcludedNames), "every counter needs a name"); + +std::uint64_t takeCount(std::atomic& counter) { + return counter.exchange(0, std::memory_order_relaxed); +} + +template +std::string takeNamedCounts(std::array, N>& counters, const std::array& names) { + std::string text; + for (std::size_t i = 0; i < N; ++i) text += " " + std::string(names[i]) + " " + std::to_string(takeCount(counters[i])); + return text; +} + +unsigned long long printed(std::uint64_t value) { + return static_cast(value); +} + +void reportHeapStatistics() { + if (!pipelineStats()) return; + static std::atomic calls{0}; + if ((calls.fetch_add(1, std::memory_order_relaxed) & 1023u) != 0u) return; + static std::mutex reportMutex; + static auto last = std::chrono::steady_clock::now(); + std::unique_lock lock(reportMutex, std::try_to_lock); + if (!lock.owns_lock()) return; + const auto now = std::chrono::steady_clock::now(); + if (now - last < std::chrono::seconds(10)) return; + last = now; + const auto binds = takeNamedCounts(setBinds, SetBindSiteNames); + const auto excluded = takeNamedCounts(heapExcludedCounts, HeapExcludedNames); + const auto stageReasons = takeNamedCounts(heapStageReasons, HeapStageReasonNames); + const auto heapDraws = takeCount(heapRecords[heapRecordIndex(false, true)]); + const auto plainDraws = takeCount(heapRecords[heapRecordIndex(false, false)]); + const auto heapDispatches = takeCount(heapRecords[heapRecordIndex(true, true)]); + const auto plainDispatches = takeCount(heapRecords[heapRecordIndex(true, false)]); + const auto commandBuffers = takeCount(commandBuffersBegun); + const auto copies = takeCount(cpuBufferCopies); + const auto copiedMiB = takeCount(cpuBufferCopyBytes) >> 20u; + static BindlessHeap::Counts lastTotals; + const auto totals = BindlessHeap::TotalStatistics(); + const auto windowDelta = [](std::uint64_t now, std::uint64_t before) { return now >= before ? now - before : now; }; + const auto spansWritten = windowDelta(totals.spansWritten, lastTotals.spansWritten); + const auto spansKept = windowDelta(totals.spansKept, lastTotals.spansKept); + const auto imageEncodes = windowDelta(totals.encodes, lastTotals.encodes); + const auto imageCopies = windowDelta(totals.encodedCopies, lastTotals.encodedCopies); + const auto slotsEvicted = windowDelta(totals.slotsEvicted, lastTotals.slotsEvicted); + const auto evictionWaits = windowDelta(totals.evictionWaits, lastTotals.evictionWaits); + const auto poolMiB = windowDelta(totals.poolBytes, lastTotals.poolBytes) >> 20u; + const auto slotPressureSubmits = windowDelta(totals.slotPressureSubmits, lastTotals.slotPressureSubmits); + const auto samplersEvicted = windowDelta(totals.samplersEvicted, lastTotals.samplersEvicted); + const auto poolMade = windowDelta(totals.poolBlocksMade, lastTotals.poolBlocksMade); + const auto poolRecycled = windowDelta(totals.poolBlocksRecycled, lastTotals.poolBlocksRecycled); + const auto poolFreed = windowDelta(totals.poolBlocksFreed, lastTotals.poolBlocksFreed); + lastTotals = totals; + static std::uint64_t lastBinds = 0; + const auto bindsTotal = heapBinds.load(std::memory_order_relaxed); + const auto heapBindsSeen = windowDelta(bindsTotal, lastBinds); + lastBinds = bindsTotal; + static std::uint64_t lastPushedKeeps = 0; + const auto pushedKeepsTotal = PushedUserDataKeeps(); + const auto pushedKeeps = windowDelta(pushedKeepsTotal, lastPushedKeeps); + lastPushedKeeps = pushedKeepsTotal; + static std::array lastUserRewrites{}; + const std::array userRewriteTotals{userWordsRewrites.load(std::memory_order_relaxed), userWordsRewriteBlockWords.load(std::memory_order_relaxed), userWordsRewriteUserWords.load(std::memory_order_relaxed)}; + std::array userRewrites{}; + for (std::size_t i = 0; i < userRewrites.size(); ++i) userRewrites[i] = windowDelta(userRewriteTotals[i], lastUserRewrites[i]); + lastUserRewrites = userRewriteTotals; + const auto templates = ShaderRecompiler::HeapTemplateCounts(); + std::fprintf(stderr, + "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " + "heap binds %llu over %llu command buffers; set binds:%s; excluded:%s; draw stages:%s; " + "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept (%llu for pushed user data only), %llu written for user words only (%llu block words, %llu user words); data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", + printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), + printed(commandBuffers), binds.c_str(), excluded.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), + printed(spansWritten), printed(spansKept), printed(pushedKeeps), printed(userRewrites[0]), printed(userRewrites[1]), printed(userRewrites[2]), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.spanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); +} + +void forgetHeapBinding(VkCommandBuffer commands) { + if (!DescriptorHeapEnabled()) return; + static_cast(NotePushDataWritten()); + std::lock_guard lock(boundHeapsMutex); + if (boundHeaps.erase(commands) != 0) boundHeapsEpoch.fetch_add(1, std::memory_order_release); +} + +} + +void NoteHeapRecord(bool compute, bool heap) { + if (!pipelineStats()) return; + heapRecords[heapRecordIndex(compute, heap)].fetch_add(1, std::memory_order_relaxed); + reportHeapStatistics(); +} + +void NoteHeapStageReason(HeapStageReason reason) { + heapStageReasons[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); +} + +void NoteCpuBufferCopy(std::uint64_t bytes) { + cpuBufferCopies.fetch_add(1, std::memory_order_relaxed); + cpuBufferCopyBytes.fetch_add(bytes, std::memory_order_relaxed); +} + +void NoteHeapExcluded(HeapExcluded reason) { + heapExcludedCounts[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); +} + +std::uint64_t HeapExcludedCount(HeapExcluded reason) { + return heapExcludedCounts[static_cast(reason)].load(std::memory_order_relaxed); +} + +std::uint64_t HeapStageReasons(HeapStageReason reason) { + return heapStageReasons[static_cast(reason)].load(std::memory_order_relaxed); +} + +void NoteCommandBufferBegun(VkCommandBuffer commands) { + commandBuffersBegun.fetch_add(1, std::memory_order_relaxed); + forgetHeapBinding(commands); +} + +void CmdPushConstants(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, + std::uint32_t offset, std::uint32_t size, const void* values) { + context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, stages, offset, size, values); + forgetHeapBinding(commands); +} + +void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, + std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site) { + context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, firstSet, setCount, + sets, 0, nullptr); + if (pipelineStats()) setBinds[static_cast(site)].fetch_add(1, std::memory_order_relaxed); + forgetHeapBinding(commands); +} + +void CmdPushDescriptorSet(PFN_vkCmdPushDescriptorSetKHR push, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t set, + std::uint32_t writeCount, const VkWriteDescriptorSet* writes, SetBindSite site) { + push(commands, bindPoint, layout, set, writeCount, writes); + if (pipelineStats()) setBinds[static_cast(site)].fetch_add(1, std::memory_order_relaxed); + forgetHeapBinding(commands); +} + +std::uint64_t DescriptorHeapBinds() { + return heapBinds.load(std::memory_order_relaxed); +} + +bool HeapPassesActive(const Context& context) { + return DescriptorHeapEnabled() && context.descriptorHeap && BindlessHeap::For(context).DescriptorHeapMode(); +} + +VkDescriptorSetAndBindingMappingEXT HeapPushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset, VkSpirvResourceTypeFlagsEXT resources) { + auto mapping = baseMapping(set, binding, resources, VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT); + mapping.sourceData.pushAddressOffset = pushOffset; + return mapping; +} + +VkDescriptorSetAndBindingMappingEXT HeapPushIndexMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, + std::uint32_t pushOffset) { + auto mapping = baseMapping(set, binding, resources, VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT); + mapping.sourceData.pushIndex.pushOffset = pushOffset; + mapping.sourceData.pushIndex.heapIndexStride = static_cast(heap.ImageHeapStride()); + mapping.sourceData.pushIndex.heapArrayStride = static_cast(heap.ImageHeapStride()); + return mapping; +} + +VkDescriptorSetAndBindingMappingEXT HeapPushSampledImageMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset, const VkSamplerCreateInfo& embeddedSampler) { + auto mapping = HeapPushIndexMapping(heap, set, binding, VK_SPIRV_RESOURCE_TYPE_COMBINED_SAMPLED_IMAGE_BIT_EXT, pushOffset); + mapping.sourceData.pushIndex.pEmbeddedSampler = &embeddedSampler; + return mapping; +} + +VkPipeline CreateHeapStagePipeline(const Context& context, VkGraphicsPipelineCreateInfo info, std::uint32_t stage, std::span mappings, const char* what) { + std::vector stages(info.pStages, info.pStages + info.stageCount); + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + mappingInfo.pNext = stages[stage].pNext; + mappingInfo.mappingCount = static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + stages[stage].pNext = &mappingInfo; + info.pStages = stages.data(); + auto heapFlags = DescriptorHeapFlags(); + heapFlags.pNext = info.pNext; + info.pNext = &heapFlags; + info.layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline), what); + return pipeline; +} + +VkPipeline CreateHeapComputePipeline(const Context& context, VkComputePipelineCreateInfo info, std::span mappings) { + if (!HeapPassesActive(context)) return VK_NULL_HANDLE; + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + mappingInfo.pNext = info.stage.pNext; + mappingInfo.mappingCount = static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + info.stage.pNext = &mappingInfo; + auto heapFlags = DescriptorHeapFlags(); + heapFlags.pNext = info.pNext; + info.pNext = &heapFlags; + info.layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + if (context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline) != VK_SUCCESS) + return VK_NULL_HANDLE; + return pipeline; +} + +VkPipeline CreateHeapGraphicsPipeline(const Context& context, VkGraphicsPipelineCreateInfo info, std::span mappings) { + if (!HeapPassesActive(context)) return VK_NULL_HANDLE; + std::vector stages(info.pStages, info.pStages + info.stageCount); + std::vector mappingInfos(stages.size(), {VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}); + for (std::size_t index = 0; index < stages.size(); ++index) { + mappingInfos[index].pNext = stages[index].pNext; + mappingInfos[index].mappingCount = static_cast(mappings.size()); + mappingInfos[index].pMappings = mappings.data(); + stages[index].pNext = &mappingInfos[index]; + } + info.pStages = stages.data(); + auto heapFlags = DescriptorHeapFlags(); + heapFlags.pNext = info.pNext; + info.pNext = &heapFlags; + info.layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + if (context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline) != VK_SUCCESS) + return VK_NULL_HANDLE; + return pipeline; +} + +namespace { + +std::atomic& pushDataMark() { + static std::atomic mark{0}; + return mark; +} + +} + +std::uint64_t NotePushDataWritten() noexcept { + static std::atomic threads{0}; + thread_local const std::uint64_t base = (threads.fetch_add(1, std::memory_order_relaxed) + 1u) << 40u; + thread_local std::uint64_t sequence = 0; + const auto mark = base | (++sequence & ((std::uint64_t{1} << 40u) - 1u)); + pushDataMark().store(mark, std::memory_order_relaxed); + return mark; +} + +std::uint64_t PushDataMark() noexcept { + return pushDataMark().load(std::memory_order_relaxed); +} + +void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values, std::uint32_t offset) { + const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, offset, {values, bytes}}; + context.Function("vkCmdPushDataEXT")(commands, &data); + static_cast(NotePushDataWritten()); +} + +void CmdPushHeapData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + CmdPushData(context, commands, bytes, values); +} + +void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { + if (resourceHeap == nullptr) return; + struct LastBound { + VkCommandBuffer commands = VK_NULL_HANDLE; + const BindlessHeap* heap = nullptr; + std::uint64_t epoch = 0; + }; + thread_local LastBound last; + const auto epoch = boundHeapsEpoch.load(std::memory_order_acquire); + if (last.commands == commands && last.heap == this && last.epoch == epoch) return; + { + std::lock_guard lock(boundHeapsMutex); + const bool inserted = boundHeaps.insert(commands).second; + last = {commands, this, epoch}; + if (!inserted) return; + } + heapBinds.fetch_add(1, std::memory_order_relaxed); + VkBindHeapInfoEXT info{VK_STRUCTURE_TYPE_BIND_HEAP_INFO_EXT}; + info.heapRange = {resourceHeap->DeviceAddress(), resourceHeapUsed + context.descriptorHeapProperties.minResourceHeapReservedRange}; + info.reservedRangeOffset = resourceHeapUsed; + info.reservedRangeSize = context.descriptorHeapProperties.minResourceHeapReservedRange; + context.Function("vkCmdBindResourceHeapEXT")(commands, &info); + info.heapRange = {samplerHeap->DeviceAddress(), + samplerHeapUsed + context.descriptorHeapProperties.minSamplerHeapReservedRangeWithEmbedded}; + info.reservedRangeOffset = samplerHeapUsed; + info.reservedRangeSize = context.descriptorHeapProperties.minSamplerHeapReservedRangeWithEmbedded; + context.Function("vkCmdBindSamplerHeapEXT")(commands, &info); +} + +void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { + if (!recorder.HasTimeline()) throw std::runtime_error("AGC bindless heap: a batch using the heap was submitted by a recorder without a timeline semaphore"); + { + std::lock_guard lock(mutex); + submitter = &recorder; + useEpoch.fetch_add(1, std::memory_order_relaxed); + if (refused && imagePool.Unused() + imageRetiring() < 2u * static_cast(imageMargin())) evictLocked(EvictIdleSubmissions); + if (refused && samplerPool.Unused() + retiringSamplers < 2u * SamplerSlotMargin) evictSamplersLocked(EvictIdleSubmissions); + for (auto entry = retiring.rbegin(); entry != retiring.rend() && entry->serial == 0u; ++entry) { + entry->serial = serial; + entry->recorder = &recorder; + if (entry->sampler) ++samplerRetiringAssigned; + else ++retiringAssigned; + } + if (!retiring.empty()) reclaimLocked(false); + noteReleasedLocked(); + } + SpanScope scope(*this); + counts.poolBatchPeakBytes = std::max(counts.poolBatchPeakBytes, poolBatchBytes); + poolBatchBytes = 0; + for (std::size_t index = 0; index < poolBlocks.size(); ++index) { + auto& block = poolBlocks[index]; + if (block.buffer == nullptr || (!block.open && index != poolCurrent)) continue; + block.recorder = &recorder; + block.serial = serial; + block.open = index == poolCurrent; + } + for (auto entry = retiredTables.rbegin(); entry != retiredTables.rend() && !entry->submitted; ++entry) { + entry->recorder = &recorder; + entry->serial = serial; + entry->submitted = true; + } + reclaimTablesLocked(); + trimPoolLocked(); +} + +void BindlessHeap::RecorderDestroyed(Recorder& recorder) { + { + std::lock_guard lock(mutex); + if (submitter == &recorder) submitter = nullptr; + for (auto& entry : retiring) { + if (entry.recorder == &recorder) entry.recorder = nullptr; + } + if (!retiring.empty()) reclaimLocked(false); + } + SpanScope scope(*this); + for (auto& block : poolBlocks) { + if (block.recorder != &recorder) continue; + block.recorder = nullptr; + block.serial = 0u; + } + for (auto& entry : retiredTables) { + if (entry.recorder != &recorder) continue; + entry.recorder = nullptr; + entry.serial = 0u; + } + reclaimTablesLocked(); +} + +BindlessHeap::Counts& BindlessHeap::Counts::operator+=(const Counts& other) { + encodes += other.encodes; + encodedCopies += other.encodedCopies; + slotsFreed += other.slotsFreed; + slotsEvicted += other.slotsEvicted; + evictionWaits += other.evictionWaits; + imageSlotsHeld += other.imageSlotsHeld; + spansWritten += other.spansWritten; + spansKept += other.spansKept; + slotPressureSubmits += other.slotPressureSubmits; + samplersEvicted += other.samplersEvicted; + poolBytes += other.poolBytes; + poolBlocksMade += other.poolBlocksMade; + poolBlocksRecycled += other.poolBlocksRecycled; + poolBlocksFreed += other.poolBlocksFreed; + poolBlocksHeld += other.poolBlocksHeld; + poolBlockBytes += other.poolBlockBytes; + spanPeakBytes = std::max(spanPeakBytes, other.spanPeakBytes); + poolBatchPeakBytes = std::max(poolBatchPeakBytes, other.poolBatchPeakBytes); + return *this; +} + +BindlessHeap::Counts BindlessHeap::TotalStatistics() { + Counts totals; + std::lock_guard lock(heapsMutex()); + for (const auto& entry : heaps()) totals += entry.second->Statistics(); + return totals; +} + +BindlessHeap::Counts BindlessHeap::Statistics() const { + SpanScope scope(*this); + std::lock_guard lock(mutex); + auto snapshot = counts; + for (const auto& block : poolBlocks) { + if (block.buffer == nullptr) continue; + ++snapshot.poolBlocksHeld; + snapshot.poolBlockBytes += block.bytes; + } + snapshot.imageSlotsHeld = imagePool.next - std::min(imagePool.next, SamplerKind + imagePool.free.size() + imageRetiring()); + return snapshot; +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferAddress.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferAddress.cpp index 857cce2cc2f8..f788d9722265 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferAddress.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferAddress.cpp @@ -7,10 +7,14 @@ VkDeviceAddress Buffer::DeviceAddress() const { return deviceAddress; } +VkDeviceAddress BufferDeviceAddress(const Context& context, VkBuffer buffer) { + const VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; + return context.Function("vkGetBufferDeviceAddressKHR")(context.device, &info); +} + void Buffer::initializeAddress(VkBufferUsageFlags usage) { if ((usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) == 0) return; - const VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; - deviceAddress = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &info); + deviceAddress = BufferDeviceAddress(context, buffer); Require(deviceAddress != 0, "vkGetBufferDeviceAddressKHR returned a null address"); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp index 01f428c6ce38..ad5d2b26168a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp @@ -410,7 +410,22 @@ std::size_t BufferPool::NextCapacity(std::size_t capacity) { return capacity < classLimit ? capacity * 2 : capacity + (std::bit_floor(capacity) >> deviceClassBits); } +namespace { + +std::atomic forceAddresses{false}; + +} + +bool BufferPool::ForceAddresses() { + return forceAddresses.load(std::memory_order_relaxed); +} + +void BufferPool::SetForceAddresses(bool force) { + forceAddresses.store(force, std::memory_order_relaxed); +} + VkBufferUsageFlags BufferPool::Usage(VkBufferUsageFlags usage, VkMemoryPropertyFlags properties) { + if (ForceAddresses() && (usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) != 0) usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; return DeviceTiered(properties) ? usage | deviceUsage : usage; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index a9362b42c4dd..0a32b0c38050 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -27,6 +28,7 @@ #include "RdnaDecoder/include/RdnaDecoder/RdnaDescriptorFormat.hpp" #include #include +#include #include #include #include @@ -107,6 +109,14 @@ struct RectPush { std::array extent; }; +struct HeapRectPush { + RectPush rect; + std::uint32_t depth; + std::uint32_t texels; +}; + +static_assert(offsetof(HeapRectPush, depth) == 16 && offsetof(HeapRectPush, texels) == 20); + class DepthToStoragePass { public: explicit DepthToStoragePass(const Context& context) : context(context) { @@ -135,6 +145,13 @@ class DepthToStoragePass { auto pipelineCacheLock = context.LockPipelineCacheForUse(); created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline); } + if (created == VK_SUCCESS && HeapPassesActive(context)) { + const auto& heap = BindlessHeap::For(context); + const std::array mappings{ + HeapPushIndexMapping(heap, 0, 0, VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT, offsetof(HeapRectPush, depth)), + HeapPushIndexMapping(heap, 0, 1, HeapPassStorageImages, offsetof(HeapRectPush, texels))}; + heapPipeline = CreateHeapComputePipeline(context, info, mappings); + } context.Function("vkDestroyShaderModule")(context.device, compute, nullptr); Check(created, "vkCreateComputePipelines depth to storage"); } catch (...) { @@ -148,17 +165,31 @@ class DepthToStoragePass { VkDevice Device() const { return context.device; } - void Record(VkCommandBuffer commands, VkImageView depthPlane, VkImageView texels, std::span rects) const { + void Record(VkCommandBuffer commands, VkImageView depthPlane, const HeapSlotOwner* depthOwner, VkImageView texels, const HeapSlotOwner* texelOwner, std::span rects) const { + const auto dispatch = context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch"); + if (heapPipeline != VK_NULL_HANDLE) { + auto& heap = BindlessHeap::For(context); + const auto depthSlot = heap.ViewSlot(HeapPassSampledKind, depthOwner, depthPlane); + const auto texelSlot = depthSlot ? heap.ViewSlot(HeapPassStorageKind, texelOwner, texels) : std::nullopt; + if (texelSlot) { + heap.BindDescriptorHeaps(commands); + context.BindComputePipeline(commands, heapPipeline); + for (const auto& rect : rects) { + const HeapRectPush push{{{static_cast(rect.offset.x), static_cast(rect.offset.y)}, {rect.extent.width, rect.extent.height}}, *depthSlot, *texelSlot}; + CmdPushData(context, commands, sizeof(push), &push); + dispatch(commands, (rect.extent.width + 7u) / 8u, (rect.extent.height + 7u) / 8u, 1); + } + return; + } + } const VkDescriptorImageInfo depthInfo{VK_NULL_HANDLE, depthPlane, VK_IMAGE_LAYOUT_GENERAL}; const VkDescriptorImageInfo texelInfo{VK_NULL_HANDLE, texels, VK_IMAGE_LAYOUT_GENERAL}; const std::array writes{imageWrite(0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, depthInfo), imageWrite(1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, texelInfo)}; context.BindComputePipeline(commands, pipeline); - pushSet(commands, VK_PIPELINE_BIND_POINT_COMPUTE, layout, 0, static_cast(writes.size()), writes.data()); - const auto pushConstants = context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants"); - const auto dispatch = context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch"); + CmdPushDescriptorSet(pushSet, commands, VK_PIPELINE_BIND_POINT_COMPUTE, layout, 0, static_cast(writes.size()), writes.data(), SetBindSite::DepthTransfer); for (const auto& rect : rects) { const RectPush push{{static_cast(rect.offset.x), static_cast(rect.offset.y)}, {rect.extent.width, rect.extent.height}}; - pushConstants(commands, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); + CmdPushConstants(context, commands, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); dispatch(commands, (rect.extent.width + 7u) / 8u, (rect.extent.height + 7u) / 8u, 1); } } @@ -175,9 +206,11 @@ class DepthToStoragePass { void release() noexcept { context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); + if (heapPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, heapPipeline, nullptr); context.Function("vkDestroyPipelineLayout")(context.device, layout, nullptr); context.Function("vkDestroyDescriptorSetLayout")(context.device, setLayout, nullptr); pipeline = VK_NULL_HANDLE; + heapPipeline = VK_NULL_HANDLE; layout = VK_NULL_HANDLE; setLayout = VK_NULL_HANDLE; } @@ -187,6 +220,7 @@ class DepthToStoragePass { VkDescriptorSetLayout setLayout = VK_NULL_HANDLE; VkPipelineLayout layout = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; }; std::mutex& depthToStoragePassesMutex() { @@ -983,7 +1017,7 @@ class DepthSurface { allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); memory = AllocateImageMemory(context, allocation, requirements.memoryTypeBits, "vkAllocateMemory depth target"); Check(context.Function("vkBindImageMemory")(context.device, image, memory, 0), "vkBindImageMemory depth"); - if (target.samples != 1u) owned = std::make_shared(this->context, image, memory); + owned = std::make_shared(this->context, image, memory); VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; viewInfo.image = image; viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; @@ -1303,13 +1337,13 @@ class DepthSurface { return texture; } - std::shared_ptr FirstSample(const Texture& source, VkComponentMapping components) { + std::shared_ptr FirstSample(Texture& source, VkComponentMapping components) { auto* recorder = RecorderFor(context); Require(recorder != nullptr, "a native multisampled depth target is sampled only by recorded draws and dispatches"); const bool d16 = target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT; const auto format = d16 ? VK_FORMAT_R16_UNORM : VK_FORMAT_R32_SFLOAT; if (firstSample == nullptr) firstSample = std::make_shared(context, format, target.extent); - firstSample->copy.Record(*recorder, source.View(), source.Layout()); + firstSample->copy.Record(*recorder, source); const std::array key{static_cast(components.r), static_cast(components.g), static_cast(components.b), static_cast(components.a)}; auto& texture = firstSample->textures[key]; if (texture == nullptr) { @@ -1388,7 +1422,8 @@ class DepthSurface { } bool SampledElsewhere() const { - return std::any_of(textures.begin(), textures.end(), [](const auto& entry) { return entry.second.use_count() > 1; }); + const auto held = [](const auto& entry) { return entry.second.use_count() > 1; }; + return std::any_of(textures.begin(), textures.end(), held) || std::any_of(stencilCopy.textures.begin(), stencilCopy.textures.end(), held); } void NoteHostWrite() { @@ -1450,8 +1485,8 @@ class DepthSurface { bool Overlaps(std::uint64_t address, std::uint64_t bytes) const { const auto end = address + bytes; - if (address < target.address + depthBytes() && target.address < end) return true; - return target.stencilAddress != 0 && address < target.stencilAddress + stencilBytes() && target.stencilAddress < end; + if (address < target.address + depthPlaneBytes && target.address < end) return true; + return target.stencilAddress != 0 && address < target.stencilAddress + stencilPlaneBytes && target.stencilAddress < end; } bool PlaneCoveredBy(bool stencilPlane, std::span> written, std::span extents) const { @@ -1472,9 +1507,9 @@ class DepthSurface { } return false; }; - if (stencilPlane) return target.stencilAddress != 0 && ((target.samples == 1u && reaches(target.stencilAddress, 1u)) || covers(target.stencilAddress, target.stencilAddress + stencilBytes())); + if (stencilPlane) return target.stencilAddress != 0 && ((target.samples == 1u && reaches(target.stencilAddress, 1u)) || covers(target.stencilAddress, target.stencilAddress + stencilPlaneBytes)); const bool d16 = target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT; - return (target.samples == 1u && reaches(target.address, d16 ? 2u : 4u)) || covers(target.address, target.address + depthBytes()); + return (target.samples == 1u && reaches(target.address, d16 ? 2u : 4u)) || covers(target.address, target.address + depthPlaneBytes); } bool CoveredBy(std::span> written, std::span extents) const { @@ -1483,26 +1518,26 @@ class DepthSurface { bool StencilWrittenInMemory() const { if (target.stencilAddress == 0) return false; - GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilBytes())); - return GuestMemory::WrittenSince(target.stencilAddress, static_cast(stencilBytes()), stencilMemory); + GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilPlaneBytes)); + return GuestMemory::WrittenSince(target.stencilAddress, static_cast(stencilPlaneBytes), stencilMemory); } void NoteMemory() { - depthMemory = GuestMemory::CollectWrites(target.address, static_cast(depthBytes())); - stencilMemory = target.stencilAddress != 0 ? GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilBytes())) : 0; + depthMemory = GuestMemory::CollectWrites(target.address, static_cast(depthPlaneBytes)); + stencilMemory = target.stencilAddress != 0 ? GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilPlaneBytes)) : 0; } bool OverwrittenOnGpu() const { - std::array, 2> ranges{{{target.address, target.address + depthBytes()}, {target.stencilAddress, target.stencilAddress + stencilBytes()}}}; + std::array, 2> ranges{{{target.address, target.address + depthPlaneBytes}, {target.stencilAddress, target.stencilAddress + stencilPlaneBytes}}}; return StorageTexture::AnyPendingOverlaps(std::span(ranges).first(target.stencilAddress != 0 ? 2u : 1u)); } bool OverwrittenInMemory() const { - GuestMemory::CollectWrites(target.address, static_cast(depthBytes())); - if (GuestMemory::WrittenSince(target.address, static_cast(depthBytes()), depthMemory)) return true; + GuestMemory::CollectWrites(target.address, static_cast(depthPlaneBytes)); + if (GuestMemory::WrittenSince(target.address, static_cast(depthPlaneBytes), depthMemory)) return true; if (target.stencilAddress == 0) return false; - GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilBytes())); - return GuestMemory::WrittenSince(target.stencilAddress, static_cast(stencilBytes()), stencilMemory); + GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilPlaneBytes)); + return GuestMemory::WrittenSince(target.stencilAddress, static_cast(stencilPlaneBytes), stencilMemory); } VkImageAspectFlags pendingClear = 0; @@ -2011,6 +2046,8 @@ class DepthSurface { const Context context; const DepthTarget target; const VkFormat hostFormat; + const std::uint64_t depthPlaneBytes = target.samples == 1u ? DepthSliceBytes(target.extent, target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT ? 2u : 4u) : MultisampledDepthBytes_nid_no_patch(target.extent, target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT ? 2u : 4u, target.samples); + const std::uint64_t stencilPlaneBytes = target.samples == 1u ? DepthSliceBytes(target.extent, 1u) : MultisampledDepthBytes_nid_no_patch(target.extent, 1u, target.samples); VkImage image = VK_NULL_HANDLE; VkImageView view = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; @@ -2100,10 +2137,11 @@ class DepthSurface { info.format = hostFormat; info.subresourceRange = {static_cast(aspect), 0u, 1u, 0u, 1u}; Check(context.Function("vkCreateImageView")(context.device, &info, nullptr, &arrayView), "vkCreateImageView depth publication"); + HeapPassSlots passSlots(context); CommandBatch batch(context); constexpr VkAccessFlags writes = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT; RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, writes, VK_ACCESS_SHADER_READ_BIT); - context.detiler->DispatchMultisampleReadback(batch.Handle(), depth ? VK_FORMAT_D32_SFLOAT : VK_FORMAT_R8_UINT, linear->Handle(), 0u, linearBytes, arrayView, target.extent.width, target.extent.height, 1u, target.samples, 0u, static_cast(elements)); + context.detiler->DispatchMultisampleReadback(batch.Handle(), depth ? VK_FORMAT_D32_SFLOAT : VK_FORMAT_R8_UINT, linear->Handle(), 0u, linearBytes, arrayView, target.extent.width, target.extent.height, 1u, target.samples, 0u, static_cast(elements), &passSlots); RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); batch.SubmitAndWait(); } catch (...) { @@ -2156,6 +2194,7 @@ class DepthSurface { struct StencilCopy { VkImage image = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; + std::shared_ptr owner; std::unique_ptr staging; std::map, std::shared_ptr> textures; std::uint64_t written = 0; @@ -2177,6 +2216,7 @@ class DepthSurface { std::uint64_t stencilMemory = 0; StencilCopy stencilCopy; VkImageView transferView = VK_NULL_HANDLE; + HeapPassSlots transferSlots{context}; std::shared_ptr depthUpload; const std::shared_ptr& depthUploadImage() { @@ -2375,6 +2415,7 @@ class DepthSurface { allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); stencilCopy.memory = AllocateImageMemory(context, allocation, requirements.memoryTypeBits, "vkAllocateMemory stencil copy"); Check(context.Function("vkBindImageMemory")(context.device, stencilCopy.image, stencilCopy.memory, 0), "vkBindImageMemory stencil copy"); + stencilCopy.owner = std::make_shared(context, stencilCopy.image, stencilCopy.memory); stencilCopy.staging = std::make_unique(context, static_cast(target.extent.width) * target.extent.height, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); } catch (...) { releaseStencilCopy(); @@ -2387,7 +2428,7 @@ class DepthSurface { } auto& texture = stencilCopy.textures[key]; if (texture == nullptr) { - texture = std::make_shared(context, stencilCopy.image, VK_FORMAT_R8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT, components, viewType); + texture = std::make_shared(context, stencilCopy.image, VK_FORMAT_R8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT, components, viewType, 0, stencilCopy.owner); texture->MarkRefreshedPerUse(); } return texture; @@ -2429,19 +2470,14 @@ class DepthSurface { void releaseStencilCopy() noexcept { stencilCopy.textures.clear(); stencilCopy.staging.reset(); - if (stencilCopy.image) context.Function("vkDestroyImage")(context.device, stencilCopy.image, nullptr); - if (stencilCopy.memory) MemoryAccounting::Free(context, stencilCopy.memory); + if (stencilCopy.owner != nullptr) stencilCopy.owner.reset(); + else { + if (stencilCopy.image) context.Function("vkDestroyImage")(context.device, stencilCopy.image, nullptr); + if (stencilCopy.memory) MemoryAccounting::Free(context, stencilCopy.memory); + } stencilCopy = {}; } - std::uint64_t depthBytes() const { - const bool d16 = target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT; - return DepthSliceBytes(target.extent, d16 ? 2u : 4u); - } - - std::uint64_t stencilBytes() const { - return DepthSliceBytes(target.extent, 1u); - } PlaneStorage mirrorPlane; PlaneStorage stencilMirror; @@ -2493,7 +2529,7 @@ class DepthSurface { const auto& areas = rects != nullptr ? *rects : whole; const auto texels = storage->AtomicView(0, storage->Descriptor().dimension == TextureDimension::k2DArray); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); - depthToStoragePassFor(context).Record(commands, depthTransferView(), texels, areas); + depthToStoragePassFor(context).Record(commands, depthTransferView(), &transferSlots, texels, storage.get(), areas); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT); depthTransferPassCount.fetch_add(1, std::memory_order_relaxed); if (batch) { @@ -2588,6 +2624,7 @@ class DepthSurface { mirrorPlane = {}; stencilMirror = {}; textures.clear(); + transferSlots.Release(); if (transferView) context.Function("vkDestroyImageView")(context.device, transferView, nullptr); transferView = VK_NULL_HANDLE; if (stencilClearFb) context.Function("vkDestroyFramebuffer")(context.device, stencilClearFb, nullptr); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp new file mode 100644 index 000000000000..8844621d30db --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp @@ -0,0 +1,247 @@ +#include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +namespace { + +enum class Hook : std::size_t { CreateImageView, DestroyImageView, CreateSampler, DestroySampler, Count }; + +using RealFunctions = std::array(Hook::Count)>; + +std::mutex& recordsMutex() { + static auto& mutex = *new std::mutex(); + return mutex; +} + +std::unordered_map& realFunctions() { + static auto& map = *new std::unordered_map(); + return map; +} + +template +TFunction realFunction(VkDevice device, Hook hook) { + std::lock_guard lock(recordsMutex()); + const auto found = realFunctions().find(device); + if (found == realFunctions().end()) return nullptr; + return reinterpret_cast(found->second[static_cast(hook)]); +} + +template +struct DeviceHandle { + VkDevice device; + THandle handle; + bool operator==(const DeviceHandle& other) const { return device == other.device && handle == other.handle; } +}; + +template +struct DeviceHandleHash { + std::size_t operator()(const DeviceHandle& key) const { + const auto device = std::hash{}(key.device); + const auto handle = std::hash{}(key.handle); + return device ^ (handle + 0x9e3779b97f4a7c15ull + (device << 6u) + (device >> 2u)); + } +}; + +struct EncodedImageView { + std::uint32_t key = 0; + std::vector bytes; +}; + +struct ViewEntry { + ImageViewRecord record; + std::vector encoded; +}; + +struct SamplerEntry { + SamplerRecord record; + std::size_t creations = 0; +}; + +using ViewKey = DeviceHandle; +using SamplerKey = DeviceHandle; + +std::unordered_map>& views() { + static auto& map = *new std::unordered_map>(); + return map; +} + +std::unordered_map>& samplers() { + static auto& map = *new std::unordered_map>(); + return map; +} + +ImageViewRecord recordOf(const VkImageViewCreateInfo& info) { + ImageViewRecord record; + record.info = info; + record.info.pNext = nullptr; + for (auto* next = static_cast(info.pNext); next != nullptr; next = next->pNext) { + if (next->sType == VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO) { + record.usage = *reinterpret_cast(next); + record.hasUsage = true; + } else if (next->sType == VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT) { + record.minLod = *reinterpret_cast(next); + record.hasMinLod = true; + } + } + return record; +} + +SamplerRecord recordOf(const VkSamplerCreateInfo& info) { + SamplerRecord record; + record.info = info; + record.info.pNext = nullptr; + for (auto* next = static_cast(info.pNext); next != nullptr; next = next->pNext) { + if (next->sType == VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO) { + record.reduction = *reinterpret_cast(next); + record.hasReduction = true; + } + } + return record; +} + +VKAPI_ATTR VkResult VKAPI_CALL createImageView(VkDevice device, const VkImageViewCreateInfo* info, const VkAllocationCallbacks* allocator, + VkImageView* view) { + const auto real = realFunction(device, Hook::CreateImageView); + if (real == nullptr) return VK_ERROR_INITIALIZATION_FAILED; + const auto result = real(device, info, allocator, view); + if (result == VK_SUCCESS) { + auto record = recordOf(*info); + static std::atomic generations{0}; + record.generation = generations.fetch_add(1, std::memory_order_relaxed) + 1u; + std::lock_guard lock(recordsMutex()); + views()[{device, *view}] = ViewEntry{std::move(record), {}}; + } + return result; +} + +VKAPI_ATTR void VKAPI_CALL destroyImageView(VkDevice device, VkImageView view, const VkAllocationCallbacks* allocator) { + { + std::lock_guard lock(recordsMutex()); + views().erase({device, view}); + } + if (const auto real = realFunction(device, Hook::DestroyImageView)) real(device, view, allocator); +} + +VKAPI_ATTR VkResult VKAPI_CALL createSampler(VkDevice device, const VkSamplerCreateInfo* info, const VkAllocationCallbacks* allocator, + VkSampler* sampler) { + const auto real = realFunction(device, Hook::CreateSampler); + if (real == nullptr) return VK_ERROR_INITIALIZATION_FAILED; + const auto result = real(device, info, allocator, sampler); + if (result == VK_SUCCESS) { + auto record = recordOf(*info); + std::lock_guard lock(recordsMutex()); + auto& entry = samplers()[{device, *sampler}]; + entry.record = std::move(record); + ++entry.creations; + } + return result; +} + +VKAPI_ATTR void VKAPI_CALL destroySampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks* allocator) { + { + std::lock_guard lock(recordsMutex()); + const auto found = samplers().find({device, sampler}); + if (found != samplers().end() && --found->second.creations == 0u) samplers().erase(found); + } + if (const auto real = realFunction(device, Hook::DestroySampler)) real(device, sampler, allocator); +} + +struct ObjectHook { + const char* name; + Hook slot; + PFN_vkVoidFunction hook; +}; + +const std::array ObjectHooks{{ + {"vkCreateImageView", Hook::CreateImageView, reinterpret_cast(&createImageView)}, + {"vkDestroyImageView", Hook::DestroyImageView, reinterpret_cast(&destroyImageView)}, + {"vkCreateSampler", Hook::CreateSampler, reinterpret_cast(&createSampler)}, + {"vkDestroySampler", Hook::DestroySampler, reinterpret_cast(&destroySampler)}, +}}; + +} + +const VkImageViewCreateInfo* ImageViewRecord::Chain() { + info.pNext = nullptr; + usage.pNext = nullptr; + minLod.pNext = nullptr; + if (hasMinLod) { + minLod.pNext = info.pNext; + info.pNext = &minLod; + } + if (hasUsage) { + usage.pNext = info.pNext; + info.pNext = &usage; + } + return &info; +} + +const VkSamplerCreateInfo* SamplerRecord::Chain() { + info.pNext = nullptr; + reduction.pNext = nullptr; + if (hasReduction) info.pNext = &reduction; + return &info; +} + +PFN_vkVoidFunction DescriptorHeapObjectFunction(VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name) { + if (device == VK_NULL_HANDLE) return nullptr; + for (const auto& entry : ObjectHooks) { + if (std::strcmp(name, entry.name) != 0) continue; + const auto function = deviceProc(device, name); + if (function == nullptr) return nullptr; + std::lock_guard lock(recordsMutex()); + realFunctions()[device][static_cast(entry.slot)] = function; + return entry.hook; + } + return nullptr; +} + +bool CopyEncodedImageView(VkDevice device, VkImageView view, std::uint32_t key, std::span target) { + std::lock_guard lock(recordsMutex()); + const auto found = views().find({device, view}); + if (found == views().end()) return false; + for (const auto& encoded : found->second.encoded) { + if (encoded.key != key || encoded.bytes.size() != target.size()) continue; + std::memcpy(target.data(), encoded.bytes.data(), target.size()); + return true; + } + return false; +} + +void KeepEncodedImageView(VkDevice device, VkImageView view, std::uint64_t generation, std::uint32_t key, std::span bytes) { + std::lock_guard lock(recordsMutex()); + const auto record = views().find({device, view}); + if (record == views().end() || record->second.record.generation != generation) return; + auto& entries = record->second.encoded; + for (auto& encoded : entries) { + if (encoded.key == key) { + encoded.bytes.assign(bytes.begin(), bytes.end()); + return; + } + } + entries.push_back({key, std::vector(bytes.begin(), bytes.end())}); +} + +std::optional FindImageView(VkDevice device, VkImageView view) { + std::lock_guard lock(recordsMutex()); + const auto found = views().find({device, view}); + if (found == views().end()) return std::nullopt; + return found->second.record; +} + +std::optional FindSampler(VkDevice device, VkSampler sampler) { + std::lock_guard lock(recordsMutex()); + const auto found = samplers().find({device, sampler}); + if (found == samplers().end()) return std::nullopt; + return found->second.record; +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index b64a3f335fbb..6b6cabe801d8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1,3 +1,6 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "HeapCacheSwitch.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" @@ -128,6 +131,9 @@ struct PixelFunctionLdsPool { std::uint32_t* header = nullptr; std::uint32_t subgroupSize = 0; std::uint32_t slots = 0; + VkDeviceSize bytes = 0; + VkDeviceAddress address = 0; + const BindlessHeap* heapWritten = nullptr; bool announced = false; }; @@ -145,6 +151,9 @@ struct MeshWindowPool { Context context{}; VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; + VkDeviceSize bytes = 0; + VkDeviceAddress address = 0; + const BindlessHeap* heapWritten = nullptr; VkDescriptorPool descriptorPool = VK_NULL_HANDLE; VkDescriptorSet set = VK_NULL_HANDLE; VkDescriptorSetLayout layout = VK_NULL_HANDLE; @@ -202,6 +211,26 @@ PixelFunctionLdsLayouts PixelFunctionLdsSetLayouts(const Context& context) { return {pool.empty, pool.bufferLayout}; } +bool PoolAddressed(const Context& context) { + return context.descriptorHeap && context.bufferDeviceAddress; +} + +VkBufferUsageFlags PoolBufferUsage(bool addressed) { + return VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | (addressed ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u); +} + +constexpr VkMemoryAllocateFlagsInfo PoolAddressFlags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, nullptr, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0}; + +template +void WriteHeapPool(const Context& context, Pool& pool, const char* missingAddress, void (Heap::*write)(std::uint64_t, std::uint64_t)) { + if (!context.descriptorHeap || !DescriptorHeapEnabled()) return; + auto& heap = BindlessHeap::For(context); + if (pool.heapWritten == &heap) return; + Require(pool.address != 0, missingAddress); + (heap.*write)(pool.address, pool.bytes); + pool.heapWritten = &heap; +} + void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, std::uint32_t subgroupSize) { const auto operations = VK_SUBGROUP_FEATURE_BASIC_BIT | VK_SUBGROUP_FEATURE_BALLOT_BIT; Require((context.subgroup.supportedStages & VK_SHADER_STAGE_FRAGMENT_BIT) != 0 && (context.subgroup.supportedOperations & operations) == operations, "pixel function LDS needs fragment subgroup elect, ballot and broadcast"); @@ -218,12 +247,14 @@ void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, s const auto bytes = 16ull + stride * pool.slots; VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bufferInfo.size = bytes; - bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + const bool addressed = PoolAddressed(context); + bufferInfo.usage = PoolBufferUsage(addressed); bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; Check(context.Function("vkCreateBuffer")(context.device, &bufferInfo, nullptr, &pool.buffer), "vkCreateBuffer pixel function LDS"); VkMemoryRequirements requirements{}; context.Function("vkGetBufferMemoryRequirements")(context.device, pool.buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + if (addressed) allocation.pNext = &PoolAddressFlags; allocation.allocationSize = requirements.size; constexpr auto hostCoherent = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; constexpr auto deviceLocalHost = hostCoherent | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; @@ -254,6 +285,10 @@ void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, s Check(allocated, "vkAllocateMemory pixel function LDS"); } Check(context.Function("vkBindBufferMemory")(context.device, pool.buffer, pool.memory, 0), "vkBindBufferMemory pixel function LDS"); + pool.bytes = bytes; + if (addressed) { + pool.address = BufferDeviceAddress(context, pool.buffer); + } Check(context.Function("vkMapMemory")(context.device, pool.memory, 0, 16, 0, reinterpret_cast(&pool.header)), "vkMapMemory pixel function LDS"); pool.header[0] = 0u; pool.header[1] = 0u; @@ -281,6 +316,7 @@ void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, s pool.announced = true; } Require(pool.subgroupSize == subgroupSize, "pixel function LDS subgroup size does not match the pool"); + WriteHeapPool(context, pool, "the pixel function LDS pool has no device address for the GPU heap", &BindlessHeap::WritePixelLdsBuffer); const VkMemoryBarrier beforeFill{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT}; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &beforeFill, 0, nullptr, 0, nullptr); context.Resolved(&DeviceFunctions::cmdFillBuffer, "vkCmdFillBuffer")(commands, pool.buffer, 0, 4, 0u); @@ -306,26 +342,39 @@ VkDescriptorSetLayout MeshWindowSetLayout(const Context& context) { return pool.layout; } +void WriteMeshWindowHeap(const Context& context, MeshWindowPool& pool) { + WriteHeapPool(context, pool, "the mesh window pool has no device address for the GPU heap", &BindlessHeap::WriteMeshWindowBuffer); +} + void PrepareMeshWindow(const Context& context) { std::lock_guard lock(MeshWindowMutex()); auto& pool = MeshWindowPools()[context.device]; Require(pool.layout != VK_NULL_HANDLE, "mesh window descriptor set layout was not created"); - if (pool.set != VK_NULL_HANDLE) return; + if (pool.set != VK_NULL_HANDLE) { + WriteMeshWindowHeap(context, pool); + return; + } try { const auto bytes = (static_cast(ShaderRecompiler::MeshWindowHeaderDwords) + static_cast(ShaderRecompiler::MeshWindowSlots) * ShaderRecompiler::MeshWindowSlotDwords) * 4ull; Require(bytes <= context.limits.maxStorageBufferRange, "mesh window pool does not fit in the device storage buffer range"); VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bufferInfo.size = bytes; - bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + const bool addressed = PoolAddressed(context); + bufferInfo.usage = PoolBufferUsage(addressed); bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; Check(context.Function("vkCreateBuffer")(context.device, &bufferInfo, nullptr, &pool.buffer), "vkCreateBuffer mesh window"); VkMemoryRequirements requirements{}; context.Function("vkGetBufferMemoryRequirements")(context.device, pool.buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + if (addressed) allocation.pNext = &PoolAddressFlags; allocation.allocationSize = requirements.size; allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Check(MemoryAccounting::Allocate(context, allocation, "mesh window", &pool.memory), "vkAllocateMemory mesh window"); Check(context.Function("vkBindBufferMemory")(context.device, pool.buffer, pool.memory, 0), "vkBindBufferMemory mesh window"); + pool.bytes = bytes; + if (addressed) { + pool.address = BufferDeviceAddress(context, pool.buffer); + } const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u}; VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; poolInfo.maxSets = 1u; @@ -353,6 +402,7 @@ void PrepareMeshWindow(const Context& context) { context.Function("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &afterFill, 0, nullptr, 0, nullptr); batch.SubmitAndWait(); pool.set = set; + WriteMeshWindowHeap(context, pool); std::fprintf(stderr, "[gpu] mesh window pool: %u workgroup slots, %llu MiB\n", ShaderRecompiler::MeshWindowSlots, static_cast(bytes >> 20u)); } catch (...) { const auto layout = pool.layout; @@ -368,7 +418,7 @@ void BindMeshWindow(const Context& context, VkCommandBuffer commands, VkPipeline std::lock_guard lock(MeshWindowMutex()); const auto& pool = MeshWindowPools().at(context.device); Require(pool.set != VK_NULL_HANDLE, "mesh window buffer was not prepared"); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::MeshWindowDescriptorSet, 1, &pool.set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::MeshWindowDescriptorSet, 1, &pool.set, SetBindSite::Draw); } void ReleaseMeshWindow(VkDevice device) { @@ -391,7 +441,7 @@ void BindPixelFunctionLds(const Context& context, VkCommandBuffer commands, VkPi std::lock_guard lock(PixelLdsMutex()); const auto& pool = PixelLdsPools().at(context.device); Require(pool.set != VK_NULL_HANDLE, "pixel function LDS buffer was not prepared"); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::PixelFunctionLdsDescriptorSet, 1, &pool.set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::PixelFunctionLdsDescriptorSet, 1, &pool.set, SetBindSite::Draw); } void CheckPixelFunctionLds(const Context& context) { @@ -655,7 +705,7 @@ void recordCmaskClear(const Context& context, Recorder& recorder, const HostImpo const auto commands = recorder.Commands(); if (resident != nullptr && !resident->Cached()) recorder.KeepBytes(resident.get(), static_cast(resident->BudgetBytes())); recorder.Keep(resident); - context.detiler->DispatchCmaskClear(commands, import.buffer, HostImportOffset(import, address), bytes, view, color.extent.width, color.extent.height, color.elementBytes, color.clearWords, color.dccAddress == 0); + context.detiler->DispatchCmaskClear(commands, import.buffer, HostImportOffset(import, address), bytes, view, color.extent.width, color.extent.height, color.elementBytes, color.clearWords, color.dccAddress == 0, resident.get()); recorder.NotePendingWrite(address, bytes); proveCmask(address, bytes, GuestMemory::MarkWritten(address, bytes)); } @@ -876,6 +926,11 @@ std::array, static_cast(AddressDrawReuse return counts; } +std::array, static_cast(ShaderResources::MoveRefusal::Count)>& addressMoveRefusals() { + static std::array, static_cast(ShaderResources::MoveRefusal::Count)> counts{}; + return counts; +} + void countAddressDrawReuse(AddressDrawReuse outcome) { addressDrawReuses()[static_cast(outcome)].fetch_add(1, std::memory_order_relaxed); } @@ -1020,6 +1075,12 @@ void reportDraw(const std::array& us, const ShaderResources: } AgcDriver::ProfilePrint_nid_no_patch("%s\n", reuse); profile.addressSeen = address; + std::string refusals = "[rescache] address-based moved-buffer refusals (cumulative):"; + for (std::size_t why = 1; why < addressMoveRefusals().size(); ++why) { + const auto count = addressMoveRefusals()[why].load(std::memory_order_relaxed); + if (count != 0) refusals += std::string(" ") + ShaderResources::MoveRefusalName(static_cast(why)) + " " + std::to_string(count); + } + AgcDriver::ProfilePrint_nid_no_patch("%s\n", refusals.c_str()); } profile.totalsUs.fill(0); profile.maxUs.fill(0); @@ -1069,7 +1130,7 @@ void countCache(std::uint64_t DrawProfile::*counter) { // every draw. bool ValidationKey(const Context& context, std::span shaders, const State& state, std::vector& key) { using Stage = ShaderRecompiler::ShaderStage; - static const bool disabled = std::getenv("APS5_NO_VALIDATE_CACHE") != nullptr; + static const bool disabled = !ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::ValidateCache); const auto add = [&](auto value) { key.push_back(static_cast(value)); }; bool keyed = !disabled; if (keyed) { @@ -1090,8 +1151,9 @@ bool ValidationKey(const Context& context, std::span shade add(KeyedPushOffset(shader)); add(program.pushConstants.size()); add(program.bdaAbiVersion); - add(program.vertexAttributes.size()); - for (const auto& attribute : program.vertexAttributes) { + const auto& attributes = DrawVertexAttributes(shader); + add(attributes.size()); + for (const auto& attribute : attributes) { add(attribute.location); add(attribute.components); add(attribute.fetchIndex); @@ -1253,10 +1315,67 @@ std::uint32_t CachedFragmentOutputs(const Context& context, std::span& drawContentKeysBuilt() { + static std::atomic built{0}; + return built; +} + +bool KeysOnTemplate(const CompiledShader& shader) { + if (!MovableBuffers()) return false; + const auto* heap = shader.heap; + if (heap == nullptr || heap->base == nullptr || shader.program->heapTemplateId == 0) return false; + const auto& bindings = shader.program->bindings; + for (std::size_t index = 0; index < bindings.size(); ++index) { + const auto role = bindings[index].role; + if (role != ShaderRecompiler::DescriptorRole::GuestImages && role != ShaderRecompiler::DescriptorRole::GuestSamplers) continue; + if (index < heap->bindings.size() && !heap->bindings[index].empty()) return false; + } + return true; +} + +struct DrawKeyMemoChoice { + decltype(ShaderRecompiler::ResultKeyMemo::words)& memo; + bool memoize; +}; + +DrawKeyMemoChoice ChooseDrawKeyMemo(const CompiledShader& shader) { + const ShaderRecompiler::HeapStageWords* owner = shader.heap; + if (owner == nullptr) return {shader.program->drawKeyMemo.words, true}; + if (!owner->memoizeKey && KeysOnTemplate(shader)) owner = owner->base.get(); + return {owner->drawKeyMemo.words, owner->memoizeKey}; +} + +std::array DrawKeyOwnerWords(const CompiledShader& shader) { + const auto ownerId = shader.program->heapTemplateId != 0 ? shader.program->heapTemplateId : static_cast(reinterpret_cast(shader.program)); + const auto variant = shader.program->PipelineVariantId(); + return {static_cast(ownerId), static_cast(ownerId >> 32u), + static_cast(shader.stage) | (shader.program->heapTemplateId != 0 ? 0x80000000u : 0u), + static_cast(variant), static_cast(variant >> 32u)}; +} + +bool ReadsAddressTable(const CompiledShader& shader) { + return std::ranges::any_of(shader.program->bindings, [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable; }); +} + +void AppendMovedBufferAlignments(const CompiledShader& shader, std::uint64_t alignment, ResourceCache::Key& key) { + for (const auto& binding : shader.program->bindings) { + if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; + const auto& words = DrawGuestWords(shader, binding); + if (words.size() != static_cast(binding.count) * 4u) continue; + for (std::uint32_t element = 0; element < binding.count; ++element) { + const auto* descriptor = words.data() + static_cast(element) * 4u; + const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; + const bool empty = descriptor[2] == 0 || (descriptor[0] == 0 && (descriptor[1] & 0xffffu) == 0); + if (written || empty) continue; + key.push_back(static_cast(descriptor[0] & (alignment - 1u))); + } + } +} + ResourceCache::Key DrawResourceKey(const Context& context, std::span shaders, const ColorTarget& target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::uint64_t indexBytes, bool ranges) { ResourceCache::Key key; key.reserve(256); @@ -1267,16 +1386,31 @@ ResourceCache::Key DrawResourceKey(const Context& context, std::span(context.device)); key.push_back(static_cast(shaders.size())); + const bool inPlaceMoves = MovableBuffers() && AnyHeapShader(shaders) && std::ranges::any_of(shaders, ReadsAddressTable); + const auto alignment = inPlaceMoves ? static_cast(GuestBufferViewAlignment(context.limits)) : 0u; for (const auto& shader : shaders) { const auto sizeAt = key.size(); key.push_back(0u); - auto& memo = shader.program->drawKeyMemo.words; - if (auto words = memo.load(std::memory_order_acquire); words != nullptr) { - key.insert(key.end(), words->begin(), words->end()); + const auto [memo, memoize] = ChooseDrawKeyMemo(shader); + std::array ownerStorage{}; + std::span owner; + if (shader.heap != nullptr) { + ownerStorage = DrawKeyOwnerWords(shader); + owner = ownerStorage; + } + const auto words = memoize ? memo.load(std::memory_order_acquire) : nullptr; + if (words != nullptr && words->size() >= owner.size() && std::equal(owner.begin(), owner.end(), words->begin())) { + key.insert(key.end(), words->begin() + static_cast(owner.size()), words->end()); } else { + drawContentKeysBuilt().fetch_add(1, std::memory_order_relaxed); ShaderResources::AppendContentKey(shader, true, MovableBuffers(), key); - memo.store(std::make_shared>(key.begin() + static_cast(sizeAt + 1u), key.end()), std::memory_order_release); + if (memoize) { + auto stored = std::make_shared>(owner.begin(), owner.end()); + stored->insert(stored->end(), key.begin() + static_cast(sizeAt + 1u), key.end()); + memo.store(std::move(stored), std::memory_order_release); + } } + if (inPlaceMoves) AppendMovedBufferAlignments(shader, alignment, key); key[sizeAt] = static_cast(key.size() - sizeAt - 1u); } key.push_back(colorAttachments); @@ -1299,7 +1433,7 @@ void CheckBufferAliases(std::span shaders, const ColorTarg for (const auto& shader : shaders) { for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; - const auto& words = binding.guestDescriptor; + const auto& words = DrawGuestWords(shader, binding); 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(); @@ -1417,8 +1551,12 @@ void CountDrawSkip(DrawSkip kind, double us) { } +std::uint64_t DrawContentKeysBuilt() { + return drawContentKeysBuilt().load(std::memory_order_relaxed); +} + bool DrawRecipes() { - static const bool noDrawRecipe = std::getenv("APS5_NO_DRAW_RECIPE") != nullptr; + static const bool noDrawRecipe = !ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::DrawRecipe); return !noDrawRecipe; } @@ -1744,7 +1882,7 @@ DrawPlan planDraw(const Context& context, const State& state, const Pm4::DrawPar ValidateSampleMask(context, state, shaders); timer.phase(PhaseValidate); const auto layoutStart = timer.profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; - const auto& attributes = shaders.front().program->vertexAttributes; + const auto& attributes = DrawVertexAttributes(shaders.front()); if (recipe != nullptr) { plan.vertexInput = recipe->vertexInput; } else if (!attributes.empty()) { @@ -1752,7 +1890,7 @@ DrawPlan planDraw(const Context& context, const State& state, const Pm4::DrawPar if (plan.retainedVertexInput == nullptr) plan.vertexInput = BuildVertexInputLayout(context, attributes); } timer.charge(PhaseVertex, layoutStart); - static const bool noDrawResourceCache = std::getenv("APS5_NO_DRAW_RESOURCE_CACHE") != nullptr; + static const bool noDrawResourceCache = !ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::DrawResourceCache); static const bool noTextureCache = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr; static const bool trimKey = std::getenv("APS5_NO_DRAW_KEY_TRIM") == nullptr; plan.candidate = recipe == nullptr && !noDrawResourceCache && !noTextureCache && std::all_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->PipelineVariantId() != 0; }); @@ -1906,7 +2044,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P const bool restartLeft = draw.indirect.has_value(); auto bounds = DrawIndexRange(kept, draw.indexSize, restartLeft); constexpr std::uint32_t ZeroFetchSlack = 0x10000u; - if (const auto zeroFrom = bounds && !shaders.front().program->vertexAttributes.empty() ? ZeroFetchVertex(shaders.front().program->vertexAttributes) : std::nullopt) { + if (const auto& attributes = DrawVertexAttributes(shaders.front()); const auto zeroFrom = bounds && !attributes.empty() ? ZeroFetchVertex(attributes) : std::nullopt) { const auto limit = *zeroFrom > draw.firstVertex ? *zeroFrom - draw.firstVertex : 0u; if (bounds->highest >= limit && bounds->highest - limit >= ZeroFetchSlack) bounds = ClampDrawIndices(kept, draw.indexSize, restartLeft, limit); } @@ -1953,7 +2091,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P return inputs; } constexpr std::uint32_t ZeroFetchSlack = 0x10000u; - if (const auto zeroFrom = state.stages.mesh || shaders.front().program->vertexAttributes.empty() ? std::nullopt : ZeroFetchVertex(shaders.front().program->vertexAttributes)) { + if (const auto& attributes = DrawVertexAttributes(shaders.front()); const auto zeroFrom = state.stages.mesh || attributes.empty() ? std::nullopt : ZeroFetchVertex(attributes)) { const auto limit = *zeroFrom > draw.firstVertex ? *zeroFrom - draw.firstVertex : 0u; if (*highest >= limit && *highest - limit >= ZeroFetchSlack) { GuestMemory::FlushGpuWrites(draw.indexAddress, static_cast(indexBytes)); @@ -1990,7 +2128,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P } APS5_LOG_CHARS_OUT_DEBUG("Index validation OK"); timing.Mark("index_upload"); - const auto& attributes = shaders.front().program->vertexAttributes; + const auto& attributes = DrawVertexAttributes(shaders.front()); inputs.vertexOffsets.assign(attributes.size(), 0); inputs.vertexHandles.reserve(attributes.size()); // An indexed draw's vertex offset moves every fetch: the copy must reach the last one. @@ -2147,7 +2285,7 @@ AddressStages addressStages(std::span shaders) { auto stages = AddressStages::None; for (const auto& shader : shaders) { if (shader.program == nullptr || std::none_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable; })) continue; - if (ShaderStoresThroughAddresses(shader.program->spirv)) return AddressStages::Storing; + if (ProgramStoresThroughAddresses(*shader.program)) return AddressStages::Storing; stages = AddressStages::ReadOnly; } return stages; @@ -2254,20 +2392,23 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat auto* recorder = Recorder::Active(); std::optional> moved; bool patched = false; - if (valid && recorder != nullptr) moved = cached->MovedReadOnlyBuffers(shaders, *recorder, &state.color, &patched); + auto refusal = ShaderResources::MoveRefusal::None; + if (valid && recorder != nullptr) moved = cached->MovedReadOnlyBuffers(shaders, *recorder, &state.color, &patched, &refusal); if (moved.has_value()) { if (trimKey) CheckBufferAliases(shaders, state.color, draw.indexAddress, indexBytes); if (counted && verifyAddressDrawReuse()) verifyServedSpace(context, state, draw, shaders, snapshots, indexBytes, *cached); - static_cast(heldSpace.release()); resolved.resources = std::move(cached); resolved.moved = std::move(*moved); + if (resolved.resources->HeapStage()) resolved.resources->RefreshHeapStage(shaders); + static_cast(heldSpace.release()); + outcome.addressBased = resolved.resources->HoldsLease(); outcome.kind = KindTemplateHit; countCache(&DrawProfile::cacheHits); if (counted) reuse = AddressDrawReuse::Reused; } else if (valid || inUse) { if (valid && cached->SpaceReuse()) static_cast(cached->ReleaseSpace()); if (valid && counted) reuse = patched ? AddressDrawReuse::PatchedData : AddressDrawReuse::MovedBuffer; - countCache(&DrawProfile::cacheMisses); + if (valid && counted) addressMoveRefusals()[static_cast(refusal)].fetch_add(1, std::memory_order_relaxed); } else { if (cached->SpaceReuse()) static_cast(cached->ReleaseSpace()); SharedResourceCache().Remove(resolved.contentKey); @@ -2647,6 +2788,7 @@ void keepRecordedDraw(Recorder& recorder, const std::shared_ptr struct StagedWrite { std::shared_ptr temporary; VkImageView target = VK_NULL_HANDLE; + const HeapSlotOwner* targetOwner = nullptr; std::uint16_t mask = 0; std::uint32_t samples = 1; VkRect2D area{}; @@ -2681,14 +2823,17 @@ struct RecordedDraw { // A remapped viewport depth range reads its scale and offset from the draw's push block (the vertex shader's // RemapPositionDepth), so draws that differ only in them share one pipeline; the draw's own state supplies them. -void patchDepthRemapPush(std::array& block, const State& state) { +void patchDepthRemapPush(std::array& block, const State& state, std::span shaders) { if (state.depthRemap.mode == 0u) return; + const auto reads = [](const CompiledShader& shader) { return shader.program != nullptr && (shader.program->pushItems & ShaderRecompiler::RuntimeAbi::DepthRemapPushBit) != 0u; }; + const auto rooted = [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->dataAddressPush; }; + if (std::ranges::any_of(shaders, rooted) && !std::ranges::any_of(shaders, reads)) return; static_assert(ShaderRecompiler::DepthRemapPushOffsetBytes + ShaderRecompiler::DepthRemapPushBytes <= PipelinePushSlotBytes); const std::array words{state.depthRemap.scale, state.depthRemap.offset}; std::memcpy(block.data() + ShaderRecompiler::DepthRemapPushOffsetBytes, words.data(), sizeof(words)); } -void recordStencilReplay(const Context& context, CommandState& recording, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, std::span>> replay, std::span shaders, const ShaderResources& resources, const std::array* bytes = nullptr, VkShaderStageFlags stages = 0) { +void recordStencilReplay(const Context& context, CommandState& recording, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, std::span>> replay, std::span shaders, const ShaderResources& resources, const std::array* bytes = nullptr, VkShaderStageFlags stages = 0, const ShaderResources::DrawBindings* drawBindings = nullptr) { const auto commands = recording.Commands(); State selected = state; auto block = bytes != nullptr ? *bytes : AssemblePushConstants(shaders); @@ -2696,10 +2841,15 @@ void recordStencilReplay(const Context& context, CommandState& recording, const resources.PatchPushConstants(block); stages = PushConstantStages(shaders); } - patchDepthRemapPush(block, state); + patchDepthRemapPush(block, state, shaders); + Require(!replay.empty(), "stencil replay has no pipelines"); + const auto placements = replay.front().second->PushPlacements(); + resources.PatchDataAddresses(block, shaders, placements, drawBindings); const auto fragment = std::ranges::find_if(shaders, [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::Fragment && !shader.program->stencilReferences.empty(); }); Require(fragment != shaders.end(), "stencil replay fragment stage is missing"); - const auto referenceOffset = fragment->pushConstantOffset + fragment->program->stencilReferenceDword * sizeof(std::uint32_t); + const auto stencilItem = fragment->program->dataAddressPush ? placements[static_cast(fragment - shaders.begin())].Item(ShaderRecompiler::RuntimeAbi::RootItem::StencilReference) : 0u; + Require(stencilItem != ShaderRecompiler::RuntimeAbi::NoPushPosition, "stencil replay fragment stage has no stencil reference in its push layout"); + const auto referenceOffset = fragment->program->dataAddressPush ? stencilItem * sizeof(std::uint32_t) : fragment->pushConstantOffset + fragment->program->stencilReferenceDword * sizeof(std::uint32_t); Require(referenceOffset <= block.size() - sizeof(std::uint32_t), "stencil replay reference exceeds the push block"); const auto run = [&](const Pm4::DrawParameters& piece, std::optional firstIndex) { std::uint32_t unusedSubdraw = 0; @@ -2730,13 +2880,14 @@ void recordStencilReplay(const Context& context, CommandState& recording, const } } -void pushDrawConstants(const Pipeline& pipeline, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, std::span shaders, const ShaderResources& resources, const std::array* bytes, VkShaderStageFlags stages, VkDeviceAddress meshArguments = 0, bool restartTable = false, std::uint32_t meshLayerStride = 0) { +void pushDrawConstants(const Pipeline& pipeline, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, std::span shaders, const ShaderResources& resources, const std::array* bytes, VkShaderStageFlags stages, VkDeviceAddress meshArguments = 0, bool restartTable = false, std::uint32_t meshLayerStride = 0, const ShaderResources::DrawBindings* drawBindings = nullptr) { auto block = bytes != nullptr ? *bytes : AssemblePushConstants(shaders); if (bytes == nullptr) { resources.PatchPushConstants(block); stages = PushConstantStages(shaders); } - patchDepthRemapPush(block, state); + patchDepthRemapPush(block, state, shaders); + resources.PatchDataAddresses(block, shaders, pipeline.PushPlacements(), drawBindings); if (state.stages.tessellation) { for (const auto& shader : shaders) Require(shader.program->pushConstants.empty() || shader.pushConstantOffset >= PipelinePushSlotBytes || shader.pushConstantOffset + shader.program->pushConstants.size() <= ShaderRecompiler::TessellationLevelPushOffsetBytes, "a stage's push constants overlap the tessellation levels"); const std::array levels{state.stages.minTessellationLevel, state.stages.maxTessellationLevel}; @@ -2855,6 +3006,20 @@ bool WriteOnlyPasses() { return enabled; } +void bindDrawResources(const Context& context, VkCommandBuffer commands, const Pipeline& pipeline, const ShaderResources& resources, const ShaderResources::DrawUse* drawUse, const ShaderResources::DrawBindings* drawBindings, bool guestBuffersChecked) { + if (pipeline.DescriptorHeap()) { + resources.BindDescriptorHeaps(commands, guestBuffersChecked); + NoteEmptyResourceSet(); + } else if (drawBindings != nullptr) { + const auto set = drawBindings->allocation.set; + const auto fragmentSet = drawBindings->fragmentAllocation.set; + if (set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.Layout(), 0, 1, &set, SetBindSite::Draw); + if (fragmentSet != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, SetBindSite::Draw); + } else { + resources.BindDrawUse(commands, pipeline.Layout(), drawUse); + } +} + void recordDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, DrawInputs& inputs, RecordedDraw& record, DrawOutcome& outcome, DrawTimer& timer, double& ownWaitedMs, const DrawTraceContext* trace = nullptr) { std::uint32_t subdraw = 0; auto* recorder = record.recorder; @@ -2872,9 +3037,11 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam // A queued DCC key store over memory the draw writes or reads in place (unknown for an // address-based build), or over its GPU-side records, lands before it, as before a dispatch // (VulkanDevice::dispatch); the flush ends an open pass, so it comes before the decision. + const auto movedReadOverlaps = [&](std::uint64_t begin, std::uint64_t end) { return std::any_of(record.moved.begin(), record.moved.end(), [&](const ShaderResources::MovedBuffer& moved) { return moved.words.empty() && moved.address < end && begin < moved.address + moved.size; }); }; const auto touches = [&](std::uint64_t begin, std::uint64_t end) { const auto bytes = static_cast(end - begin); if (resources.WritesOverlap(begin, bytes) || resources.ReadsOverlap(begin, bytes)) return true; + if (movedReadOverlaps(begin, end)) return true; if (!gpuIndirect) return false; return (begin < args->arguments + args->RangeBytes() && args->arguments < end) || (args->countIndirect && begin < args->countAddress + 4 && args->countAddress < end); }; @@ -2914,9 +3081,10 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam } for (const auto image : record.multisampleImages) passAttachments.emplace_back(image, true); const bool unknownMemory = addressBased || resources.UsesAddressTable() || resources.HasCopiedWrites(); - static_cast(StorageTexture::StoreDrawnLinearTouching("draw access", [&](std::uint64_t begin, std::uint64_t end) { return std::any_of(passReads.begin(), passReads.end(), [&](const auto& read) { return read.first < end && begin < read.second; }) || resources.WritesOverlap(begin, static_cast(end - begin)); }, unknownMemory)); + static_cast(StorageTexture::StoreDrawnLinearTouching("draw access", [&](std::uint64_t begin, std::uint64_t end) { return std::any_of(passReads.begin(), passReads.end(), [&](const auto& read) { return read.first < end && begin < read.second; }) || resources.WritesOverlap(begin, static_cast(end - begin)) || movedReadOverlaps(begin, end); }, unknownMemory)); const auto drawUse = resources.BeginDrawUse(*recorder); const auto drawBindings = resources.PrepareDrawBindings(*recorder, record.moved, false, drawUse != nullptr ? drawUse->record.get() : nullptr); + if (drawBindings != nullptr) passReads.insert(passReads.end(), drawBindings->movedReads.begin(), drawBindings->movedReads.end()); static const bool addressReadPasses = std::getenv("APS5_NO_ADDRESS_READ_PASSES") == nullptr; const bool readOnlyBda = addressReadPasses && resources.BdaReadOnly(); outcome.addressDraw = addressBased; @@ -3026,16 +3194,12 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam record.pipeline->Begin(recording, *record.framebuffer, state.renderExtent, state, record.masked); } APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); - if (drawBindings != nullptr) { - const auto set = drawBindings->allocation.set; - const auto fragmentSet = drawBindings->fragmentAllocation.set; - if (set != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), 0, 1, &set, 0, nullptr); - if (fragmentSet != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, 0, nullptr); - } else { - resources.BindDrawUse(commands, record.pipeline->Layout(), drawUse.get()); - } - if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; })) BindPixelFunctionLds(context, commands, record.pipeline->Layout()); - if (UsesMeshWindow(shaders)) BindMeshWindow(context, commands, record.pipeline->Layout()); + const bool heapPipeline = record.pipeline->DescriptorHeap(); + NoteHeapRecord(false, heapPipeline); + Require(heapPipeline || !resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); + bindDrawResources(context, commands, *record.pipeline, resources, drawUse.get(), drawBindings.get(), true); + if (!heapPipeline && std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; })) BindPixelFunctionLds(context, commands, record.pipeline->Layout()); + if (!heapPipeline && UsesMeshWindow(shaders)) BindMeshWindow(context, commands, record.pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); std::array movedPush; const std::array* pushBytes = record.pushBytes; @@ -3048,7 +3212,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam pushBytes = &movedPush; } } - pushDrawConstants(*record.pipeline, commands, state, draw, shaders, resources, pushBytes, pushStages, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty(), inputs.meshLayerStride); + pushDrawConstants(*record.pipeline, commands, state, draw, shaders, resources, pushBytes, pushStages, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty(), inputs.meshLayerStride, drawBindings.get()); APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded"); static const bool timeEachDraw = std::getenv("APS5_PROFILE_GPU_DRAWS") != nullptr; auto eachDrawTiming = Recorder::NoTiming; @@ -3062,7 +3226,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam noteDrawFaultToken(context, *recorder, commands, shaders, draw, static_cast(state.stages.mesh.has_value() ? AgcDriver::FaultStage::mesh : AgcDriver::FaultStage::graphics), record.indirect != nullptr ? record.indirect->args : nullptr); if (record.stencilReplay.empty()) recordDrawCommands(context, commands, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); else { - recordStencilReplay(context, recording, state, draw, inputs, record.stencilReplay, shaders, resources, pushBytes, pushStages); + recordStencilReplay(context, recording, state, draw, inputs, record.stencilReplay, shaders, resources, pushBytes, pushStages, drawBindings.get()); for (const auto& [reference, pipeline] : record.stencilReplay) recorder->Keep(pipeline); } if (record.pipeline->SplitsFaces()) { @@ -3106,11 +3270,12 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam recorder->LeaveRenderPassOpen(passKey, drawTiming, fenced, passAccess, std::move(storeProxies)); timer.phase(PhaseRecord); keepRecordedDraw(*recorder, record.resources, std::move(record.pipeline), std::move(record.framebuffer), inputs, std::move(record.targets), std::move(record.targetSlices), state.scissor, std::move(scratch), std::move(checkRecords), record.listed, record.completion, outcome, drawUse, record.spaceKeep != nullptr && *record.spaceKeep != nullptr ? record.spaceKeep->get() : nullptr); + if (drawBindings != nullptr && !drawBindings->movedReads.empty()) recorder->NotePendingReads(drawBindings->movedReads, Recorder::ReadKind::DrawInput); timer.phase(PhaseKeep); if (!record.staged.empty()) { const auto merged = recorder->Commands(); for (auto& write : record.staged) { - RecordStagedMerge(context, merged, *write.temporary, write.target, write.mask, write.samples, write.area); + RecordStagedMerge(context, merged, *write.temporary, write.target, write.mask, write.samples, write.area, write.targetOwner); recorder->Keep(write.temporary); } } @@ -3198,6 +3363,8 @@ struct TargetBinding { std::shared_ptr multisampleOwner; std::shared_ptr stagedTemporary; VkImageView stagedTarget = VK_NULL_HANDLE; + const HeapSlotOwner* stagedTargetOwner = nullptr; + std::shared_ptr stagedTargetKeep; std::unique_ptr dump; }; @@ -3251,7 +3418,7 @@ void keepHeldSpace(PreparedDraw& prepared) { } bool ShapeMemoEnabled() { - static const bool enabled = std::getenv("APS5_NO_SHAPE_MEMO") == nullptr; + static const bool enabled = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::ShapeMemo); return enabled; } @@ -3564,7 +3731,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara recipeOut = nullptr; } if (state.quadList || StripPatches(state, shaders)) recipeOut = nullptr; - if (context.recorder != nullptr) context.recorder->BoundKeptBytes(); + if (context.recorder != nullptr) context.recorder->BoundDrawBatch(); auto& timing = prepared.timing.emplace("Graphics.Draw"); // APS5_PROFILE_DRAW prints the time of each phase of the draw (microseconds) and the [draws] totals. static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; @@ -3612,7 +3779,10 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara binding.stagedTemporary = AcquireStagedTemporary(context, color.extent, color.samples); PrepareMultisampleTargetForDraw_nid_no_patch(context, packed); static_cast(MultisampleTargetView(context, packed, binding.multisampleOwner, &binding.multisampleImage)); - binding.stagedTarget = MultisampleTargetStorageView(context, TargetMergeSurface(packed)); + const auto storage = MultisampleTargetStorageView(context, TargetMergeSurface(packed)); + binding.stagedTarget = storage.view; + binding.stagedTargetOwner = storage.owner; + binding.stagedTargetKeep = storage.keep; Require(MultisampleTargetStorable(context, packed), "a partial write of a multisampled packed color target needs a multisample image of this form to allow storage"); targetViews.push_back(binding.stagedTemporary->View()); timer.phase(PhaseReadTarget); @@ -3766,8 +3936,9 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara for (const auto& shader : shaders) { for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages && binding.role != ShaderRecompiler::DescriptorRole::ImageTable) continue; - for (std::size_t offset = 0; offset + 8u <= binding.guestDescriptor.size(); offset += 8u) { - const auto words = std::span(binding.guestDescriptor).subspan(offset, 8u); + const auto& guestWords = DrawGuestWords(shader, binding); + for (std::size_t offset = 0; offset + 8u <= guestWords.size(); offset += 8u) { + const auto words = std::span(guestWords).subspan(offset, 8u); if (words[0] == 0u && (words[1] & 0xffu) == 0u) continue; const auto texture = DecodeTextureResource(words); Require(!DepthSurfaceAt(context, words, texture), "stencil replay refuses sampled depth-surface feedback"); @@ -4037,6 +4208,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D if (binding.multisampled) { record.multisampleImages.push_back(binding.multisampleImage); record.multisampleTargets.push_back(binding.multisampleOwner); + if (binding.stagedTargetKeep != nullptr && binding.stagedTargetKeep != binding.multisampleOwner) record.multisampleTargets.push_back(binding.stagedTargetKeep); } if (binding.stagedTemporary != nullptr) { record.multisampleImages.push_back(binding.stagedTemporary->Image()); @@ -4048,7 +4220,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D const auto right = std::min(static_cast(state.scissor.offset.x) + state.scissor.extent.width, color.extent.width); const auto bottom = std::min(static_cast(state.scissor.offset.y) + state.scissor.extent.height, color.extent.height); area.extent = {static_cast(std::max(right - area.offset.x, 0)), static_cast(std::max(bottom - area.offset.y, 0))}; - record.staged.push_back({binding.stagedTemporary, binding.stagedTarget, color.stagedMask, color.samples, area}); + record.staged.push_back({binding.stagedTemporary, binding.stagedTarget, binding.stagedTargetOwner, color.stagedMask, color.samples, area}); } } record.indirect = args != nullptr ? &indirect : nullptr; @@ -4087,6 +4259,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D recipe->fragmentOutputs = inputs.fragmentOutputs; recipe->shaderStages = inputs.shaderStages; recipe->hasDepth = state.depth.has_value(); + recipe->movedBuffers = !resolved.moved.empty(); *recipeOut = std::move(recipe); } timing.Mark("draw_and_resource_release"); @@ -4213,10 +4386,11 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D APS5_LOG_OUT_DEBUG("Beginning pipeline renderExtent=%ux%u", state.renderExtent.width, state.renderExtent.height); pipeline->Begin(recording, *framebuffer, state.renderExtent, state, masked.has_value() ? &*masked : nullptr); APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); - const auto drawUse = recorded ? resources->BeginDrawUse(*recorder) : nullptr; - resources->BindDrawUse(commands, pipeline->Layout(), drawUse.get()); - if (pixelLdsSubgroup != 0u) BindPixelFunctionLds(context, commands, pipeline->Layout()); - if (UsesMeshWindow(shaders)) BindMeshWindow(context, commands, pipeline->Layout()); + const bool heapPipeline = pipeline->DescriptorHeap(); + const auto drawUse = recorded && !heapPipeline ? resources->BeginDrawUse(*recorder) : nullptr; + bindDrawResources(context, commands, *pipeline, *resources, drawUse.get(), nullptr, false); + if (pixelLdsSubgroup != 0u && !heapPipeline) BindPixelFunctionLds(context, commands, pipeline->Layout()); + if (!heapPipeline && UsesMeshWindow(shaders)) BindMeshWindow(context, commands, pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); pushDrawConstants(*pipeline, commands, state, draw, shaders, *resources, nullptr, 0, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty(), inputs.meshLayerStride); APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded"); @@ -4512,7 +4686,7 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters& DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, const DrawRecipe& recipe, const DrawTraceContext* trace) { const DepthCopySourceScope depthCopySource(state.depthCopySource); - if (context.recorder != nullptr) context.recorder->BoundKeptBytes(); + if (context.recorder != nullptr) context.recorder->BoundDrawBatch(); static_cast(snapshots); PerformanceTimer timing("Graphics.DrawWithRecipe"); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; @@ -4592,10 +4766,14 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con return miss(DrawRecipeMiss::Proof); } const auto moved = resources->MovedReadOnlyBuffers(shaders, *recorder, &state.color); - if (!moved.has_value()) return miss(DrawRecipeMiss::Buffers); + if (!moved.has_value()) { + timer.phase(PhaseLookup); + return miss(DrawRecipeMiss::Buffers); + } CheckBufferAliases(shaders, state.color, draw.indexAddress, inputs.indexBytes); + if (resources->HeapStage()) resources->RefreshHeapStage(shaders); if (recipe.hasDepth && writesDepthTarget(state)) NoteDepthSurfaceWrite(context, *state.depth); - SharedResourceCache().Touch(recipe.key); + SharedResourceCache().TouchAging(recipe.key, resources->CacheTouchedAt()); countCache(&DrawProfile::cacheHits); timer.phase(PhaseLookup); outcome.completion = resources->ChecksFaults(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp index 0e1930cc01fe..a4a9909ba329 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp @@ -1,4 +1,6 @@ #include "prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -179,6 +181,11 @@ FirstSampleCopy::FirstSampleCopy(const Context& context, VkFormat format, VkExte pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = renderPass; Check(context.Function("vkCreateGraphicsPipelines")(context.device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline), "vkCreateGraphicsPipelines first sample"); + if (HeapPassesActive(context)) { + auto mapping = HeapPushIndexMapping(BindlessHeap::For(context), 0, 0, VK_SPIRV_RESOURCE_TYPE_COMBINED_SAMPLED_IMAGE_BIT_EXT, 0); + mapping.sourceData.pushIndex.pEmbeddedSampler = &samplerInfo; + heapPipeline = CreateHeapGraphicsPipeline(context, pipelineInfo, std::span(&mapping, 1)); + } } catch (...) { release(); throw; @@ -190,6 +197,7 @@ FirstSampleCopy::~FirstSampleCopy() { } void FirstSampleCopy::release() noexcept { + if (heapPipeline) context.Function("vkDestroyPipeline")(context.device, heapPipeline, nullptr); if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); if (fragment) context.Function("vkDestroyShaderModule")(context.device, fragment, nullptr); if (vertex) context.Function("vkDestroyShaderModule")(context.device, vertex, nullptr); @@ -213,6 +221,30 @@ void FirstSampleCopy::release() noexcept { memory = VK_NULL_HANDLE; } +void FirstSampleCopy::Record(Recorder& recorder, Texture& texture) { + const auto source = texture.View(); + const auto layout = texture.Layout(); + const auto slot = heapPipeline != VK_NULL_HANDLE ? BindlessHeap::For(context).TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, &texture, source, layout) : std::nullopt; + if (slot) { + recorder.RecordUncounted([&](CommandState& recording) { + const auto commands = recording.Commands(); + BindlessHeap::For(context).BindDescriptorHeaps(commands); + VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; + begin.renderPass = renderPass; + begin.framebuffer = framebuffer; + begin.renderArea = {{0, 0}, extent}; + context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE); + recording.BindPipeline(context, heapPipeline, 0); + const std::uint32_t pushed = *slot; + CmdPushData(context, commands, sizeof(pushed), &pushed); + context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); + context.Resolved(&DeviceFunctions::cmdEndRenderPass, "vkCmdEndRenderPass")(commands); + }); + return; + } + Record(recorder, source, layout); +} + void FirstSampleCopy::Record(Recorder& recorder, VkImageView source, VkImageLayout layout) { const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1}; VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; @@ -245,7 +277,7 @@ void FirstSampleCopy::Record(Recorder& recorder, VkImageView source, VkImageLayo begin.renderArea = {{0, 0}, extent}; context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE); recording.BindPipeline(context, pipeline, 0); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, SetBindSite::FirstSampleCopy); context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); context.Resolved(&DeviceFunctions::cmdEndRenderPass, "vkCmdEndRenderPass")(commands); }); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp index 2cbe33c58770..9dc16da90d54 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/ColorTransfer_spv.h" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -6,10 +7,23 @@ #include #include #include +#include #include namespace AgcDriver::Graphics { +namespace { + +struct HeapPush { + std::array values; + std::uint32_t pad; + std::array buffers; +}; + +static_assert(offsetof(HeapPush, buffers) == 24 && sizeof(HeapPush) == 56); + +} + GpuColorTransfer::GpuColorTransfer(const Context& context) : context(context) { VkShaderModule module = VK_NULL_HANDLE; try { @@ -39,6 +53,10 @@ GpuColorTransfer::GpuColorTransfer(const Context& context) : context(context) { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &pipeline), "vkCreateComputePipelines color transfer"); } + std::array mappings{}; + for (std::uint32_t i = 0; i < mappings.size(); ++i) mappings[i] = HeapPushAddressMapping(0, i, static_cast(offsetof(HeapPush, buffers) + i * sizeof(VkDeviceAddress))); + heapPipeline = CreateHeapComputePipeline(context, pipelineInfo, mappings); + if (heapPipeline != VK_NULL_HANDLE) addressUsage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; context.Function("vkDestroyShaderModule")(context.device, module, nullptr); module = VK_NULL_HANDLE; const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4}; @@ -53,10 +71,10 @@ GpuColorTransfer::GpuColorTransfer(const Context& context) : context(context) { allocation.pSetLayouts = &descriptorLayout; Check(context.Function("vkAllocateDescriptorSets")(context.device, &allocation, &descriptorSet), "vkAllocateDescriptorSets color transfer"); const auto& table = HalfFloatScanoutThresholds(); - thresholds = std::make_unique(context, sizeof(table), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + thresholds = std::make_unique(context, sizeof(table), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | addressUsage); std::memcpy(thresholds->Bytes().data(), table.data(), sizeof(table)); const auto& luminance = AgcDriver::PqEotfNits(); - pqNits = std::make_unique(context, sizeof(luminance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + pqNits = std::make_unique(context, sizeof(luminance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | addressUsage); std::memcpy(pqNits->Bytes().data(), luminance.data(), sizeof(luminance)); const std::array tableInfo{{{thresholds->Handle(), 0, sizeof(table)}, {pqNits->Handle(), 0, sizeof(luminance)}}}; std::array tableWrites{}; @@ -83,6 +101,7 @@ GpuColorTransfer::~GpuColorTransfer() { void GpuColorTransfer::release() noexcept { if (descriptorPool) context.Function("vkDestroyDescriptorPool")(context.device, descriptorPool, nullptr); if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); + if (heapPipeline) context.Function("vkDestroyPipeline")(context.device, heapPipeline, nullptr); if (pipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, pipelineLayout, nullptr); if (descriptorLayout) context.Function("vkDestroyDescriptorSetLayout")(context.device, descriptorLayout, nullptr); } @@ -96,8 +115,8 @@ void GpuColorTransfer::prepare(std::uint32_t newWidth, std::uint32_t newHeight, if (tiled && width == newWidth && height == newHeight && mode == newMode && elementBytes == newElementBytes) return; constexpr VkBufferUsageFlags copies = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; auto newTiled = std::make_unique(context, layout.Bytes(), copies); - auto newTiledDevice = std::make_unique(context, layout.Bytes(), copies | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); - auto newLinear = std::make_unique(context, linearBytes, copies | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + auto newTiledDevice = std::make_unique(context, layout.Bytes(), copies | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | addressUsage); + auto newLinear = std::make_unique(context, linearBytes, copies | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | addressUsage); const std::array buffers{{{newTiledDevice->Handle(), 0, layout.Bytes()}, {newLinear->Handle(), 0, linearBytes}}}; std::array writes{}; for (std::uint32_t i = 0; i < writes.size(); ++i) { @@ -146,9 +165,16 @@ void GpuColorTransfer::dispatch(VkCommandBuffer commands, bool toTiled, bool swa const auto barrier = context.Function("vkCmdPipelineBarrier"); barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr); const std::array push{width, height, (width + 127u) / 128u, (toTiled ? 1u : 0u) | (swapRedBlue ? 2u : 0u) | (tiledSource ? 4u : 0u) | (tenBit ? 8u : 0u) | (halfFloat ? 16u : 0u) | (pqWhiteNits ? 32u : 0u), std::bit_cast(pqWhiteNits.value_or(0.0f))}; - context.BindComputePipeline(commands, pipeline); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet, 0, nullptr); - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + if (heapPipeline != VK_NULL_HANDLE) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.BindComputePipeline(commands, heapPipeline); + const HeapPush pushed{push, 0u, {BufferDeviceAddress(context, tiledDevice->Handle()), BufferDeviceAddress(context, linear->Handle()), thresholds->DeviceAddress(), pqNits->DeviceAddress()}}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + } else { + context.BindComputePipeline(commands, pipeline); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet, SetBindSite::ColorTransfer); + CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + } context.Function("vkCmdDispatch")(commands, (width + 7u) / 8u, (height + 7u) / 8u, 1); VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 3892c8c28e6b..af4f6b1bbaa7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Graphics/include/MapImportGate.hpp" #include "prx/libSceAgcDriver/Graphics/include/AdaptiveStaging.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" #include "ThreadOwned.hpp" @@ -71,6 +72,7 @@ constexpr unsigned long UDMABUF_CREATE_LIST = 0; #include #include #include +#include #include #include #include @@ -748,8 +750,7 @@ const char* bindImport(const Context& context, HostImport& entry, VkExternalMemo allocated = true; entry.memoryType = allocation.memoryTypeIndex; if (const auto result = context.Function("vkBindBufferMemory")(context.device, entry.buffer, entry.memory, 0); result != VK_SUCCESS) return failed("vkBindBufferMemory", result); - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, entry.buffer}; - entry.address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + entry.address = BufferDeviceAddress(context, entry.buffer); if (entry.address == 0) return failed("vkGetBufferDeviceAddressKHR", VK_ERROR_UNKNOWN); return nullptr; } @@ -977,10 +978,9 @@ const char* createChunkedDmaBufImport(const Context& context, HostImport& entry, failure = result; return "vkBindBufferMemory"; } - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; entry.buffer = buffer; entry.memory = VK_NULL_HANDLE; - entry.address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + entry.address = BufferDeviceAddress(context, buffer); entry.chunk = std::move(chunk); entry.dmaBuf = true; return nullptr; @@ -1086,8 +1086,7 @@ bool createSparseDmaBufImport(const Context& context, HostImport& entry, int fil context.Function("vkDestroyFence")(context.device, fence, nullptr); if (bound != VK_SUCCESS) fail("vkQueueBindSparse", bound); if (waited != VK_SUCCESS) fail("vkWaitForFences", waited); - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; - const auto address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + const auto address = BufferDeviceAddress(context, buffer); if (address == 0) fail("vkGetBufferDeviceAddressKHR", VK_ERROR_UNKNOWN); entry.buffer = buffer; entry.memory = VK_NULL_HANDLE; @@ -1252,6 +1251,7 @@ const char* settleImport(const Context& context, HostImports& state, const HostI if ((result = context.Function("vkResetCommandBuffer")(settle.settleCommands, 0)) != VK_SUCCESS) return "vkResetCommandBuffer (settle)"; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + NoteCommandBufferBegun(settle.settleCommands); if ((result = context.Function("vkBeginCommandBuffer")(settle.settleCommands, &begin)) != VK_SUCCESS) return "vkBeginCommandBuffer (settle)"; const VkBufferCopy region{0, 0, 4}; context.Function("vkCmdCopyBuffer")(settle.settleCommands, source, settle.settleTarget, 1, ®ion); @@ -1346,6 +1346,7 @@ void submitSettleBatch(const Context& context, HostImports& state) { if ((result = context.Function("vkResetCommandBuffer")(batch.commands, 0)) != VK_SUCCESS) return fail("vkResetCommandBuffer (settle batch)"); VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + NoteCommandBufferBegun(batch.commands); if ((result = context.Function("vkBeginCommandBuffer")(batch.commands, &begin)) != VK_SUCCESS) return fail("vkBeginCommandBuffer (settle batch)"); const auto copy = context.Resolved(&DeviceFunctions::cmdCopyBuffer, "vkCmdCopyBuffer"); RecordMemoryBarrier(context, batch.commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); @@ -3267,6 +3268,10 @@ VkDeviceAddress mirrorAddress(const ImageMirror& mirror) { return mirror.resident != nullptr ? mirror.resident->DeviceAddress() : mirror.buffer->DeviceAddress(); } +VkDeviceAddress mirrorHandleAddress(const ImageMirror& mirror) { + return mirror.resident != nullptr ? mirror.resident->HandleAddress() : mirror.buffer->DeviceAddress(); +} + bool sameRange(const std::weak_ptr& mirrored, const std::shared_ptr& range) { return !mirrored.owner_before(range) && !range.owner_before(mirrored); } @@ -3690,6 +3695,13 @@ std::vector> refreshHeapRuns(const GuestBu return checked; } +void refreshWritableMirrors(const GuestBufferMemory::AddressSpace& space, std::vector& blocks) { + for (const auto index : space.writableMirrors) { + const auto& region = space.base[index]; + if (prepareRefresh(*region.mirror, region.begin, region.end - region.begin)) appendBlocks(blocks, *region.mirror, region.begin, region.end - region.begin); + } +} + bool heapMirrorWatched(ImageMirror& mirror) { const auto serial = GuestMemory::UnwatchSerial(); if (mirror.watchedSerial.load(std::memory_order_relaxed) == serial) return true; @@ -4514,11 +4526,13 @@ void runImportProbe(const Context& context, std::uint64_t base, std::uint64_t by allocate.commandBufferCount = 3; if ((probe.result = context.Function("vkAllocateCommandBuffers")(context.device, &allocate, commands)) != VK_SUCCESS) return "vkAllocateCommandBuffers"; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + NoteCommandBufferBegun(commands[0]); if ((probe.result = context.Function("vkBeginCommandBuffer")(commands[0], &begin)) != VK_SUCCESS) return "vkBeginCommandBuffer"; const VkBufferCopy region{0, 0, bytes}; context.Function("vkCmdCopyBuffer")(commands[0], import.buffer, destination, 1, ®ion); if ((probe.result = context.Function("vkEndCommandBuffer")(commands[0])) != VK_SUCCESS) return "vkEndCommandBuffer"; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + NoteCommandBufferBegun(commands[1]); if ((probe.result = context.Function("vkBeginCommandBuffer")(commands[1], &begin)) != VK_SUCCESS) return "vkBeginCommandBuffer"; context.Function("vkCmdFillBuffer")(commands[1], import.buffer, 0, bytes, 0x02020202u); if ((probe.result = context.Function("vkEndCommandBuffer")(commands[1])) != VK_SUCCESS) return "vkEndCommandBuffer"; @@ -5374,10 +5388,7 @@ void GuestBufferMemory::AcquireRegistered() { // before any of them is dereferenced. served = true; mirrored = space->mirrored; - for (const auto index : space->writableMirrors) { - const auto& region = space->base[index]; - if (prepareRefresh(*region.mirror, region.begin, region.end - region.begin)) appendBlocks(blocks, *region.mirror, region.begin, region.end - region.begin); - } + refreshWritableMirrors(*space, blocks); lap(timing.mirrorsUs, at); } } @@ -5988,10 +5999,7 @@ bool GuestBufferMemory::RetakeSpace() { if (reuse) { noteEpochMirrors(true, *space); } else { - for (const auto index : space->writableMirrors) { - const auto& region = space->base[index]; - if (prepareRefresh(*region.mirror, region.begin, region.end - region.begin)) appendBlocks(blocks, *region.mirror, region.begin, region.end - region.begin); - } + refreshWritableMirrors(*space, blocks); if (epochMirrors()) noteEpochMirrors(false, *space); } const auto checked = refreshHeapRuns(*space, blocks); @@ -6406,6 +6414,16 @@ bool GuestBufferMemory::bindableInPlace(std::uint64_t offset, bool addressable) return offset % context.limits.minStorageBufferOffsetAlignment == 0; } +VkDeviceSize GuestBufferViewAlignment(const VkPhysicalDeviceLimits& limits) { + Require(limits.minStorageBufferOffsetAlignment != 0, "no storage buffer offset alignment"); + const auto storage = std::max(limits.minStorageBufferOffsetAlignment, 4); + return UniformConstantBuffersEnabled() ? std::max(storage, limits.minUniformBufferOffsetAlignment) : storage; +} + +VkDeviceSize GuestBufferMemory::viewAlignment() const { + return GuestBufferViewAlignment(context.limits); +} + bool GuestBufferMemory::stagingEligible(const Region& region, bool addressable) const { return !region.adaptiveInPlace && stagingWanted(region, addressable); } @@ -7021,6 +7039,7 @@ void GuestBufferMemory::copyRegion(Region& region, bool addressable) { readBytes += region.snapshot.size(); } region.snapshot.clear(); + NoteCpuBufferCopy(readBytes); if (uploadGeneration != 0 && uploadUnchanged(region.begin, region.sparse, region.backed, static_cast(allocated), uploadGeneration)) insertUploaded(context, region.begin, region.backed, static_cast(allocated), usage, region.buffer, uploadGeneration); if (profile) readUs.fetch_add(microsecondsSince(readStart), std::memory_order_relaxed); if (profile) { @@ -7419,35 +7438,63 @@ void GuestBufferMemory::RecordCopyBacks(Recorder& recorder) { recorder.EndGpuTiming(timing, copiedBytes); } -VkDescriptorBufferInfo GuestBufferMemory::Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const { - Require(uploaded && !committed, "guest GPU memory is not available"); - Require(bytes != 0 && bytes <= std::numeric_limits::max() - address, "invalid guest buffer view"); +VkDescriptorBufferInfo GuestBufferMemory::Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, VkDeviceAddress* handleAddress) const { + std::string failure; + const auto info = TryDescriptor(address, bytes, adjustment, &failure, handleAddress); + if (!info.has_value()) Require(false, failure); + return *info; +} + +std::optional GuestBufferMemory::TryDescriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, std::string* failure, VkDeviceAddress* handleAddress) const { + const auto fail = [failure](std::string text) -> std::optional { + if (failure != nullptr) *failure = std::move(text); + return std::nullopt; + }; + if (!uploaded || committed) return fail("guest GPU memory is not available"); + if (bytes == 0 || bytes > std::numeric_limits::max() - address) return fail("invalid guest buffer view"); const auto* found = owner(address, address + bytes); - Require(found != nullptr, "guest buffer has no GPU owner"); + if (found == nullptr) return fail("guest buffer has no GPU owner"); const auto& region = *found; const auto describe = [&](const char* what) { + if (failure == nullptr) return std::string(); char text[256]; std::snprintf(text, sizeof(text), "guest buffer view 0x%llx+0x%llx %s its GPU owner 0x%llx-0x%llx (buffer %d, direct %d, mirror %d)", static_cast(address), static_cast(bytes), what, static_cast(region.begin), static_cast(region.end), region.buffer != nullptr, region.direct != nullptr, region.mirror != nullptr); return std::string(text); }; - if (!(address >= region.begin && address + bytes <= region.end && (region.buffer != nullptr || region.direct != nullptr || region.mirror != nullptr))) Require(false, describe("exceeds")); + if (!(address >= region.begin && address + bytes <= region.end && (region.buffer != nullptr || region.direct != nullptr || region.mirror != nullptr))) return fail(describe("exceeds")); const auto base = region.direct != nullptr ? region.direct->base - region.direct->lead : region.mirror != nullptr ? mirrorStart(*region.mirror) : region.begin; const auto offset = address - base; - Require(context.limits.minStorageBufferOffsetAlignment != 0, "no storage buffer offset alignment"); - Require(base % 4 == 0, "a guest buffer view in a GPU owner that does not start at a DWORD boundary is not implemented"); - adjustment = static_cast(offset % std::max(context.limits.minStorageBufferOffsetAlignment, 4)); + if (base % 4 != 0) return fail("a guest buffer view in a GPU owner that does not start at a DWORD boundary is not implemented"); + adjustment = static_cast(offset % viewAlignment()); + if (bytes / 4 + adjustment / 4 + 2 > std::numeric_limits::max() / 4) return fail("guest buffer view range overflow"); auto range = ViewBytes(bytes, adjustment); const auto end = region.direct != nullptr ? region.direct->base + region.direct->bytes : servedEnd(region); const bool cut = (region.direct == nullptr || region.runCut) && end < region.end; if (cut) { - Require(address - adjustment < end, "guest buffer view starts past its copy"); + if (address - adjustment >= end) return fail("guest buffer view starts past its copy"); range = std::min(range, end - (address - adjustment)); } if (bytes <= context.limits.maxStorageBufferRange) range = std::min(range, context.limits.maxStorageBufferRange & ~std::uint64_t{3}); - if (address - adjustment + range > end) Require(false, describe("rounded up to its view range exceeds")); - Require(range <= context.limits.maxStorageBufferRange, "guest buffer view exceeds descriptor range limit"); + if (address - adjustment + range > end) return fail(describe("rounded up to its view range exceeds")); + if (range > context.limits.maxStorageBufferRange) return fail("guest buffer view exceeds descriptor range limit"); const auto handle = region.direct != nullptr ? region.direct->buffer : region.mirror != nullptr ? mirrorHandle(*region.mirror) : region.buffer->Handle(); - return {handle, offset - adjustment, range}; + if (handleAddress != nullptr) *handleAddress = region.direct != nullptr ? region.direct->address - region.direct->lead : region.mirror != nullptr ? mirrorHandleAddress(*region.mirror) : region.buffer->DeviceAddress(); + return VkDescriptorBufferInfo{handle, offset - adjustment, range}; +} + +std::optional GuestBufferMemory::ImportedView(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const { + if (bytes == 0 || bytes > std::numeric_limits::max() - address) return std::nullopt; + const auto* import = ExistingHostImportFor(context, address, bytes); + if (import == nullptr || import->address == 0) return std::nullopt; + const auto offset = HostImportOffset(*import, address); + adjustment = static_cast(offset % viewAlignment()); + const auto start = offset - adjustment; + const auto end = import->lead + import->bytes; + auto range = (ViewBytes(bytes, adjustment) + 3u) & ~std::uint64_t{3}; + if (bytes <= context.limits.maxStorageBufferRange) range = std::min(range, context.limits.maxStorageBufferRange & ~std::uint64_t{3}); + range = std::min(range, end - start); + if (range < adjustment + bytes || range > context.limits.maxStorageBufferRange) return std::nullopt; + return VkDeviceAddressRangeEXT{import->address - import->lead + start, range}; } std::uint64_t GuestBufferMemory::ViewBytes(std::uint64_t bytes, std::uint32_t adjustment) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp index 9bca233c7895..6d258a164536 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp @@ -1,14 +1,26 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/MultisampleReadbackUint_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/MultisampleReadbackDepth_spv.h" #include #include +#include #include namespace AgcDriver::Graphics { namespace { +struct HeapReadbackPush { + std::array values; + std::uint32_t pad; + VkDeviceAddress buffer; + std::uint32_t slot; + std::uint32_t pad2; +}; + +static_assert(offsetof(HeapReadbackPush, buffer) == 32 && offsetof(HeapReadbackPush, slot) == 40 && sizeof(HeapReadbackPush) == 48); + std::uint32_t readbackElementBytes(VkFormat format) { switch (format) { case VK_FORMAT_R8_UINT: return 1u; @@ -22,8 +34,8 @@ std::uint32_t readbackElementBytes(VkFormat format) { } -VkPipeline TextureDetiler::multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth) { - const auto key = elementBytes | (depth ? 32u : 0u); +VkPipeline TextureDetiler::multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth, bool heap) { + const auto key = elementBytes | (depth ? 32u : 0u) | (heap ? 64u : 0u); for (const auto& entry : readbackPipelines) if (entry.first == key) return entry.second; if (readbackDescriptorLayout == VK_NULL_HANDLE) { const std::array bindings{{ @@ -60,7 +72,12 @@ VkPipeline TextureDetiler::multisampleReadbackPipeline(std::uint32_t elementByte info.layout = readbackPipelineLayout; readbackPipelines.reserve(readbackPipelines.size() + 1u); VkPipeline result = VK_NULL_HANDLE; - { + if (heap) { + const std::array mappings{ + HeapPushAddressMapping(0u, 0u, offsetof(HeapReadbackPush, buffer)), + HeapPushIndexMapping(BindlessHeap::For(context), 0u, 1u, VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT, offsetof(HeapReadbackPush, slot))}; + result = CreateHeapComputePipeline(context, info, mappings); + } else { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1u, &info, nullptr, &result), "vkCreateComputePipelines multisample readback"); } @@ -68,7 +85,7 @@ VkPipeline TextureDetiler::multisampleReadbackPipeline(std::uint32_t elementByte return result; } -void TextureDetiler::DispatchMultisampleReadback(VkCommandBuffer commands, VkFormat format, VkBuffer destination, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements) { +void TextureDetiler::DispatchMultisampleReadback(VkCommandBuffer commands, VkFormat format, VkBuffer destination, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements, const HeapSlotOwner* owner) { GuestMemory::AssertGpuLockHeld("TextureDetiler::DispatchMultisampleReadback"); const auto elementBytes = readbackElementBytes(format); Require(commands != VK_NULL_HANDLE && destination != VK_NULL_HANDLE && arrayView != VK_NULL_HANDLE, "multisample readback requires commands, buffer and array view"); @@ -87,7 +104,19 @@ void TextureDetiler::DispatchMultisampleReadback(VkCommandBuffer commands, VkFor Require(groupsX != 0u, "device has no multisample readback workgroups"); const auto groupsY = (groups + groupsX - 1u) / groupsX; Require(groupsY <= context.limits.maxComputeWorkGroupCount[1] && groupsX * groupsY * 64u <= std::numeric_limits::max(), "multisample readback dispatch exceeds device limits"); - const auto pipeline = multisampleReadbackPipeline(elementBytes, format == VK_FORMAT_D32_SFLOAT); + const std::array push{width, height, layers, fragments, firstElement, elements, static_cast(groupsX * 64u)}; + const auto address = owner != nullptr && HeapPassesActive(context) ? bufferAddress(destination) : 0; + const auto heapPipeline = address != 0 ? multisampleReadbackPipeline(elementBytes, format == VK_FORMAT_D32_SFLOAT, true) : VK_NULL_HANDLE; + const auto slot = heapPipeline != VK_NULL_HANDLE ? BindlessHeap::For(context).ViewSlot(HeapPassSampledKind, owner, arrayView) : std::nullopt; + if (slot) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.BindComputePipeline(commands, heapPipeline); + const HeapReadbackPush pushed{push, 0u, address + offset, *slot, 0u}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + context.Function("vkCmdDispatch")(commands, static_cast(groupsX), static_cast(groupsY), 1u); + return; + } + const auto pipeline = multisampleReadbackPipeline(elementBytes, format == VK_FORMAT_D32_SFLOAT, false); const auto set = allocateFrom(readbackDescriptorSets, readbackDescriptorLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 64u}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 64u}}, "vkCreateDescriptorPool multisample readback", "vkAllocateDescriptorSets multisample readback", "vkResetDescriptorPool multisample readback"); const VkDescriptorBufferInfo buffer{destination, offset, bytes}; const VkDescriptorImageInfo image{VK_NULL_HANDLE, arrayView, VK_IMAGE_LAYOUT_GENERAL}; @@ -97,9 +126,8 @@ void TextureDetiler::DispatchMultisampleReadback(VkCommandBuffer commands, VkFor }}; context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0u, nullptr); context.BindComputePipeline(commands, pipeline); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, readbackPipelineLayout, 0u, 1u, &set, 0u, nullptr); - const std::array push{width, height, layers, fragments, firstElement, elements, static_cast(groupsX * 64u)}; - context.Function("vkCmdPushConstants")(commands, readbackPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data()); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, readbackPipelineLayout, 0u, 1u, &set, SetBindSite::ColorTransfer); + CmdPushConstants(context, commands, readbackPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, static_cast(groupsX), static_cast(groupsY), 1u); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp index 72d4247ac08f..d28cacc734a9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp @@ -1,6 +1,7 @@ #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" #include #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp" @@ -214,7 +215,7 @@ std::shared_ptr stageGuestSamples(const Context& context, const Multisam return staging; } -class MultisampleTarget : public std::enable_shared_from_this { +class MultisampleTarget : public std::enable_shared_from_this, public HeapSlotOwner { public: MultisampleTarget(const Context& context, const ColorTarget& target, bool guestSamples = false, std::optional initialClear = std::nullopt, std::shared_ptr preparedUpload = {}, std::vector initialBaseline = {}) : context(context), target(target), cmask(target.cmaskAddress, target.cmaskBytes), colorFill(target), guestColorBaseline(std::move(initialBaseline)) { this->context.bufferPool.reset(); @@ -301,7 +302,7 @@ class MultisampleTarget : public std::enable_shared_from_this const auto bytes = static_cast(target.extent.width) * target.extent.height * target.samples * target.elementBytes; for (std::uint64_t offset = 0; offset < bytes; offset += stride) { const auto count = std::min(stride, bytes - offset); - context.detiler->DispatchMultisampleImage(commands, target.elementBytes, upload->Handle(), offset, (count + 3u) & ~std::uint64_t{3}, uploadView, target.extent.width, target.extent.height, 1u, target.samples, static_cast(offset / target.elementBytes), static_cast(count / target.elementBytes)); + context.detiler->DispatchMultisampleImage(commands, target.elementBytes, upload->Handle(), offset, (count + 3u) & ~std::uint64_t{3}, uploadView, target.extent.width, target.extent.height, 1u, target.samples, static_cast(offset / target.elementBytes), static_cast(count / target.elementBytes), this); } RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); if (recorder != nullptr) { @@ -744,7 +745,7 @@ class MultisampleTarget : public std::enable_shared_from_this std::shared_ptr FirstSample(VkComponentMapping components) { const auto source = Sampled({}); if (firstSampleCopy == nullptr) firstSampleCopy = std::make_unique(context, target.format, target.extent); - firstSampleCopy->Record(*Recorder::Active(), source->View(), source->Layout()); + firstSampleCopy->Record(*Recorder::Active(), *source); const std::array key{static_cast(components.r), static_cast(components.g), static_cast(components.b), static_cast(components.a)}; auto& texture = firstSampleTextures[key]; if (texture == nullptr) { @@ -1107,6 +1108,7 @@ class MultisampleTarget : public std::enable_shared_from_this } reinterpretCopies.clear(); for (const auto& [format, resolvePass] : resolvePasses) context.Function("vkDestroyRenderPass")(context.device, resolvePass, nullptr); + ReleaseHeapSlots(context); if (uploadView) context.Function("vkDestroyImageView")(context.device, uploadView, nullptr); if (orderView) context.Function("vkDestroyImageView")(context.device, orderView, nullptr); if (twinView) context.Function("vkDestroyImageView")(context.device, twinView, nullptr); @@ -1736,7 +1738,7 @@ SampleOrderTarget MultisampleTargetOrderTarget(const Context& context, const Col auto& found = acquire(context, target); found.drawn = true; ++found.contents; - return {found.image, found.OrderView(), found.orderFormat, target.extent, target.samples, SampleOrderMethod::Storage, found.shared_from_this()}; + return {found.image, found.OrderView(), found.orderFormat, target.extent, target.samples, SampleOrderMethod::Storage, found.shared_from_this(), &found}; } VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, VkImage* image) { @@ -1854,7 +1856,7 @@ MultisampleColorSnapshot ReadMultisampleTargetColorSnapshot_nid_no_patch(const C return snapshotTarget(context, target)->ColorSnapshot(); } -VkImageView MultisampleTargetStorageView(const Context& context, const GuestTextureResource& resource, bool uintStorage) { +MultisampleStorage MultisampleTargetStorageView(const Context& context, const GuestTextureResource& resource, bool uintStorage) { TargetsLock lock; discardRetiredTargets(); const auto format = ResolveTextureFormat(resource.format); @@ -1866,13 +1868,14 @@ VkImageView MultisampleTargetStorageView(const Context& context, const GuestText if (rendered.eqaaFragments != 0) throw std::runtime_error(eqaaReadRefusal("storage image access to", rendered, resource)); if (sameStorageForm(context, rendered.format, format) && rendered.extent.width == resource.width && rendered.extent.height == resource.height && rendered.samples == resource.samples && rendered.mip == 0) { if (!holdHostOnly(*target)) continue; - return target->Storage(StorageFormatForGuest(context, resource.format), uintStorage); + return {target->Storage(StorageFormatForGuest(context, resource.format), uintStorage), target.get(), target}; } other = target.get(); } if (other == nullptr) { Require(Recorder::Active() != nullptr, "a multisampled color target is only written by recorded dispatches"); - return createFilled(context, resource, format, "writing", true).Storage(StorageFormatForGuest(context, resource.format), uintStorage); + auto& created = createFilled(context, resource, format, "writing", true); + return {created.Storage(StorageFormatForGuest(context, resource.format), uintStorage), &created, created.shared_from_this()}; } char text[320]; std::snprintf(text, sizeof(text), "AGC graphics: storage image access to multisampled color target 0x%llx (%ux%u, %u samples, vk format %d) as a %ux%u texture of %u samples and guest format %u (vk %d) is not implemented", static_cast(resource.baseAddress), other->target.extent.width, other->target.extent.height, other->target.samples, static_cast(other->target.format), resource.width, resource.height, resource.samples, resource.format, static_cast(format)); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp index 32daf39052aa..1b2643f47e0e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp @@ -1,14 +1,30 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/MultisampleUpload_spv.h" #include #include #include +#include #include namespace AgcDriver::Graphics { -VkPipeline TextureDetiler::multisampleUploadPipeline(std::uint32_t elementBytes) { - const auto key = (1u << 19u) | elementBytes; +namespace { + +struct HeapMultisamplePush { + std::array values; + std::uint32_t pad; + VkDeviceAddress buffer; + std::uint32_t slot; + std::uint32_t pad2; +}; + +static_assert(offsetof(HeapMultisamplePush, buffer) == 32 && offsetof(HeapMultisamplePush, slot) == 40 && sizeof(HeapMultisamplePush) == 48); + +} + +VkPipeline TextureDetiler::multisampleUploadPipeline(std::uint32_t elementBytes, bool heap) { + const auto key = (1u << 19u) | (heap ? 1u << 18u : 0u) | elementBytes; for (const auto& entry : pipelines) if (entry.first == key) return entry.second; if (multisampleUploadModule == VK_NULL_HANDLE) multisampleUploadModule = CreateShaderModule(context, MULTISAMPLE_UPLOAD_SPV, sizeof(MULTISAMPLE_UPLOAD_SPV), "vkCreateShaderModule multisample upload"); const VkSpecializationMapEntry entry{0u, 0u, sizeof(elementBytes)}; @@ -22,7 +38,12 @@ VkPipeline TextureDetiler::multisampleUploadPipeline(std::uint32_t elementBytes) info.layout = imagePipelineLayout; pipelines.reserve(pipelines.size() + 1u); VkPipeline result = VK_NULL_HANDLE; - { + if (heap) { + const std::array mappings{ + HeapPushAddressMapping(0u, 0u, offsetof(HeapMultisamplePush, buffer)), + HeapPushIndexMapping(BindlessHeap::For(context), 0u, 1u, HeapPassStorageImages, offsetof(HeapMultisamplePush, slot))}; + result = CreateHeapComputePipeline(context, info, mappings); + } else { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1u, &info, nullptr, &result), "vkCreateComputePipelines multisample upload"); } @@ -30,7 +51,7 @@ VkPipeline TextureDetiler::multisampleUploadPipeline(std::uint32_t elementBytes) return result; } -void TextureDetiler::DispatchMultisampleImage(VkCommandBuffer commands, std::uint32_t elementBytes, VkBuffer source, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements) { +void TextureDetiler::DispatchMultisampleImage(VkCommandBuffer commands, std::uint32_t elementBytes, VkBuffer source, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements, const HeapSlotOwner* owner) { Require(context.storageImageMultisample && context.storageImageWriteWithoutFormat, "device does not enable multisampled storage image writes without format"); Require(commands != VK_NULL_HANDLE && source != VK_NULL_HANDLE && arrayView != VK_NULL_HANDLE, "multisample upload requires commands, buffer and array view"); Require(std::has_single_bit(elementBytes) && elementBytes <= 16u, "multisample upload element size is unsupported"); @@ -47,16 +68,27 @@ void TextureDetiler::DispatchMultisampleImage(VkCommandBuffer commands, std::uin Require(groupsX != 0u, "device has no multisample upload workgroups"); const auto groupsY = (groups + groupsX - 1u) / groupsX; Require(groupsY <= context.limits.maxComputeWorkGroupCount[1] && groupsX * groupsY * 64u <= std::numeric_limits::max(), "multisample upload dispatch exceeds the device limits"); - const auto target = multisampleUploadPipeline(elementBytes); + const std::array push{width, height, layers, fragments, firstElement, elements, static_cast(groupsX * 64u)}; + const auto address = owner != nullptr && HeapPassesActive(context) ? bufferAddress(source) : 0; + const auto heapTarget = address != 0 ? multisampleUploadPipeline(elementBytes, true) : VK_NULL_HANDLE; + const auto slot = heapTarget != VK_NULL_HANDLE ? BindlessHeap::For(context).ViewSlot(HeapPassStorageKind, owner, arrayView) : std::nullopt; + if (slot) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.BindComputePipeline(commands, heapTarget); + const HeapMultisamplePush pushed{push, 0u, address + offset, *slot, 0u}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + context.Function("vkCmdDispatch")(commands, static_cast(groupsX), static_cast(groupsY), 1u); + return; + } + const auto target = multisampleUploadPipeline(elementBytes, false); const auto set = allocateSet(true); const VkDescriptorBufferInfo buffer{source, offset, bytes}; const VkDescriptorImageInfo image{VK_NULL_HANDLE, arrayView, VK_IMAGE_LAYOUT_GENERAL}; const std::array writes{{{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, 0u, 0u, 1u, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, nullptr, &buffer, nullptr}, {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, 1u, 0u, 1u, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &image, nullptr, nullptr}}}; context.Function("vkUpdateDescriptorSets")(context.device, 2u, writes.data(), 0u, nullptr); context.BindComputePipeline(commands, target); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0u, 1u, &set, 0u, nullptr); - const std::array push{width, height, layers, fragments, firstElement, elements, static_cast(groupsX * 64u)}; - context.Function("vkCmdPushConstants")(commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data()); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0u, 1u, &set, SetBindSite::ColorTransfer); + CmdPushConstants(context, commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, static_cast(groupsX), static_cast(groupsY), 1u); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index 5eda4cff3231..7d40fa74d3e5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -3,7 +3,9 @@ #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp" +#include "prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineJournal.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/PatchVertexLayer.hpp" @@ -18,9 +20,9 @@ #include #include #include +#include #include #include -#include #include #include #include @@ -389,7 +391,7 @@ void appendKey(std::vector& key, const TValue& value) { key.insert(key.end(), bytes.begin(), bytes.end()); } -bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& state, const VertexInputLayout& input, const PipelineSetLayouts& resources, std::span shaders) { +bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& state, const VertexInputLayout& input, const PipelineSetLayouts& resources, std::span shaders, std::span pushPlacements) { using Stage = ShaderRecompiler::ShaderStage; if (!context.graphicsPipelineLibrary || context.pipelineExecutableInfo || (state.stages.tessellation && !context.tessellationPipelineCache) || state.depthBiasPerFace || state.rectList || BarycentricPatches(state, shaders) || SplitsAlternateAlpha(state) || std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; }) || UsesMeshWindow(shaders) || FragmentInterlock(shaders)) return false; keys = {}; @@ -403,18 +405,30 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& appendKey(key, KeyedPushOffset(shader)); appendKey(key, state.meshLayerBase); appendKey(key, state.meshLayerCount); + appendKey(key, pushPlacements[static_cast(&shader - shaders.data())]); if (resources.split) { auto& sets = shader.stage == Stage::Fragment ? keys.fragmentSets : keys.preRasterizationSets; - for (const auto& binding : shader.program->bindings) { - Require(binding.descriptorSet < 2u, "split pipeline library descriptor set exceeds two slots"); - sets |= 1u << binding.descriptorSet; + if (HeapShader(shader)) { + sets |= FragmentSetBit; + for (const auto& binding : shader.program->bindings) { + if (binding.descriptorSet == 0u) sets |= MainSetBit; + } + } else { + for (const auto& binding : shader.program->bindings) { + Require(binding.descriptorSet < 2u, "split pipeline library descriptor set exceeds two slots"); + sets |= 1u << binding.descriptorSet; + } } } } + if (resources.split && AnyHeapShader(shaders)) { + keys.preRasterizationSets |= FragmentSetBit; + keys.fragmentSets |= FragmentSetBit; + } if (resources.split) { const auto unused = 3u & ~(keys.preRasterizationSets | keys.fragmentSets); - keys.preRasterizationSets |= unused & 1u; - keys.fragmentSets |= unused & 2u; + keys.preRasterizationSets |= unused & MainSetBit; + keys.fragmentSets |= unused & FragmentSetBit; } for (const auto& binding : input.bindings) { appendKey(keys.vertexInput, binding.binding); @@ -493,11 +507,11 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& appendKey(key, ~0u); appendKey(key, sets); appendKey(key, pushStagesOf(context)); - if ((sets & 1u) != 0u) { + if ((sets & MainSetBit) != 0u) { appendKey(key, resources.mainKey.size()); for (const auto word : resources.mainKey) appendKey(key, word); } - if ((sets & 2u) != 0u) { + if ((sets & FragmentSetBit) != 0u) { appendKey(key, resources.fragmentKey.size()); for (const auto word : resources.fragmentKey) appendKey(key, word); } @@ -512,7 +526,7 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const ShaderResources& resources, std::span shaders, VkImageLayout attachmentLayout) : Pipeline(context, state, vertexInput, resources.SetLayouts(), shaders, attachmentLayout) {} -Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span shaders, VkImageLayout attachmentLayout) : context(context), _modules(shaders.size()), attachments(state.colors.size() + (state.depth ? 1u : 0u)), colorAttachments(state.colors.size()), depthBounds(state.depth.has_value() && state.depthBoundsTest), depthBias(state.depth.has_value() && state.depthBias), dynamicRendering(context.graphicsPipelineLibrary) { +Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span shaders, VkImageLayout attachmentLayout) : context(context), _modules(shaders.size()), pushPlacements(PushDataPlacements(shaders)), attachments(state.colors.size() + (state.depth ? 1u : 0u)), colorAttachments(state.colors.size()), depthBounds(state.depth.has_value() && state.depthBoundsTest), depthBias(state.depth.has_value() && state.depthBias), dynamicRendering(context.graphicsPipelineLibrary) { PerformanceTimer timing("Vulkan.GraphicsPipeline"); for (const auto& color : state.colors) boundAttachments.push_back(color.partialWriteMask == 0u); if (state.depth) boundAttachments.push_back(true); @@ -564,6 +578,19 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput std::vector stages(shaders.size()); std::vector specializations; specializations.reserve(shaders.size()); + std::vector> heapMappings(shaders.size()); + std::vector heapMappingInfos(shaders.size(), VkShaderDescriptorSetAndBindingMappingInfoEXT{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}); + if (context.descriptorHeap && DescriptorHeapEnabled() && AnyHeapShader(shaders)) { + auto& heap = BindlessHeap::For(context); + const bool rooted = RootedPushData(shaders); + descriptorHeap = std::all_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { + const auto index = static_cast(&shader - shaders.data()); + return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], + {.gdsAddress = shader.program->dataAddressPush, .faultAddress = PushesGeneratedFaultAddress(shader, rooted), .pixelLds = shader.program->functionLdsBuffer, .meshWindow = shader.program->meshWindowBuffer}, + &pushPlacements[index], &shader.program->bindings); + }); + } + Require(descriptorHeap || !AnyHeapShader(shaders), "a pipeline with GPU-mode stages does not map onto VK_EXT_descriptor_heap"); const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT meshSubgroup{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT, nullptr, 32u}; for (std::uint32_t i = 0; i < shaders.size(); ++i) { const auto& shader = *shaders[i].program; @@ -576,13 +603,21 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput stages[i].module = _modules[i]; stages[i].pName = "main"; if (shaders[i].stage == ShaderRecompiler::ShaderStage::Mesh && context.meshWave32 && shader.hostSubgroupSize == 32u) stages[i].pNext = &meshSubgroup; + if (descriptorHeap) { + heapMappingInfos[i].mappingCount = static_cast(heapMappings[i].size()); + heapMappingInfos[i].pMappings = heapMappings[i].data(); + heapMappingInfos[i].pNext = stages[i].pNext; + stages[i].pNext = &heapMappingInfos[i]; + } specializations.emplace_back(shader, context.atomicLockTable, state.meshLayerBase, state.meshLayerCount); + specializations.back().PlacePushData(pushPlacements[i]); + if (descriptorHeap) specializations.back().PlaceHeapImageSlots(BindlessHeap::For(context).ImageSlots()); stages[i].pSpecializationInfo = specializations.back().Info(); } if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && !shader.program->stencilReferences.empty(); })) { for (std::size_t i = 0; i < shaders.size(); ++i) { if (shaders[i].stage != ShaderRecompiler::ShaderStage::Vertex) continue; - Require(stages[i].flags == 0u && stages[i].pNext == nullptr, "stencil replay vertex stage allows varying subgroup size"); + Require(stages[i].flags == 0u && (stages[i].pNext == nullptr || stages[i].pNext == &heapMappingInfos[i]), "stencil replay vertex stage allows varying subgroup size"); } } // A descriptor set layout with the same bindings as this one is compatible with the pipeline @@ -594,12 +629,12 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput const VkPushConstantRange push{pushStages, 0, PipelinePushSlotBytes}; const std::array slots{{{pushStagesOf(context), 0, PipelinePushSlotBytes}, {VK_SHADER_STAGE_FRAGMENT_BIT, PipelinePushSlotBytes, PipelinePushSlotBytes}}}; VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layoutInfo.flags = pixelLds || meshWindow || !resources.split ? 0 : VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT; + layoutInfo.flags = !pixelLds && !meshWindow && resources.split && context.graphicsPipelineLibrary ? VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT : 0; layoutInfo.setLayoutCount = meshWindow ? 4u : pixelLds ? 3u : resources.split ? 2u : 1u; layoutInfo.pSetLayouts = setLayouts.data(); layoutInfo.pushConstantRangeCount = dynamicRendering ? static_cast(slots.size()) : pushStages != 0 ? 1 : 0; layoutInfo.pPushConstantRanges = dynamicRendering ? slots.data() : pushStages != 0 ? &push : nullptr; - Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &layout), "vkCreatePipelineLayout graphics"); + if (!descriptorHeap) Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &layout), "vkCreatePipelineLayout graphics"); std::vector colors; std::vector references(state.blends.size(), VkAttachmentReference{VK_ATTACHMENT_UNUSED, attachmentLayout}); for (std::uint32_t index = 0; index < state.colors.size(); ++index) { @@ -686,7 +721,7 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput viewports.viewportCount = ViewportCount(state); viewports.scissorCount = ViewportCount(state); PipelineLibraryKeys keys; - libraries = libraryKeys(keys, context, state, vertexInput, resources, shaders); + libraries = libraryKeys(keys, context, state, vertexInput, resources, shaders, pushPlacements); std::vector dynamicStates{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; if (state.stencilReplayReference) dynamicStates.push_back(VK_DYNAMIC_STATE_STENCIL_REFERENCE); if (depthBounds) dynamicStates.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS); @@ -797,6 +832,13 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput pipelineInfo.layout = layout; pipelineInfo.renderPass = renderPass; if (dynamicRendering) pipelineInfo.pNext = &rendering; + VkPipelineCreateFlags2CreateInfoKHR heapFlags{}; + if (descriptorHeap) { + heapFlags = DescriptorHeapFlags(static_cast(pipelineInfo.flags), pipelineInfo.pNext); + pipelineInfo.pNext = &heapFlags; + pipelineInfo.flags = 0; + pipelineInfo.layout = VK_NULL_HANDLE; + } timing.Mark("modules_and_state"); if (prebuilding && !libraries) { for (const auto module : _modules) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); @@ -804,14 +846,14 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput return; } if (prebuilding) { - static_cast(LinkPipelineFromLibraries(context, pipelineInfo, rendering, layoutInfo, keys, &optimized, true, _modules)); + static_cast(LinkPipelineFromLibraries(context, pipelineInfo, rendering, layoutInfo, keys, descriptorHeap, &optimized, true, _modules)); for (const auto module : _modules) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); _modules.clear(); prebuilt = true; return; } const VkPipelineCache pipelineCache = (state.stages.tessellation || barycentricPatches || state.rectList) && !context.tessellationPipelineCache ? VK_NULL_HANDLE : context.pipelineCache; - if (libraries) pipeline = LinkPipelineFromLibraries(context, pipelineInfo, rendering, layoutInfo, keys, &optimized, false, _modules); + if (libraries) pipeline = LinkPipelineFromLibraries(context, pipelineInfo, rendering, layoutInfo, keys, descriptorHeap, &optimized, false, _modules); else { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateGraphicsPipelines")(context.device, pipelineCache, 1, &pipelineInfo, nullptr, &pipeline), "vkCreateGraphicsPipelines"); @@ -1074,12 +1116,21 @@ void Pipeline::ContinueBackFaces(CommandState& recording, const State& state, co void Pipeline::PushConstants(VkCommandBuffer commands, VkShaderStageFlags stages, std::span bytes) const { if (stages == 0) return; + if (descriptorHeap) { + thread_local PushDataShadow shadow; + const auto [first, end] = shadow.Changed(commands, PushDataMark(), bytes); + if (first >= end) return; + const VkPushDataInfoEXT info{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, static_cast(first), {bytes.data() + first, end - first}}; + context.Function("vkCmdPushDataEXT")(commands, &info); + shadow.Pushed(NotePushDataWritten()); + return; + } if (dynamicRendering) { - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, pushStagesOf(context), 0, PipelinePushSlotBytes, bytes.data()); - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, VK_SHADER_STAGE_FRAGMENT_BIT, PipelinePushSlotBytes, PipelinePushSlotBytes, bytes.data() + PipelinePushSlotBytes); + CmdPushConstants(context, commands, layout, pushStagesOf(context), 0, PipelinePushSlotBytes, bytes.data()); + CmdPushConstants(context, commands, layout, VK_SHADER_STAGE_FRAGMENT_BIT, PipelinePushSlotBytes, PipelinePushSlotBytes, bytes.data() + PipelinePushSlotBytes); return; } - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, stages, 0, PipelinePushSlotBytes, bytes.data()); + CmdPushConstants(context, commands, layout, stages, 0, PipelinePushSlotBytes, bytes.data()); } namespace { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp index 40151aece0c2..2e46591c7ad8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Graphics/include/PipelineJournal.hpp" #include "prx/libc/include/HostThread.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libc/include/HostThreadLocal.hpp" @@ -913,8 +914,9 @@ class Journal { if (error) throw std::filesystem::filesystem_error("cannot resolve the pipeline journal directory", directory, error); directory = native; #endif - path = directory / "pipelines.journal"; - lockPath = directory / "pipelines.journal.lock"; + const std::string name = GpuHeapEnabled() ? "pipelines-heap.journal" : "pipelines.journal"; + path = directory / name; + lockPath = directory / (name + ".lock"); maxBytes = configured("APS5_PIPELINE_JOURNAL_MAX_MIB", 1024u) << 20u; Libc::StartHostThread([this] { run(); }).detach(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp index 3125f979f590..136402951b06 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp @@ -113,10 +113,10 @@ std::span PipelineLibraryDynamicStates() { return dynamicStates; } -VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPipelineCreateInfo& info, const VkPipelineRenderingCreateInfoKHR& rendering, const VkPipelineLayoutCreateInfo& layout, const PipelineLibraryKeys& keys, std::shared_ptr* optimized, bool partsOnly, std::span modules) { +VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPipelineCreateInfo& info, const VkPipelineRenderingCreateInfoKHR& rendering, const VkPipelineLayoutCreateInfo& layout, const PipelineLibraryKeys& keys, bool descriptorHeap, std::shared_ptr* optimized, bool partsOnly, std::span modules) { Require(info.renderPass == VK_NULL_HANDLE && info.pDynamicState != nullptr, "pipeline library parts need dynamic rendering and the library dynamic states"); const bool split = (layout.flags & VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT) != 0; - Require(!split || (layout.setLayoutCount == 2u && layout.pSetLayouts != nullptr && ((keys.preRasterizationSets | keys.fragmentSets) & ~3u) == 0u), "split pipeline library layout requires two descriptor set slots and a valid mask"); + Require(!split || ((layout.setLayoutCount == 2u || layout.setLayoutCount == 3u) && layout.pSetLayouts != nullptr && ((keys.preRasterizationSets | keys.fragmentSets) & ~((1u << layout.setLayoutCount) - 1u)) == 0u), "split pipeline library layout requires two or three descriptor set slots and a valid mask"); auto& store = Libraries(); std::unique_lock lock(store.mutex); ++store.activeBuilds[context.device]; @@ -139,9 +139,9 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip auto found = device.layouts.find(key); if (found != device.layouts.end()) return found->second; auto info = layout; - std::array sets{VK_NULL_HANDLE, VK_NULL_HANDLE}; + std::array sets{VK_NULL_HANDLE, VK_NULL_HANDLE, VK_NULL_HANDLE}; if (mask.has_value()) { - for (std::uint32_t set = 0; set < sets.size(); ++set) { + for (std::uint32_t set = 0; set < layout.setLayoutCount; ++set) { if ((*mask & (1u << set)) != 0u) sets[set] = layout.pSetLayouts[set]; } info.pSetLayouts = sets.data(); @@ -150,8 +150,10 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip Check(context.Function("vkCreatePipelineLayout")(context.device, &info, nullptr, &handle), "vkCreatePipelineLayout library"); return device.layouts.emplace(key, handle).first->second; }; - const auto fullLayout = layoutFor(keys.layout, std::nullopt); - const std::array partLayouts{VK_NULL_HANDLE, split ? layoutFor(keys.preRasterizationLayout, keys.preRasterizationSets) : fullLayout, split ? layoutFor(keys.fragmentLayout, keys.fragmentSets) : fullLayout, VK_NULL_HANDLE}; + const std::array memoryMarker{std::byte{descriptorHeap ? std::uint8_t{2} : std::uint8_t{0}}}; + const Key memoryKey(memoryMarker.begin(), memoryMarker.end()); + const auto fullLayout = descriptorHeap ? VkPipelineLayout{VK_NULL_HANDLE} : layoutFor(Combined(keys.layout, memoryKey), std::nullopt); + const std::array partLayouts{VK_NULL_HANDLE, split && !descriptorHeap ? layoutFor(Combined(keys.preRasterizationLayout, memoryKey), keys.preRasterizationSets) : fullLayout, split && !descriptorHeap ? layoutFor(Combined(keys.fragmentLayout, memoryKey), keys.fragmentSets) : fullLayout, VK_NULL_HANDLE}; std::vector preRasterization; const VkPipelineShaderStageCreateInfo* fragment = nullptr; bool mesh = false; @@ -168,7 +170,8 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT, VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_OUTPUT_INTERFACE_BIT_EXT, }; - const std::array partKeys{&keys.vertexInput, &keys.preRasterization, &keys.fragmentShader, &keys.fragmentOutput}; + std::array markedParts{Combined(keys.vertexInput, memoryKey), Combined(keys.preRasterization, memoryKey), Combined(keys.fragmentShader, memoryKey), Combined(keys.fragmentOutput, memoryKey)}; + const std::array partKeys{&markedParts[0], &markedParts[1], &markedParts[2], &markedParts[3]}; const Key none; VkPipelineRenderingCreateInfoKHR shaderRendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR}; shaderRendering.viewMask = rendering.viewMask; @@ -198,6 +201,7 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip library.flags = flags[part]; VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &library}; create.flags = optimize ? VK_PIPELINE_CREATE_LIBRARY_BIT_KHR | VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT : VK_PIPELINE_CREATE_LIBRARY_BIT_KHR; + auto partFlags = DescriptorHeapFlags(static_cast(create.flags), &library); create.pDynamicState = info.pDynamicState; create.layout = partLayouts[part]; switch (flags[part]) { @@ -225,6 +229,11 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip create.layout = VK_NULL_HANDLE; break; } + if (descriptorHeap) { + create.pNext = &partFlags; + create.flags = 0; + create.layout = VK_NULL_HANDLE; + } VkPipeline handle = VK_NULL_HANDLE; // Built without the store's mutex: a draw whose parts are resident is not held behind // another thread's build, and builds from several threads (the registration prebuild, the @@ -273,11 +282,18 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip linked.libraryCount = static_cast(libraries.size()); linked.pLibraries = libraries.data(); VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &linked}; + create.flags = 0; + create.layout = info.layout; + auto linkFlags = DescriptorHeapFlags(0, &linked); + if (descriptorHeap) { + create.pNext = &linkFlags; + create.flags = 0; + create.layout = VK_NULL_HANDLE; + } if (sampleCounts) { linkedSamples.pNext = create.pNext; create.pNext = &linkedSamples; } - create.layout = info.layout; VkPipeline pipeline = VK_NULL_HANDLE; lock.unlock(); { @@ -294,20 +310,25 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip const auto createPipelines = context.Function("vkCreateGraphicsPipelines"); const auto cache = context.pipelineCache; const auto cacheSynchronization = context.pipelineCacheSynchronization; - const auto libraryLayout = fullLayout; - std::function relink = [slot, createPipelines, cache, cacheSynchronization, libraryLayout, libraries, sampleCounts, attachmentSamples, &store, devicePointer = &device] { + const auto libraryLayout = descriptorHeap ? VkPipelineLayout{VK_NULL_HANDLE} : fullLayout; + std::function relink = [slot, createPipelines, cache, cacheSynchronization, libraryLayout, libraries, sampleCounts, attachmentSamples, &store, devicePointer = &device, descriptorHeap] { if (slot->released.load()) return; auto linkedSamples = sampleCounts ? attachmentSamples(*sampleCounts) : VkAttachmentSampleCountInfoNV{}; VkPipelineLibraryCreateInfoKHR linked{VK_STRUCTURE_TYPE_PIPELINE_LIBRARY_CREATE_INFO_KHR}; linked.libraryCount = static_cast(libraries.size()); linked.pLibraries = libraries.data(); VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &linked}; + create.flags = VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT; + create.layout = libraryLayout; + auto relinkFlags = DescriptorHeapFlags(static_cast(VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT), &linked); + if (descriptorHeap) { + create.pNext = &relinkFlags; + create.flags = 0; + } if (sampleCounts) { linkedSamples.pNext = create.pNext; create.pNext = &linkedSamples; } - create.flags = VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT; - create.layout = libraryLayout; VkPipeline result = VK_NULL_HANDLE; const auto pipelineCreationResult = [&] { auto pipelineCacheLock = cacheSynchronization != nullptr ? cacheSynchronization->LockForPipelineUse() : PipelineCacheSynchronization::PipelineUseLock{}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 256b8d032123..a5d52065750a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -12,10 +12,12 @@ #include "prx/libSceAgcDriver/Graphics/include/ReferenceStorage.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libkernel/Time/include/SleepWake.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp" #include "prx/libSceAgcDriver/Graphics/include/ParallelCompare.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp" #include "prx/libSceAgcDriver/Graphics/include/DeferredDestruction.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/SubmissionSnapshots.hpp" @@ -678,6 +680,21 @@ using WriteRanges = Recorder::WriteRanges; // GPU) or follows the write-back. AtomicSharedPtr pendingWrites; +struct PendingWritesSeen { + std::uint64_t generation = std::numeric_limits::max(); + std::shared_ptr ranges; +}; + +const std::shared_ptr& currentPendingWrites() { + auto& seen = HostThreadLocal(); + const auto generation = publishGeneration.load(std::memory_order_acquire); + if (generation != seen.generation) { + seen.ranges = pendingWrites.load(std::memory_order_acquire); + seen.generation = generation; + } + return seen.ranges; +} + bool HookSnapshotEnabled() { // Debug aid: APS5_NO_HOOK_SNAPSHOT=1 takes the GpuMutex on every access as before. static const bool enabled = std::getenv("APS5_NO_HOOK_SNAPSHOT") == nullptr; @@ -693,36 +710,35 @@ bool SnapshotOverlaps(const WriteRanges* snapshot, std::uint64_t address, std::s bool SnapshotOverlaps(std::uint64_t address, std::size_t bytes) { if (bytes == 0) return false; - const auto snapshot = pendingWrites.load(std::memory_order_acquire); - return SnapshotOverlaps(snapshot.get(), address, bytes); + return SnapshotOverlaps(currentPendingWrites().get(), address, bytes); } -bool HookClearAccess() { - static const bool enabled = std::getenv("APS5_NO_HOOK_CLEAR_ACCESS") == nullptr; - return enabled; } -struct ThreadWriteRanges { - std::uint64_t generation = ~std::uint64_t{0}; - std::shared_ptr ranges; -}; -struct ThreadWriteRangesTag {}; - -bool ThreadSnapshotOverlaps(std::uint64_t address, std::size_t bytes) { - auto& copy = ThreadScratch(); - const auto generation = publishGeneration.load(std::memory_order_acquire); - if (copy.generation != generation) { - copy.ranges = pendingWrites.load(std::memory_order_acquire); - copy.generation = generation; +bool Recorder::ReadsSettled(std::span> ranges, const WriteRanges* before) { + if (!HookSnapshotEnabled()) return false; + const bool labels = !QueuedLabelRanges().empty(); + const auto* now = currentPendingWrites().get(); + for (const auto& [begin, end] : ranges) { + const auto bytes = static_cast(end - begin); + if (labels && QueuedLabelOverlaps(begin, bytes)) return false; + if (AgcDriver::Graphics::SnapshotOverlaps(before, begin, bytes) || AgcDriver::Graphics::SnapshotOverlaps(now, begin, bytes)) return false; } - return SnapshotOverlaps(copy.ranges.get(), address, bytes); + return !StorageTexture::AnyPendingOverlaps(ranges) && !AnyShadowedOverlaps(ranges); +} + +namespace { + +bool HookClearAccess() { + static const bool enabled = std::getenv("APS5_NO_HOOK_CLEAR_ACCESS") == nullptr; + return enabled; } struct ClearAccessesTag {}; using ClearAccesses = HostThreadSlot; bool ClearAccess(std::uint64_t address, std::size_t bytes) { - return StorageTexture::PendingClearOnThread(address, bytes) && LiveUnitsClear(address, bytes) && !ThreadSnapshotOverlaps(address, bytes); + return StorageTexture::PendingClearOnThread(address, bytes) && LiveUnitsClear(address, bytes) && !SnapshotOverlaps(address, bytes); } // Whether one merged range of the snapshot contains [address, end) entirely. @@ -733,8 +749,7 @@ bool SnapshotCovers(const WriteRanges* snapshot, std::uint64_t address, std::uin } bool SnapshotCovers(std::uint64_t address, std::uint64_t end) { - const auto snapshot = pendingWrites.load(std::memory_order_acquire); - return SnapshotCovers(snapshot.get(), address, end); + return SnapshotCovers(currentPendingWrites().get(), address, end); } // Attribution of the pending-write syncs the hook makes (the [hooksync] line every 10 s, under @@ -1403,7 +1418,6 @@ Recorder::Recorder(const Context& context, bool timelineSemaphores) : context(co cmdEndQuery = context.Function("vkCmdEndQuery"); cmdResetQueryPool = context.Function("vkCmdResetQueryPool"); cmdCopyQueryPoolResults = context.Function("vkCmdCopyQueryPoolResults"); - cmdPushConstants = context.Function("vkCmdPushConstants"); cmdDispatch = context.Function("vkCmdDispatch"); } if (!timelineSemaphores) return; @@ -1428,6 +1442,9 @@ Recorder::~Recorder() { } catch (const std::exception& error) { std::fprintf(stderr, "[gpu] recorder teardown: %s\n", error.what()); } + if (DescriptorHeapEnabled()) { + if (auto* heap = BindlessHeap::Existing(context)) heap->RecorderDestroyed(*this); + } ForgetHtileMasks_nid_no_patch(id); progressWatcher.reset(); holdKept.clear(); @@ -1470,8 +1487,10 @@ Recorder::~Recorder() { if (labelTableOwner == this) labelTableOwner = nullptr; } if (meshArgumentPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, meshArgumentPipeline, nullptr); + if (meshArgumentHeapPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, meshArgumentHeapPipeline, nullptr); if (meshArgumentLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, meshArgumentLayout, nullptr); if (changedCopyPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, changedCopyPipeline, nullptr); + if (changedCopyHeapPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, changedCopyHeapPipeline, nullptr); if (changedCopyLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, changedCopyLayout, nullptr); if (boundChangedCopyPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, boundChangedCopyPipeline, nullptr); if (boundChangedCopyLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, boundChangedCopyLayout, nullptr); @@ -1487,6 +1506,7 @@ Recorder::~Recorder() { sampleCounter.reset(); } if (dispatchArgumentPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, dispatchArgumentPipeline, nullptr); + if (dispatchArgumentHeapPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, dispatchArgumentHeapPipeline, nullptr); if (dispatchArgumentLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, dispatchArgumentLayout, nullptr); for (const auto fence : spare) context.Function("vkDestroyFence")(context.device, fence, nullptr); spare.clear(); @@ -1951,7 +1971,7 @@ void Recorder::flushDeferredDispatch() { open->runAccess.clear(); auto after = std::move(open->afterRun); open->afterRun.clear(); - constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; + constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; recordBarrier(open->commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, dispatchedAccess); CountBarriers(CommandClass::DispatchTrailing); open->coveredAccess = dispatchedAccess; @@ -2032,7 +2052,7 @@ bool Recorder::SnapshotWriteOverlaps(std::uint64_t address, std::size_t bytes) { } std::shared_ptr Recorder::PendingWriteSnapshot() { - return pendingWrites.load(std::memory_order_acquire); + return currentPendingWrites(); } bool Recorder::SnapshotOverlaps(const WriteRanges* snapshot, std::uint64_t address, std::size_t bytes) { @@ -2229,6 +2249,7 @@ void Recorder::ensureOpen() { } VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + NoteCommandBufferBegun(batch->commands); Check(function(beginCommandBuffer, "vkBeginCommandBuffer")(batch->commands, &begin), "vkBeginCommandBuffer recorder"); static const bool suppress = std::getenv("APS5_NO_STATE_SUPPRESSION") == nullptr; batch->graphicsState.Begin(batch->commands, suppress); @@ -2760,6 +2781,7 @@ bool Recorder::RecordDispatchArguments(VkCommandBuffer commands, VkDeviceAddress pipelineInfo.stage.pName = "main"; pipelineInfo.layout = dispatchArgumentLayout; Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &dispatchArgumentPipeline), "vkCreateComputePipelines dispatch arguments"); + dispatchArgumentHeapPipeline = createPushOnlyHeapPipeline(pipelineInfo); context.Function("vkDestroyShaderModule")(context.device, module, nullptr); dispatchArgumentState = 1; } catch (const std::exception& error) { @@ -2769,7 +2791,7 @@ bool Recorder::RecordDispatchArguments(VkCommandBuffer commands, VkDeviceAddress } if (dispatchArgumentState < 0) return false; recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); - context.BindComputePipeline(commands, dispatchArgumentPipeline); + bindPushOnlyPipeline(commands, dispatchArgumentPipeline, dispatchArgumentHeapPipeline); const auto* limit = context.limits.maxComputeWorkGroupCount; struct { VkDeviceAddress source; @@ -2779,7 +2801,7 @@ bool Recorder::RecordDispatchArguments(VkCommandBuffer commands, VkDeviceAddress } parameters{source, arguments, {limit[0], limit[1], limit[2], threadGroup != nullptr ? 1u : 0u}, {1u, 1u, 1u, 0u}}; if (threadGroup != nullptr) std::copy(threadGroup->begin(), threadGroup->end(), parameters.group.begin()); static_assert(sizeof(parameters) == PushBytes); - function(cmdPushConstants, "vkCmdPushConstants")(commands, dispatchArgumentLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); + pushOnlyParameters(commands, dispatchArgumentHeapPipeline, dispatchArgumentLayout, PushBytes, ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, 1, 1, 1); const VkPipelineStageFlags readers = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | (threadGroup != nullptr ? VK_PIPELINE_STAGE_TRANSFER_BIT : 0u); const VkAccessFlags reads = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | (threadGroup != nullptr ? VK_ACCESS_TRANSFER_READ_BIT : 0u); @@ -3098,15 +3120,14 @@ void Recorder::dispatchDumps(VkCommandBuffer commands, std::uint32_t firstDump, std::uint32_t phase; } parameters{sampleCounter->DeviceAddress(), sampleCounter->DeviceAddress() + DumpListOffset, firstDump, dumps, firstSegment, lastSegment, 0u}; static_assert(sizeof(parameters) == SampleDumpPushBytes); - const auto push = function(cmdPushConstants, "vkCmdPushConstants"); const auto dispatch = function(cmdDispatch, "vkCmdDispatch"); - push(commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); + CmdPushConstants(context, commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); dispatch(commands, 1, 1, 1); if (dumps == 0) return; const auto publish = [&](std::uint32_t phase) { recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); parameters.phase = phase; - push(commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); + CmdPushConstants(context, commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); dispatch(commands, 1, 1, 1); }; publish(1u); @@ -3148,7 +3169,6 @@ void Recorder::endSamples(Batch& batch) { void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) { const auto commands = batch.commands; const auto copy = function(cmdCopyQueryPoolResults, "vkCmdCopyQueryPoolResults"); - const auto push = function(cmdPushConstants, "vkCmdPushConstants"); const auto dispatch = function(cmdDispatch, "vkCmdDispatch"); const auto bindCompute = context.ComputeBinding(); std::size_t done = 0; @@ -3171,13 +3191,13 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) { std::uint32_t store; } parameters{sampleCounter->DeviceAddress(), target, count, last && target != 0 ? 1u : 0u}; static_assert(sizeof(parameters) == SampleCounterPushBytes); - push(commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, ¶meters); + CmdPushConstants(context, commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, ¶meters); dispatch(commands, 1, 1, 1); if (parameters.store == 1u) { const auto publish = [&](std::uint32_t store) { recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); parameters.store = store; - push(commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, ¶meters); + CmdPushConstants(context, commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, ¶meters); dispatch(commands, 1, 1, 1); }; publish(3u); @@ -3246,6 +3266,7 @@ bool Recorder::RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress rec auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &meshArgumentPipeline), "vkCreateComputePipelines mesh arguments"); } + meshArgumentHeapPipeline = createPushOnlyHeapPipeline(pipelineInfo); context.Function("vkDestroyShaderModule")(context.device, module, nullptr); meshArgumentState = 1; } catch (const std::exception& error) { @@ -3255,20 +3276,48 @@ bool Recorder::RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress rec } if (meshArgumentState < 0) return false; recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); - context.BindComputePipeline(commands, meshArgumentPipeline); + bindPushOnlyPipeline(commands, meshArgumentPipeline, meshArgumentHeapPipeline); struct { VkDeviceAddress record; VkDeviceAddress arguments; std::array rules; } parameters{record, arguments, {rules[0], rules[1], rules[2], rules[3], rules[4], rules[5], rules[6], 0u}}; static_assert(sizeof(parameters) == PushBytes); - function(cmdPushConstants, "vkCmdPushConstants")(commands, meshArgumentLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); + pushOnlyParameters(commands, meshArgumentHeapPipeline, meshArgumentLayout, PushBytes, ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, 1, 1, 1); recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_MESH_SHADER_BIT_EXT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_SHADER_READ_BIT); CountBarriers(CommandClass::Draw, 2); return true; } +VkPipeline Recorder::createPushOnlyHeapPipeline(const VkComputePipelineCreateInfo& info) const { + if (!DescriptorHeapEnabled() || !context.descriptorHeap || !BindlessHeap::For(context).DescriptorHeapMode()) return VK_NULL_HANDLE; + auto heapFlags = DescriptorHeapFlags(); + auto heapInfo = info; + heapInfo.pNext = &heapFlags; + heapInfo.layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + try { + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + if (context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &heapInfo, nullptr, &pipeline) != VK_SUCCESS) return VK_NULL_HANDLE; + } catch (const std::exception&) { + return VK_NULL_HANDLE; + } + return pipeline; +} + +void Recorder::bindPushOnlyPipeline(VkCommandBuffer commands, VkPipeline pipeline, VkPipeline heapPipeline) const { + context.BindComputePipeline(commands, heapPipeline != VK_NULL_HANDLE ? heapPipeline : pipeline); +} + +void Recorder::pushOnlyParameters(VkCommandBuffer commands, VkPipeline heapPipeline, VkPipelineLayout layout, std::uint32_t bytes, const void* values) const { + if (heapPipeline == VK_NULL_HANDLE) { + CmdPushConstants(context, commands, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, bytes, values); + return; + } + CmdPushData(context, commands, bytes, values); +} + bool Recorder::RecordChangedCopy(VkCommandBuffer commands, VkDeviceAddress result, VkDeviceAddress snapshot, VkDeviceAddress target, std::uint32_t dwords, VkDeviceAddress counter) { constexpr std::uint32_t PushBytes = 40; constexpr std::uint32_t GroupSize = 64; @@ -3289,6 +3338,7 @@ bool Recorder::RecordChangedCopy(VkCommandBuffer commands, VkDeviceAddress resul pipelineInfo.stage.pName = "main"; pipelineInfo.layout = changedCopyLayout; Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &changedCopyPipeline), "vkCreateComputePipelines changed copy"); + changedCopyHeapPipeline = createPushOnlyHeapPipeline(pipelineInfo); context.Function("vkDestroyShaderModule")(context.device, module, nullptr); changedCopyState = 1; } catch (const std::exception& error) { @@ -3298,7 +3348,7 @@ bool Recorder::RecordChangedCopy(VkCommandBuffer commands, VkDeviceAddress resul } if (changedCopyState < 0) return false; static const bool alwaysCopy = std::getenv("APS5_CHANGED_COPY_ALWAYS") != nullptr; - context.BindComputePipeline(commands, changedCopyPipeline); + bindPushOnlyPipeline(commands, changedCopyPipeline, changedCopyHeapPipeline); const auto perDispatch = static_cast(std::min(std::uint64_t{context.limits.maxComputeWorkGroupCount[0]} * GroupSize, std::numeric_limits::max() - GroupSize)); for (std::uint32_t done = 0; done < dwords;) { const auto count = std::min(dwords - done, perDispatch); @@ -3311,7 +3361,7 @@ bool Recorder::RecordChangedCopy(VkCommandBuffer commands, VkDeviceAddress resul std::uint32_t always; } parameters{result + VkDeviceAddress{done} * 4u, snapshot + VkDeviceAddress{done} * 4u, target + VkDeviceAddress{done} * 4u, counter, count, alwaysCopy ? 1u : 0u}; static_assert(sizeof(parameters) == PushBytes); - function(cmdPushConstants, "vkCmdPushConstants")(commands, changedCopyLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); + pushOnlyParameters(commands, changedCopyHeapPipeline, changedCopyLayout, PushBytes, ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, (count + GroupSize - 1) / GroupSize, 1, 1); done += count; } @@ -3393,9 +3443,9 @@ bool Recorder::RecordBoundChangedCopy(VkCommandBuffer commands, BoundWords resul writes[binding].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; writes[binding].pBufferInfo = &infos[binding]; } - cmdPushChangedCopySet(commands, VK_PIPELINE_BIND_POINT_COMPUTE, boundChangedCopyLayout, 0, static_cast(writes.size()), writes.data()); + CmdPushDescriptorSet(cmdPushChangedCopySet, commands, VK_PIPELINE_BIND_POINT_COMPUTE, boundChangedCopyLayout, 0, static_cast(writes.size()), writes.data(), SetBindSite::ChangedCopy); const Parameters parameters{bases[0], bases[1], bases[2], count, alwaysCopy ? 1u : 0u, counter != VK_NULL_HANDLE ? 1u : 0u}; - function(cmdPushConstants, "vkCmdPushConstants")(commands, boundChangedCopyLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(parameters), ¶meters); + CmdPushConstants(context, commands, boundChangedCopyLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(parameters), ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, (count + GroupSize - 1) / GroupSize, 1, 1); done += count; } @@ -3589,6 +3639,12 @@ void Recorder::KeepBytes(const void* owner, std::size_t bytes) { if (open->keptOwners.insert(owner).second) open->keptBytes += bytes; } +void Recorder::BoundDrawBatch() { + BoundKeptBytes(); + if (open == nullptr || !DescriptorHeapEnabled() || !GuestMemory::GpuMutex().HeldByThisThread()) return; + if (auto* heap = BindlessHeap::Existing(context); heap != nullptr && heap->TakeSlotPressure()) Submit(); +} + void Recorder::BoundKeptBytes() { if (!GuestMemory::GpuMutex().HeldByThisThread()) return; if (open != nullptr && open->keptBytes >= KeptBytesBudget) Submit(); @@ -3657,7 +3713,7 @@ std::shared_ptr Recorder::mirrorDrawInput(std::map(context.limits.minStorageBufferOffsetAlignment, 16); + const VkDeviceSize alignment = std::max(GuestBufferViewAlignment(context.limits), 16); auto offset = (drawUploadUsed + alignment - 1) & ~(alignment - 1); if (drawUpload == nullptr || offset + bytes > drawUpload->Bytes().size()) { drawUpload = std::make_shared(context, std::max(DrawUploadChunk, bytes), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); @@ -3731,7 +3787,7 @@ std::shared_ptr Recorder::ReusableDrawSnapshot(std::uint64_t address, st } std::shared_ptr Recorder::containingDrawSnapshot(std::uint64_t address, std::size_t bytes, VkDeviceSize* offset) { - const VkDeviceSize alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); + const VkDeviceSize alignment = GuestBufferViewAlignment(context.limits); const auto registry = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); auto entry = drawSnapshots.upper_bound({address, SnapshotUse::Storage, std::numeric_limits::max()}); for (std::size_t probe = 0; probe < ContainingSnapshotProbes && entry != drawSnapshots.begin(); ++probe) { @@ -4761,6 +4817,8 @@ void Recorder::Submit() { submission.pSignalSemaphores = &timeline; } if (hold != VK_NULL_HANDLE || timeline != VK_NULL_HANDLE) submission.pNext = &timelineInfo; + auto* const heapAtSubmit = DescriptorHeapEnabled() ? BindlessHeap::Existing(context) : nullptr; + if (heapAtSubmit != nullptr && !HasTimeline()) throw std::runtime_error("AGC bindless heap: a batch using the heap was submitted by a recorder without a timeline semaphore"); DestroyDeferredAtIdle(context); const auto submitStart = std::chrono::steady_clock::now(); batch->submitStarted.store(true, std::memory_order_release); @@ -4773,6 +4831,14 @@ void Recorder::Submit() { if (batch->guestWork) LibcRunReportMilestone_nid_no_patch(2); batch->submitted = true; batch->serial = ++submissions; + std::exception_ptr heapFailure; + if (heapAtSubmit != nullptr) { + try { + heapAtSubmit->Submitted(*this, batch->serial); + } catch (...) { + heapFailure = std::current_exception(); + } + } batch->submittedAt = std::chrono::steady_clock::now(); CaptureTrace::Log("submit-confirmed batch=%llu tokens=%s", static_cast(batch->serial), tokensStr.c_str()); if (DrawProfiled()) { @@ -4797,6 +4863,7 @@ void Recorder::Submit() { inFlight.push_back(std::move(batch)); inFlightKeptBytes += inFlight.back()->keptBytes; if (activeRecorder == this) pendingLabelSince.store(NoPendingLabel, std::memory_order_release); + if (heapFailure != nullptr) std::rethrow_exception(heapFailure); } std::uint64_t Recorder::SubmitAndEpoch() { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp index b66cf6f94108..7d3f00ebe6e5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp @@ -413,8 +413,7 @@ ResidentBuffer::ResidentBuffer(const Context& context, std::uint64_t base, std:: index = last; } submit(binds); - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; - address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + address = BufferDeviceAddress(context, buffer); if (address == 0) fail("vkGetBufferDeviceAddressKHR of a resident heap mirror", VK_ERROR_UNKNOWN); } catch (...) { release(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp index 460f9486dcfc..f6fcb247ec93 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" @@ -52,6 +53,11 @@ VkBuffer BindExactBuffer(const Context& context, std::size_t size, VkBufferUsage return buffer; } +VkBufferUsageFlags UsageWithoutUnsupportedAddress(const Context& context, VkBufferUsageFlags requested, VkBufferUsageFlags pooled) { + if (!context.bufferDeviceAddress && (requested & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) == 0) return pooled & ~static_cast(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + return pooled; +} + } Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties) : Buffer(context, size, usage, properties, false) {} @@ -61,9 +67,9 @@ std::shared_ptr Buffer::WithinDeviceLocalHeadroom(const Context& context return buffer->ready ? buffer : nullptr; } -Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, bool headroom) : context(context), size(size), capacity(BufferPool::Capacity(size)), usage(BufferPool::Usage(usage, properties)), properties(properties) { +Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, bool headroom) : context(context), size(size), capacity(BufferPool::Capacity(size)), usage(UsageWithoutUnsupportedAddress(context, usage, BufferPool::Usage(usage, properties))), properties(properties) { Require(size != 0, "zero-sized GPU buffer"); - const bool addressable = (usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0; + const bool addressable = (this->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0; Require(!addressable || context.bufferDeviceAddress, "buffer device address is not enabled"); cache = GetBufferPool(context); if (const auto allocation = cache->Take(size, this->usage, properties, "vkAllocateMemory buffer")) { @@ -84,7 +90,14 @@ Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usag deviceAddress = 0; try { buffer = BindExactBuffer(context, size, this->usage, memory, offset, allocationBytes); - initializeAddress(usage); + initializeAddress(this->usage); + } catch (...) { + release(); + throw; + } + } else if (deviceAddress == 0) { + try { + initializeAddress(this->usage); } catch (...) { release(); throw; @@ -122,7 +135,7 @@ Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usag slab = true; allocationBytes = capacity; Check(context.Resolved(&DeviceFunctions::bindBufferMemory, "vkBindBufferMemory")(context.device, buffer, memory, offset), "vkBindBufferMemory slab"); - initializeAddress(usage); + initializeAddress(this->usage); mapping = slot.mapping; #ifdef __APPLE__ ClearPooledTail(mapping, size, capacity, properties); @@ -132,7 +145,7 @@ Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usag } memory = cache->AllocateMemory(allocation, "vkAllocateMemory buffer"); Check(context.Resolved(&DeviceFunctions::bindBufferMemory, "vkBindBufferMemory")(context.device, buffer, memory, 0), "vkBindBufferMemory"); - initializeAddress(usage); + initializeAddress(this->usage); if ((properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) Check(context.Resolved(&DeviceFunctions::mapMemory, "vkMapMemory")(context.device, memory, 0, VK_WHOLE_SIZE, 0, &mapping), "vkMapMemory"); ready = true; } catch (...) { @@ -178,7 +191,7 @@ void Buffer::Invalidate() { Check(context.Function("vkInvalidateMappedMemoryRanges")(context.device, 1, &range), "vkInvalidateMappedMemoryRanges"); } -DeviceBuffer::DeviceBuffer(const Context& context, std::size_t size, VkBufferUsageFlags usage) : context(context), size(size), capacity(BufferPool::Capacity(size)), usage(BufferPool::Usage(usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { +DeviceBuffer::DeviceBuffer(const Context& context, std::size_t size, VkBufferUsageFlags usage) : context(context), size(size), capacity(BufferPool::Capacity(size)), usage(UsageWithoutUnsupportedAddress(context, usage, BufferPool::Usage(usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT))) { Require(size != 0, "zero-sized device buffer"); cache = GetBufferPool(context); auto pooled = cache->Take(size, this->usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, "vkAllocateMemory device buffer"); @@ -222,6 +235,8 @@ DeviceBuffer::DeviceBuffer(const Context& context, std::size_t size, VkBufferUsa allocation.allocationSize = ClassAllocationBytes(requirements, capacity); allocationBytes = allocation.allocationSize; allocation.memoryTypeIndex = context.DeviceMemoryType(requirements.memoryTypeBits, allocation.allocationSize, "device buffer"); + const VkMemoryAllocateFlagsInfo addressFlags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, nullptr, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0}; + if ((this->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0) allocation.pNext = &addressFlags; const auto deviceType = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); std::uint32_t allocatedType = allocation.memoryTypeIndex; memory = cache->AllocateMemory(allocation, "vkAllocateMemory device buffer", context.RefusedDeviceMemoryFallback(requirements.memoryTypeBits, allocation.memoryTypeIndex), &allocatedType); @@ -403,6 +418,7 @@ CommandBatch::CommandBatch(const Context& context) : context(context) { fence = created; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + NoteCommandBufferBegun(commands); Check(context.Function("vkBeginCommandBuffer")(commands, &begin), "vkBeginCommandBuffer"); WriteCheckpointSentinel(context, commands); // Work recorded so far goes first in queue order, so this batch sees its results. diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp index 6bcc4b660557..f762a763d350 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" #include "prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" @@ -18,10 +19,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include @@ -44,6 +47,20 @@ struct DepthPush { std::uint32_t bit; }; +struct HeapStoragePush { + StoragePush push; + std::uint32_t image; +}; + +struct HeapDepthPush { + DepthPush push; + std::uint32_t depth; + std::uint32_t stencil; +}; + +static_assert(offsetof(HeapStoragePush, image) == 28); +static_assert(offsetof(HeapDepthPush, depth) == 20 && offsetof(HeapDepthPush, stencil) == 24); + bool exactDepth(VkFormat format) { return format == VK_FORMAT_D16_UNORM || format == VK_FORMAT_D32_SFLOAT || format == VK_FORMAT_D16_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT_S8_UINT; } @@ -90,7 +107,7 @@ void transitionLocated(const Context& context, VkCommandBuffer commands, VkImage context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, sourceStages, destinationStages, 0, 0, nullptr, 0, nullptr, 1, &barrier); } -class CopyImage { +class CopyImage : public HeapSlotOwner { public: CopyImage(const Context& context, VkFormat format, std::uint32_t samples, VkExtent2D extent, bool stencil) : context(context), format(format), samples(samples), extent(extent) { try { @@ -147,6 +164,7 @@ class CopyImage { } void release() noexcept { + ReleaseHeapSlots(context); if (stencilView) context.Function("vkDestroyImageView")(context.device, stencilView, nullptr); if (depthView) context.Function("vkDestroyImageView")(context.device, depthView, nullptr); if (image) context.Function("vkDestroyImage")(context.device, image, nullptr); @@ -167,6 +185,20 @@ class SampleOrders { void Storage(VkCommandBuffer commands, const SampleOrderTarget& target, const std::array& map, VkExtent2D region) { const auto pipeline = storagePipeline(target.format); + const StoragePush push{map, {region.width, region.height}, target.samples}; + const auto dispatch = [&] { context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, ((region.width + 1u) / 2u + 7u) / 8u, ((region.height + 1u) / 2u + 7u) / 8u, 1); }; + const auto heapPipeline = heapStoragePipelines[storageIndex(target.format)]; + if (heapPipeline != VK_NULL_HANDLE && target.owner != nullptr) { + auto& heap = BindlessHeap::For(context); + if (const auto slot = heap.ViewSlot(HeapPassStorageKind, target.owner, target.view)) { + heap.BindDescriptorHeaps(commands); + context.BindComputePipeline(commands, heapPipeline); + const HeapStoragePush pushed{push, *slot}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + dispatch(); + return; + } + } const auto set = allocate(storageSetLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, setsPerPool}}); const VkDescriptorImageInfo imageInfo{VK_NULL_HANDLE, target.view, VK_IMAGE_LAYOUT_GENERAL}; VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; @@ -176,11 +208,10 @@ class SampleOrders { write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; write.pImageInfo = &imageInfo; context.Function("vkUpdateDescriptorSets")(context.device, 1, &write, 0, nullptr); - const StoragePush push{map, {region.width, region.height}, target.samples}; context.BindComputePipeline(commands, pipeline); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, storagePipelineLayout, 0, 1, &set, 0, nullptr); - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, storagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); - context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, ((region.width + 1u) / 2u + 7u) / 8u, ((region.height + 1u) / 2u + 7u) / 8u, 1); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, storagePipelineLayout, 0, 1, &set, SetBindSite::Detiler); + CmdPushConstants(context, commands, storagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); + dispatch(); } void Depth(CommandState& recording, const SampleOrderTarget& target, const std::array& map, VkExtent2D region, const SampleOrderPass& order, std::vector>& kept) { @@ -215,37 +246,35 @@ class SampleOrders { context.Function("vkCmdCopyImage")(commands, target.image, located ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, copy->image, VK_IMAGE_LAYOUT_GENERAL, 1, ®ion3d); if (located) transitionLocated(context, commands, target.image, target.format, info, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, fragmentStages, depthAccess); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, fragmentStages, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | depthAccess); - drawDepth(recording, target, map, region, order, copy->depthView, stencil ? copy->stencilView : copy->depthView, kept); + drawDepth(recording, target, map, region, order, copy->depthView, stencil ? copy->stencilView : copy->depthView, copy.get(), kept); } void Import(CommandState& recording, const SampleOrderTarget& target, VkImageView samples, std::vector>& kept) { constexpr std::uint32_t sameSamplesDrawn = KeptSampleOrder | 0x88888888u; constexpr std::array map{sameSamplesDrawn, sameSamplesDrawn, sameSamplesDrawn, sameSamplesDrawn}; - drawDepth(recording, target, map, target.extent, SampleOrderPass{}, samples, samples, kept); + drawDepth(recording, target, map, target.extent, SampleOrderPass{}, samples, samples, nullptr, kept); } Context context; private: - void drawDepth(CommandState& recording, const SampleOrderTarget& target, const std::array& map, VkExtent2D region, const SampleOrderPass& order, VkImageView depthSource, VkImageView stencilSource, std::vector>& kept) { + void drawDepth(CommandState& recording, const SampleOrderTarget& target, const std::array& map, VkExtent2D region, const SampleOrderPass& order, VkImageView depthSource, VkImageView stencilSource, const HeapSlotOwner* owner, std::vector>& kept) { const auto commands = recording.Commands(); const bool stencil = target.method != SampleOrderMethod::Depth; const auto& locations = order.locations; const bool located = order.located; const VkSampleLocationsInfoEXT info{VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT, nullptr, static_cast(target.samples), {1, 1}, target.samples, locations.data()}; const auto& pass = depthPass(target.format, target.samples, target.method, located, locations); - const auto set = allocate(sampledSetLayout, {{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, setsPerPool * 2u}}); - std::array images{{{VK_NULL_HANDLE, depthSource, VK_IMAGE_LAYOUT_GENERAL}, {VK_NULL_HANDLE, stencilSource, VK_IMAGE_LAYOUT_GENERAL}}}; - std::array writes{}; - for (std::uint32_t binding = 0; binding < writes.size(); ++binding) { - writes[binding].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[binding].dstSet = set; - writes[binding].dstBinding = binding; - writes[binding].descriptorCount = 1; - writes[binding].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; - writes[binding].pImageInfo = &images[binding]; + std::optional depthSlot; + std::optional stencilSlot; + if (pass.heapDepth != VK_NULL_HANDLE && owner != nullptr) { + auto& heap = BindlessHeap::For(context); + depthSlot = heap.ViewSlot(HeapPassSampledKind, owner, depthSource); + stencilSlot = depthSlot && stencil ? heap.ViewSlot(HeapPassSampledKind, owner, stencilSource) : depthSlot; } - context.Function("vkUpdateDescriptorSets")(context.device, stencil ? 2u : 1u, writes.data(), 0, nullptr); + const bool heapPass = depthSlot && stencilSlot; + VkDescriptorSet set = VK_NULL_HANDLE; + if (!heapPass) set = writeDepthSet(depthSource, stencilSource, stencil); const std::array views{target.view}; auto framebuffer = std::make_shared(context, pass.renderPass, views, region); kept.push_back(framebuffer); @@ -267,18 +296,24 @@ class SampleOrders { recording.SetViewport(context, viewport); recording.SetScissor(context, scissor); const auto slots = CommandState::DynamicSlots(depthOrderDynamicStates); - const auto draw = [&](VkPipeline pipeline, std::uint32_t bit, std::uint32_t writeMask, std::uint32_t reference) { - recording.BindPipeline(context, pipeline, slots); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, sampledPipelineLayout, 0, 1, &set, 0, nullptr); + const auto draw = [&](VkPipeline pipeline, VkPipeline heapPipeline, std::uint32_t bit, std::uint32_t writeMask, std::uint32_t reference) { + recording.BindPipeline(context, heapPass ? heapPipeline : pipeline, slots); + if (heapPass) BindlessHeap::For(context).BindDescriptorHeaps(commands); + else CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, sampledPipelineLayout, 0, 1, &set, SetBindSite::Detiler); recording.SetStencilWriteMask(context, VK_STENCIL_FACE_FRONT_AND_BACK, writeMask); recording.SetStencilReference(context, VK_STENCIL_FACE_FRONT_AND_BACK, reference); const DepthPush push{map, bit}; - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, sampledPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push), &push); + if (heapPass) { + const HeapDepthPush pushed{push, *depthSlot, *stencilSlot}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + } else { + CmdPushConstants(context, commands, sampledPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push), &push); + } context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, 3, 1, 0, 0); }; - draw(pass.depth, 0u, 0xffu, 0u); + draw(pass.depth, pass.heapDepth, 0u, 0xffu, 0u); if (target.method == SampleOrderMethod::DepthStencilBits) { - for (std::uint32_t bit = 0; bit < 8u; ++bit) draw(pass.stencilBits, bit, 1u << bit, 0xffu); + for (std::uint32_t bit = 0; bit < 8u; ++bit) draw(pass.stencilBits, pass.heapStencilBits, bit, 1u << bit, 0xffu); } context.Resolved(&DeviceFunctions::cmdEndRenderPass, "vkCmdEndRenderPass")(commands); } @@ -294,8 +329,33 @@ class SampleOrders { VkRenderPass renderPass = VK_NULL_HANDLE; VkPipeline depth = VK_NULL_HANDLE; VkPipeline stencilBits = VK_NULL_HANDLE; + VkPipeline heapDepth = VK_NULL_HANDLE; + VkPipeline heapStencilBits = VK_NULL_HANDLE; }; + VkDescriptorSet writeDepthSet(VkImageView depthSource, VkImageView stencilSource, bool stencil) { + const auto set = allocate(sampledSetLayout, {{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, setsPerPool * 2u}}); + std::array images{{{VK_NULL_HANDLE, depthSource, VK_IMAGE_LAYOUT_GENERAL}, {VK_NULL_HANDLE, stencilSource, VK_IMAGE_LAYOUT_GENERAL}}}; + std::array writes{}; + for (std::uint32_t binding = 0; binding < writes.size(); ++binding) { + writes[binding].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[binding].dstSet = set; + writes[binding].dstBinding = binding; + writes[binding].descriptorCount = 1; + writes[binding].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + writes[binding].pImageInfo = &images[binding]; + } + context.Function("vkUpdateDescriptorSets")(context.device, stencil ? 2u : 1u, writes.data(), 0, nullptr); + return set; + } + + static std::size_t storageIndex(VkFormat format) { + const std::array formats{VK_FORMAT_R8_UINT, VK_FORMAT_R16_UINT, VK_FORMAT_R32_UINT, VK_FORMAT_R32G32_UINT, VK_FORMAT_R32G32B32A32_UINT}; + const auto found = std::ranges::find(formats, format); + Require(found != formats.end(), "reordering the samples of a color target through a storage view of this format is not implemented"); + return static_cast(found - formats.begin()); + } + using DepthKey = std::tuple>; using CopyKey = std::tuple; @@ -331,10 +391,7 @@ class SampleOrders { } VkPipeline storagePipeline(VkFormat format) { - const std::array formats{VK_FORMAT_R8_UINT, VK_FORMAT_R16_UINT, VK_FORMAT_R32_UINT, VK_FORMAT_R32G32_UINT, VK_FORMAT_R32G32B32A32_UINT}; - const auto found = std::ranges::find(formats, format); - Require(found != formats.end(), "reordering the samples of a color target through a storage view of this format is not implemented"); - const auto index = static_cast(found - formats.begin()); + const auto index = storageIndex(format); if (storagePipelines[index] != VK_NULL_HANDLE) return storagePipelines[index]; if (storageSetLayout == VK_NULL_HANDLE) storageSetLayout = setLayout(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT); if (storagePipelineLayout == VK_NULL_HANDLE) storagePipelineLayout = pipelineLayout(storageSetLayout, VK_SHADER_STAGE_COMPUTE_BIT, sizeof(StoragePush)); @@ -351,6 +408,10 @@ class SampleOrders { auto pipelineCacheLock = context.LockPipelineCacheForUse(); created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &storagePipelines[index]); } + if (created == VK_SUCCESS && HeapPassesActive(context)) { + const auto mapping = HeapPushIndexMapping(BindlessHeap::For(context), 0, 0, HeapPassStorageImages, offsetof(HeapStoragePush, image)); + heapStoragePipelines[index] = CreateHeapComputePipeline(context, info, std::span(&mapping, 1)); + } destroyModule(shader); Check(created, "vkCreateComputePipelines sample order"); return storagePipelines[index]; @@ -454,14 +515,27 @@ class SampleOrders { auto pipelineCacheLock = context.LockPipelineCacheForUse(); created = context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline); } + VkPipeline heapPipeline = VK_NULL_HANDLE; + if (created == VK_SUCCESS && HeapPassesActive(context)) { + const auto& heap = BindlessHeap::For(context); + const std::array mappings{ + HeapPushIndexMapping(heap, 0, 0, VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT, offsetof(HeapDepthPush, depth)), + HeapPushIndexMapping(heap, 0, 1, VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT, offsetof(HeapDepthPush, stencil))}; + heapPipeline = CreateHeapGraphicsPipeline(context, info, mappings); + } destroyModule(fragment); destroyModule(vertex); Check(created, "vkCreateGraphicsPipelines sample order"); - return pipeline; + return std::pair{pipeline, heapPipeline}; }; - if (method == SampleOrderMethod::DepthStencilExport) pass.depth = create(SAMPLE_ORDER_STENCILEXPORT_SPV, sizeof(SAMPLE_ORDER_STENCILEXPORT_SPV), true); - else pass.depth = create(SAMPLE_ORDER_DEPTH_SPV, sizeof(SAMPLE_ORDER_DEPTH_SPV), true); - if (method == SampleOrderMethod::DepthStencilBits) pass.stencilBits = create(SAMPLE_ORDER_STENCILBITS_SPV, sizeof(SAMPLE_ORDER_STENCILBITS_SPV), false); + if (method == SampleOrderMethod::DepthStencilExport) std::tie(pass.depth, pass.heapDepth) = create(SAMPLE_ORDER_STENCILEXPORT_SPV, sizeof(SAMPLE_ORDER_STENCILEXPORT_SPV), true); + else std::tie(pass.depth, pass.heapDepth) = create(SAMPLE_ORDER_DEPTH_SPV, sizeof(SAMPLE_ORDER_DEPTH_SPV), true); + if (method == SampleOrderMethod::DepthStencilBits) std::tie(pass.stencilBits, pass.heapStencilBits) = create(SAMPLE_ORDER_STENCILBITS_SPV, sizeof(SAMPLE_ORDER_STENCILBITS_SPV), false); + if (method == SampleOrderMethod::DepthStencilBits && (pass.heapDepth == VK_NULL_HANDLE) != (pass.heapStencilBits == VK_NULL_HANDLE)) { + if (pass.heapDepth) context.Function("vkDestroyPipeline")(context.device, pass.heapDepth, nullptr); + if (pass.heapStencilBits) context.Function("vkDestroyPipeline")(context.device, pass.heapStencilBits, nullptr); + pass.heapDepth = pass.heapStencilBits = VK_NULL_HANDLE; + } } catch (...) { destroyPass(pass); throw; @@ -525,6 +599,8 @@ class SampleOrders { } void destroyPass(const DepthPass& pass) noexcept { + if (pass.heapStencilBits) context.Function("vkDestroyPipeline")(context.device, pass.heapStencilBits, nullptr); + if (pass.heapDepth) context.Function("vkDestroyPipeline")(context.device, pass.heapDepth, nullptr); if (pass.stencilBits) context.Function("vkDestroyPipeline")(context.device, pass.stencilBits, nullptr); if (pass.depth) context.Function("vkDestroyPipeline")(context.device, pass.depth, nullptr); if (pass.renderPass) context.Function("vkDestroyRenderPass")(context.device, pass.renderPass, nullptr); @@ -534,6 +610,9 @@ class SampleOrders { copies.clear(); for (const auto& [key, pass] : depthPasses) destroyPass(pass); depthPasses.clear(); + for (const auto pipeline : heapStoragePipelines) { + if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); + } for (const auto pipeline : storagePipelines) { if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); } @@ -554,6 +633,7 @@ class SampleOrders { VkPipelineLayout storagePipelineLayout = VK_NULL_HANDLE; VkPipelineLayout sampledPipelineLayout = VK_NULL_HANDLE; std::array storagePipelines{}; + std::array heapStoragePipelines{}; std::map depthPasses; std::map, std::uint64_t>> copies; std::uint64_t uses = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp index 12f34093a092..0824458be7f3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp" #include "PipelineSpecialization.hpp" #include @@ -25,17 +26,11 @@ namespace AgcDriver::Graphics { } } - Sampler::Sampler(const Context& context, const GuestSamplerResource& descriptor) : context(context) { + VkSamplerCreateInfo Sampler::CreateInfo(const Context& context, const GuestSamplerResource& descriptor, VkSamplerReductionModeCreateInfoEXT& reduction) { Validate(context, descriptor); - forcesDegamma = descriptor.forceDegamma; - disablesDegamma = descriptor.disableDegamma; - VkSamplerCreateInfo info{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - VkSamplerReductionModeCreateInfoEXT reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT, nullptr, descriptor.reductionMode}; - if (descriptor.reductionMode != VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT) { - info.pNext = &reduction; - requiresFilterMinmax = descriptor.magFilter == VK_FILTER_LINEAR || descriptor.minFilter == VK_FILTER_LINEAR; - } + reduction = {VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT, nullptr, descriptor.reductionMode}; + if (descriptor.reductionMode != VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT) info.pNext = &reduction; info.magFilter = descriptor.magFilter; info.minFilter = descriptor.minFilter; info.mipmapMode = descriptor.mipmapMode; @@ -50,12 +45,19 @@ namespace AgcDriver::Graphics { info.minLod = descriptor.minLod; info.maxLod = descriptor.maxLod; info.borderColor = descriptor.borderColor; - opaqueBlackBorder = ReadsOpaqueBlackBorder(descriptor); info.unnormalizedCoordinates = descriptor.unnormalizedCoordinates ? VK_TRUE : VK_FALSE; - if (descriptor.nonSeamlessCube) { - if (context.nonSeamlessCubeMap) info.flags |= VK_SAMPLER_CREATE_NON_SEAMLESS_CUBE_MAP_BIT_EXT; - else requiresNonSeamlessCube = true; - } + if (descriptor.nonSeamlessCube && context.nonSeamlessCubeMap) info.flags |= VK_SAMPLER_CREATE_NON_SEAMLESS_CUBE_MAP_BIT_EXT; + return info; + } + + Sampler::Sampler(const Context& context, const GuestSamplerResource& descriptor) : context(context) { + VkSamplerReductionModeCreateInfoEXT reduction{}; + const auto info = CreateInfo(context, descriptor, reduction); + forcesDegamma = descriptor.forceDegamma; + disablesDegamma = descriptor.disableDegamma; + requiresFilterMinmax = descriptor.reductionMode != VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT && (descriptor.magFilter == VK_FILTER_LINEAR || descriptor.minFilter == VK_FILTER_LINEAR); + opaqueBlackBorder = ReadsOpaqueBlackBorder(descriptor); + requiresNonSeamlessCube = descriptor.nonSeamlessCube && !context.nonSeamlessCubeMap; Check(context.Function("vkCreateSampler")(context.device, &info, nullptr, &sampler), "vkCreateSampler"); } @@ -64,6 +66,7 @@ namespace AgcDriver::Graphics { } void Sampler::release() noexcept { + ReleaseHeapSlots(context); if (sampler) context.Function("vkDestroySampler")(context.device, sampler, nullptr); } @@ -101,6 +104,7 @@ namespace AgcDriver::Graphics { auto resource = DecodeSamplerResource(words, unnormalizedProven, forceDegammaPaired, integerBorder); resource.compareEnable = compareEnable; auto sampler = std::make_shared(context, resource); + sampler->SetCacheKey(key); // The cap keeps live samplers well below the device's limit (NVIDIA: ~4000); a set in flight // still holds the evicted sampler through its own shared_ptr. while (entries.size() >= capacity) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp index c2cd061f377b..d2e489552d87 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp @@ -141,8 +141,8 @@ bool faultReportOnlyCached(const ShaderRecompiler::SharedSpirv& spirv, std::uint } -bool ShaderStoresThroughAddresses(const ShaderRecompiler::SharedSpirv& spirv) { - return storesThroughAddressesCached(spirv); +bool ProgramStoresThroughAddresses(const ShaderRecompiler::RecompileResult& program) { + return program.gpuResolvedImages ? program.bdaStores : storesThroughAddressesCached(program.spirv); } bool SpirvStoresThroughAddresses(std::span words) { @@ -232,7 +232,7 @@ void ShaderResources::prepareAddressBindings(std::span sha Require(shader.program->bdaAbiVersion == (faults == 0 ? 0u : ShaderRecompiler::BdaAbi::Version), "incompatible BDA ABI version"); // Rect-list validation needs a fault buffer, but never accesses guest addresses. usesBda = usesBda || tables != 0; - if (tables != 0 && storesThroughAddressesCached(shader.program->spirv)) bdaReadOnly = false; + if (tables != 0 && ProgramStoresThroughAddresses(*shader.program)) bdaReadOnly = false; usesFaultBuffer = usesFaultBuffer || faults != 0; const bool tableFaultsOnly = std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap; }); faultChecks = faultChecks || tables != 0 || (faults != 0 && (!tableFaultsOnly || shader.program->imageTableFaults != 0 || shader.program->poisonedSrtReads != 0 || shader.program->windowLaneGuards != 0 || shader.program->descriptorFaults != 0 || loopGuarded)); @@ -247,8 +247,8 @@ void ShaderResources::prepareAddressBindings(std::span sha } } -VkDescriptorBufferInfo ShaderResources::descriptor(Allocation& allocation) { - if (allocation.guest) return wholeDwordRange(guestMemory.Descriptor(allocation.address, allocation.size, allocation.adjustment)); +VkDescriptorBufferInfo ShaderResources::descriptor(const Allocation& allocation, std::uint32_t& adjustment) const { + if (allocation.guest) return wholeDwordRange(guestMemory.Descriptor(allocation.address, allocation.size, adjustment)); if (allocation.role == ShaderRecompiler::DescriptorRole::GuestBuffers) { const auto placeholder = allocation.oversized ? context.oversizedBuffer : context.emptyBuffer; Require(placeholder != VK_NULL_HANDLE, "no placeholder buffer for a null V#"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index a9d0d5dcd77d..0b54e4f87276 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" +#include "HeapCacheSwitch.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" @@ -10,6 +11,7 @@ #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/PlaceholderImages.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" @@ -24,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -55,6 +58,16 @@ namespace AgcDriver::Graphics { namespace { +std::uint32_t takenSlot(std::optional slot, const char* what) { + Require(slot.has_value(), what); + return *slot; +} + +bool UintStorageBinding(std::uint32_t binding) { + const auto kind = binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); + return ShaderRecompiler::RuntimeAbi::UintStorageImageKind(kind); +} + bool overlap(std::uint64_t first, std::size_t firstSize, std::uint64_t second, std::size_t secondSize) { return first < second + secondSize && second < first + firstSize; } @@ -1404,7 +1417,7 @@ struct StorageTextureCache { }; StorageTextureCache& StorageTextures() { - static StorageTextureCache cache; + static auto& cache = *new StorageTextureCache(); return cache; } @@ -1979,9 +1992,9 @@ bool StorageDedupeEnabled() { } // Whether storage element `element` of `binding` repeats the previous element's eight words. -bool SameAsPreviousStorageElement(const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t element) { +bool SameAsPreviousStorageElement(std::span guest, std::uint32_t element) { if (element == 0) return false; - const auto words = binding.guestDescriptor.begin() + static_cast(element) * 8u; + const auto words = guest.begin() + static_cast(element) * 8u; return std::equal(words, words + 8, words - 8); } @@ -2054,10 +2067,24 @@ void ShaderResources::Complete() { prepareAddressBindings(shaders, deferredSnapshots); buildPrepare(shaders, nullptr, 0, 0, 0); } - buildComplete(); + completeBuild(shaders); forgetDeferredInputs(); } +void ShaderResources::completeBuild(std::span shaders) { + try { + buildComplete(); + if (heapStage) { + layOutHeapStages(shaders); + RefreshHeapStage(shaders); + } + } catch (...) { + retireHeapTables(); + release(); + throw; + } +} + void ShaderResources::forgetDeferredInputs() { // The compiled shader and the captured regions belong to the dispatch, which returns while this // object lives on in the resource cache and the recorder: nothing may reach for them after the @@ -2068,7 +2095,7 @@ void ShaderResources::forgetDeferredInputs() { void ShaderResources::build(std::span shaders, const ColorTarget* target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::size_t indexBytes) { buildPrepare(shaders, target, colorAttachments, indexAddress, indexBytes); - buildComplete(); + completeBuild(shaders); if (!GuestMemory::WriteIndexEnabled()) return; countIndex(IndexBuilds); subscribeBuilt(shaders); @@ -2240,7 +2267,7 @@ TableState CurrentTableState() { constexpr auto NoRepresentative = std::numeric_limits::max(); -std::vector variantRepresentatives(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::uint64_t elementBase, std::uint64_t capacity); +std::vector variantRepresentatives(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::span imageWords, std::uint64_t elementBase, std::uint64_t capacity); struct ReusedTableElement { TextureKey key{}; @@ -2280,16 +2307,16 @@ std::vector& ReusedTables() { return ShaderRecompiler::ThreadOwned(slot); } -bool SameTable(const ReusedTable& table, VkDevice device, const ShaderRecompiler::DescriptorBinding& binding) { - return table.device == device && table.words == binding.guestDescriptor && table.shapes == binding.imageShapes && table.depthCompare == binding.imageDepthCompare; +bool SameTable(const ReusedTable& table, VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::span words) { + return table.device == device && std::ranges::equal(table.words, words) && table.shapes == binding.imageShapes && table.depthCompare == binding.imageDepthCompare; } -ReusedTable* FindReusedTable(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, const TableState& state) { +ReusedTable* FindReusedTable(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::span words, const TableState& state) { if (state.epoch == 0) return nullptr; auto& tables = ReusedTables(); std::erase_if(tables, [&](const ReusedTable& table) { return table.state != state; }); for (auto& table : tables) { - if (SameTable(table, device, binding)) return &table; + if (SameTable(table, device, binding, words)) return &table; } return nullptr; } @@ -2333,10 +2360,10 @@ void logTableLookups(const ReusedTable& table, const std::vector words) { auto& tables = ReusedTables(); - std::erase_if(tables, [&](const ReusedTable& entry) { return SameTable(entry, table.device, binding); }); - table.words = binding.guestDescriptor; + std::erase_if(tables, [&](const ReusedTable& entry) { return SameTable(entry, table.device, binding, words); }); + table.words.assign(words.begin(), words.end()); table.shapes = binding.imageShapes; table.depthCompare = binding.imageDepthCompare; tables.insert(tables.begin(), std::move(table)); @@ -2439,13 +2466,14 @@ void ShaderResources::buildPrepare(std::span shaders, cons allocations.reserve(plannedAllocations); std::vector occupied; occupied.reserve(plannedBindings); + heapStage = AnyHeapShader(shaders); for (const auto& shader : shaders) { Require(shader.program != nullptr, "missing compiled shader"); ShaderRecompiler::RuntimeAbi::RequireVersion(shader.program->runtimeAbiVersion); if (shader.program->poisonedSrtReads != 0) { const auto& programBindings = shader.program->bindings; const auto flat = std::find_if(programBindings.begin(), programBindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt; }); - if (flat != programBindings.end()) srtGuardFaults.push_back({IrStage(shader.stage), flat->guestDescriptor}); + if (flat != programBindings.end()) srtGuardFaults.push_back({IrStage(shader.stage), DrawGuestWords(shader, *flat)}); } const VkShaderStageFlags flags = VulkanStage(shader.stage); std::uint64_t stageStorageBuffers = 0; @@ -2461,28 +2489,42 @@ void ShaderResources::buildPrepare(std::span shaders, cons Require(stageStorageBuffers <= limits.maxPerStageDescriptorUpdateAfterBindStorageBuffers && stageResources <= limits.maxPerStageUpdateAfterBindResources, "shader descriptors exceed per-stage limits"); updateAfterBind = true; }; + const bool heapShader = HeapShader(shader); + if (heapShader) { + Require(DescriptorHeapEnabled(), "a GPU-mode stage needs VK_EXT_descriptor_heap (APS5_GPU_HEAP)"); + heapStage = true; + dataTableBound = BindsRole(shaders, ShaderRecompiler::DescriptorRole::BdaPagetable); + dataFaultBound = BindsRole(shaders, ShaderRecompiler::DescriptorRole::FaultBuffer); + if (shader.stage == ShaderRecompiler::ShaderStage::Compute) NoteHeapComputeStage(); + } for (const auto& binding : shader.program->bindings) { - Require(binding.descriptorSet == ShaderRecompiler::RuntimeAbi::DescriptorSet || (shader.stage == ShaderRecompiler::ShaderStage::Fragment && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet), "unexpected descriptor set: a shader resource must use its stage's descriptor set"); + Require(binding.descriptorSet == ShaderRecompiler::RuntimeAbi::DescriptorSet || ((shader.stage == ShaderRecompiler::ShaderStage::Fragment || heapShader) && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet) || (heapShader && binding.role == ShaderRecompiler::DescriptorRole::Gds && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::GpuGdsSet), "unexpected descriptor set: a shader resource must use its stage's descriptor set"); if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable) { const bool storage = binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable; Require(binding.binding == (storage ? ShaderRecompiler::RuntimeAbi::ImageStorageTableBinding : ShaderRecompiler::RuntimeAbi::ImageTableBinding) && binding.kind == (storage ? ShaderRecompiler::DescriptorKind::StorageImage : ShaderRecompiler::DescriptorKind::SampledImage) && binding.guestDescriptor.size() == static_cast(binding.count) * 8u && binding.imageShapes.size() == binding.count && binding.imageDepthCompare.size() == binding.count && binding.imageSamplers.size() == binding.count, "image table binding is malformed"); + NoteImageTableBuild(); auto& table = tableStage(shader); Require(storage ? !table.storage : !table.sampled, "a stage binds two image tables"); Require(table.images == nullptr || table.images->count == binding.count, "a stage's image tables disagree on their elements"); (storage ? table.storage : table.sampled) = true; table.images = &binding; + table.imageWords = DrawGuestWords(shader, binding); + Require(table.imageWords.size() == static_cast(binding.count) * 8u, "a draw's image table words differ in size from its binding"); table.firstSampler = firstSampler; continue; } - Require(std::find(occupied.begin(), occupied.end(), binding.binding) == occupied.end(), "duplicate shader binding"); + const bool heapStorage = heapShader && ClassifyHeapBinding(binding) == HeapBindingClass::StorageImage; + const bool sharedHeapArray = heapShader && (binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers || (binding.role == ShaderRecompiler::DescriptorRole::GuestImages && binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) || heapStorage); + Require(std::find(occupied.begin(), occupied.end(), binding.binding) == occupied.end() || sharedHeapArray, "duplicate shader binding"); occupied.push_back(binding.binding); if (binding.role == ShaderRecompiler::DescriptorRole::SamplerTable) { - addSamplerTable(binding, flags, tableStage(shader)); + addSamplerTable(binding, DrawGuestWords(shader, binding), flags, tableStage(shader)); continue; } if (binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap) { - Require(binding.kind == ShaderRecompiler::DescriptorKind::StorageBuffer && binding.count == 1 && binding.guestDescriptor.size() >= ShaderRecompiler::ImageTableAbi::HeaderWords && !binding.readOnly && binding.guestDescriptor[ShaderRecompiler::ImageTableAbi::HeaderVersion] == ShaderRecompiler::ImageTableAbi::Version, "image table map binding is malformed"); - const auto size = binding.guestDescriptor.size() * sizeof(std::uint32_t); + const auto& mapWords = DrawGuestWords(shader, binding); + Require(binding.kind == ShaderRecompiler::DescriptorKind::StorageBuffer && binding.count == 1 && mapWords.size() >= ShaderRecompiler::ImageTableAbi::HeaderWords && !binding.readOnly && mapWords[ShaderRecompiler::ImageTableAbi::HeaderVersion] == ShaderRecompiler::ImageTableAbi::Version, "image table map binding is malformed"); + const auto size = mapWords.size() * sizeof(std::uint32_t); Require(size <= context.limits.maxStorageBufferRange, "image table map exceeds the storage buffer range limit"); stageStorageBuffers += 1; stageResources += 1; @@ -2490,19 +2532,45 @@ void ShaderResources::buildPrepare(std::span shaders, cons requireStageLimits(); auto& table = tableStage(shader); Require(table.mapAllocation == std::numeric_limits::max(), "a stage binds two image table maps"); - table.map = binding.guestDescriptor; + table.map = mapWords; allocations.push_back({0, size, false, std::make_unique(context, size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT), ShaderRecompiler::DescriptorRole::ImageTableMap}); table.mapAllocation = allocations.size() - 1u; bindings.push_back({{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, flags, nullptr}, {allocations.size() - 1u}}); + bindings.back().heap = table.heap; continue; } + if (heapShader) { + if (heapStorage) { + Require(ShaderRecompiler::RuntimeAbi::GpuHeapStorageKind(binding.binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)), "a heap storage image binding has an atomic or unknown kind"); + addImageBinding(binding, DrawGuestWords(shader, binding), flags); + bindings.back().heap = true; + continue; + } + const auto heapClass = ClassifyHeapBinding(binding); + if (heapClass == HeapBindingClass::Unsupported) Require(false, std::string("a GPU-mode fragment stage has an unsupported ") + roleName(binding.role) + " binding"); + if (heapClass == HeapBindingClass::SharedImage) { + Require(binding.kind == ShaderRecompiler::DescriptorKind::SampledImage || binding.kind == ShaderRecompiler::DescriptorKind::Sampler, "a GPU-mode stage binds sampled images and samplers only"); + addImageBinding(binding, DrawGuestWords(shader, binding), flags); + bindings.back().heap = true; + continue; + } + if (heapClass == HeapBindingClass::ShaderData) { + Require(binding.count == 1 && !DrawGuestWords(shader, binding).empty(), "invalid GPU-mode shader data binding"); + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, DrawGuestWords(shader, binding)); + Binding item{{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, flags, nullptr}, {}, {}}; + item.heap = true; + item.role = binding.role; + bindings.push_back(std::move(item)); + continue; + } + } const bool addressRole = binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; const bool bufferRole = addressRole || binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers || binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt || binding.role == ShaderRecompiler::DescriptorRole::Gds; const bool imageRole = binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers; if (imageRole) { if (binding.kind == ShaderRecompiler::DescriptorKind::SampledImage || binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) stageResources += binding.count; requireStageLimits(); - addImageBinding(binding, flags); + addImageBinding(binding, DrawGuestWords(shader, binding), flags); continue; } if (!bufferRole) Require(false, std::string("unsupported descriptor role ") + roleName(binding.role)); @@ -2515,7 +2583,8 @@ void ShaderResources::buildPrepare(std::span shaders, cons requireStageLimits(); Binding item{{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, binding.count, flags, nullptr}, {}}; if (binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers) { - Require(binding.guestDescriptor.size() == static_cast(binding.count) * 4, "guest buffer descriptor must contain four DWORDs per array element"); + const auto& guestWords = DrawGuestWords(shader, binding); + Require(guestWords.size() == static_cast(binding.count) * 4, "guest buffer descriptor must contain four DWORDs per array element"); for (std::uint32_t element = 0; element < binding.count; ++element) { // An element the recompiler did not classify (a producer without the // vector) counts as written, like imageWritten below. @@ -2523,12 +2592,12 @@ void ShaderResources::buildPrepare(std::span shaders, cons const bool atomic = element < binding.bufferAtomic.size() && binding.bufferAtomic[element]; const bool read = element < binding.bufferRead.size() && binding.bufferRead[element]; const std::uint32_t extent = element < binding.bufferExtent.size() ? binding.bufferExtent[element] : 0u; - const auto index = addGuestBuffer(std::span(binding.guestDescriptor).subspan(static_cast(element) * 4, 4), target, indexAddress, indexBytes, written, atomic, read, extent); + const auto index = addGuestBuffer(std::span(guestWords).subspan(static_cast(element) * 4, 4), target, indexAddress, indexBytes, written, atomic, read, extent); const bool classified = element < binding.bufferWritten.size() && element < binding.bufferRead.size() && element < binding.bufferAtomic.size(); allocations[index].writeOnly = classified && allocations[index].guest && allocations[index].written && binding.bufferWritten[element] && !read && !atomic; const auto& push = shader.program->pushConstants; const auto pushDataBytes = shader.program->stencilReferences.empty() ? push.size() : shader.program->stencilReferenceDword * sizeof(std::uint32_t); - if (pushDataBytes != 0u) { + if (pushDataBytes != 0u && !shader.program->dataAddressPush) { const auto position = shader.program->memoryOffsetDword * 4u + element; Require(position < pushDataBytes, "guest buffer offset lies outside the shader's push constants"); allocations[index].pushByte = static_cast(shader.pushConstantOffset + position); @@ -2538,27 +2607,42 @@ void ShaderResources::buildPrepare(std::span shaders, cons } item.allocations.push_back(index); } + if (heapShader && shader.program->bufferAddressCount != 0u) { + Require(shader.program->bufferAddressCount == binding.count, "a GPU-mode stage's buffer address words disagree with its buffer binding"); + item.heap = true; + item.addressed = true; + item.dataStage = static_cast(HeapStageIndex(shader.stage)); + item.addressDword = shader.program->bufferAddressDword; + addressedBuffers = true; + } } else if (addressRole) { item.allocations.push_back(allocations.size()); allocations.push_back({0, 0, false, nullptr, binding.role}); + item.heap = (heapShader && shader.program->dataAddressPush) || (heapStage && !heapShader && binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer); } else if (binding.role == ShaderRecompiler::DescriptorRole::Gds) { Require(binding.count == 1 && binding.guestDescriptor.empty(), "invalid GDS descriptor contract"); + static_assert(Pm4::GdsBytes == ShaderRecompiler::RuntimeAbi::GdsBytes); const auto gds = Pm4::GdsAddress(); guestMemory.AddWritable(gds, Pm4::GdsBytes, true); item.allocations.push_back(allocations.size()); allocations.push_back({gds, Pm4::GdsBytes, true, nullptr, ShaderRecompiler::DescriptorRole::ShaderData, true}); + if (heapShader && shader.program->dataAddressPush) { + item.heap = true; + if (gdsAllocation == std::numeric_limits::max()) gdsAllocation = item.allocations.back(); + } } else { Require(binding.count == 1, "shader data and flattened SRT descriptors must not be arrays"); - Require(!binding.guestDescriptor.empty(), "empty shader data descriptor"); + const auto& guestWords = DrawGuestWords(shader, binding); + Require(!guestWords.empty(), "empty shader data descriptor"); if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) { - ValidateRuntimeResources(shader, binding.guestDescriptor); + ValidateRuntimeResources(shader, guestWords); } - item.allocations.push_back(addDataBuffer(binding.guestDescriptor)); + item.allocations.push_back(addDataBuffer(guestWords)); if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) shaderData = static_cast(item.allocations.back()); } bindings.push_back(std::move(item)); } - for (const auto index : offsetsInData) allocations[index].dataAllocation = shaderData; + for (const auto index : offsetsInData) allocations[index].dataAllocation = heapShader ? HeapRingData(HeapStageIndex(shader.stage)) : shaderData; for (auto index = firstDeferred; index < deferredImages.size(); ++index) { deferredImages[index].firstSampler = firstSampler; deferredImages[index].samplerCount = samplers.size() - firstSampler; @@ -2579,8 +2663,8 @@ void ShaderResources::buildPrepare(std::span shaders, cons const auto faults = map[ShaderRecompiler::ImageTableAbi::HeaderElementFaults]; const auto samplerFaults = map[ShaderRecompiler::ImageTableAbi::HeaderSamplerFaults]; Require(static_cast(faults) + elements <= map.size() && static_cast(samplerFaults) + map[ShaderRecompiler::ImageTableAbi::HeaderSamplerCount] / 4u <= map.size(), "image table map is truncated"); - if (table.images == nullptr) continue; - table.set = splitSets && table.stage == ShaderRecompiler::ShaderStage::Fragment ? 1u : 0u; + if (table.images == nullptr || table.heap) continue; + table.set = splitSets && !heapStage && table.stage == ShaderRecompiler::ShaderStage::Fragment ? 1u : 0u; table.elementBase = tableElements[table.set]; table.map[ShaderRecompiler::ImageTableAbi::HeaderElementBase] = table.elementBase; tableElements[table.set] += elements; @@ -2607,7 +2691,22 @@ void ShaderResources::buildPrepare(std::span shaders, cons // For every build, locked ones included: their stage B then takes the fast path too, and the // collects cost the same wherever they run. if (precollectImages()) phase(BuildPhase::Precollect); - if (drawBuild && !usesBda && std::all_of(allocations.begin(), allocations.end(), [&](const Allocation& allocation) { return !allocation.guest || allocation.pushByte >= 0 || (allocation.dataAllocation >= 0 && allocation.dataByte < allocations[static_cast(allocation.dataAllocation)].size); })) guestMemory.AllowAdjustedRegions(); + const auto heapDataBytes = [&](std::int64_t ring) -> std::uint64_t { + const auto stage = HeapRingStage(ring); + for (const auto& shader : shaders) { + if (HeapStageIndex(shader.stage) != stage || !HeapShader(shader)) continue; + for (const auto& binding : shader.program->bindings) { + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) return binding.guestDescriptor.size() * sizeof(std::uint32_t); + } + } + return 0; + }; + const auto patchable = [&](const Allocation& allocation) { + if (!allocation.guest || allocation.pushByte >= 0) return true; + if (IsHeapRingData(allocation.dataAllocation)) return allocation.dataByte < heapDataBytes(allocation.dataAllocation); + return allocation.dataAllocation >= 0 && allocation.dataByte < allocations[static_cast(allocation.dataAllocation)].size; + }; + if (drawBuild && !usesBda && std::all_of(allocations.begin(), allocations.end(), patchable)) guestMemory.AllowAdjustedRegions(); requireGuestBuffers(); guestMemory.UploadPrepare(usesBda); timing.uploadMs = phase(BuildPhase::Upload); @@ -2615,6 +2714,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons std::array, 2> descriptions; bool tablesUpdateAfterBind = false; for (const auto& binding : bindings) { + if (binding.heap) continue; const auto set = setOf(binding); descriptions[set].push_back(binding.layout); (set == 0 ? layoutBindingFlags : fragmentBindingFlags).push_back(binding.flags | (updateAfterBind && binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0)); @@ -2661,8 +2761,12 @@ void ShaderResources::buildPrepare(std::span shaders, cons owns = true; return CreateSetLayout(context, description, updateAfterBind, flags); }; + if (heapStage) { + Require(splitSets && descriptions[1].empty(), "a GPU-mode fragment stage needs split sets and no per-draw fragment bindings"); + fragmentLayoutKey = {HeapLayoutKeyTag}; + } _layout = createLayout(layoutKey, descriptions[0], layoutBindingFlags, ownsLayout); - if (splitSets) { + if (splitSets && !heapStage) { fragment.layout = createLayout(fragmentLayoutKey, descriptions[1], fragmentBindingFlags, fragment.ownsLayout); { const auto sizes = splitPoolSizes(1); @@ -2745,7 +2849,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons bool SplitsSets(const Context& context, std::span shaders) { const auto fragmentSet = [](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const auto& binding) { return binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet; }); }; const auto fragmentStage = [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::Fragment; }; - return std::any_of(shaders.begin(), shaders.end(), fragmentSet) || (context.graphicsPipelineLibrary && std::any_of(shaders.begin(), shaders.end(), fragmentStage)); + return std::any_of(shaders.begin(), shaders.end(), fragmentSet) || AnyHeapShader(shaders) || (context.graphicsPipelineLibrary && std::any_of(shaders.begin(), shaders.end(), fragmentStage)); } DescribedSetLayouts DescribeSetLayouts(const Context& context, std::span shaders) { @@ -2759,21 +2863,36 @@ DescribedSetLayouts DescribeSetLayouts(const Context& context, std::spandataAddressPush; for (const auto& binding : shader.program->bindings) { - const auto set = binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet ? 1 : 0; + const auto set = !heapStage && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet ? 1 : 0; + if (heapStage && !gpuMode && binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer) continue; + if (addressedStage) { + using Role = ShaderRecompiler::DescriptorRole; + const bool tableRole = binding.role == Role::ImageTable || binding.role == Role::ImageStorageTable || binding.role == Role::SamplerTable || binding.role == Role::ImageTableMap; + const bool addressRole = binding.role == Role::BdaPagetable || binding.role == Role::FaultBuffer || (binding.role == Role::GuestBuffers && shader.program->bufferAddressCount != 0u) || (binding.role == Role::Gds && shader.program->dataAddressPush); + const bool heapStorage = ClassifyHeapBinding(binding) == HeapBindingClass::StorageImage; + if (tableRole || addressRole || heapStorage) continue; + } if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable) { - tableFlags[split && shader.stage == ShaderRecompiler::ShaderStage::Fragment ? 1 : 0] |= flags; + tableFlags[split && !heapStage && shader.stage == ShaderRecompiler::ShaderStage::Fragment ? 1 : 0] |= flags; continue; } if (binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable) { storageTableFlags[split && shader.stage == ShaderRecompiler::ShaderStage::Fragment ? 1 : 0] |= flags; continue; } + if (gpuMode) { + const auto heapClass = ClassifyHeapBinding(binding); + if (heapClass == HeapBindingClass::SharedImage || heapClass == HeapBindingClass::ShaderData) continue; + } if (binding.role == ShaderRecompiler::DescriptorRole::SamplerTable) { descriptions[set].push_back({binding.binding, VK_DESCRIPTOR_TYPE_SAMPLER, context.samplerTableCapacity, flags, nullptr}); bindingFlags[set].push_back(VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | (context.samplerTableUpdateAfterBind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0)); @@ -2817,6 +2936,11 @@ DescribedSetLayouts DescribeSetLayouts(const Context& context, std::spanLayout(result.mainKey, descriptions[0], updateAfterBind, bindingFlags[0]); + if (heapStage) { + Require(split && descriptions[1].empty(), "a GPU-mode stage needs split sets and no per-draw fragment bindings"); + result.fragmentKey = {HeapLayoutKeyTag}; + return result; + } if (split) result.layouts.fragment = context.descriptorCache->Layout(result.fragmentKey, descriptions[1], updateAfterBind, bindingFlags[1]); return result; } @@ -2839,6 +2963,14 @@ ShaderRecompiler::PipelineIdentity DescribedPipelineIdentity(const ShaderRecompi const bool fixedCapacity = binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding.role == ShaderRecompiler::DescriptorRole::SamplerTable; const std::uint64_t count = fixedCapacity ? 0u : binding.count; mix(binding.descriptorSet | (static_cast(binding.binding) << 16u) | (static_cast(binding.kind) << 40u) | (count << 48u)); + mix(binding.samplerEmbedded.size()); + for (const auto value : binding.samplerEmbedded) mix(value); + mix(binding.samplerEmbeddedWords.size()); + for (const auto value : binding.samplerEmbeddedWords) mix(value); + for (const auto* flags : {&binding.samplerDepthCompare, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored}) { + mix(flags->size()); + for (std::size_t element = 0; element < flags->size(); ++element) mix((*flags)[element] ? 1u : 0u); + } } if (identity.Empty()) identity.low = 1; return identity; @@ -2859,7 +2991,7 @@ void ShaderResources::buildComplete() { source.singleLevelImage = source.mipmappedImage = false; source.pinnedLod.reset(); } - for (const auto& deferred : deferredImages) resolveImageBinding(*deferred.binding, bindings[deferred.index], std::span>(samplers).subspan(deferred.firstSampler, deferred.samplerCount)); + for (const auto& deferred : deferredImages) resolveImageBinding(*deferred.binding, deferred.words, bindings[deferred.index], std::span>(samplers).subspan(deferred.firstSampler, deferred.samplerCount)); previousSampled = {}; deferredImages.clear(); applySamplerVariants(); @@ -2881,6 +3013,10 @@ void ShaderResources::buildComplete() { if (bda) bda->SetSrtGuards(std::move(srtGuardFaults)); finishImageTables(); phase(BuildPhase::Bda); + for (const auto& binding : bindings) { + if (!binding.addressed) continue; + for (const auto index : binding.allocations) static_cast(descriptor(allocations[index])); + } if (_set != VK_NULL_HANDLE || fragment.set != VK_NULL_HANDLE) { // One update call for the whole set: the info arrays are sized up front so every write's // pointer into them stays valid until the call. @@ -2903,6 +3039,7 @@ void ShaderResources::buildComplete() { return VkDescriptorImageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; }; for (const auto& binding : bindings) { + if (binding.heap) continue; if (binding.flags != 0) { const auto set = setOf(binding); const bool sampled = binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; @@ -2974,8 +3111,8 @@ void ShaderResources::buildComplete() { write.pImageInfo = images.data() + images.size(); for (const auto index : binding.imageAllocations) { if (index == std::numeric_limits::max()) images.push_back(absentImage(binding.layout.binding)); - else if (storageTextures[index] == nullptr) images.push_back({VK_NULL_HANDLE, multisampleStorageViews[index], VK_IMAGE_LAYOUT_GENERAL}); - else images.push_back({VK_NULL_HANDLE, storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index], ShaderRecompiler::RuntimeAbi::UintStorageImageBinding(binding.layout.binding) || storageUint[index]), VK_IMAGE_LAYOUT_GENERAL}); + else if (storageTextures[index] == nullptr) images.push_back({VK_NULL_HANDLE, multisampleStorage[index].view, VK_IMAGE_LAYOUT_GENERAL}); + else images.push_back({VK_NULL_HANDLE, storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index], UintStorageBinding(binding.layout.binding) || storageUint[index]), VK_IMAGE_LAYOUT_GENERAL}); } Require(binding.imageAllocations.size() == binding.layout.descriptorCount, "descriptor allocations disagree with compact binding"); break; @@ -3011,6 +3148,10 @@ void ShaderResources::buildComplete() { pushPatches.emplace_back(static_cast(allocation.pushByte), allocation.adjustment); continue; } + if (IsHeapRingData(allocation.dataAllocation)) { + heapStages[HeapRingStage(allocation.dataAllocation)].dataPatches.emplace_back(allocation.dataByte, allocation.adjustment); + continue; + } Require(allocation.dataAllocation >= 0, "a guest buffer off the storage buffer offset alignment in a shader without shader data is not implemented"); auto& data = allocations[static_cast(allocation.dataAllocation)]; Require(data.buffer != nullptr && allocation.dataByte < data.size, "guest buffer offset lies outside the shader's data buffer"); @@ -3081,19 +3222,37 @@ void ShaderResources::noteReusable() { // Taken whether or not the object turns out reusable: the lookups' records are this build's. captureValidation(spaceReusable); reusable = false; - importsReconcilable = false; + unreusableReason = Unreusable::Unchecked; spaceReuse = false; + importsReconcilable = false; directRegions.clear(); - if (!spaceReusable && (htileClear.has_value() || guestMemory.HasCopiedWrites() || HoldsLease() || usesBda || !multisampleSources.empty() || (bda != nullptr && LoopGuardEnabled()))) return; - if (std::any_of(textures.begin(), textures.end(), [](const std::shared_ptr& texture) { return texture != nullptr && texture->RefreshedPerUse(); })) return; - if (TemplateDataRefresh() && std::any_of(allocations.begin(), allocations.end(), [](const Allocation& allocation) { return allocation.buffer != nullptr && !allocation.guest && allocation.role != ShaderRecompiler::DescriptorRole::ImageTableMap && allocation.size > MaxRefreshBytes; })) return; + if (!spaceReusable) { + if (htileClear.has_value()) unreusableReason = Unreusable::HtileClear; + else if (guestMemory.HasCopiedWrites()) unreusableReason = Unreusable::CopiedWrites; + else if (HoldsLease()) unreusableReason = Unreusable::Lease; + else if (usesBda) unreusableReason = Unreusable::Bda; + else if (!multisampleSources.empty()) unreusableReason = Unreusable::MultisampleSource; + else if (bda != nullptr && LoopGuardEnabled()) unreusableReason = Unreusable::LoopGuard; + if (unreusableReason != Unreusable::Unchecked) return; + } + if (std::any_of(textures.begin(), textures.end(), [](const std::shared_ptr& texture) { return texture != nullptr && texture->RefreshedPerUse(); })) { + unreusableReason = Unreusable::TextureRefreshedPerUse; + return; + } + if (TemplateDataRefresh() && std::any_of(allocations.begin(), allocations.end(), [](const Allocation& allocation) { return allocation.buffer != nullptr && !allocation.guest && allocation.role != ShaderRecompiler::DescriptorRole::ImageTableMap && allocation.size > MaxRefreshBytes; })) { + unreusableReason = Unreusable::TemplateDataRefresh; + return; + } if (spaceReusable) { spaceReuse = true; reusable = true; return; } const auto regions = guestMemory.DirectRegions(); - if (!regions.has_value()) return; + if (!regions.has_value()) { + unreusableReason = Unreusable::NoDirectRegions; + return; + } bool mirrored = false; for (const auto& [begin, end] : *regions) { // No reconcile here: the upload just took these imports, and the set is about to be recorded @@ -3103,7 +3262,10 @@ void ShaderResources::noteReusable() { // bit set, so the two spaces never collide. const bool imported = serial != 0; if (serial == 0) serial = ImageMirrorSerial(context, begin, static_cast(end - begin)); - if (serial == 0) return; + if (serial == 0) { + unreusableReason = Unreusable::RegionNotServed; + return; + } directRegions.push_back({begin, end, serial}); mirrored = mirrored || !imported; } @@ -3120,6 +3282,20 @@ void ShaderResources::noteReusable() { reusable = true; } +const char* ShaderResources::UnreusableReasonName(Unreusable reason) { + constexpr std::array(Unreusable::Count)> names{"unchecked", "htile clear", "copied writes", "lease", "bda", "multisample source", "loop guard", "texture refreshed per use", "template data refresh", "no direct regions", "region not served"}; + const auto index = static_cast(reason); + return index < names.size() ? names[index] : "unknown"; +} + +namespace { +std::atomic movedBehindGpuWrites{0}; +} + +std::uint64_t ShaderResources::MovedBehindGpuWrites() { + return movedBehindGpuWrites.load(std::memory_order_relaxed); +} + std::uint64_t ShaderResources::DepthGuardRefusals() { return depthGuardRefusals.load(std::memory_order_relaxed); } @@ -3127,7 +3303,7 @@ std::uint64_t ShaderResources::DepthGuardRefusals() { bool ShaderResources::NeverReusable(std::span shaders) { const bool loopGuard = LoopGuardEnabled(); return std::any_of(shaders.begin(), shaders.end(), [loopGuard](const CompiledShader& shader) { - return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const ShaderRecompiler::DescriptorBinding& binding) { return (binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable && (SpaceReuseDisabled() || ShaderStoresThroughAddresses(shader.program->spirv))) || (loopGuard && binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer); }); + return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const ShaderRecompiler::DescriptorBinding& binding) { return (binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable && (SpaceReuseDisabled() || ProgramStoresThroughAddresses(*shader.program))) || (loopGuard && binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer); }); }); } @@ -3198,6 +3374,18 @@ void VisitContentKey(const CompiledShader& shader, bool dataWords, bool movableB visit(static_cast(shader.stage)); visit(static_cast(program.PipelineVariantId())); visit(static_cast(program.PipelineVariantId() >> 32u)); + if (shader.heap != nullptr && program.heapTemplateId != 0) { + visit(0u); + visit(HeapLayoutKeyTag); + visit(static_cast(program.heapTemplateId)); + visit(static_cast(program.heapTemplateId >> 32u)); + for (const auto& binding : program.bindings) { + if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages && binding.role != ShaderRecompiler::DescriptorRole::GuestSamplers) continue; + visit(binding.binding); + for (const auto word : DrawGuestWords(shader, binding)) visit(word); + } + return; + } visit(static_cast(program.bindings.size())); const auto packBits = [&](const ShaderRecompiler::ElementFlags& bits) { visit(static_cast(bits.size())); @@ -3211,10 +3399,11 @@ void VisitContentKey(const CompiledShader& shader, bool dataWords, bool movableB } }; for (const auto& binding : program.bindings) { - for (const auto word : {static_cast(binding.kind), static_cast(binding.role), binding.descriptorSet, binding.binding, binding.count, binding.readOnly ? 1u : 0u, binding.imageShape.has_value() ? static_cast(*binding.imageShape) + 1u : 0u, static_cast(binding.guestDescriptor.size())}) visit(word); - if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable && binding.guestDescriptor.size() > CompactTableKeyWords) { + const auto& guestWords = DrawGuestWords(shader, binding); + for (const auto word : {static_cast(binding.kind), static_cast(binding.role), binding.descriptorSet, binding.binding, binding.count, binding.readOnly ? 1u : 0u, binding.imageShape.has_value() ? static_cast(*binding.imageShape) + 1u : 0u, static_cast(guestWords.size())}) visit(word); + if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable && guestWords.size() > CompactTableKeyWords) { TableKeyHash hash; - hash.bytes(binding.guestDescriptor.data(), binding.guestDescriptor.size() * sizeof(std::uint32_t)); + hash.bytes(guestWords.data(), guestWords.size() * sizeof(std::uint32_t)); hash.bytes(binding.imageSamplers.data(), binding.imageSamplers.size() * sizeof(binding.imageSamplers[0])); hash.bytes(binding.imageShapes.data(), binding.imageShapes.size() * sizeof(binding.imageShapes[0])); for (const auto* set : {&binding.imageWritten, &binding.samplerDepthCompare, &binding.imageDepthCompare, &binding.imageAtomic, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored, &binding.imageUnnormalized, &binding.imageUnnormalizedBaseLevel, &binding.bufferWritten}) hash.bits(*set); @@ -3223,22 +3412,22 @@ void VisitContentKey(const CompiledShader& shader, bool dataWords, bool movableB for (const auto word : {0xc0de7ab1u, static_cast(first), static_cast(first >> 32u), static_cast(second), static_cast(second >> 32u)}) visit(word); continue; } - if (movableBuffers && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers && binding.guestDescriptor.size() == static_cast(binding.count) * 4u) { + if (movableBuffers && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers && guestWords.size() == static_cast(binding.count) * 4u) { for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; + const auto* words = guestWords.data() + static_cast(element) * 4u; const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; const bool empty = words[2] == 0 || (words[0] == 0 && (words[1] & 0xffffu) == 0); if (written || empty) { for (std::uint32_t index = 0; index < 4u; ++index) visit(words[index]); } else { for (const auto word : {0u, words[1] & 0xffff0000u, 0u, words[3]}) visit(word); } } - } else if (binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap && binding.guestDescriptor.size() > CompactTableKeyWords) { + } else if (binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap && guestWords.size() > CompactTableKeyWords) { TableKeyHash hash; - hash.bytes(binding.guestDescriptor.data(), binding.guestDescriptor.size() * sizeof(std::uint32_t)); + hash.bytes(guestWords.data(), guestWords.size() * sizeof(std::uint32_t)); const auto first = hash.a(); const auto second = hash.b(); for (const auto word : {0xc0de7ab2u, static_cast(first), static_cast(first >> 32u), static_cast(second), static_cast(second >> 32u)}) visit(word); } else if ((dataWords && !movableBuffers) || !DataRole(binding.role)) { - for (const auto word : binding.guestDescriptor) visit(word); + for (const auto word : guestWords) visit(word); } packBits(binding.imageWritten); packBits(binding.samplerDepthCompare); @@ -3270,6 +3459,15 @@ std::vector ShaderResources::ContentKey(const CompiledShader& sha void ShaderResources::AppendContentKey(const CompiledShader& shader, bool dataWords, bool movableBuffers, std::vector& key) { Require(shader.program != nullptr, "missing compiled shader"); + if (shader.heap != nullptr && shader.program->heapTemplateId != 0) { + std::size_t heapWords = key.size() + 8; + for (const auto& binding : shader.program->bindings) { + if (binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers) heapWords += 1 + DrawGuestWords(shader, binding).size(); + } + key.reserve(heapWords); + VisitContentKey(shader, dataWords, movableBuffers, [&](std::uint32_t word) { key.push_back(word); }); + return; + } std::size_t words = key.size() + 5; const auto addWords = [&](std::size_t count) { if (count > key.max_size() - words) throw std::length_error("resource content key exceeds vector limits"); @@ -3277,11 +3475,12 @@ void ShaderResources::AppendContentKey(const CompiledShader& shader, bool dataWo }; for (const auto& binding : shader.program->bindings) { addWords(20); - if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable && binding.guestDescriptor.size() > CompactTableKeyWords) continue; + const auto& guestWords = DrawGuestWords(shader, binding); + if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable && guestWords.size() > CompactTableKeyWords) continue; addWords(binding.imageSamplers.size() * 2u); addWords(binding.imageShapes.size()); - if (binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap && binding.guestDescriptor.size() > CompactTableKeyWords) addWords(5); - else if ((dataWords && !movableBuffers) || !DataRole(binding.role)) addWords(binding.guestDescriptor.size()); + if (binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap && guestWords.size() > CompactTableKeyWords) addWords(5); + else if ((dataWords && !movableBuffers) || !DataRole(binding.role)) addWords(guestWords.size()); for (const auto* bits : {&binding.imageWritten, &binding.samplerDepthCompare, &binding.imageDepthCompare, &binding.imageAtomic, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored, &binding.imageUnnormalized, &binding.imageUnnormalizedBaseLevel, &binding.bufferWritten}) addWords(bits->size() / 32u + (bits->size() % 32u != 0 ? 1u : 0u)); } key.reserve(words); @@ -3753,7 +3952,8 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::spansize() : textures.size(); const auto elementAt = [only](std::size_t k) { return only != nullptr ? (*only)[k] : k; }; - const auto fail = [&reason](FastFail why) { + const auto fail = [&reason, &overlapping](FastFail why) { + if (why != FastFail::StorageKeys && why != FastFail::Pending) overlapping.clear(); reason = why; countFastFail(why); return false; @@ -3852,6 +4052,7 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::span= storageKeys.size() || !StorageImageServesKeys(*storageTextures[i], storageKeys[i]))) return fail(FastFail::StorageKeys); if (i != 0 && storageTextures[i] == storageTextures[i - 1]) continue; @@ -3872,7 +4073,13 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::spanProvedKeys() != image->UploadedKeys()) return fail(FastFail::StorageKeys); + if (!keyProofs) return fail(FastFail::StorageKeys); + if (image->ProvedKeys() != image->UploadedKeys()) { + if (!OwnImageRefreshEnabled()) return fail(FastFail::StorageKeys); + keysMoved = true; + overlapping.push_back({i, true, false}); + continue; + } countKeysProven(true); } if (!unchanged) query(address, address + bytes, image, nullptr, {i, true, false}); @@ -3880,6 +4087,7 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::spanGenerationFor(address, bytes)}); images.push_back(image); } + if (keysMoved) return fail(FastFail::StorageKeys); if (!pending.empty()) { if (!StorageTexture::ScanPending(pending)) return fail(FastFail::ClearedView); // A foreign image over a view under uncompressed keys is no failure while FindPending @@ -4057,7 +4265,7 @@ ShaderResources::OwnRefreshFallback ShaderResources::refreshOwnObjects(std::span if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages) continue; if (binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) { for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = std::span(DrawGuestWords(shader, binding)).subspan(static_cast(element) * 8u, 8u); if (IsNullSampledTextureResource(words)) continue; if (textureIndex >= textures.size()) return OwnRefreshFallback::Uncached; const auto index = textureIndex++; @@ -4067,7 +4275,7 @@ ShaderResources::OwnRefreshFallback ShaderResources::refreshOwnObjects(std::span } } else if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) { for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = std::span(DrawGuestWords(shader, binding)).subspan(static_cast(element) * 8u, 8u); if (IsNullTextureResource(words)) continue; if (storageIndex >= storageTextures.size()) return OwnRefreshFallback::Uncached; const auto index = storageIndex++; @@ -4078,7 +4286,8 @@ ShaderResources::OwnRefreshFallback ShaderResources::refreshOwnObjects(std::span } } for (const auto& table : tableStages) { - const auto* images = table.elementTextures.empty() ? nullptr : tableImages(shaders, table.stage); + std::span imageWords; + const auto* images = table.elementTextures.empty() ? nullptr : tableImages(shaders, table.stage, imageWords); for (std::size_t element = 0; element < table.elementTextures.size(); ++element) { const auto index = table.elementTextures[element]; if (index == std::numeric_limits::max()) continue; @@ -4117,11 +4326,13 @@ bool CompletePendingCpuWrites(const Context& context, std::uint64_t address, std return false; } -const ShaderRecompiler::DescriptorBinding* ShaderResources::tableImages(std::span shaders, ShaderRecompiler::ShaderStage stage) { +const ShaderRecompiler::DescriptorBinding* ShaderResources::tableImages(std::span shaders, ShaderRecompiler::ShaderStage stage, std::span& words) { for (const auto& shader : shaders) { if (shader.stage != stage || shader.program == nullptr) continue; for (const auto& binding : shader.program->bindings) { - if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable) return &binding; + if (binding.role != ShaderRecompiler::DescriptorRole::ImageTable) continue; + words = DrawGuestWords(shader, binding); + return &binding; } } return nullptr; @@ -4196,7 +4407,7 @@ void ShaderResources::subscribeIndex(std::span shaders) { for (auto block = GuestMemory::WriteBlockOf(begin); block <= GuestMemory::WriteBlockOf(begin + bytes - 1); ++block) subscribedBlocks.emplace_back(block, i); } for (const auto& table : tableStages) { - if (table.images == nullptr || table.map.size() < ShaderRecompiler::ImageTableAbi::HeaderWords) continue; + if ((!table.sampled && !table.storage) || table.map.size() < ShaderRecompiler::ImageTableAbi::HeaderWords) continue; const auto tables = table.map[ShaderRecompiler::ImageTableAbi::HeaderTableCount]; for (std::uint32_t index = 0; index < tables; ++index) { const auto header = ShaderRecompiler::ImageTableAbi::TableHeader(index); @@ -4220,9 +4431,10 @@ void ShaderResources::subscribeIndex(std::span shaders) { if (shader.program == nullptr) break; for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages || binding.kind != ShaderRecompiler::DescriptorKind::SampledImage) continue; - const auto elementWords = binding.count != 0 ? binding.guestDescriptor.size() / binding.count : 0; + const auto& guestWords = DrawGuestWords(shader, binding); + const auto elementWords = binding.count != 0 ? guestWords.size() / binding.count : 0; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); + const auto words = std::span(guestWords).subspan(static_cast(element) * elementWords, elementWords); if (IsNullTextureResource(words)) continue; if (textureIndex < indexElements.size() && words.size() <= 8) { auto& entry = indexElements[textureIndex]; @@ -4237,16 +4449,18 @@ void ShaderResources::subscribeIndex(std::span shaders) { } } for (const auto& table : tableStages) { - if (table.images == nullptr) continue; + std::span imageWords; + const auto* images = table.elementTextures.empty() ? nullptr : tableImages(shaders, table.stage, imageWords); + if (images == nullptr) continue; for (std::size_t element = 0; element < table.elementTextures.size(); ++element) { const auto index = table.elementTextures[element]; - if (index >= indexElements.size() || (element + 1) * 8u > table.images->guestDescriptor.size()) continue; + if (index >= indexElements.size() || (element + 1) * 8u > imageWords.size()) continue; auto& entry = indexElements[index]; - const auto words = std::span(table.images->guestDescriptor).subspan(element * 8u, 8u); + const auto words = imageWords.subspan(element * 8u, 8u); std::copy(words.begin(), words.end(), entry.words.begin()); entry.count = 8; - entry.shape = element < table.images->imageShapes.size() ? std::optional(table.images->imageShapes[element]) : std::nullopt; - entry.depthCompare = element < table.images->imageDepthCompare.size() && table.images->imageDepthCompare[element]; + entry.shape = element < images->imageShapes.size() ? std::optional(images->imageShapes[element]) : std::nullopt; + entry.depthCompare = element < images->imageDepthCompare.size() && images->imageDepthCompare[element]; entry.known = true; } } @@ -4321,7 +4535,7 @@ bool ShaderResources::reresolveElements(const std::vector& elements if (texture == nullptr) return false; if (texture != textures[i]) replaced.emplace_back(i, std::move(texture)); } - if (!replaced.empty() && (!drawBuild || usesBda)) { + if (!replaced.empty() && (!drawBuild || usesBda || heapStage)) { lookupLog().clear(); return false; } @@ -4549,9 +4763,10 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages) continue; if (binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) { - const auto elementWords = binding.count != 0 ? binding.guestDescriptor.size() / binding.count : 0; + const auto& guestWords = DrawGuestWords(shader, binding); + const auto elementWords = binding.count != 0 ? guestWords.size() / binding.count : 0; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto raw = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); + const auto raw = std::span(guestWords).subspan(static_cast(element) * elementWords, elementWords); std::array narrowed{}; const auto words = firstLayerWords(raw, binding.imageShape, narrowed, false); if (IsNullSampledTextureResource(words)) continue; @@ -4563,12 +4778,13 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr ++textureIndex; } } else if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) { + const auto& guestWords = DrawGuestWords(shader, binding); for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = std::span(guestWords).subspan(static_cast(element) * 8u, 8u); if (IsNullTextureResource(words)) continue; if (storageIndex >= storageTextures.size()) return false; std::shared_ptr expected; - if (SameAsPreviousStorageElement(binding, element) && StorageDedupeEnabled()) expected = storageTextures[storageIndex - 1]; + if (SameAsPreviousStorageElement(guestWords, element) && StorageDedupeEnabled()) expected = storageTextures[storageIndex - 1]; else expected = cachedStorageTexture(context, words, DecodeTextureResource(words), storageMips[storageIndex], 0, storageWritten[storageIndex]); if (expected != storageTextures[storageIndex]) return false; ++storageIndex; @@ -4576,9 +4792,9 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr } } } - const auto currentTableEntry = [&](const ShaderRecompiler::DescriptorBinding& images, std::uint32_t element) { + const auto currentTableEntry = [&](const ShaderRecompiler::DescriptorBinding& images, std::span imageWords, std::uint32_t element) { if (textureIndex >= textures.size()) return false; - const auto raw = std::span(images.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto raw = imageWords.subspan(static_cast(element) * 8u, 8u); std::array narrowed{}; const auto words = firstLayerWords(raw, images.imageShapes.at(element), narrowed, false); const auto resource = DecodeTextureResource(words); @@ -4587,11 +4803,12 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr }; for (const auto& table : tableStages) { if (table.elementTextures.empty()) continue; - const auto* images = tableImages(shaders, table.stage); - if (images == nullptr || images->count != table.elementTextures.size()) return false; + std::span imageWords; + const auto* images = tableImages(shaders, table.stage, imageWords); + if (images == nullptr || images->count != table.elementTextures.size() || imageWords.size() != static_cast(images->count) * 8u) return false; std::vector> cached; - if (auto* reused = FindReusedTable(context.device, *images, CurrentTableState()); reused != nullptr && TableCurrent(*reused) && CachedTableTextures(*reused, cached)) { - if (!reused->representatives.empty() && reused->representatives != variantRepresentatives(context.device, *images, table.elementBase, context.imageTableCapacity)) return false; + if (auto* reused = FindReusedTable(context.device, *images, imageWords, CurrentTableState()); reused != nullptr && TableCurrent(*reused) && CachedTableTextures(*reused, cached)) { + if (!reused->representatives.empty() && reused->representatives != variantRepresentatives(context.device, *images, imageWords, table.elementBase, table.heap ? std::numeric_limits::max() : context.imageTableCapacity)) return false; logTableLookups(*reused, cached); auto next = cached.begin(); bool same = true; @@ -4605,7 +4822,7 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr if (entry.substitute) continue; if (entry.live) { if (index == std::numeric_limits::max()) continue; - same = index == textureIndex && currentTableEntry(*images, element); + same = index == textureIndex && currentTableEntry(*images, imageWords, element); ++textureIndex; continue; } @@ -4618,11 +4835,11 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr TextureCounts().tablesReused.fetch_add(1, std::memory_order_relaxed); continue; } - if (!table.representatives.empty() && table.representatives != variantRepresentatives(context.device, *images, table.elementBase, context.imageTableCapacity)) return false; + if (!table.representatives.empty() && table.representatives != variantRepresentatives(context.device, *images, imageWords, table.elementBase, table.heap ? std::numeric_limits::max() : context.imageTableCapacity)) return false; for (std::uint32_t element = 0; element < images->count; ++element) { if (table.elementTextures[element] == std::numeric_limits::max()) continue; if (!table.representatives.empty() && table.representatives[element] != NoRepresentative) continue; - if (table.elementTextures[element] != textureIndex || !currentTableEntry(*images, element)) return false; + if (table.elementTextures[element] != textureIndex || !currentTableEntry(*images, imageWords, element)) return false; ++textureIndex; } } @@ -4915,6 +5132,7 @@ bool chargeShaderKey(ChurnCounts& profile, const ResourceCache::Key& key, std::s std::shared_ptr ResourceCache::Find(const Key& key) { resourceCacheFinds.fetch_add(1, std::memory_order_relaxed); + operations.fetch_add(1, std::memory_order_relaxed); std::lock_guard lock(mutex); const auto found = index.find(key); if (found == index.end()) { @@ -4923,7 +5141,7 @@ std::shared_ptr ResourceCache::Find(const Key& key) { return nullptr; } entries.splice(entries.begin(), entries, found->second); - noteUse(key); + noteUse(*found->second); return found->second->second; } @@ -4944,24 +5162,35 @@ void ResourceCache::noteEvicted(const Key& key) { if (!churning || capacity >= MaximumEntries) return; const auto previous = capacity; capacity = std::min(capacity * 2u, MaximumEntries); + publishAgingWindow(); if (shrankLast) shrinkWindow = std::min(shrinkWindow * 2u, MaximumShrinkWindow); shrankLast = false; - usedKeys.clear(); - usesSinceCheck = 0; + resetUses(); + usesWindowStart.store(operations.load(std::memory_order_relaxed), std::memory_order_relaxed); std::fprintf(stderr, "[rescache] capacity %zu -> %zu entries: keys it evicted keep coming back\n", previous, capacity); } -void ResourceCache::noteUse(const Key& key) { +void ResourceCache::resetUses() { + ++useWindow; + usedEntries = 0; + usesSinceCheck = 0; +} + +void ResourceCache::noteUse(Entry& entry) { if (fixedCapacity || capacity <= baseEntries) return; - usedKeys.insert(KeyHash{}(key)); + if (entry.usedWindow != useWindow) { + entry.usedWindow = useWindow; + ++usedEntries; + } if (++usesSinceCheck < capacity * shrinkWindow) return; - const auto used = usedKeys.size(); + const auto used = usedEntries; const auto uses = usesSinceCheck; - usedKeys.clear(); - usesSinceCheck = 0; + resetUses(); + usesWindowStart.store(operations.load(std::memory_order_relaxed), std::memory_order_relaxed); if (used * 4u > capacity) return; const auto previous = capacity; capacity = std::max(capacity / 2u, baseEntries); + publishAgingWindow(); shrankLast = true; evictionsSinceCheck = 0; returnsSinceCheck = 0; @@ -5104,6 +5333,7 @@ void ResourceCache::noteMiss(const Key& key) { } void ResourceCache::Insert(const Key& key, std::shared_ptr resources, std::vector>* evicted) { + operations.fetch_add(1, std::memory_order_relaxed); std::lock_guard lock(mutex); dropReleasedTextures(evicted); if (!resources->HasCachedStorageImages() || resources->HoldsReleasedTexture()) return; @@ -5112,15 +5342,16 @@ void ResourceCache::Insert(const Key& key, std::shared_ptr reso entries.erase(found->second); index.erase(found); } - entries.emplace_front(key, std::move(resources)); + entries.push_front({key, std::move(resources)}); index.emplace(key, entries.begin()); if (capacity == 0) { const char* value = std::getenv("APS5_RESOURCE_CACHE_ENTRIES"); const auto parsed = value ? std::strtoull(value, nullptr, 10) : 0ull; fixedCapacity = parsed != 0; capacity = fixedCapacity ? static_cast(parsed) : baseEntries; + publishAgingWindow(); } - noteUse(key); + noteUse(entries.front()); while (entries.size() > capacity) { noteEvicted(entries.back().first); if (evicted != nullptr) evicted->push_back(std::move(entries.back().second)); @@ -5189,13 +5420,26 @@ void ResourceCache::dropReleasedTextures(std::vector& touchedAt) { + const auto now = operations.load(std::memory_order_relaxed); + const auto last = touchedAt.load(std::memory_order_relaxed); + if (last != 0u && last >= usesWindowStart.load(std::memory_order_relaxed) && now - last < agingWindow.load(std::memory_order_relaxed)) return; + touchedAt.store(now == 0u ? 1u : now, std::memory_order_relaxed); + static_cast(Touch(key)); +} + +void ResourceCache::publishAgingWindow() { + agingWindow.store((capacity == 0 ? baseEntries : capacity) / 8u, std::memory_order_relaxed); +} + bool ResourceCache::Touch(const Key& key) { resourceCacheTouches.fetch_add(1, std::memory_order_relaxed); + operations.fetch_add(1, std::memory_order_relaxed); std::lock_guard lock(mutex); const auto found = index.find(key); if (found == index.end()) return false; entries.splice(entries.begin(), entries, found->second); - noteUse(key); + noteUse(*found->second); return true; } @@ -5215,17 +5459,19 @@ void ResourceCache::Clear() { evictedOrder.clear(); evictionsSinceCheck = 0; returnsSinceCheck = 0; - usedKeys.clear(); - usesSinceCheck = 0; + resetUses(); + usesWindowStart.store(operations.load(std::memory_order_relaxed), std::memory_order_relaxed); shrinkWindow = baseShrinkWindow; shrankLast = false; if (!fixedCapacity) capacity = 0; + publishAgingWindow(); } void ResourceCache::SetBase(std::size_t entries, std::size_t window) { std::lock_guard lock(mutex); baseEntries = entries; baseShrinkWindow = window; + publishAgingWindow(); } std::size_t ResourceCache::Size() const { @@ -5414,9 +5660,21 @@ DescriptorCache::SetAllocation DescriptorCache::Allocate(VkDescriptorSetLayout l return {set, pool, chain.size() - 1, updateAfterBind, VK_NULL_HANDLE, {}, variableCount, {}}; } +namespace { +std::atomic& rewrittenSets() { + static std::atomic sets{0}; + return sets; +} +} + +std::uint64_t DescriptorCache::RewrittenSets() { + return rewrittenSets().load(std::memory_order_relaxed); +} + DescriptorCache::SetAllocation DescriptorCache::AllocateRewritten(VkDescriptorSetLayout layout, std::span sizes, bool updateAfterBind, std::optional variableCount) { { std::lock_guard lock(mutex); + rewrittenSets().store(rewrittenSets().load(std::memory_order_relaxed) + 1u, std::memory_order_relaxed); if (const auto found = recycled.find({layout, variableCount.value_or(0u)}); found != recycled.end() && !found->second.empty()) { const auto allocation = found->second.back(); found->second.pop_back(); @@ -5622,20 +5880,22 @@ std::uint64_t ShaderResources::DataWordsHash(const CompiledShader& shader) { Require(shader.program != nullptr, "missing compiled shader"); std::uint64_t hash = FnvOffset; for (const auto& binding : shader.program->bindings) { - if (DataRole(binding.role)) mixDataWords(hash, binding.guestDescriptor); + if (DataRole(binding.role)) mixDataWords(hash, DrawGuestWords(shader, binding)); } return hash; } bool ShaderResources::DataWordsDiffer(const CompiledShader& shader) const { Require(shader.program != nullptr, "missing compiled shader"); + if (heapStage) return false; const auto& program = *shader.program; for (const auto& binding : program.bindings) { if (!DataRole(binding.role)) continue; const auto held = std::ranges::find_if(bindings, [&](const Binding& candidate) { return candidate.layout.binding == binding.binding; }); if (held == bindings.end() || held->allocations.size() != 1) return true; const auto& allocation = allocations[held->allocations.front()]; - if (allocation.dataWords.size() != binding.guestDescriptor.size() || !std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), binding.guestDescriptor.begin())) return true; + const auto& guestWords = DrawGuestWords(shader, binding); + if (allocation.dataWords.size() != guestWords.size() || !std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), guestWords.begin())) return true; } return false; } @@ -5648,6 +5908,7 @@ bool ShaderResources::RefreshData(VkCommandBuffer commands, const CompiledShader bool ShaderResources::refreshData(VkCommandBuffer commands, const CompiledShader& shader, Recorder* recorder) { Require(shader.program != nullptr, "missing compiled shader"); + if (heapStage) return false; const auto& program = *shader.program; bool recorded = false; // One [gputime] range of class TemplateDataRefresh around the updates, begun at the first one @@ -5660,13 +5921,14 @@ bool ShaderResources::refreshData(VkCommandBuffer commands, const CompiledShader Require(held != bindings.end(), "template bindings disagree with the shader"); Require(held->allocations.size() == 1, "data binding without its buffer"); auto& allocation = allocations[held->allocations.front()]; - const auto size = binding.guestDescriptor.size() * sizeof(std::uint32_t); + const auto& guestWords = DrawGuestWords(shader, binding); + const auto size = guestWords.size() * sizeof(std::uint32_t); Require(allocation.buffer != nullptr && !allocation.guest && allocation.size == size && size <= MaxRefreshBytes, "template data buffer cannot take the dispatch's words"); - if (allocation.dataWords.size() == binding.guestDescriptor.size() && std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), binding.guestDescriptor.begin())) continue; - if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, binding.guestDescriptor); + if (allocation.dataWords.size() == guestWords.size() && std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), guestWords.begin())) continue; + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, guestWords); if (recorder != nullptr && timing == Recorder::NoTiming) timing = recorder->BeginGpuTiming(Recorder::CommandClass::TemplateDataRefresh); - writeDataWords(commands, held->allocations.front(), binding.guestDescriptor); - allocation.dataWords.assign(binding.guestDescriptor.begin(), binding.guestDescriptor.end()); + writeDataWords(commands, held->allocations.front(), guestWords); + allocation.dataWords.assign(guestWords.begin(), guestWords.end()); refreshedBytes += size; recorded = true; } @@ -5694,6 +5956,17 @@ VkBuffer ShaderResources::shaderDataBuffer(const CompiledShader& shader) const { } void ShaderResources::forgetShaderDataWords(const CompiledShader& shader) { + if (HeapShader(shader)) { + auto& stageState = heapStages[HeapStageIndex(shader.stage)]; + ++stageState.pushVersion; + if (stageState.data.table.address != 0u) { + auto& heap = BindlessHeap::For(context); + BindlessHeap::SpanScope spans(heap); + heap.RetireTable(spans, stageState.data.table); + } + stageState.dataInput.clear(); + stageState.dataOrigin = 0; + } if (const auto allocation = shaderDataAllocation(shader)) { allocations[*allocation].dataWords.clear(); rehashDataWords(); @@ -5719,7 +5992,7 @@ void ShaderResources::PrecollectSurfaces() const { for (const auto& range : describedRanges) GuestMemory::CollectWrites(range.address, static_cast(range.bytes)); } -void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& binding, VkShaderStageFlags flags) { +void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, VkShaderStageFlags flags) { Require(binding.count != 0, "empty descriptor binding"); const auto heap = static_cast(binding.binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)); const auto capacity = binding.count; @@ -5732,20 +6005,20 @@ void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) { // Storage images are guest textures the shader writes (looked up in stage B). Require(binding.role == ShaderRecompiler::DescriptorRole::GuestImages, "storage image binding has a non-image role"); - Require(binding.guestDescriptor.size() == static_cast(binding.count) * 8u, "guest storage image descriptors must contain 8 dwords each"); + Require(guest.size() == static_cast(binding.count) * 8u, "guest storage image descriptors must contain 8 dwords each"); Require(context.detiler != nullptr, "device texture detiler is unavailable"); Require(capacity <= context.limits.maxPerStageDescriptorStorageImages, "shader storage-image descriptors exceed per-stage limits"); bindings.push_back({{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, capacity, flags, nullptr}, {}, {}}); plannedStorageImages += binding.count; - deferredImages.push_back({&binding, bindings.size() - 1}); + deferredImages.push_back({&binding, guest, bindings.size() - 1}); return; } const bool sampledImage = binding.kind == ShaderRecompiler::DescriptorKind::SampledImage; const bool samplerKind = binding.kind == ShaderRecompiler::DescriptorKind::Sampler; if (!(sampledImage || samplerKind)) Require(false, std::string("unsupported descriptor kind ") + kindName(binding.kind) + " for role " + roleName(binding.role)); Require((sampledImage && binding.role == ShaderRecompiler::DescriptorRole::GuestImages) || (samplerKind && binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers), "guest image descriptor role disagrees with its kind"); - Require(binding.guestDescriptor.size() % binding.count == 0, "guest image descriptor size is not a multiple of the binding count"); - const auto elementWords = binding.guestDescriptor.size() / binding.count; + Require(guest.size() % binding.count == 0, "guest image descriptor size is not a multiple of the binding count"); + const auto elementWords = guest.size() / binding.count; Binding item{{binding.binding, sampledImage ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLER, capacity, flags, nullptr}, {}, {}}; @@ -5763,7 +6036,7 @@ void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& Require(binding.samplerDepthCompare.size() == binding.count, "guest sampler binding is missing depth comparison metadata"); Require(binding.samplerUnnormalized.empty() || binding.samplerUnnormalized.size() == binding.count, "guest sampler binding has unnormalized coordinate metadata of another size"); for (std::uint32_t element = 0; element < binding.count; ++element) { - auto guestWords = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); + auto guestWords = std::span(guest).subspan(static_cast(element) * elementWords, elementWords); std::array normalizedWords{}; if (element < binding.samplerCoordinatesIgnored.size() && binding.samplerCoordinatesIgnored[element]) { std::copy(guestWords.begin(), guestWords.end(), normalizedWords.begin()); @@ -5783,12 +6056,13 @@ void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& } samplerSources.push_back({{words[0], words[1], words[2], words[3]}, compareEnable, unnormalized, integerBorder}); item.imageAllocations.push_back(samplers.size() - 1); + item.embeddedSamplers.push_back(element < binding.samplerEmbedded.size() && binding.samplerEmbedded[element] != ShaderRecompiler::RuntimeAbi::NoEmbeddedSampler); } Require(samplers.size() <= context.limits.maxDescriptorSetSamplers, "pipeline sampler descriptors exceed device limits"); } bindings.push_back(std::move(item)); - if (sampledImage) deferredImages.push_back({&binding, bindings.size() - 1}); + if (sampledImage) deferredImages.push_back({&binding, guest, bindings.size() - 1}); } namespace { @@ -5796,12 +6070,13 @@ namespace { // Calls `visit(binding, element, words)` for every sampled and storage image element of a compiled // shader's bindings, in plan order (the order addImageBinding and resolveImageBinding walk). template -void forEachImageElement(const ShaderRecompiler::RecompileResult& program, Visit&& visit) { - for (const auto& binding : program.bindings) { +void forEachImageElement(const CompiledShader& shader, Visit&& visit) { + for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages || binding.count == 0) continue; if (binding.kind != ShaderRecompiler::DescriptorKind::SampledImage && binding.kind != ShaderRecompiler::DescriptorKind::StorageImage) continue; - const auto elementWords = binding.guestDescriptor.size() / binding.count; - for (std::uint32_t element = 0; element < binding.count; ++element) visit(binding, element, std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords)); + const auto& words = DrawGuestWords(shader, binding); + const auto elementWords = words.size() / binding.count; + for (std::uint32_t element = 0; element < binding.count; ++element) visit(binding, element, std::span(words).subspan(static_cast(element) * elementWords, elementWords)); } } @@ -5829,10 +6104,10 @@ bool ShaderResources::precollectImages() { auto& counters = TextureCounts(); for (const auto& deferred : deferredImages) { const auto& binding = *deferred.binding; - const auto elementWords = binding.guestDescriptor.size() / binding.count; + const auto elementWords = deferred.words.size() / binding.count; for (std::uint32_t element = 0; element < binding.count; ++element) { const bool sampled = binding.kind == ShaderRecompiler::DescriptorKind::SampledImage; - const auto raw = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); + const auto raw = std::span(deferred.words).subspan(static_cast(element) * elementWords, elementWords); std::array narrowed{}; const auto words = firstLayerWords(raw, sampled ? binding.imageShape : std::nullopt, narrowed, false); if (sampled && !imageRecords.empty()) { @@ -5951,15 +6226,15 @@ void ShaderResources::applySamplerVariants() { } } -void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBinding& binding, Binding& item, std::span> shaderSamplers) { +void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, Binding& item, std::span> shaderSamplers) { auto& counters = TextureCounts(); // The element's stage-A record, when the pass ran (records follow the plan order exactly). const auto nextRecord = [&]() -> ImageRecord* { return nextImageRecord < imageRecords.size() ? &imageRecords[nextImageRecord++] : nullptr; }; if (binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) { Require(binding.imageSamplers.size() == binding.count, "guest sampled image binding is missing its image-sampler pairs"); - const auto elementWords = binding.guestDescriptor.size() / binding.count; + const auto elementWords = guest.size() / binding.count; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto raw = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); + const auto raw = std::span(guest).subspan(static_cast(element) * elementWords, elementWords); std::array narrowed{}; const auto words = firstLayerWords(raw, binding.imageShape, narrowed, true); auto* record = nextRecord(); @@ -6052,8 +6327,8 @@ void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBind // storage writes). std::uint32_t mipOffset = 0; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); - const bool sameAsPrevious = SameAsPreviousStorageElement(binding, element); + const auto words = std::span(guest).subspan(static_cast(element) * 8u, 8u); + const bool sameAsPrevious = SameAsPreviousStorageElement(guest, element); if (sameAsPrevious) ++mipOffset; else mipOffset = 0; const auto* record = nextRecord(); @@ -6068,9 +6343,9 @@ void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBind if (resource.dimension == TextureDimension::k2DMsaa) { Require(!(element < binding.imageAtomic.size() && binding.imageAtomic[element]) && !(element < binding.imageAtomic64.size() && binding.imageAtomic64[element]), "storage image atomics on a multisampled texture are not implemented"); storageTextures.push_back(nullptr); - multisampleStorageViews.resize(storageTextures.size(), VK_NULL_HANDLE); - const bool uintStorage = ShaderRecompiler::RuntimeAbi::UintStorageImageBinding(binding.binding); - multisampleStorageViews.back() = MultisampleTargetStorageView(context, resource, uintStorage); + multisampleStorage.resize(storageTextures.size()); + const bool uintStorage = UintStorageBinding(binding.binding); + multisampleStorage.back() = MultisampleTargetStorageView(context, resource, uintStorage); multisampleSources.push_back(resource.baseAddress); storageMips.push_back(0); storageKeys.push_back(0); @@ -6184,6 +6459,7 @@ ShaderResources::TableStage& ShaderResources::tableStage(const CompiledShader& s table.program = shader.program; table.poison = shader.program->imageTablePoison; table.messages.assign(table.poison.size(), nullptr); + table.heap = HeapShader(shader) && shader.program->dataAddressPush; return table; } @@ -6200,21 +6476,21 @@ std::uint32_t ShaderResources::rejectTableElement(TableStage& table, std::span(table.poison.size() - 1u)); } -void ShaderResources::addSamplerTable(const ShaderRecompiler::DescriptorBinding& binding, VkShaderStageFlags flags, TableStage& table) { +void ShaderResources::addSamplerTable(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, VkShaderStageFlags flags, TableStage& table) { namespace Abi = ShaderRecompiler::ImageTableAbi; - Require(binding.kind == ShaderRecompiler::DescriptorKind::Sampler && binding.guestDescriptor.size() == static_cast(binding.count) * 4u && binding.samplerDepthCompare.size() == binding.count && binding.count % Abi::SamplerEntryElements == 0u, "sampler table binding is malformed"); - Require(context.samplerTableCapacity != 0, "sampler tables need runtimeDescriptorArray and descriptorBindingPartiallyBound, which the device lacks"); + Require(binding.kind == ShaderRecompiler::DescriptorKind::Sampler && guest.size() == static_cast(binding.count) * 4u && binding.samplerDepthCompare.size() == binding.count && binding.count % Abi::SamplerEntryElements == 0u, "sampler table binding is malformed"); + Require(table.heap || context.samplerTableCapacity != 0, "sampler tables need runtimeDescriptorArray and descriptorBindingPartiallyBound, which the device lacks"); const VkDescriptorBindingFlags samplerTableFlags = VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | (context.samplerTableUpdateAfterBind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0); Binding item{{binding.binding, VK_DESCRIPTOR_TYPE_SAMPLER, context.samplerTableCapacity, flags, nullptr}, {}, {}, samplerTableFlags}; static const bool noSamplerCache = std::getenv("APS5_NO_SAMPLER_CACHE") != nullptr; for (std::uint32_t entry = 0; entry < binding.count / Abi::SamplerEntryElements; ++entry) { const auto first = entry * Abi::SamplerEntryElements; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(first) * 4u, 4u); + const auto words = guest.subspan(static_cast(first) * 4u, 4u); std::string rejected; - if (first + Abi::SamplerEntryElements > context.samplerTableCapacity) rejected = "the sampler table exceeds the device's capacity of " + std::to_string(context.samplerTableCapacity) + " samplers"; + if (!table.heap && first + Abi::SamplerEntryElements > context.samplerTableCapacity) rejected = "the sampler table exceeds the device's capacity of " + std::to_string(context.samplerTableCapacity) + " samplers"; for (std::uint32_t element = first; rejected.empty() && element < first + Abi::SamplerEntryElements; ++element) { try { - const auto elementWords = std::span(binding.guestDescriptor.data() + static_cast(element) * 4u, 4u); + const auto elementWords = std::span(guest.data() + static_cast(element) * 4u, 4u); auto resource = DecodeSamplerResource(elementWords); resource.compareEnable = binding.samplerDepthCompare.at(element); Sampler::Validate(context, resource); @@ -6233,7 +6509,7 @@ void ShaderResources::addSamplerTable(const ShaderRecompiler::DescriptorBinding& continue; } for (std::uint32_t element = first; element < first + Abi::SamplerEntryElements; ++element) { - const auto elementWords = std::span(binding.guestDescriptor).subspan(static_cast(element) * 4u, 4u); + const auto elementWords = guest.subspan(static_cast(element) * 4u, 4u); const bool compareEnable = binding.samplerDepthCompare.at(element); if (context.samplerCache != nullptr && !noSamplerCache) { samplers.push_back(context.samplerCache->Get(context, elementWords, compareEnable, false)); @@ -6248,6 +6524,10 @@ void ShaderResources::addSamplerTable(const ShaderRecompiler::DescriptorBinding& } const auto setSamplers = context.samplerTableUpdateAfterBind ? context.descriptorIndexingLimits.maxDescriptorSetUpdateAfterBindSamplers : context.limits.maxDescriptorSetSamplers; Require(samplers.size() <= setSamplers, "pipeline sampler descriptors exceed device limits"); + if (table.heap) { + table.tableSamplers = std::move(item.imageAllocations); + return; + } bindings.push_back(std::move(item)); } @@ -6264,7 +6544,7 @@ void noteVariantSurface(std::uint64_t address, std::size_t members, const GuestT std::fprintf(stderr, "[textures] surface 0x%llx has %zu dynamic-resolution variants in one image table; they share the %ux%u texture (chosen by %s)\n", static_cast(address), members, chosen.width, chosen.height, rule); } -std::vector variantRepresentatives(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::uint64_t elementBase, std::uint64_t capacity) { +std::vector variantRepresentatives(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::span imageWords, std::uint64_t elementBase, std::uint64_t capacity) { struct Member { std::uint32_t element; GuestTextureResource resource; @@ -6273,7 +6553,7 @@ std::vector variantRepresentatives(VkDevice device, const ShaderR std::map> families; for (std::uint32_t element = 0; element < binding.count && elementBase + element < capacity; ++element) { if (element < binding.imageWritten.size() && binding.imageWritten[element]) continue; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = imageWords.subspan(static_cast(element) * 8u, 8u); GuestTextureResource resource{}; try { if (IsNullTextureResource(words)) continue; @@ -6327,7 +6607,7 @@ std::vector variantRepresentatives(VkDevice device, const ShaderR return representatives; } -std::vector arrayPartners(const ShaderRecompiler::DescriptorBinding& binding, std::uint64_t elementBase, std::uint64_t capacity) { +std::vector arrayPartners(const ShaderRecompiler::DescriptorBinding& binding, std::span imageWords, std::uint64_t elementBase, std::uint64_t capacity) { struct Candidate { std::uint32_t element; std::array key; @@ -6336,7 +6616,7 @@ std::vector arrayPartners(const ShaderRecompiler::DescriptorBindi std::vector arrays; for (std::uint32_t element = 0; element < binding.count && elementBase + element < capacity; ++element) { if (element < binding.imageWritten.size() && binding.imageWritten[element]) continue; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = imageWords.subspan(static_cast(element) * 8u, 8u); GuestTextureResource resource{}; try { if (IsNullSampledTextureResource(words)) continue; @@ -6365,7 +6645,7 @@ std::vector arrayPartners(const ShaderRecompiler::DescriptorBindi void ShaderResources::resolveImageTables() { const auto none = [](const std::array& set) { return set[0] == std::numeric_limits::max() && set[1] == std::numeric_limits::max(); }; - if (none(tableBindings) && none(storageTableBindings)) return; + if (none(tableBindings) && none(storageTableBindings) && std::none_of(tableStages.begin(), tableStages.end(), [](const TableStage& table) { return table.heap && table.images != nullptr; })) return; auto& counters = TextureCounts(); for (std::size_t set = 0; set < tableBindings.size(); ++set) { if (storageTableBindings[set] != std::numeric_limits::max()) bindings[storageTableBindings[set]].imageAllocations.assign(std::min(tableElements[set], StorageTableCapacity(context)), std::numeric_limits::max()); @@ -6373,11 +6653,12 @@ void ShaderResources::resolveImageTables() { } for (auto& table : tableStages) { if (table.images == nullptr) continue; - auto* item = tableBindings[table.set] != std::numeric_limits::max() ? &bindings[tableBindings[table.set]] : nullptr; + auto* item = !table.heap && tableBindings[table.set] != std::numeric_limits::max() ? &bindings[tableBindings[table.set]] : nullptr; const auto& binding = *table.images; const auto faults = table.map[ShaderRecompiler::ImageTableAbi::HeaderElementFaults]; const auto stageSamplers = std::span>(samplers).subspan(table.firstSampler, table.samplerCount); table.elementTextures.assign(binding.count, std::numeric_limits::max()); + if (table.heap) table.elementStorage.assign(binding.count, std::numeric_limits::max()); const auto capacityMessage = [&] { return "the image table exceeds the device's capacity of " + std::to_string(context.imageTableCapacity) + " images"; }; std::vector samplerKey; for (std::uint32_t sampler = 0; sampler < table.samplerCount; ++sampler) { @@ -6390,7 +6671,7 @@ void ShaderResources::resolveImageTables() { textureFirstLayer.push_back(firstLayer); describedRanges.push_back({"texture", resource.baseAddress, guestBytes, resource.width, resource.height, resource.format, static_cast(resource.tileMode), resource.dccAddress, true}); table.elementTextures[element] = textures.size() - 1u; - item->imageAllocations[static_cast(table.elementBase) + element] = textures.size() - 1u; + if (item != nullptr) item->imageAllocations[static_cast(table.elementBase) + element] = textures.size() - 1u; }; const auto refusal = [&](std::uint32_t element, std::span words, const std::shared_ptr& texture, const GuestTextureResource& resource) -> std::string { try { @@ -6502,7 +6783,7 @@ void ShaderResources::resolveImageTables() { const auto state = CurrentTableState(); std::vector> cached; const bool storageTable = std::find(binding.imageWritten.begin(), binding.imageWritten.end(), true) != binding.imageWritten.end(); - auto* reused = storageTable || item == nullptr ? nullptr : FindReusedTable(context.device, binding, state); + auto* reused = storageTable || item == nullptr ? nullptr : FindReusedTable(context.device, binding, table.imageWords, state); if (reused != nullptr && AnyPendingCpuWrites(context)) { bool landed = false; for (const auto& entry : reused->elements) { @@ -6510,7 +6791,7 @@ void ShaderResources::resolveImageTables() { } if (landed && CurrentTableState() != state) reused = nullptr; } - if (reused != nullptr && !reused->representatives.empty() && reused->representatives != variantRepresentatives(context.device, binding, table.elementBase, context.imageTableCapacity)) reused = nullptr; + if (reused != nullptr && !reused->representatives.empty() && reused->representatives != variantRepresentatives(context.device, binding, table.imageWords, table.elementBase, table.heap ? std::numeric_limits::max() : context.imageTableCapacity)) reused = nullptr; if (reused != nullptr && TableCurrent(*reused) && CachedTableTextures(*reused, cached)) { logTableLookups(*reused, cached); table.representatives = reused->representatives; @@ -6518,9 +6799,9 @@ void ShaderResources::resolveImageTables() { if (!replay) reused->bound.assign(binding.count, {}); auto next = cached.begin(); for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = table.imageWords.subspan(static_cast(element) * 8u, 8u); const auto& entry = reused->elements[element]; - if (static_cast(table.elementBase) + element >= context.imageTableCapacity) { + if (!table.heap && static_cast(table.elementBase) + element >= context.imageTableCapacity) { if (!entry.rejected && !entry.live && !entry.substitute) ++next; table.map[faults + element] = rejectTableElement(table, words, capacityMessage()); } else if (entry.rejected) { @@ -6543,9 +6824,9 @@ void ShaderResources::resolveImageTables() { } for (std::uint32_t element = 0; element < binding.count; ++element) { const auto& entry = reused->elements[element]; - if (!entry.substitute || static_cast(table.elementBase) + element >= context.imageTableCapacity) continue; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); - const auto representativeWords = std::span(binding.guestDescriptor).subspan(static_cast(entry.representative) * 8u, 8u); + if (!entry.substitute || (!table.heap && static_cast(table.elementBase) + element >= context.imageTableCapacity)) continue; + const auto words = table.imageWords.subspan(static_cast(element) * 8u, 8u); + const auto representativeWords = table.imageWords.subspan(static_cast(entry.representative) * 8u, 8u); const auto index = table.elementTextures[entry.representative]; const auto message = index == std::numeric_limits::max() ? std::string("the dynamic-resolution variant this entry borrows from was rejected") : refusal(element, representativeWords, textures[index], entry.representativeResource); if (!message.empty()) { @@ -6568,7 +6849,7 @@ void ShaderResources::resolveImageTables() { ReusedTable fresh; fresh.bound.assign(binding.count, {}); bool reusable = state.epoch != 0; - if (binding.count > 1) table.representatives = variantRepresentatives(context.device, binding, table.elementBase, context.imageTableCapacity); + if (binding.count > 1) table.representatives = variantRepresentatives(context.device, binding, table.imageWords, table.elementBase, table.heap ? std::numeric_limits::max() : context.imageTableCapacity); const auto& representatives = table.representatives; std::vector representativeNeeded(representatives.size(), false); for (const auto representative : representatives) { @@ -6576,7 +6857,7 @@ void ShaderResources::resolveImageTables() { } std::unordered_map representativeSources; std::vector substitutes; - const auto partners = binding.count > 1 ? arrayPartners(binding, table.elementBase, context.imageTableCapacity) : std::vector{}; + const auto partners = binding.count > 1 ? arrayPartners(binding, table.imageWords, table.elementBase, context.imageTableCapacity) : std::vector{}; std::vector order; if (!partners.empty()) { reusable = false; @@ -6590,9 +6871,9 @@ void ShaderResources::resolveImageTables() { } for (std::uint32_t position = 0; position < binding.count; ++position) { const auto element = order.empty() ? position : order[position]; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = table.imageWords.subspan(static_cast(element) * 8u, 8u); const auto absolute = static_cast(table.elementBase) + element; - if (absolute >= context.imageTableCapacity) { + if (!table.heap && absolute >= context.imageTableCapacity) { table.map[faults + element] = rejectTableElement(table, words, capacityMessage()); reusable = false; continue; @@ -6611,7 +6892,7 @@ void ShaderResources::resolveImageTables() { const auto partner = partners[element]; const auto index = table.elementTextures[partner]; if (index != std::numeric_limits::max() && textures[index] != nullptr && textures[index]->HasArrayView()) { - const auto partnerWords = std::span(binding.guestDescriptor).subspan(static_cast(partner) * 8u, 8u); + const auto partnerWords = table.imageWords.subspan(static_cast(partner) * 8u, 8u); const auto partnerResource = DecodeTextureResource(partnerWords); reusable = false; fresh.bound[element] = bind(element, words, textures[index], partnerResource, DescribeSurface(partnerResource).guestBytes, false); @@ -6639,11 +6920,11 @@ void ShaderResources::resolveImageTables() { if (element < binding.imageWritten.size() && binding.imageWritten[element]) { reusable = false; const auto storageBinding = storageTableBindings[table.set]; - if (storageBinding == std::numeric_limits::max()) { + if (!table.heap && storageBinding == std::numeric_limits::max()) { table.map[faults + element] = rejectTableElement(table, words, "set " + std::to_string(table.set) + " has no image storage table, but the shader stores to its table element " + std::to_string(absolute)); continue; } - if (absolute >= StorageTableCapacity(context)) { + if (!table.heap && absolute >= StorageTableCapacity(context)) { table.map[faults + element] = rejectTableElement(table, words, "the stored table element " + std::to_string(absolute) + " of set " + std::to_string(table.set) + " is past the image storage table's capacity of " + std::to_string(StorageTableCapacity(context)) + " images"); continue; } @@ -6671,10 +6952,11 @@ void ShaderResources::resolveImageTables() { storageAtomic64.push_back(element < binding.imageAtomic64.size() && binding.imageAtomic64[element]); storageUint.push_back(uintStorage); describedRanges.push_back({"storage", resource.baseAddress, guestBytes, resource.width, resource.height, resource.format, static_cast(resource.tileMode), resource.dccAddress, true}); - bindings[storageBinding].imageAllocations[absolute] = storageTextures.size() - 1u; + if (table.heap) table.elementStorage[element] = storageTextures.size() - 1u; + else bindings[storageBinding].imageAllocations[absolute] = storageTextures.size() - 1u; continue; } - if (item == nullptr) { + if (item == nullptr && !table.heap) { table.map[faults + element] = rejectTableElement(table, words, "a sampled image table entry has no sampled image table binding"); reusable = false; continue; @@ -6704,7 +6986,7 @@ void ShaderResources::resolveImageTables() { } for (const auto element : substitutes) { const auto representative = representatives[element]; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(representative) * 8u, 8u); + const auto words = table.imageWords.subspan(static_cast(representative) * 8u, 8u); const auto index = table.elementTextures[representative]; const auto source = representativeSources.find(representative); const auto message = index == std::numeric_limits::max() || source == representativeSources.end() ? std::string("the dynamic-resolution variant this entry borrows from was rejected") : refusal(element, words, textures[index], source->second); @@ -6718,7 +7000,7 @@ void ShaderResources::resolveImageTables() { continue; } table.elementTextures[element] = index; - item->imageAllocations[static_cast(table.elementBase) + element] = index; + if (item != nullptr) item->imageAllocations[static_cast(table.elementBase) + element] = index; counters.variantSubstituted.fetch_add(1, std::memory_order_relaxed); } counters.tablesResolved.fetch_add(1, std::memory_order_relaxed); @@ -6733,10 +7015,11 @@ void ShaderResources::resolveImageTables() { fresh.samplers = std::move(samplerKey); fresh.replayable = static_cast(table.elementBase) + binding.count <= context.imageTableCapacity; fresh.representatives = table.representatives; - RememberTable(std::move(fresh), binding); + RememberTable(std::move(fresh), binding, table.imageWords); } } } + for (auto& table : tableStages) table.imageWords = {}; reportTextureCounters(); } @@ -6748,10 +7031,29 @@ std::uint64_t SampledLookupKeyProofs() { return sampledLookupKeyProofs; } +namespace { +std::atomic drawInputCopies{0}; +} + +std::uint64_t DrawInputCopies() { + return drawInputCopies.load(std::memory_order_relaxed); +} + std::uint64_t SampledTexturesCleared() { return TextureCounts().cleared.load(std::memory_order_relaxed); } +namespace { + +std::atomic heapPushedStages{0}; +std::atomic heapOverflowStages{0}; + +} + +HeapBufferPathCounts HeapBufferPaths() { + return {heapPushedStages.load(std::memory_order_relaxed), heapOverflowStages.load(std::memory_order_relaxed)}; +} + std::uint64_t SampledTexturesImported() { return TextureCounts().imported.load(std::memory_order_relaxed); } @@ -6800,6 +7102,10 @@ void ShaderResources::finishImageTables() { faults.push_back({IrStage(table.stage), table.program->imageTableShader, table.poison, table.messages}); ranges.insert(ranges.end(), table.program->imageTableRanges.begin(), table.program->imageTableRanges.end()); } + for (auto& table : tableStages) { + table.program = nullptr; + table.images = nullptr; + } if (bda == nullptr) return; bda->SetImageTables(std::move(faults), std::move(ranges)); } @@ -6854,7 +7160,7 @@ std::vector ShaderResources::PresyncSurfaces() const { } // Stage A has not run (an address-based build, or the pass is off): decoded from the shader. if (deferredCompute.program == nullptr) return surfaces; - forEachImageElement(*deferredCompute.program, [&](const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t, std::span words) { + forEachImageElement(deferredCompute, [&](const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t, std::span words) { if (IsNullTextureResource(words)) return; const auto resource = DecodeTextureResource(words); const auto guestBytes = SurfaceGuestBytes(resource); @@ -6863,9 +7169,10 @@ std::vector ShaderResources::PresyncSurfaces() const { }); for (const auto& binding : deferredCompute.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::ImageTable) continue; - for (std::size_t element = 0; element < binding.guestDescriptor.size() / 8u; ++element) { + const auto& words = DrawGuestWords(deferredCompute, binding); + for (std::size_t element = 0; element < words.size() / 8u; ++element) { try { - const auto resource = DecodeTextureResource(std::span(binding.guestDescriptor).subspan(element * 8u, 8u)); + const auto resource = DecodeTextureResource(std::span(words).subspan(element * 8u, 8u)); const auto guestBytes = SurfaceGuestBytes(resource); consider(resource.format, resource.baseAddress, guestBytes, true); considerKeys(resource.dccAddress, guestBytes); @@ -6877,6 +7184,7 @@ std::vector ShaderResources::PresyncSurfaces() const { } ShaderResources::~ShaderResources() { + retireHeapTables(); release(); } @@ -6923,6 +7231,7 @@ void ShaderResources::release() noexcept { std::uint32_t ShaderResources::setOf(const Binding& binding) const { constexpr auto count = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); if (binding.set >= 0) return static_cast(binding.set); + if (heapStage) return 0u; return splitSets && binding.layout.binding / count == static_cast(ShaderRecompiler::RuntimeAbi::Stage::Fragment) ? 1u : 0u; } @@ -6951,35 +7260,43 @@ ShaderResources::DrawBindings::~DrawBindings() { release(fragmentLayout, fragmentAllocation); } -std::optional> ShaderResources::MovedReadOnlyBuffers(std::span shaders, Recorder& recorder, const ColorTarget* target, bool* patchedData) const { +std::optional> ShaderResources::MovedReadOnlyBuffers(std::span shaders, Recorder& recorder, const ColorTarget* target, bool* patchedData, MoveRefusal* refusal) const { + const auto refuse = [&](MoveRefusal why) { + if (refusal != nullptr) *refusal = why; + return std::optional>{}; + }; std::vector moved; std::size_t movedBytes = 0; - if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE) || (usesBda && !spaceReuse)) return moved; + if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE && !heapStage) || (usesBda && !spaceReuse)) return moved; for (const auto& shader : shaders) { - if (shader.program == nullptr) return std::nullopt; + if (shader.program == nullptr) return refuse(MoveRefusal::Shape); + const bool heapShader = HeapShader(shader); for (const auto& binding : shader.program->bindings) { + if (heapShader && (DataRole(binding.role) || binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers)) continue; if (DataRole(binding.role)) { const auto kept = std::find_if(bindings.begin(), bindings.end(), [&](const Binding& item) { return item.layout.binding == binding.binding; }); - if (kept == bindings.end() || kept->allocations.size() != 1) return std::nullopt; + if (kept == bindings.end() || kept->allocations.size() != 1) return refuse(MoveRefusal::Shape); const auto index = kept->allocations.front(); const auto& item = allocations[index]; - if (item.guest || item.buffer == nullptr || item.size != binding.guestDescriptor.size() * sizeof(std::uint32_t)) return std::nullopt; + const auto& guestWords = DrawGuestWords(shader, binding); + if (item.guest || item.buffer == nullptr || item.size != guestWords.size() * sizeof(std::uint32_t)) return refuse(MoveRefusal::Shape); const bool patched = std::any_of(dataPatches.begin(), dataPatches.end(), [&](const DataPatch& patch) { return patch.allocation == index; }); - const bool same = !item.dataWords.empty() ? item.dataWords == binding.guestDescriptor : !patched && std::memcmp(item.buffer->Bytes().data(), binding.guestDescriptor.data(), item.size) == 0; + const bool same = !item.dataWords.empty() ? item.dataWords == guestWords : !patched && std::memcmp(item.buffer->Bytes().data(), guestWords.data(), item.size) == 0; if (same) continue; if (item.dataWords.empty() && patched) { if (patchedData != nullptr) *patchedData = true; - return std::nullopt; + return refuse(MoveRefusal::Bindings); } if (moved.empty()) moved.reserve(allocations.size()); - moved.push_back({index, 0, item.size, binding.guestDescriptor}); + moved.push_back({index, 0, item.size, guestWords}); continue; } if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; + const auto& guestWords = DrawGuestWords(shader, binding); const auto kept = std::find_if(bindings.begin(), bindings.end(), [&](const Binding& item) { return item.layout.binding == binding.binding; }); - if (kept == bindings.end() || kept->allocations.size() != binding.count || binding.guestDescriptor.size() != static_cast(binding.count) * 4u) return std::nullopt; + if (kept == bindings.end() || kept->allocations.size() != binding.count || guestWords.size() != static_cast(binding.count) * 4u) return refuse(MoveRefusal::Shape); for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; + const auto* words = guestWords.data() + static_cast(element) * 4u; const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; const auto address = descriptor.Base48(); const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; @@ -6989,21 +7306,50 @@ std::optional> ShaderResources::MovedR const bool empty = size == 0 || address == 0; if (!item.guest) { if (empty) continue; - return std::nullopt; + return refuse(MoveRefusal::NotGuest); } if (item.address == address && item.size == size) continue; - if (written || empty || item.written || size > context.limits.maxStorageBufferRange) return std::nullopt; + if (written || empty || item.written) return refuse(MoveRefusal::Written); + if (size > context.limits.maxStorageBufferRange) return refuse(MoveRefusal::Limit); const auto begin = address - item.adjustment; const auto bytes = static_cast(GuestBufferMemory::ViewBytes(size, item.adjustment)); - if (bytes > maxDrawSnapshotBytes - movedBytes) return std::nullopt; - if (!GuestMemory::Accessible(reinterpret_cast(begin), bytes)) return std::nullopt; - if (guestMemory.WritesOverlap(begin, bytes) || PendingStorageOverlaps(begin, bytes, nullptr) || AnyShadowedOverlaps(begin, bytes)) return std::nullopt; + const bool behind = recorder.PendingWriteOverlaps(begin, bytes); + const bool inPlace = (usesBda && heapStage) || (behind && heapShader && addressedBuffers); + const auto sharesClassic = [&] { return std::any_of(bindings.begin(), bindings.end(), [&](const Binding& other) { return !(other.heap && other.addressed) && std::find(other.allocations.begin(), other.allocations.end(), index) != other.allocations.end(); }); }; + if (heapStage && !inPlace && sharesClassic()) return refuse(MoveRefusal::SharedBinding); + if (!inPlace && bytes > maxDrawSnapshotBytes - movedBytes) return refuse(MoveRefusal::Limit); + if (!GuestMemory::Accessible(reinterpret_cast(begin), bytes)) return refuse(MoveRefusal::Inaccessible); + if (guestMemory.WritesOverlap(begin, bytes) || PendingStorageOverlaps(begin, bytes, nullptr) || AnyShadowedOverlaps(begin, bytes)) return refuse(MoveRefusal::Overlap); MovedBuffer entry{index, address, static_cast(size)}; - const bool pending = recorder.PendingWriteOverlaps(begin, bytes); - if (pending && !movedInPlace(recorder, item, address, size, entry)) return std::nullopt; + if (behind && !inPlace && (heapStage || !movedInPlace(recorder, item, address, size, entry))) return refuse(MoveRefusal::Overlap); + if (behind && inPlace) { + const auto overlaps = [&](const std::shared_ptr& writer) { return writer != nullptr && writer->WritesOverlap(begin, bytes); }; + if (context.copiedWriters != nullptr && std::any_of(context.copiedWriters->begin(), context.copiedWriters->end(), overlaps)) return refuse(MoveRefusal::Overlap); + const auto drawWriters = DrawCopiedWriters(); + if (std::any_of(drawWriters->begin(), drawWriters->end(), overlaps)) return refuse(MoveRefusal::Overlap); + } + VkDeviceAddressRangeEXT view{}; + if (inPlace) { + std::uint32_t adjustment = 0; + bool found = false; + if (behind) { + const auto imported = guestMemory.ImportedView(address, static_cast(size), adjustment); + if (imported.has_value()) view = *imported; + found = view.address != 0; + } else { + VkDeviceAddress handle = 0; + found = guestMemory.TryDescriptor(address, static_cast(size), adjustment, nullptr, &handle).has_value() && handle != 0; + } + const bool classic = sharesClassic(); + if (!found) return refuse(MoveRefusal::NotImported); + if (adjustment != item.adjustment) return refuse(MoveRefusal::Alignment); + if (classic) return refuse(MoveRefusal::SharedBinding); + } if (moved.empty()) moved.reserve(allocations.size()); + entry.heapInPlace = inPlace; + entry.view = view; moved.push_back(entry); - if (!pending) movedBytes += bytes; + if (!inPlace && entry.inPlace == VK_NULL_HANDLE) movedBytes += bytes; } } } @@ -7054,6 +7400,9 @@ const char* ShaderResources::MoveRefusalName(MoveRefusal refusal) { case MoveRefusal::Inaccessible: return "unmapped"; case MoveRefusal::Overlap: return "pending write"; case MoveRefusal::Bindings: return "no bindings made"; + case MoveRefusal::NotImported: return "not imported"; + case MoveRefusal::Alignment: return "alignment changed"; + case MoveRefusal::SharedBinding: return "shared with a classic binding"; case MoveRefusal::Count: break; } return "?"; @@ -7067,13 +7416,14 @@ std::optional> ShaderResources::MovedD }; std::vector moved; if (shader.program == nullptr || usesBda) return refuse(MoveRefusal::Shape); - if (_set == VK_NULL_HANDLE) return moved; + if (_set == VK_NULL_HANDLE && !heapStage) return moved; for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; const auto kept = std::find_if(bindings.begin(), bindings.end(), [&](const Binding& item) { return item.layout.binding == binding.binding; }); - if (kept == bindings.end() || kept->allocations.size() != binding.count || binding.guestDescriptor.size() != static_cast(binding.count) * 4u) return refuse(MoveRefusal::Shape); + const auto& guestWords = DrawGuestWords(shader, binding); + if (kept == bindings.end() || kept->allocations.size() != binding.count || guestWords.size() != static_cast(binding.count) * 4u) return refuse(MoveRefusal::Shape); for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; + const auto* words = guestWords.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 = guestBufferBytes(std::span(words, 4)); @@ -7118,13 +7468,18 @@ std::size_t ShaderResources::DrawUploadLimit() { std::shared_ptr ShaderResources::PrepareDrawBindings(Recorder& recorder, std::span moved, bool movedOnly, const BdaResources* faultRecord) const { requireGuestBuffers(moved); - if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE) || (usesBda && !spaceReuse)) return {}; + if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE && !heapStage) || (usesBda && !spaceReuse)) return {}; + const bool readsInPlace = usesBda && heapStage; + movedOnly = movedOnly || readsInPlace; + thread_local std::vector>* inPlaceSlot = nullptr; + auto& inPlace = ShaderRecompiler::ThreadOwned(inPlaceSlot); + inPlace.clear(); prepareFaultSlot(); auto split = guestMemory.SplitInPlaceReads(); const bool sharedOnly = split && split->own.empty(); thread_local std::vector>* readsSlot = nullptr; auto& reads = ShaderRecompiler::ThreadOwned(readsSlot); - if (!sharedOnly) guestMemory.InPlaceReads(reads); + if (!readsInPlace && !sharedOnly) guestMemory.InPlaceReads(reads); const auto maxSnapshotBytes = maxDrawSnapshotBytes; const auto uploadLimit = DrawUploadLimit(); std::size_t totalSnapshotBytes = 0; @@ -7146,6 +7501,21 @@ std::shared_ptr ShaderResources::PrepareDrawBindi for (std::size_t index = 0; index < allocations.size(); ++index) { const auto& item = allocations[index]; const auto override = std::find_if(moved.begin(), moved.end(), [&](const MovedBuffer& entry) { return entry.allocation == index; }); + if (override != moved.end() && override->words.empty()) result->movedReads.emplace_back(override->address, override->address + override->size); + if (override != moved.end() && override->words.empty() && (readsInPlace || override->heapInPlace)) { + if (!readsInPlace || override->view.address != 0) movedBehindGpuWrites.fetch_add(1, std::memory_order_relaxed); + if (override->view.address != 0) { + inPlace.push_back({index, override->view}); + continue; + } + std::uint32_t adjustment = 0; + VkDeviceAddress handle = 0; + const auto info = wholeDwordRange(guestMemory.Descriptor(override->address, override->size, adjustment, &handle)); + Require(handle != 0, "a moved buffer read in place has no device address"); + inPlace.push_back({index, {handle + info.offset, info.range}}); + Require(adjustment == item.adjustment, "a moved buffer read in place lost its view's alignment"); + continue; + } const bool words = override != moved.end() && !override->words.empty(); const bool offsets = inPlaceData && !item.guest && item.buffer != nullptr && std::any_of(moved.begin(), moved.end(), [&](const MovedBuffer& entry) { return toldInData(entry, index); }); if (words || (offsets && override == moved.end())) { @@ -7230,13 +7600,15 @@ std::shared_ptr ShaderResources::PrepareDrawBindi if (GuestMemory::TrackerGeneration() != stamp[0]) stamped = false; else if (!uploaded || stamp[1] != 0) recorder.NoteUnwrittenDrawSnapshot(begin, bytes, stamp, buffer, offset); } + drawInputCopies.fetch_add(1, std::memory_order_relaxed); selected.push_back(index); keep({begin, std::move(buffer), offset, bytes}); totalSnapshotBytes += bytes; CaptureTrace::Log("draw-snapshot batch=%llu address=%llx bytes=%zu", static_cast(recorder.Submissions() + 1), static_cast(begin), bytes); } - if (selected.empty() && !rebound) return {}; - writeDrawSets(*result, selected, faultRecord); + if (selected.empty() && inPlace.empty() && !rebound) return {}; + Require(inPlace.empty() || addressedBuffers, "a moved buffer read in place has no addressed binding"); + writeDrawSets(*result, selected, faultRecord, inPlace); recorder.Keep(result); for (const auto& snapshot : result->snapshots) { if (snapshot.buffer != nullptr) recorder.KeepBytes(snapshot.buffer.get(), snapshot.buffer->Bytes().size()); @@ -7244,13 +7616,46 @@ std::shared_ptr ShaderResources::PrepareDrawBindi return result; } -void ShaderResources::writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord) const { +void ShaderResources::writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace) const { + if (!heapStage) writeRewrittenSets(result, selected, faultRecord); + if (addressedBuffers) { + auto& overrides = result.addressOverrides; + overrides.clear(); + overrides.reserve(selected.size() + inPlace.size()); + for (std::size_t index = 0; index < selected.size(); ++index) { + const auto& snapshot = result.snapshots[index]; + overrides.push_back({selected[index], {snapshot.buffer->DeviceAddress() + snapshot.offset, snapshot.bytes}}); + } + for (const auto& [index, range] : inPlace) overrides.push_back({index, range}); + for (std::size_t next = 1; next < overrides.size(); ++next) { + for (auto at = next; at > 0 && overrides[at - 1].first > overrides[at].first; --at) std::swap(overrides[at - 1], overrides[at]); + } + const auto last = std::unique(overrides.rbegin(), overrides.rend(), [](const auto& a, const auto& b) { return a.first == b.first; }); + overrides.erase(overrides.begin(), last.base()); + bool overridden = false; + for (const auto& [index, range] : overrides) overridden = overridden || (index < addressedAllocations.size() && addressedAllocations[index] && range.address != 0); + if (overridden) { + result.heapOffsets = heapOffsets; + result.addressOffsets = true; + } else { + overrides.clear(); + } + } +} + +const VkDeviceAddressRangeEXT* ShaderResources::DrawBindings::AddressOverride(std::size_t allocation) const { + const auto entry = std::lower_bound(addressOverrides.begin(), addressOverrides.end(), allocation, [](const auto& item, std::size_t index) { return item.first < index; }); + return entry != addressOverrides.end() && entry->first == allocation ? &entry->second : nullptr; +} + +void ShaderResources::writeRewrittenSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord) const { Require(context.descriptorCache != nullptr, "draw snapshots require a descriptor cache"); std::array described{}; thread_local std::array, 2>* countsSlot = nullptr; auto& counts = ShaderRecompiler::ThreadOwned(countsSlot); for (auto& sizes : counts) sizes.clear(); for (const auto& binding : bindings) { + if (binding.heap) continue; const auto set = setOf(binding); described[set] = true; const auto count = (binding.flags & VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT) != 0 ? std::max(1u, static_cast(binding.imageAllocations.size())) : binding.layout.descriptorCount; @@ -7269,7 +7674,7 @@ void ShaderResources::writeDrawSets(DrawBindings& result, std::spanAllocateRewritten(fragment.layout, sizesOf(1), updateAfterBind, variableOf(1)); result.fragmentLayout = fragment.layout; Require(result.fragmentAllocation.set != VK_NULL_HANDLE, "draw snapshot descriptor allocation failed"); @@ -7289,6 +7694,7 @@ void ShaderResources::writeDrawSets(DrawBindings& result, std::spandstBinding == binding.layout.binding && nextWrite->dstSet == original) { auto& write = *nextWrite++; @@ -7339,8 +7745,21 @@ void ShaderResources::BindDrawUse(VkCommandBuffer commands, VkPipelineLayout lay requireGuestBuffers(); const auto set = use->bindings->allocation.set; const auto fragmentSet = use->bindings->fragmentAllocation.set; - if (set != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &set, 0, nullptr); - if (fragmentSet != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, 0, nullptr); + if (set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &set, SetBindSite::Draw); + if (fragmentSet != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, SetBindSite::Draw); +} + +namespace { + +std::size_t DataOffsetIndex(std::size_t stage, ShaderRecompiler::RuntimeAbi::Binding binding) { + Require(binding == ShaderRecompiler::RuntimeAbi::Binding::ShaderData || binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt || binding == ShaderRecompiler::RuntimeAbi::Binding::UserData, "only shader data and the flattened SRT have ring offsets"); + return stage * 3u + (binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt ? 1u : binding == ShaderRecompiler::RuntimeAbi::Binding::UserData ? 2u : 0u); +} + +} + +void ShaderResources::RefreshMovedAddresses(DrawBindings& rewritten) const { + if (rewritten.addressOffsets) rewritten.heapOffsets = heapOffsets; } void ShaderResources::prepareFaultSlot() const { @@ -7373,11 +7792,966 @@ void ShaderResources::requireGuestBuffers(std::span moved) co } } +void ShaderResources::BindDescriptorHeaps(VkCommandBuffer commands, bool guestBuffersChecked) const { + if (!guestBuffersChecked) requireGuestBuffers(); + prepareFaultSlot(); + BindlessHeap::For(context).BindDescriptorHeaps(commands); +} + void ShaderResources::Bind(VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout) const { requireGuestBuffers(); prepareFaultSlot(); - if (_set != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, 0, 1, &_set, 0, nullptr); - if (fragment.set != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragment.set, 0, nullptr); + if (_set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, bindPoint, layout, 0, 1, &_set, bindPoint == VK_PIPELINE_BIND_POINT_COMPUTE ? SetBindSite::Dispatch : SetBindSite::Draw); + if (fragment.set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, bindPoint, layout, ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragment.set, bindPoint == VK_PIPELINE_BIND_POINT_COMPUTE ? SetBindSite::Dispatch : SetBindSite::Draw); +} + +PipelineSetLayouts ShaderResources::SetLayouts() const { + if (!heapStage) return {_layout, fragment.layout, splitSets, layoutKey, fragmentLayoutKey}; + return {_layout, VK_NULL_HANDLE, true, layoutKey, fragmentLayoutKey}; +} + +void ShaderResources::RefreshHeapStage(std::span shaders) { + resolveBufferAddresses(); + BindlessHeap* heap = nullptr; + std::optional spans; + for (const auto& shader : shaders) { + if (!HeapShader(shader)) continue; + if (!spans) { + heap = &BindlessHeap::For(context); + spans.emplace(*heap); + } + writeHeapStage(*spans, *heap, shader); + } +} + +VkDeviceAddressRangeEXT ShaderResources::bufferAddress(const Allocation& allocation) const { + auto adjustment = allocation.adjustment; + if (allocation.guest) { + VkDeviceAddress handle = 0; + const auto info = wholeDwordRange(guestMemory.Descriptor(allocation.address, allocation.size, adjustment, &handle)); + Require(handle != 0, "an addressed guest buffer has no device address"); + return {handle + info.offset, info.range}; + } + if (allocation.role == ShaderRecompiler::DescriptorRole::BdaPagetable || allocation.role == ShaderRecompiler::DescriptorRole::FaultBuffer) { + Require(bda != nullptr, "BDA descriptors have no memory owner"); + if (allocation.role == ShaderRecompiler::DescriptorRole::BdaPagetable) return {bda->TableAddress(), bda->Table().range}; + return {bda->FaultAddress(), bda->Fault().range}; + } + if (allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.buffer != nullptr) return {allocation.buffer->DeviceAddress(), allocation.size}; + auto info = descriptor(allocation, adjustment); + if (info.buffer == VK_NULL_HANDLE) info = {context.emptyBuffer, 0, EmptyBufferBytes}; + const auto base = BufferDeviceAddress(context, info.buffer); + Require(base != 0, "an addressed buffer has no device address"); + return {base + info.offset, info.range}; +} + +void ShaderResources::resolveBufferAddresses() { + if (!resolvedAddresses.empty()) return; + if (emptyAddress == 0) emptyAddress = BufferDeviceAddress(context, context.emptyBuffer); + if (gdsAllocation != std::numeric_limits::max() && resolvedGds == 0) resolvedGds = bufferAddress(allocations[gdsAllocation]).address; + if (!addressedBuffers) return; + resolvedAddresses.assign(allocations.size(), {}); + for (const auto& binding : bindings) { + if (!binding.addressed) continue; + for (const auto index : binding.allocations) { + const auto& allocation = allocations[index]; + if (allocation.guest || allocation.role == ShaderRecompiler::DescriptorRole::GuestBuffers) resolvedAddresses[index] = bufferAddress(allocation); + } + } +} + +VkDeviceAddressRangeEXT ShaderResources::bufferRange(std::uint32_t index, const DrawBindings* overrides) const { + const bool verify = ShaderRecompiler::HeapVerifyEnabled(); + const auto& allocation = allocations[index]; + const auto* override = overrides != nullptr ? overrides->AddressOverride(index) : nullptr; + const bool overridden = override != nullptr && override->address != 0; + const bool owned = !overridden && !allocation.guest && allocation.buffer != nullptr && allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.role != ShaderRecompiler::DescriptorRole::BdaPagetable && allocation.role != ShaderRecompiler::DescriptorRole::FaultBuffer; + const bool resolved = !overridden && index < resolvedAddresses.size() && resolvedAddresses[index].address != 0; + VkDeviceAddress address = 0; + VkDeviceSize range = 0; + if (owned) { + address = allocation.buffer->DeviceAddress(); + range = allocation.size; + } else if (resolved) { + address = resolvedAddresses[index].address; + range = resolvedAddresses[index].size; + if (verify) { + const auto fresh = bufferAddress(allocation); + if (fresh.address != address || fresh.size != range) throw std::runtime_error("AGC graphics: a GPU heap buffer address resolved when the draw's resources were built changed"); + } + } else if (overridden) { + address = override->address; + range = override->size; + } else { + const auto fresh = bufferAddress(allocation); + address = fresh.address; + range = fresh.size; + } + return {address, std::min(range, context.limits.maxStorageBufferRange)}; +} + +std::pair ShaderResources::shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const { + if (!heapStage || !HeapShader(shader)) return {shaderDataBuffer(shader), 0}; + const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; + return BindlessHeap::For(context).DataLocation(offsets[DataOffsetIndex(HeapStageIndex(shader.stage), ShaderRecompiler::RuntimeAbi::Binding::ShaderData)]); +} + +bool ShaderResources::pushImageMatches(std::span shaders, std::span placements) const { + const auto& image = pushImage; + return image.valid && image.count == shaders.size() && shaders.size() <= image.programs.size() && + std::equal(shaders.begin(), shaders.end(), image.programs.begin(), [](const CompiledShader& shader, const ShaderRecompiler::RecompileResult* program) { return shader.program == program; }) && + std::ranges::equal(placements, image.placements); +} + +void ShaderResources::resetPushImage(std::span shaders, std::span placements) const { + namespace Abi = ShaderRecompiler::RuntimeAbi; + auto& image = pushImage; + image.bytes.fill(std::byte{0}); + image.mask = 0; + image.programs.fill(nullptr); + image.stages.fill({}); + image.valid = shaders.size() <= image.programs.size(); + image.count = shaders.size(); + image.placements.assign(placements.begin(), placements.end()); + for (std::size_t index = 0; index < shaders.size() && index < image.programs.size(); ++index) image.programs[index] = shaders[index].program; + const auto own = [&](std::uint32_t position, std::uint32_t width) { + if (position == Abi::NoPushPosition) return; + for (auto dword = position; dword < position + width && dword < Abi::PushDataDwords; ++dword) image.mask |= std::uint64_t{1} << dword; + }; + for (std::size_t index = 0; index < shaders.size(); ++index) { + const auto& placement = placements[index]; + const bool rootedStage = shaders[index].program != nullptr && shaders[index].program->dataAddressPush; + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + const auto kind = static_cast(item); + const bool global = kind == Abi::RootItem::PagetableAddress || kind == Abi::RootItem::FaultAddress || kind == Abi::RootItem::GdsAddress; + if (global || rootedStage) own(placement.items[item], Abi::RootAddressItem(kind) ? 2u : 1u); + } + if (!rootedStage) continue; + own(placement.pushed.count != 0u ? placement.pushed.base : Abi::NoPushPosition, placement.pushed.count); + for (std::uint32_t buffer = 0; buffer < std::min(placement.pushedBuffers, Abi::PushedBufferLimit); ++buffer) own(placement.bufferRoots[buffer], Abi::PushedBufferWords); + own(placement.bufferOverflow, 2u); + } +} + +void ShaderResources::writeDataRoots(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten, bool cached) const { + namespace Abi = ShaderRecompiler::RuntimeAbi; + if (!heapStage) return; + const bool addressed = rewritten != nullptr && rewritten->addressOffsets; + const auto& offsets = addressed ? rewritten->heapOffsets : heapOffsets; + Require(placements.size() == shaders.size(), "the push layout does not describe the draw's stages"); + std::optional gds; + const auto gdsAddress = [&] { + if (gds) return *gds; + gds = VkDeviceAddress{0}; + if (gdsAllocation == std::numeric_limits::max()) return *gds; + const auto* override = rewritten != nullptr && rewritten->addressOffsets ? rewritten->AddressOverride(gdsAllocation) : nullptr; + const bool overridden = override != nullptr && override->address != 0; + gds = overridden ? override->address : resolvedGds; + Require(*gds != 0, "the GDS buffer has no device address"); + const bool verify = ShaderRecompiler::HeapVerifyEnabled(); + if (verify && !overridden && bufferAddress(allocations[gdsAllocation]).address != *gds) throw std::runtime_error("AGC graphics: the GDS address resolved when the draw's resources were built changed"); + return *gds; + }; + auto& image = pushImage; + if (cached) { + if (!pushImageMatches(shaders, placements)) resetPushImage(shaders, placements); + if (!image.valid) cached = false; + } + VkDeviceAddress table = 0; + VkDeviceAddress fault = 0; + if (bda != nullptr && (dataTableBound || dataFaultBound)) { + if (dataTableBound) table = bda->TableAddress(); + if (dataFaultBound) fault = bda->FaultAddress(); + } + const auto target = cached ? std::span(image.bytes) : bytes; + bool rooted = false; + for (std::size_t index = 0; index < shaders.size(); ++index) { + const auto& shader = shaders[index]; + const auto& placement = placements[index]; + const auto put = [&](Abi::RootItem item, std::uint32_t word, std::uint32_t value) { + const auto position = placement.Item(item); + if (position == Abi::NoPushPosition) return; + Require((position + word + 1u) * sizeof(std::uint32_t) <= target.size(), "a root item lies outside the push data"); + std::memcpy(target.data() + (position + word) * sizeof(std::uint32_t), &value, sizeof(value)); + }; + const auto putAddress = [&](Abi::RootItem item, VkDeviceAddress address) { + put(item, 0u, static_cast(address)); + put(item, 1u, static_cast(address >> 32u)); + }; + putAddress(Abi::RootItem::PagetableAddress, table); + putAddress(Abi::RootItem::FaultAddress, fault); + if (placement.Item(Abi::RootItem::GdsAddress) != Abi::NoPushPosition) putAddress(Abi::RootItem::GdsAddress, gdsAddress()); + if (shader.program == nullptr || !shader.program->dataAddressPush) continue; + rooted = true; + const auto stage = HeapStageIndex(shader.stage); + const auto data = offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]; + const std::array addresses{data, offsets[DataOffsetIndex(stage, Abi::Binding::UserData)], offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)], heapTableMapSet[stage] ? heapTableMaps[stage] : data}; + if (cached) { + auto& kept = image.stages[index]; + if (!kept.live && kept.version == heapStages[stage].pushVersion && kept.addresses == addresses) continue; + kept.version = heapStages[stage].pushVersion; + kept.addresses = addresses; + kept.live = false; + } + putAddress(Abi::RootItem::ShaderData, addresses[0]); + putAddress(Abi::RootItem::UserData, addresses[1]); + putAddress(Abi::RootItem::SrtAddress, addresses[2]); + putAddress(Abi::RootItem::TableMap, addresses[3]); + writePushedData(target, shader, placement.pushed); + const bool live = shader.program->pushedBufferCount != 0u; + if (live) writePushedBuffers(target, stage, placement, addressed ? rewritten : nullptr, data); + if (cached) image.stages[index].live = live; + } + if (cached) { + for (auto mask = image.mask; mask != 0u; mask &= mask - 1u) { + const auto dword = static_cast(std::countr_zero(mask)); + std::memcpy(bytes.data() + dword * sizeof(std::uint32_t), image.bytes.data() + dword * sizeof(std::uint32_t), sizeof(std::uint32_t)); + } + } + if (rooted) NoteDataAddressPush(); +} + +void ShaderResources::PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const { + if (!heapStage) return; + const bool verify = ShaderRecompiler::HeapVerifyEnabled(); + const bool addressed = rewritten != nullptr && rewritten->addressOffsets; + if (addressed) { + pushImage.valid = false; + writeDataRoots(bytes, shaders, placements, rewritten, false); + return; + } + if (!verify) { + writeDataRoots(bytes, shaders, placements, rewritten, ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::PushImage)); + return; + } + std::array reference; + std::copy(bytes.begin(), bytes.end(), reference.begin()); + writeDataRoots(reference, shaders, placements, rewritten, false); + writeDataRoots(bytes, shaders, placements, rewritten, true); + std::uint64_t fresh = 0; + for (const auto& placement : placements) { + if (placement.bufferOverflow != ShaderRecompiler::RuntimeAbi::NoPushPosition) fresh |= std::uint64_t{3} << placement.bufferOverflow; + } + for (std::size_t dword = 0; dword < ShaderRecompiler::RuntimeAbi::PushDataDwords; ++dword) { + if ((fresh >> dword & 1u) != 0u) continue; + if (std::memcmp(reference.data() + dword * sizeof(std::uint32_t), bytes.data() + dword * sizeof(std::uint32_t), sizeof(std::uint32_t)) != 0) + throw std::runtime_error("AGC graphics: a GPU heap draw's cached push data differs from the push data written in full"); + } +} + +void ShaderResources::writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const DrawBindings* overrides, VkDeviceAddress empty) const { + namespace Abi = ShaderRecompiler::RuntimeAbi; + const auto uniformAlignment = UniformConstantBuffersEnabled() ? context.limits.minUniformBufferOffsetAlignment : VkDeviceSize{1}; + const auto clampedSize = [](const VkDeviceAddressRangeEXT& range) { + return static_cast(std::min(range.size, 0xffffffffu)); + }; + const auto record = [&](VkDeviceAddress address, std::uint32_t size) { + Require((address & (uniformAlignment - 1u)) == 0u, "a pushed buffer address is off the uniform buffer offset alignment"); + return std::array{static_cast(address), static_cast(address >> 32u), size, 0u}; + }; + const auto encode = [&](const VkDeviceAddressRangeEXT& range) { + const auto size = clampedSize(range); + const auto address = size != 0u && range.address != 0u ? range.address : empty; + return record(address, address == empty ? 0u : size); + }; + static const std::vector none; + const auto& elements = stage < addressedElements.size() ? addressedElements[stage] : none; + Require(elements.size() == placement.pushedBuffers, "a stage's buffer addresses do not match its push layout's buffer count"); + heapPushedStages.store(heapPushedStages.load(std::memory_order_relaxed) + 1u, std::memory_order_relaxed); + Require(empty != 0u, "a stage with pushed buffers has no shader data to stand in for an empty buffer"); + const auto put = [&](std::uint32_t position, std::span words) { + Require(position != Abi::NoPushPosition && (position + words.size()) * sizeof(std::uint32_t) <= bytes.size(), "a stage's pushed buffer words lie outside the push data"); + std::memcpy(bytes.data() + position * sizeof(std::uint32_t), words.data(), words.size_bytes()); + }; + const auto rootOf = [&](std::size_t index) { return index < Abi::PushedBufferLimit ? placement.bufferRoots[index] : Abi::NoPushPosition; }; + bool overflowed = false; + for (std::size_t index = 0; index < elements.size() && !overflowed; ++index) overflowed = rootOf(index) == Abi::NoPushPosition; + BindlessHeap::DataSpan overflow{}; + if (overflowed) { + heapOverflowStages.fetch_add(1, std::memory_order_relaxed); + overflow = BindlessHeap::For(context).Allocate(elements.size() * Abi::OverflowRecordWords); + } + for (std::size_t index = 0; index < elements.size(); ++index) { + const auto words = encode(bufferRange(elements[index], overrides)); + if (const auto root = rootOf(index); root != Abi::NoPushPosition) put(root, std::span(words).first(Abi::PushedBufferWords)); + if (overflowed) std::copy(words.begin(), words.end(), overflow.words.begin() + static_cast(index * Abi::OverflowRecordWords)); + } + if (!overflowed) return; + const std::array address{static_cast(overflow.address), static_cast(overflow.address >> 32u)}; + put(placement.bufferOverflow, address); +} + +void ShaderResources::writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const { + const auto& program = *shader.program; + if (placement.count == 0u) return; + const auto& stageState = heapStages[HeapStageIndex(shader.stage)]; + const auto& words = stageState.data.words; + Require(stageState.pushedUserWords == 0u || placement.count >= stageState.pushedPlaced, "a stage's shader data was kept for user data its pipeline does not push"); + Require(placement.count <= program.pushedData.size() && (placement.base + placement.count) * sizeof(std::uint32_t) <= bytes.size(), "a stage's pushed shader data does not fit"); + if (placement.count == stageState.pushedPlaced && (stageState.userWords == 0u || stageState.userWords == stageState.pushRunUserWords)) { + const auto& runs = stageState.userWords == 0u ? stageState.wholePushRuns : stageState.splitPushRuns; + for (const auto& run : runs) { + const auto& source = run.user ? stageState.user.words : words; + Require(run.dword + run.count <= source.size(), "a pushed shader-data dword lies outside the stage's shader data"); + std::memcpy(bytes.data() + (placement.base + run.index) * sizeof(std::uint32_t), source.data() + run.dword, run.count * sizeof(std::uint32_t)); + } + return; + } + for (std::uint32_t index = 0; index < placement.count; ++index) { + const auto dword = program.pushedData[index]; + const bool user = dword < stageState.userWords; + const auto& source = user ? stageState.user.words : words; + Require(dword < source.size(), "a pushed shader-data dword lies outside the stage's shader data"); + std::memcpy(bytes.data() + (placement.base + index) * sizeof(std::uint32_t), &source[dword], sizeof(std::uint32_t)); + } +} + +VkImageView ShaderResources::heapPlaceholderView(std::uint32_t kind) const { + return context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(kind); +} + +void ShaderResources::buildHeapTableMap(std::vector& map, BindlessHeap& heap, const CompiledShader& shader, const TableStage& table, HeapStageState& stageState) { + constexpr auto noElement = std::numeric_limits::max(); + namespace Abi = ShaderRecompiler::RuntimeAbi; + namespace TableAbi = ShaderRecompiler::ImageTableAbi; + const auto image = [&](std::uint32_t slot) { + stageState.mapImages.slots.push_back(slot); + return slot; + }; + const ShaderRecompiler::DescriptorBinding* images = nullptr; + for (const auto& binding : shader.program->bindings) { + if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable) + images = &binding; + } + const auto elements = images != nullptr ? static_cast(images->count) : std::size_t{0}; + const auto base = static_cast(map.size()); + map[TableAbi::HeaderElementBase] = base; + const auto sampledAbsent = image(heap.AbsentSlot(Abi::FirstImageBinding, heapPlaceholderView(Abi::FirstImageBinding))); + const auto storageAbsent = image(heap.AbsentSlot(Abi::FirstStorageImageBinding, heapPlaceholderView(Abi::FirstStorageImageBinding))); + for (std::size_t element = 0; element < elements; ++element) { + const auto index = element < table.elementTextures.size() ? table.elementTextures[element] : noElement; + if (index == noElement) { + map.push_back(sampledAbsent); + continue; + } + const auto view = textureFirstLayer[index] ? textures[index]->FirstLayerView() : arrayViewTextures.contains(index) ? textures[index]->ArrayView() : textures[index]->View(); + map.push_back(image(takenSlot(heap.TextureSlot(Abi::FirstImageBinding, textures[index].get(), view, textures[index]->Layout()), "the global image heap is full"))); + } + const auto appendStorageSlots = [&](std::uint32_t kind, std::uint32_t absent, const char* full, const auto& wanted, const auto& viewOf) { + for (std::size_t element = 0; element < elements; ++element) { + const auto index = element < table.elementStorage.size() ? table.elementStorage[element] : noElement; + if (!wanted(element) || index == noElement || storageTextures[index] == nullptr) { + map.push_back(absent); + continue; + } + map.push_back(image(takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), viewOf(*storageTextures[index], index)), full))); + } + }; + appendStorageSlots( + Abi::FirstStorageImageBinding, storageAbsent, "the global storage image heap is full", [](std::size_t) { return true; }, + [&](StorageTexture& image, std::size_t index) { return image.StorageView(storageMips[index], storageFirstLayer[index]); }); + const auto samplerSlotOf = [&](std::size_t index) { + const auto slot = takenSlot(heap.SamplerSlot(samplers[index]), "the global sampler heap is full"); + stageState.mapSamplers.slots.push_back(slot); + return slot; + }; + const auto firstSampler = std::find_if(table.tableSamplers.begin(), table.tableSamplers.end(), [&](const auto index) { return index != noElement; }); + const std::uint32_t fallbackSampler = firstSampler != table.tableSamplers.end() ? samplerSlotOf(*firstSampler) : 0u; + for (const auto index : table.tableSamplers) map.push_back(index == noElement ? fallbackSampler : samplerSlotOf(index)); + const auto atomicElement = [&](std::size_t element, bool wide) { + if (images == nullptr) return false; + const auto& flags = wide ? images->imageAtomic64 : images->imageAtomic; + return element < flags.size() && flags[element]; + }; + const auto anyAtomic = [&](bool wide) { + for (std::size_t element = 0; element < elements; ++element) { + if (atomicElement(element, wide)) return true; + } + return false; + }; + const auto samplerSpan = std::max(elements, map[TableAbi::HeaderSamplerCount]); + Require(table.tableSamplers.size() <= samplerSpan, "an image table map has more table samplers than its header counts"); + const auto extraBase = base + 2u * elements + samplerSpan; + if (anyAtomic(false) || anyAtomic(true)) { + map.resize(extraBase, fallbackSampler); + for (const bool wide : {false, true}) { + const auto kind = wide ? Abi::FirstAtomic64ImageBinding : Abi::FirstAtomicImageBinding; + appendStorageSlots( + kind, image(heap.AbsentSlot(kind, heapPlaceholderView(kind))), "the global atomic image heap is full", + [&](std::size_t element) { return atomicElement(element, wide); }, + [&](StorageTexture& image, std::size_t index) { + return wide ? image.Atomic64View(storageMips[index], storageFirstLayer[index]) + : image.AtomicView(storageMips[index], storageFirstLayer[index]); + }); + } + } + const bool storageTable = std::ranges::any_of(shader.program->bindings, [](const ShaderRecompiler::DescriptorBinding& binding) { + return binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable; + }); + if (storageTable) { + map.resize(extraBase + 2u * elements, fallbackSampler); + const auto kind = Abi::FirstUintStorageImageBinding; + appendStorageSlots( + kind, image(heap.AbsentSlot(kind, heapPlaceholderView(kind))), "the global storage image heap is full", [](std::size_t) { return true; }, + [&](StorageTexture& image, std::size_t index) { return image.UintStorageViewOrDefault(storageMips[index], storageFirstLayer[index]); }); + } + if (map.size() == base) map.push_back(sampledAbsent); +} + +void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, std::size_t stageIndex) { + constexpr auto noElement = std::numeric_limits::max(); + heapTableMapSet[stageIndex] = false; + const auto table = std::find_if(tableStages.begin(), tableStages.end(), + [&](const TableStage& candidate) { return candidate.stage == shader.stage && candidate.heap; }); + if (table == tableStages.end() || table->mapAllocation == noElement) return; + const bool verifyMap = ShaderRecompiler::HeapVerifyEnabled(); + auto& stageState = heapStages[stageIndex]; + const bool mapCurrent = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::TableMap) && stageState.mapBuilt && stageState.map.table.address != 0u && + HeapStageState::SlotSet::Current(heap, stageState.mapImages, stageState.mapSamplers); + if (mapCurrent && !verifyMap) { + stageState.mapTouched = HeapStageState::SlotSet::Touch(heap, stageState.mapImages, stageState.mapSamplers, stageState.mapTouched); + heap.NoteTableKept(spans); + heapTableMaps[stageIndex] = stageState.map.table.address; + heapTableMapSet[stageIndex] = true; + return; + } + stageState.mapBuilt = false; + stageState.mapImages.slots.clear(); + stageState.mapSamplers.slots.clear(); + struct MapStorage {}; + auto& map = HostThreadLocal, MapStorage>(); + map.assign(table->map.begin(), table->map.end()); + buildHeapTableMap(map, heap, shader, *table, stageState); + if (mapCurrent && !std::ranges::equal(stageState.map.words, map)) throw std::runtime_error("AGC graphics: a GPU heap stage's image table map changed although its slots did not"); + heapTableMaps[stageIndex] = heapSpan(spans, heap, stageState.map, map); + heapTableMapSet[stageIndex] = true; + stageState.mapImages.CaptureImageGenerations(heap); + stageState.mapSamplers.CaptureSamplerGenerations(heap); + stageState.mapBuilt = true; +} + +std::uint64_t ShaderResources::heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words) { + if (kept.table.address != 0u && ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::StageData) && std::ranges::equal(kept.words, words)) { + heap.NoteTableKept(spans); + return kept.table.address; + } + return heapTable(spans, heap, kept, words); +} + +std::uint64_t ShaderResources::heapTable(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words) { + heap.RetireTable(spans, kept.table); + const auto span = heap.AllocateTable(spans, words.size(), kept.table); + BindlessHeap::Write(*span, words); + kept.words.assign(words.begin(), words.end()); + return span->address; +} + +bool ShaderResources::keptTable(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept) { + if (kept.table.address == 0u) return false; + heap.NoteTableKept(spans); + return true; +} + +void ShaderResources::retireHeapTables() noexcept { + try { + auto* heap = BindlessHeap::Existing(context); + if (heap == nullptr) return; + BindlessHeap::SpanScope spans(*heap); + for (auto& stage : heapStages) { + heap->RetireTable(spans, stage.data.table); + heap->RetireTable(spans, stage.flat.table); + heap->RetireTable(spans, stage.map.table); + } + } catch (...) { + } +} + +bool ShaderResources::ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const { + return binding.heap && (binding.layout.stageFlags & stageBit) != 0u; +} + +VkImageView ShaderResources::heapSampledView(std::size_t index) const { + const auto& texture = textures[index]; + if (textureSrgb[index]) return texture->SrgbView(textureFirstLayer[index], textureBaseLevel[index]); + if (textureBaseLevel[index]) return texture->BaseLevelView(); + if (textureFirstLayer[index]) return texture->FirstLayerView(); + if (arrayViewTextures.contains(index)) return texture->ArrayView(); + return texture->View(); +} + +VkImageView ShaderResources::heapMultisampleStorageView(std::size_t index) const { + return index < multisampleStorage.size() ? multisampleStorage[index].view : VK_NULL_HANDLE; +} + +const HeapSlotOwner* ShaderResources::heapMultisampleStorageOwner(std::size_t index) const { + return index < multisampleStorage.size() ? multisampleStorage[index].owner : nullptr; +} + +VkImageView ShaderResources::heapStorageView(std::size_t index, std::uint32_t binding) const { + const auto& texture = storageTextures[index]; + if (storageAtomic64[index]) return texture->Atomic64View(storageMips[index], storageFirstLayer[index]); + if (storageAtomic[index]) return texture->AtomicView(storageMips[index], storageFirstLayer[index]); + return texture->StorageView(storageMips[index], storageFirstLayer[index], UintStorageBinding(binding)); +} + +void ShaderResources::layOutStagePush(HeapStageState& state, const CompiledShader& shader, const ShaderRecompiler::StagePushPlacement& placement) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + const auto& program = *shader.program; + state.splitUser = (program.pushItems & Abi::RootItemBit(Abi::RootItem::UserData)) != 0u && placement.Item(Abi::RootItem::UserData) != Abi::NoPushPosition; + const auto placed = std::min(placement.pushed.count, program.pushedData.size()); + const auto userWords = std::max(program.heapUserWords.size(), program.shaderDataUserWords.size()); + for (std::size_t item = 0; item < placed; ++item) { + const auto dword = program.pushedData[item]; + if (dword < userWords && dword < 64u) state.pushedUserWords |= std::uint64_t{1} << dword; + } + state.pushedPlaced = static_cast(placed); + state.pushRunUserWords = static_cast(userWords); + const auto runsOf = [&](std::vector& runs, std::size_t split) { + for (std::size_t item = 0; item < placed; ++item) { + const auto dword = program.pushedData[item]; + const bool user = dword < split; + if (!runs.empty()) { + auto& run = runs.back(); + if (run.user == user && run.index + run.count == item && run.dword + run.count == dword) { + ++run.count; + continue; + } + } + runs.push_back({static_cast(item), dword, 1u, user}); + } + }; + runsOf(state.splitPushRuns, userWords); + runsOf(state.wholePushRuns, 0u); +} + +void ShaderResources::collectAddressedElements() { + for (auto& elements : addressedElements) elements.clear(); + addressedAllocations.assign(allocations.size(), 0); + for (const auto& binding : bindings) { + if (!binding.addressed) continue; + Require(binding.dataStage < addressedElements.size(), "an addressed buffer binding names no data stage"); + for (const auto index : binding.allocations) { + addressedElements[binding.dataStage].push_back(static_cast(index)); + addressedAllocations[index] = 1; + } + } +} + +void ShaderResources::layOutHeapStages(std::span shaders) { + const bool addressed = std::ranges::any_of(shaders, [&](const CompiledShader& shader) { return HeapShader(shader) && shader.program->dataAddressPush; }); + const auto placements = addressed ? PushDataPlacements(shaders) : std::vector{}; + for (std::size_t shaderIndex = 0; shaderIndex < shaders.size(); ++shaderIndex) { + const auto& shader = shaders[shaderIndex]; + if (!HeapShader(shader)) continue; + const VkShaderStageFlags stageBit = VulkanStage(shader.stage); + auto& state = heapStages[HeapStageIndex(shader.stage)]; + state.owned.clear(); + for (std::size_t index = 0; index < bindings.size(); ++index) { + if (ownsHeapBinding(bindings[index], stageBit)) state.owned.push_back(static_cast(index)); + } + state.laidOutFor = stageBit; + state.keyTaken = false; + state.mapBuilt = false; + ++state.pushVersion; + state.pushedUserWords = 0; + state.pushedPlaced = 0; + state.splitUser = false; + state.pushRunUserWords = 0; + state.splitPushRuns.clear(); + state.wholePushRuns.clear(); + if (placements.empty() || !shader.program->dataAddressPush) continue; + layOutStagePush(state, shader, placements[shaderIndex]); + } + collectAddressedElements(); +} + +ShaderResources::HeapElementClass ShaderResources::classifyHeapElement(const Binding& binding, std::size_t element) const { + if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) return HeapElementClass::Sampler; + const auto index = binding.imageAllocations[element]; + if (index == std::numeric_limits::max()) return HeapElementClass::Absent; + if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) return HeapElementClass::SampledImage; + if (storageTextures[index] != nullptr) return HeapElementClass::StorageImage; + return heapMultisampleStorageView(index) != VK_NULL_HANDLE ? HeapElementClass::MultisampleStorage : HeapElementClass::Absent; +} + +template +bool ShaderResources::forEachHeapElement(const Binding& binding, Visit&& visit) const { + const auto type = binding.layout.descriptorType; + if (type != VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE && type != VK_DESCRIPTOR_TYPE_STORAGE_IMAGE && type != VK_DESCRIPTOR_TYPE_SAMPLER) return true; + for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { + if (!visit(HeapElement{classifyHeapElement(binding, element), binding.imageAllocations[element], element})) return false; + } + return true; +} + +template +void ShaderResources::visitHeapSlotKey(std::span owned, Emit&& emit) const { + const auto put = [&](std::uintptr_t first, std::uintptr_t view, std::uintptr_t layout) { return emit(first) && emit(view) && emit(layout); }; + for (const auto bindingIndex : owned) { + const auto& binding = bindings[bindingIndex]; + const bool completed = forEachHeapElement(binding, [&](const HeapElement& item) { + switch (item.kind) { + case HeapElementClass::Absent: + return emit(0u); + case HeapElementClass::SampledImage: + return put(reinterpret_cast(textures[item.index].get()), reinterpret_cast(heapSampledView(item.index)), static_cast(textures[item.index]->Layout())); + case HeapElementClass::StorageImage: + return put(reinterpret_cast(storageTextures[item.index].get()), reinterpret_cast(heapStorageView(item.index, binding.layout.binding)), static_cast(VK_IMAGE_LAYOUT_GENERAL)); + case HeapElementClass::MultisampleStorage: + return put(reinterpret_cast(heapMultisampleStorageOwner(item.index)), reinterpret_cast(heapMultisampleStorageView(item.index)), static_cast(VK_IMAGE_LAYOUT_GENERAL)); + case HeapElementClass::Sampler: + return emit(reinterpret_cast(samplers[item.index].get())); + } + return true; + }); + if (!completed) return; + } +} + +void ShaderResources::appendHeapSlotKey(std::span owned, std::vector& key) const { + key.clear(); + visitHeapSlotKey(owned, [&](std::uintptr_t word) { + key.push_back(word); + return true; + }); +} + +bool ShaderResources::heapSlotKeySame(std::span owned, std::span key) const { + std::size_t cursor = 0; + bool same = true; + visitHeapSlotKey(owned, [&](std::uintptr_t word) { + same = cursor < key.size() && key[cursor] == word; + ++cursor; + return same; + }); + return same && cursor == key.size(); +} + +void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, std::span owned, + std::span key) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + struct TakenStorage {}; + auto& taken = HostThreadLocal>, TakenStorage>(); + taken.clear(); + state.samplers.slots.clear(); + std::size_t cursor = 0; + for (const auto bindingIndex : owned) { + const auto& binding = bindings[bindingIndex]; + const auto kind = binding.layout.binding % bindingCount; + forEachHeapElement(binding, [&](const HeapElement& item) { + const auto index = item.index; + const auto keyView = [&] { return reinterpret_cast(key[cursor + 1]); }; + switch (item.kind) { + case HeapElementClass::Absent: + taken.emplace_back(kind, heap.AbsentSlot(kind, heapPlaceholderView(kind))); + break; + case HeapElementClass::SampledImage: + taken.emplace_back(kind, takenSlot(heap.TextureSlot(kind, textures[index].get(), keyView(), textures[index]->Layout()), "the global image heap is full")); + break; + case HeapElementClass::StorageImage: + taken.emplace_back(kind, takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), keyView()), "the global storage image heap is full")); + break; + case HeapElementClass::MultisampleStorage: + taken.emplace_back(kind, takenSlot(heap.ViewSlot(kind, heapMultisampleStorageOwner(index), keyView()), "the global storage image heap is full")); + break; + case HeapElementClass::Sampler: { + const bool embedded = item.element < binding.embeddedSamplers.size() && binding.embeddedSamplers[item.element]; + state.samplers.slots.push_back(embedded ? ShaderRecompiler::RuntimeAbi::NoEmbeddedSampler : takenSlot(heap.SamplerSlot(samplers[index]), "the global sampler heap is full")); + break; + } + } + cursor += heapElementKeyWords(item.kind); + return true; + }); + } + std::stable_sort(taken.begin(), taken.end(), [](const auto& left, const auto& right) { return left.first < right.first; }); + state.images.slots.clear(); + state.kindRanges.clear(); + for (const auto& [kind, slot] : taken) { + if (state.kindRanges.empty() || state.kindRanges.back().kind != kind) + state.kindRanges.push_back({kind, static_cast(state.images.slots.size()), 0u}); + state.images.slots.push_back(slot); + ++state.kindRanges.back().count; + } +} + +void ShaderResources::verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const { + constexpr auto bindingCount = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); + static std::atomic checked{0}, wrong{0}, storageChecked{0}, storageWrong{0}; + const auto wrongBefore = wrong.load() + storageWrong.load(); + for (const auto& binding : bindings) { + if (!ownsHeapBinding(binding, stageBit)) continue; + const auto kind = binding.layout.binding % bindingCount; + const auto kindSlots = state.Slots(kind); + forEachHeapElement(binding, [&](const HeapElement& item) { + const bool bound = item.element < kindSlots.size(); + switch (item.kind) { + case HeapElementClass::Absent: + case HeapElementClass::Sampler: + break; + case HeapElementClass::SampledImage: + ++checked; + if (!bound || heap.SlotTexture(kind, kindSlots[item.element]) != textures[item.index].get()) ++wrong; + break; + case HeapElementClass::StorageImage: + ++storageChecked; + if (!bound || !heap.SlotHoldsStorage(kind, kindSlots[item.element], storageTextures[item.index].get(), heapStorageView(item.index, binding.layout.binding))) ++storageWrong; + break; + case HeapElementClass::MultisampleStorage: + ++storageChecked; + if (!bound || !heap.SlotHoldsStorage(kind, kindSlots[item.element], heapMultisampleStorageOwner(item.index), heapMultisampleStorageView(item.index))) ++storageWrong; + break; + } + return true; + }); + } + if ((checked.load() + storageChecked.load()) % 100000u < 8u) { + std::fprintf(stderr, "[heap-slots] verify: %llu image slots checked, %llu hold another texture; %llu storage slots checked, %llu hold another image or view\n", + static_cast(checked.load()), static_cast(wrong.load()), + static_cast(storageChecked.load()), static_cast(storageWrong.load())); + } + if (wrong.load() + storageWrong.load() != wrongBefore) throw std::runtime_error("AGC graphics: a GPU heap stage's slots hold another image, view or texture than its bindings"); +} + +namespace { + +[[noreturn]] void ThrowHeapSlotMismatch(const char* format, ...) { + char text[320]; + va_list arguments; + va_start(arguments, format); + std::vsnprintf(text, sizeof(text), format, arguments); + va_end(arguments); + throw std::runtime_error(text); +} + +} + +void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const HeapStageState& stageState, + std::vector& patched, bool current, bool leading) const { + namespace Abi = ShaderRecompiler::RuntimeAbi; + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + constexpr auto metadataWords = sizeof(Abi::ResourceMetadata) / sizeof(std::uint32_t); + const auto& program = *shader.program; + const auto& samplerSlots = stageState.samplers.slots; + Require(!leading || program.runtimeImageCount == 0u || program.imageMetadataDword >= patched.size(), "GPU-mode image metadata lies among a stage's user words"); + for (std::uint32_t image = 0; !leading && image < program.runtimeImageCount; ++image) { + const auto offset = program.imageMetadataDword + image * metadataWords; + const auto kind = patched[offset + offsetof(Abi::ResourceMetadata, binding) / 4u] % bindingCount; + const bool storageKind = kind >= Abi::FirstStorageImageBinding && kind < static_cast(Abi::Binding::Samplers); + const auto kindSlots = stageState.Slots(kind); + if (storageKind && (!Abi::GpuHeapStorageKind(kind) || kindSlots.empty())) continue; + auto& first = patched[offset + offsetof(Abi::ResourceMetadata, firstElement) / 4u]; + if (kind < Abi::FirstImageBinding) continue; + if (!(kind < bindingCount && first < kindSlots.size())) { + ThrowHeapSlotMismatch( + "AGC graphics: GPU-mode image metadata names an element the stage does not bind (stage %u, image %u of %u, kind %u, first %u, slots of the kind %zu, flags 0x%x, element count %u, bindings %zu, stage state reused %d)", + static_cast(shader.stage), image, program.runtimeImageCount, kind, first, + kindSlots.size(), patched[offset + offsetof(Abi::ResourceMetadata, flags) / 4u], + patched[offset + offsetof(Abi::ResourceMetadata, elementCount) / 4u], bindings.size(), current ? 1 : 0); + } + first = kindSlots[first]; + } + for (const auto& word : program.heapSlotWords) { + if (leading && word.dword >= patched.size()) continue; + Require(word.dword < patched.size(), "a GPU-mode slot word lies outside the shader data"); + if (word.kind == static_cast(Abi::Binding::Samplers)) { + if (word.element >= samplerSlots.size()) { + ThrowHeapSlotMismatch("AGC graphics: a GPU-mode slot word names a sampler the stage does not bind (stage %u, element %u, sampler slots %zu, bindings %zu)", + static_cast(shader.stage), word.element, samplerSlots.size(), bindings.size()); + } + patched[word.dword] = samplerSlots[word.element]; + continue; + } + const auto wordSlots = stageState.Slots(word.kind); + if (!(word.kind < bindingCount && word.element < wordSlots.size())) { + ThrowHeapSlotMismatch( + "AGC graphics: a GPU-mode slot word names an image the stage does not bind (stage %u, kind %u, element %u, slots of the kind %zu, bindings %zu)", + static_cast(shader.stage), word.kind, word.element, + wordSlots.size(), bindings.size()); + } + patched[word.dword] = wordSlots[word.element]; + } + const bool slotWords = !program.registrationModule; + if (leading) { + Require(slotWords || program.samplerSlotDword >= patched.size(), "GPU-mode sampler slots lie among a stage's user words"); + return; + } + Require(slotWords || program.samplerSlotDword + samplerSlots.size() <= patched.size(), "GPU-mode sampler slots exceed the shader data"); + if (!slotWords) std::copy(samplerSlots.begin(), samplerSlots.end(), patched.begin() + program.samplerSlotDword); +} + +namespace { + +std::vector& PatchedShaderData() { + struct PatchedStorage {}; + return HostThreadLocal, PatchedStorage>(); +} + +void ApplyUserData(std::vector& target, std::span userData, const std::vector>& patches) { + std::copy_n(userData.begin(), std::min(userData.size(), target.size()), target.begin()); + for (const auto& [byte, adjustment] : patches) { + if (byte < target.size() * sizeof(std::uint32_t)) reinterpret_cast(target.data())[byte] = static_cast(adjustment); + } +} + +} + +void ShaderResources::buildPatchedData(std::vector& patched, const CompiledShader& shader, const HeapStageState& stageState, std::span words, std::span userData, bool current) const { + ValidateRuntimeResources(shader, words); + patched.assign(words.begin(), words.end()); + for (const auto& [byte, adjustment] : stageState.dataPatches) { + Require(byte < patched.size() * sizeof(std::uint32_t), "a GPU-mode guest buffer offset lies outside the shader data"); + } + ApplyUserData(patched, userData, stageState.dataPatches); + patchHeapSlotWords(shader, stageState, patched, current); +} + +std::uint64_t ShaderResources::commitStageData(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, std::span patched, std::span words, std::span userData) { + const auto address = heapTable(spans, heap, stageState.data, patched); + ++stageState.pushVersion; + stageState.dataInput.assign(words.begin(), words.end()); + stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); + stageState.dataOrigin = shader.heap != nullptr ? shader.heap->dataOrigin : 0u; + stageState.dataProgram = shader.program; + return address; +} + +std::uint64_t ShaderResources::writeSplitUserData(BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, std::span words, std::span userData, std::size_t userWords, const std::vector& patched, bool current, std::uint64_t dataAddress) { + const bool verifySlots = ShaderRecompiler::HeapVerifyEnabled(); + const auto userFront = words.first(userWords); + auto& input = stageState.userInput; + const bool sameUserInput = current && stageState.userProgram == shader.program && stageState.user.words.size() == userWords && + input.size() == userWords + userData.size() && std::equal(userFront.begin(), userFront.end(), input.begin()) && + std::equal(userData.begin(), userData.end(), input.begin() + static_cast(userWords)); + struct UserStorage {}; + auto& built = HostThreadLocal, UserStorage>(); + if (!sameUserInput || verifySlots) { + built.assign(userFront.begin(), userFront.end()); + ApplyUserData(built, userData, stageState.dataPatches); + patchHeapSlotWords(shader, stageState, built, current, true); + if (verifySlots && !std::equal(built.begin(), built.end(), patched.begin())) + throw std::runtime_error("AGC graphics: a GPU-mode stage's user-data block differs from the user words of its full shader data"); + if (verifySlots && sameUserInput && !std::ranges::equal(built, stageState.user.words)) + throw std::runtime_error("AGC graphics: a GPU-mode stage's user-data block changed although its words, user data and slots did not"); + input.assign(userFront.begin(), userFront.end()); + input.insert(input.end(), userData.begin(), userData.end()); + stageState.userProgram = shader.program; + } + const auto& user = sameUserInput ? stageState.user.words : built; + const auto counted = std::min(userWords, 64u); + const auto userMask = counted == 64u ? ~std::uint64_t{0} : (std::uint64_t{1} << counted) - 1u; + const auto pushedUser = stageState.pushedUserWords & userMask; + const bool userChanged = !sameUserInput && !std::ranges::equal(stageState.user.words, user); + if (userChanged) ++stageState.pushVersion; + if (userWords <= 64u && pushedUser == userMask) { + if (stageState.user.words.size() == user.size() && userChanged) NotePushedUserDataKeep(); + if (userChanged) stageState.user.words.assign(user.begin(), user.end()); + return dataAddress; + } + if (userChanged) stageState.user.words.assign(user.begin(), user.end()); + const auto span = heap.Allocate(user.size()); + BindlessHeap::Write(span, user); + return span.address; +} + +std::pair ShaderResources::writeSplitHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, + std::span words, std::span userData, bool sameWalk, bool current) { + const bool verifySlots = ShaderRecompiler::HeapVerifyEnabled(); + const auto& program = *shader.program; + const auto userWords = std::min(std::max(program.heapUserWords.size(), program.shaderDataUserWords.size()), words.size()); + stageState.userWords = static_cast(userWords); + auto& patched = PatchedShaderData(); + const bool dataKept = sameWalk && !verifySlots && keptTable(spans, heap, stageState.data); + auto dataAddress = stageState.data.table.address; + if (!dataKept) { + buildPatchedData(patched, shader, stageState, words, userData, current); + if (verifySlots && sameWalk && stageState.data.words.size() == patched.size() && + !std::equal(patched.begin() + static_cast(userWords), patched.end(), stageState.data.words.begin() + static_cast(userWords))) + throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its walked words and slots did not"); + dataAddress = commitStageData(spans, heap, shader, stageState, patched, words, userData); + } + return {dataAddress, writeSplitUserData(heap, shader, stageState, words, userData, userWords, patched, current, dataAddress)}; +} + +bool ShaderResources::refreshHeapStageSlots(BindlessHeap& heap, HeapStageState& stageState, VkShaderStageFlags stageBit) { + const bool verifySlots = ShaderRecompiler::HeapVerifyEnabled(); + Require(stageState.laidOutFor == stageBit, "a GPU heap stage was refreshed for a stage its resources were not laid out for"); + const auto& owned = stageState.owned; + const bool keyed = stageState.keyTaken; + static const bool slotsBypassed = !ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::Slots); + bool current = !slotsBypassed && (keyed && !verifySlots ? true : heapSlotKeySame(owned, stageState.key)); + if (keyed && verifySlots && !slotsBypassed && !current) throw std::runtime_error("AGC graphics: a GPU heap stage's textures, views or samplers changed after its resources were built"); + const auto slotSerial = heap.SlotSerial(); + const bool unmoved = current && EpochProofs() && stageState.slotSerial == slotSerial; + if (!unmoved && current) current = HeapStageState::SlotSet::Current(heap, stageState.images, stageState.samplers); + if (!current) { + appendHeapSlotKey(owned, stageState.key); + takeHeapSlots(heap, stageState, owned, stageState.key); + stageState.images.CaptureImageGenerations(heap); + stageState.samplers.CaptureSamplerGenerations(heap); + stageState.keyTaken = true; + } else { + stageState.touchedEpoch = HeapStageState::SlotSet::Touch(heap, stageState.images, stageState.samplers, stageState.touchedEpoch); + } + stageState.slotSerial = slotSerial; + if (verifySlots) verifyHeapSlots(heap, stageState, stageBit); + return current; +} + +void ShaderResources::writeHeapDataBinding(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, const ShaderRecompiler::DescriptorBinding& binding, bool current) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + const auto stageIndex = HeapStageIndex(shader.stage); + auto& stageState = heapStages[stageIndex]; + const bool verifySlots = ShaderRecompiler::HeapVerifyEnabled(); + const std::size_t dataIndex = DataOffsetIndex(stageIndex, Abi::Binding::ShaderData); + const bool shaderData = binding.role == ShaderRecompiler::DescriptorRole::ShaderData; + const bool heapFlattened = !shaderData && shader.heap != nullptr && !shader.heap->flattenedSrt.empty(); + const auto& words = heapFlattened ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); + const auto userData = + shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; + const auto userFront = static_cast(std::min(userData.size(), words.size())); + const auto origin = shaderData && shader.heap != nullptr ? shader.heap->dataOrigin : 0u; + const bool sameShape = shaderData && current && ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::StageData) && stageState.dataInput.size() == words.size() + userData.size(); + const bool sameOrigin = sameShape && origin != 0u && origin == stageState.dataOrigin && stageState.dataProgram == shader.program; + const bool sameWords = sameShape && (sameOrigin || std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)); + if (verifySlots && sameOrigin && !std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)) + throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data differs from the data of the same origin"); + const bool sameInput = sameWords && std::equal(userData.begin(), userData.end(), stageState.dataInput.begin() + static_cast(words.size())); + if (shaderData && stageState.splitUser) { + const auto [dataAddress, userAddress] = writeSplitHeapStage(spans, heap, shader, stageState, words, userData, sameWords, current); + heapOffsets[dataIndex] = dataAddress; + heapOffsets[DataOffsetIndex(stageIndex, Abi::Binding::UserData)] = userAddress; + return; + } + if (sameInput && !verifySlots && keptTable(spans, heap, stageState.data)) { + heapOffsets[dataIndex] = stageState.data.table.address; + return; + } + if (!shaderData) { + heapOffsets[DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt)] = heapSpan(spans, heap, stageState.flat, words); + return; + } + auto& patched = PatchedShaderData(); + buildPatchedData(patched, shader, stageState, words, userData, current); + if (verifySlots && sameInput && !std::ranges::equal(stageState.data.words, patched)) + throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); + if (sameWords) NoteUserWordsRewrite(patched.size(), userData.size()); + heapOffsets[dataIndex] = commitStageData(spans, heap, shader, stageState, patched, words, userData); +} + +void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader) { + const auto stageIndex = HeapStageIndex(shader.stage); + auto& stageState = heapStages[stageIndex]; + const bool current = refreshHeapStageSlots(heap, stageState, VulkanStage(shader.stage)); + const auto& program = *shader.program; + if (program.dataAddressPush) writeHeapTableMap(spans, heap, shader, stageIndex); + const auto previousUserWords = stageState.userWords; + stageState.userWords = 0; + for (const auto& binding : program.bindings) { + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt) writeHeapDataBinding(spans, heap, shader, binding, current); + } + if (stageState.userWords != previousUserWords) ++stageState.pushVersion; } namespace { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 757d3bc163cd..e81f2323d060 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -42,6 +42,8 @@ struct Module { std::set> perPrimitiveMembers; std::map variables; std::map constants; + std::map specConstants; + std::map specIds; std::set interface; std::map inputs; std::map outputs; @@ -171,6 +173,13 @@ struct Module { } }; +bool heapImageSlotsLength(const Module& module, std::uint32_t id) { + const auto constant = module.specConstants.find(id); + const auto specId = module.specIds.find(id); + return constant != module.specConstants.end() && constant->second == ShaderRecompiler::RuntimeAbi::GpuImageHeapSlots && specId != module.specIds.end() && + specId->second == ShaderRecompiler::PipelineSpecialization::HeapImageSlots; +} + Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysicalDeviceSubgroupProperties& subgroup, bool fragmentShaderBarycentric, bool descriptorIndexing, bool imageInt64Atomics, bool geometryShader, bool sampleRateShading, bool bufferInt64Atomics, bool shaderClipDistance, bool shaderCullDistance, bool viewportIndexLayer, bool runtimeDescriptorArray, bool demoteToHelperInvocation, bool shaderTerminateInvocation, bool shaderResourceMinLod, bool fmaFloat16, std::span primitiveLocations = {}) { using Stage = ShaderRecompiler::ShaderStage; Require(compiled.program != nullptr, "missing compiled shader"); @@ -250,10 +259,11 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi capability == spv::CapabilitySignedZeroInfNanPreserve; const bool isBdaCapability = - shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && - (capability == spv::CapabilityInt64 || - capability == spv::CapabilityPhysicalStorageBufferAddresses || - capability == spv::CapabilityStorageBuffer8BitAccess); + (shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && + (capability == spv::CapabilityInt64 || + capability == spv::CapabilityPhysicalStorageBufferAddresses || + capability == spv::CapabilityStorageBuffer8BitAccess)) || + ((shader.bufferAddressCount != 0u || shader.dataAddressPush) && (capability == spv::CapabilityInt64 || capability == spv::CapabilityPhysicalStorageBufferAddresses)); const bool isTessellationCapability = (control || evaluation) && @@ -367,7 +377,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi terminateExtension = true; break; } - Require(extension == "SPV_KHR_float_controls" || (fmaFloat16 && extension == "SPV_KHR_fma") || (imageInt64Atomics && extension == "SPV_EXT_shader_image_int64") || (atomicLockTable && extension == "SPV_KHR_physical_storage_buffer") || (viewportIndexLayer && extension == "SPV_EXT_shader_viewport_index_layer") || (fragment && demoteToHelperInvocation && extension == "SPV_EXT_demote_to_helper_invocation") || (mesh && (extension == "SPV_EXT_mesh_shader" || extension == "SPV_KHR_physical_storage_buffer")) || (fragment && !primitiveLocations.empty() && extension == "SPV_EXT_mesh_shader") || (geometry && state.tessellationCapture && extension == "SPV_KHR_physical_storage_buffer") || ((descriptorIndexing || runtimeDescriptorArray) && extension == "SPV_EXT_descriptor_indexing") || (shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && (extension == "SPV_KHR_physical_storage_buffer" || extension == "SPV_KHR_8bit_storage")), "unsupported SPIR-V extension"); + Require(extension == "SPV_KHR_float_controls" || (fmaFloat16 && extension == "SPV_KHR_fma") || (imageInt64Atomics && extension == "SPV_EXT_shader_image_int64") || (atomicLockTable && extension == "SPV_KHR_physical_storage_buffer") || (viewportIndexLayer && extension == "SPV_EXT_shader_viewport_index_layer") || (fragment && demoteToHelperInvocation && extension == "SPV_EXT_demote_to_helper_invocation") || (mesh && (extension == "SPV_EXT_mesh_shader" || extension == "SPV_KHR_physical_storage_buffer")) || (fragment && !primitiveLocations.empty() && extension == "SPV_EXT_mesh_shader") || (geometry && state.tessellationCapture && extension == "SPV_KHR_physical_storage_buffer") || ((descriptorIndexing || runtimeDescriptorArray) && extension == "SPV_EXT_descriptor_indexing") || (shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && (extension == "SPV_KHR_physical_storage_buffer" || extension == "SPV_KHR_8bit_storage")) || ((shader.bufferAddressCount != 0u || shader.dataAddressPush) && extension == "SPV_KHR_physical_storage_buffer"), "unsupported SPIR-V extension"); break; } case spv::OpTerminateInvocation: @@ -429,6 +439,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi decoration.perVertex = true; } if (kind == spv::DecorationBlock) decoration.block = true; + if (kind == spv::DecorationSpecId && count == 4) module.specIds[instruction[1]] = instruction[3]; if (kind == spv::DecorationAliased) decoration.aliased = true; break; } @@ -450,6 +461,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi case spv::OpTypeRuntimeArray: case spv::OpTypeStruct: case spv::OpTypePointer: + case spv::OpTypeSampler: Require(count >= 2 && module.types.emplace(instruction[1], std::vector(instruction.begin(), instruction.end())).second, "invalid or duplicate SPIR-V type"); break; case spv::OpVariable: @@ -459,6 +471,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi if (count == 4) module.constants.emplace(instruction[2], instruction[3]); break; case spv::OpSpecConstant: + if (count == 4) module.specConstants.emplace(instruction[2], instruction[3]); break; default: break; } @@ -510,6 +523,9 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi for (const auto& [name, operands] : module.modes) Require(operands.empty() && (name == spv::ExecutionModeOriginUpperLeft || name == spv::ExecutionModeEarlyFragmentTests || name == spv::ExecutionModeDepthReplacing || name == spv::ExecutionModeDepthLess || name == spv::ExecutionModeDepthGreater || name == spv::ExecutionModePixelInterlockOrderedEXT || name == spv::ExecutionModeStencilRefReplacingEXT), "unsupported fragment execution mode"); } else Require(module.modes.empty(), "unsupported vertex execution mode"); std::set> descriptors; + std::set declared; + std::set embeddedSamplers; + std::set embeddedOwners; std::map, bool> bufferViews; bool push = false; for (const auto& [id, variable] : module.variables) { @@ -572,7 +588,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } } } else if (variable.storage == spv::StorageClassPushConstant) { - Require(!push && (!shader.pushConstants.empty() || shader.readsDepthRemapPush || mesh || (control && !rectListControl) || (geometry && state.tessellationCapture)) && (type[0] & 0xffffu) == spv::OpTypeStruct, "invalid push constant interface"); + Require(!push && (!shader.pushConstants.empty() || shader.readsDepthRemapPush || shader.dataAddressPush || mesh || (control && !rectListControl) || (geometry && state.tessellationCapture)) && (type[0] & 0xffffu) == spv::OpTypeStruct, "invalid push constant interface"); push = true; Require(type.size() == 3 && module.decorations[typeId].block, "push constant variable must be a Block struct with exactly one member"); const auto offset = module.offsets.find({typeId, 0}); @@ -580,7 +596,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi const auto& array = module.Type(type[2]); Require(array.size() == 4 && (array[0] & 0xffffu) == spv::OpTypeArray && module.Signature(array[2]) == "u32", "push constant member must be an array of u32"); const auto length = module.constants.find(array[3]); - Require(length != module.constants.end() && length->second == PipelinePushSlotBytes / 4, "push constant array must contain 32 elements"); + Require(length != module.constants.end() && length->second == (shader.dataAddressPush ? ShaderRecompiler::RuntimeAbi::PushDataDwords : PipelinePushSlotBytes / 4), "push constant array must contain 32 elements"); const auto stride = module.decorations[type[2]].stride; Require(stride.has_value() && *stride == 4, "push constant array must have an ArrayStride of 4"); } else if (variable.storage == spv::StorageClassWorkgroup) { @@ -588,19 +604,62 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } else if (variable.storage == spv::StorageClassUniformConstant) { Require(decoration.set && decoration.binding, "unbound shader resource"); const auto key = std::make_pair(*decoration.set, *decoration.binding); + if (key.first == ShaderRecompiler::RuntimeAbi::EmbeddedSamplerSet) { + const auto owner = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { + return item.role == ShaderRecompiler::DescriptorRole::GuestSamplers && std::find(item.samplerEmbedded.begin(), item.samplerEmbedded.end(), key.second) != item.samplerEmbedded.end(); + }); + Require(shader.gpuResolvedImages && owner != shader.bindings.end(), "an embedded sampler has no constant sampler element in the recompiler binding metadata"); + Require(type.size() == 2 && (type[0] & 0xffffu) == spv::OpTypeSampler, "an embedded sampler must be declared as a single sampler"); + Require(embeddedSamplers.insert(key.second).second, "duplicate embedded sampler binding"); + embeddedOwners.insert(&*owner); + continue; + } const auto binding = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return item.descriptorSet == key.first && item.binding == key.second; }); - Require(descriptors.insert(key).second || (binding != shader.bindings.end() && (binding->role == ShaderRecompiler::DescriptorRole::ImageTable || binding->role == ShaderRecompiler::DescriptorRole::ImageStorageTable)), "duplicate SPIR-V resource binding"); + bool tableAlias = false; + { + namespace Abi = ShaderRecompiler::RuntimeAbi; + const bool tables = shader.dataAddressPush && std::any_of(shader.bindings.begin(), shader.bindings.end(), [](const auto& item) { return item.role == ShaderRecompiler::DescriptorRole::ImageTable || item.role == ShaderRecompiler::DescriptorRole::ImageStorageTable || item.role == ShaderRecompiler::DescriptorRole::SamplerTable; }); + const bool samplerAlias = key.second == Abi::BindingNumber(Abi::Stage::Fragment, Abi::Binding::Samplers); + const bool imageAlias = key.second == Abi::BindingNumber(Abi::Stage::Fragment, static_cast(Abi::FirstImageBinding)) || key.second == Abi::BindingNumber(Abi::Stage::Fragment, static_cast(Abi::FirstStorageImageBinding)); + tableAlias = tables && key.first == Abi::FragmentDescriptorSet && (samplerAlias || imageAlias); + if (tableAlias && binding == shader.bindings.end()) { + const auto count = type.size() == 4 && (type[0] & 0xffffu) == spv::OpTypeArray ? module.constants.find(type[3]) : module.constants.end(); + const bool array = type.size() == 4 && (type[0] & 0xffffu) == spv::OpTypeArray; + Require(array && (samplerAlias ? count != module.constants.end() && count->second == Abi::GpuSamplerHeapSlots : heapImageSlotsLength(module, type[3])), + "an image table's heap array length disagrees with the global heap"); + continue; + } + } + Require(descriptors.insert(key).second || tableAlias || (binding != shader.bindings.end() && (binding->role == ShaderRecompiler::DescriptorRole::ImageTable || binding->role == ShaderRecompiler::DescriptorRole::ImageStorageTable)), "duplicate SPIR-V resource binding"); Require(binding != shader.bindings.end(), "SPIR-V resource is absent from recompiler binding metadata"); Require(binding->kind == ShaderRecompiler::DescriptorKind::Sampler || binding->kind == ShaderRecompiler::DescriptorKind::SampledImage || binding->kind == ShaderRecompiler::DescriptorKind::StorageImage, "SPIR-V descriptor type disagrees with recompiler binding metadata"); if (binding->role == ShaderRecompiler::DescriptorRole::ImageTable || binding->role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding->role == ShaderRecompiler::DescriptorRole::SamplerTable) { Require(type.size() == 3 && (type[0] & 0xffffu) == spv::OpTypeRuntimeArray, "image table must be declared as a runtime descriptor array"); + declared.insert(&*binding); continue; } Require(type.size() == 4 && (type[0] & 0xffffu) == spv::OpTypeArray, "typed heap must be declared as a descriptor array"); const auto heap = static_cast(binding->binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)); const auto capacity = ShaderRecompiler::RuntimeAbi::HeapCapacity(heap); const auto count = module.constants.find(type[3]); - Require(binding->count != 0u && binding->count <= capacity && count != module.constants.end() && count->second == binding->count, "typed heap array length disagrees with compact binding"); + const bool heapArray = binding->kind != ShaderRecompiler::DescriptorKind::StorageImage || (ShaderRecompiler::RuntimeAbi::GpuHeapStorageKind(static_cast(heap)) && ClassifyHeapBinding(*binding) == HeapBindingClass::StorageImage); + if (shader.gpuResolvedImages && heapArray) { + const auto slots = binding->kind == ShaderRecompiler::DescriptorKind::Sampler ? ShaderRecompiler::RuntimeAbi::GpuSamplerHeapSlots : ShaderRecompiler::RuntimeAbi::GpuImageHeapSlots; + const bool length = binding->kind == ShaderRecompiler::DescriptorKind::Sampler ? count != module.constants.end() && count->second == slots : heapImageSlotsLength(module, type[3]); + Require(binding->count != 0u && length, "GPU-mode heap array length disagrees with the global heap"); + } else { + Require(binding->count != 0u && binding->count <= capacity && count != module.constants.end() && count->second == binding->count, "typed heap array length disagrees with compact binding"); + } + } else if (variable.storage == spv::StorageClassUniform && decoration.set && *decoration.set == ShaderRecompiler::RuntimeAbi::PushedBufferSet) { + Require(shader.gpuResolvedImages && shader.dataAddressPush, "a pushed constant buffer outside a heap stage"); + } else if (variable.storage == spv::StorageClassUniform) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + const auto kind = decoration.binding ? *decoration.binding % bindingCount : bindingCount; + Require(shader.dataAddressPush && decoration.set && decoration.binding && *decoration.set == Abi::GpuDataSet && + (kind == static_cast(Abi::Binding::ShaderData) || kind == static_cast(Abi::Binding::UserData) || + kind == static_cast(Abi::Binding::FlattenedSrt)), + "a uniform buffer is only the GPU heap's shader data, user data or flattened SRT"); } else { Require(variable.storage == spv::StorageClassStorageBuffer && decoration.set && decoration.binding, "unsupported or unbound shader resource"); const auto key = std::make_pair(*decoration.set, *decoration.binding); @@ -608,15 +667,22 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi Require(mesh && *decoration.binding == 0u, "mesh window buffer binding is wrong"); continue; } - if (*decoration.set == ShaderRecompiler::PixelFunctionLdsDescriptorSet) { + if (*decoration.set == ShaderRecompiler::RuntimeAbi::PushedBufferSet) { + Require(shader.gpuResolvedImages && shader.dataAddressPush, "a pushed buffer outside a heap stage"); + continue; + } + const bool gpuData = shader.gpuResolvedImages && key.first == ShaderRecompiler::RuntimeAbi::GpuDataSet && + std::any_of(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return item.binding == key.second && (item.role == ShaderRecompiler::DescriptorRole::ShaderData || item.role == ShaderRecompiler::DescriptorRole::FlattenedSrt); }); + if (!gpuData && *decoration.set == ShaderRecompiler::PixelFunctionLdsDescriptorSet) { Require(fragment && *decoration.binding == 0u, "pixel function LDS buffer binding is wrong"); continue; } - const auto binding = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return item.descriptorSet == key.first && item.binding == key.second; }); + const auto binding = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return (gpuData || item.descriptorSet == key.first) && item.binding == key.second; }); const bool array = binding != shader.bindings.end() && binding->role == ShaderRecompiler::DescriptorRole::GuestBuffers; const auto [view, first] = bufferViews.emplace(key, decoration.aliased); Require(descriptors.insert(key).second || (!first && view->second && decoration.aliased && array), "duplicate SPIR-V resource binding"); Require(binding != shader.bindings.end(), "SPIR-V resource is absent from recompiler binding metadata"); + declared.insert(&*binding); Require(binding->kind == ShaderRecompiler::DescriptorKind::StorageBuffer, "SPIR-V descriptor type disagrees with recompiler binding metadata"); Require(!binding->readOnly, "read-only descriptor metadata is unsupported because the recompiler emits no NonWritable decoration"); Require(array || (shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && (binding->role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding->role == ShaderRecompiler::DescriptorRole::FaultBuffer)) || binding->role == ShaderRecompiler::DescriptorRole::ShaderData || binding->role == ShaderRecompiler::DescriptorRole::FlattenedSrt || binding->role == ShaderRecompiler::DescriptorRole::ImageTableMap || binding->role == ShaderRecompiler::DescriptorRole::Gds, "SPIR-V descriptor role is unsupported"); @@ -651,8 +717,12 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } else { Require(shader.vertexAttributes.empty(), "vertex attribute metadata is invalid for this stage"); } - Require(descriptors.size() == shader.bindings.size(), "recompiler binding metadata contains undeclared resources"); - Require(push == (!shader.pushConstants.empty() || shader.readsDepthRemapPush || mesh || (control && !rectListControl && !barycentricPatches) || (geometry && state.tessellationCapture)), "recompiler push constant metadata disagrees with SPIR-V"); + const auto addressedBindings = static_cast(std::count_if(shader.bindings.begin(), shader.bindings.end(), [&](const ShaderRecompiler::DescriptorBinding& binding) { return !declared.contains(&binding) && ((shader.bufferAddressCount != 0u && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers) || (shader.dataAddressPush && (binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt || binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer || binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding.role == ShaderRecompiler::DescriptorRole::SamplerTable || binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap))); })); + const auto embeddedOnly = static_cast(std::count_if(embeddedOwners.begin(), embeddedOwners.end(), [&](const ShaderRecompiler::DescriptorBinding* owner) { + return !descriptors.contains(std::make_pair(owner->descriptorSet, owner->binding)); + })); + Require(descriptors.size() + addressedBindings + embeddedOnly == shader.bindings.size(), "recompiler binding metadata contains undeclared resources"); + Require(push == (!shader.pushConstants.empty() || shader.readsDepthRemapPush || shader.dataAddressPush || mesh || (control && !rectListControl && !barycentricPatches) || (geometry && state.tessellationCapture)), "recompiler push constant metadata disagrees with SPIR-V"); for (const auto id : module.interface) Require(module.variables.contains(id), "entry point interface contains an unknown variable"); if (mesh) Require(module.primitiveIndices == state.stages.mesh->outputPrimitiveSize, "mesh shader does not export primitive indices"); if (fragment) Require(module.primitiveInputs == 0 || !primitiveLocations.empty(), "per-primitive pixel inputs need the barycentric emulation layout"); @@ -714,7 +784,7 @@ std::set ValidateShaders(std::span shaders, const auto expected = state.rectList || patches ? (i == 0 ? Stage::Vertex : tessStages[i]) : tessellation ? tessStages[i] : geometry && i == 1 ? Stage::Geometry : i == shaders.size() - 1 ? Stage::Fragment : state.stages.path == ShaderPath::Geometry ? Stage::Mesh : Stage::Vertex; Require(shaders[i].program != nullptr, "missing compiled shader"); Require(shaders[i].stage == expected, "graphics stage order disagrees"); - for (const auto& binding : shaders[i].program->bindings) Require(binding.descriptorSet == ShaderRecompiler::RuntimeAbi::DescriptorSet || (shaders[i].stage == ShaderRecompiler::ShaderStage::Fragment && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet), "graphics resource uses a descriptor set other than its stage's"); + for (const auto& binding : shaders[i].program->bindings) Require(binding.descriptorSet == ShaderRecompiler::RuntimeAbi::DescriptorSet || (shaders[i].program->dataAddressPush && binding.role == ShaderRecompiler::DescriptorRole::Gds && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::GpuGdsSet) || ((shaders[i].stage == ShaderRecompiler::ShaderStage::Fragment || HeapShader(shaders[i])) && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet), "graphics resource uses a descriptor set other than its stage's"); const auto current = Inspect(shaders[i], state, subgroup, fragmentShaderBarycentric, descriptorIndexing, imageInt64Atomics, geometryShader, sampleRateShading, bufferInt64Atomics, shaderClipDistance, shaderCullDistance, viewportIndexLayer, runtimeDescriptorArray, demoteToHelperInvocation, shaderTerminateInvocation, shaderResourceMinLod, fmaFloat16, primitiveLocations); if (i != 0) { for (const auto& [location, signature] : current.inputs) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/StagedMerge.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/StagedMerge.cpp index f0d94d26668e..57b2295cb928 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/StagedMerge.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/StagedMerge.cpp @@ -1,9 +1,11 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/StagedMerge.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/PackedMerge_spv.h" #include +#include #include #include #include @@ -23,7 +25,15 @@ struct MergePush { std::uint32_t samples; }; -class Temporary final : public StagedTemporary { +struct HeapMergePush { + MergePush push; + std::uint32_t temporary; + std::uint32_t target; +}; + +static_assert(offsetof(HeapMergePush, temporary) == 24 && offsetof(HeapMergePush, target) == 28); + +class Temporary final : public StagedTemporary, public HeapSlotOwner { public: Temporary(const Context& context, VkExtent2D extent, std::uint32_t samples) : context(context), extent(extent), samples(samples) { try { @@ -70,6 +80,7 @@ class Temporary final : public StagedTemporary { private: void release() noexcept { + ReleaseHeapSlots(context); if (view) context.Function("vkDestroyImageView")(context.device, view, nullptr); if (image) context.Function("vkDestroyImage")(context.device, image, nullptr); if (memory) context.Function("vkFreeMemory")(context.device, memory, nullptr); @@ -99,8 +110,25 @@ class StagedMerges { return temporaries.back(); } - void Merge(VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area) { + void Merge(VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area, const HeapSlotOwner* targetOwner) { const auto pipeline = mergePipeline(); + const auto x = static_cast(area.offset.x); + const auto y = static_cast(area.offset.y); + const MergePush push{{x, y}, {x + area.extent.width, y + area.extent.height}, mask, samples}; + auto* owned = dynamic_cast(&temporary); + if (heapPipeline != VK_NULL_HANDLE && targetOwner != nullptr && owned != nullptr) { + auto& heap = BindlessHeap::For(context); + const auto temporarySlot = heap.ViewSlot(HeapPassStorageKind, owned, temporary.View()); + const auto targetSlot = temporarySlot ? heap.ViewSlot(HeapPassStorageKind, targetOwner, target) : std::nullopt; + if (targetSlot) { + heap.BindDescriptorHeaps(commands); + context.BindComputePipeline(commands, heapPipeline); + const HeapMergePush pushed{push, *temporarySlot, *targetSlot}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, (area.extent.width + 7u) / 8u, (area.extent.height + 7u) / 8u, 1); + return; + } + } const auto set = allocate(); const std::array images{{{VK_NULL_HANDLE, temporary.View(), VK_IMAGE_LAYOUT_GENERAL}, {VK_NULL_HANDLE, target, VK_IMAGE_LAYOUT_GENERAL}}}; std::array writes{}; @@ -113,12 +141,9 @@ class StagedMerges { writes[binding].pImageInfo = &images[binding]; } context.Function("vkUpdateDescriptorSets")(context.device, 2, writes.data(), 0, nullptr); - const auto x = static_cast(area.offset.x); - const auto y = static_cast(area.offset.y); - const MergePush push{{x, y}, {x + area.extent.width, y + area.extent.height}, mask, samples}; context.BindComputePipeline(commands, pipeline); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, 0, nullptr); - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::StagedMerge); + CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, (area.extent.width + 7u) / 8u, (area.extent.height + 7u) / 8u, 1); } @@ -151,6 +176,13 @@ class StagedMerges { auto pipelineCacheLock = context.LockPipelineCacheForUse(); created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline); } + if (created == VK_SUCCESS && HeapPassesActive(context)) { + const auto& heap = BindlessHeap::For(context); + const std::array mappings{ + HeapPushIndexMapping(heap, 0, 0, HeapPassStorageImages, offsetof(HeapMergePush, temporary)), + HeapPushIndexMapping(heap, 0, 1, HeapPassStorageImages, offsetof(HeapMergePush, target))}; + heapPipeline = CreateHeapComputePipeline(context, info, mappings); + } context.Function("vkDestroyShaderModule")(context.device, shader, nullptr); Check(created, "vkCreateComputePipelines staged merge"); return pipeline; @@ -198,6 +230,7 @@ class StagedMerges { void release() noexcept { temporaries.clear(); if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); + if (heapPipeline) context.Function("vkDestroyPipeline")(context.device, heapPipeline, nullptr); for (const auto pool : pools) context.Function("vkDestroyDescriptorPool")(context.device, pool, nullptr); if (pipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, pipelineLayout, nullptr); if (setLayout) context.Function("vkDestroyDescriptorSetLayout")(context.device, setLayout, nullptr); @@ -207,6 +240,7 @@ class StagedMerges { VkDescriptorSetLayout setLayout = VK_NULL_HANDLE; VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; std::vector pools; std::vector serials; std::size_t current = 0; @@ -257,12 +291,13 @@ void RecordStagedClear(const Context& context, VkCommandBuffer commands, StagedT if (Recorder::Active() != nullptr) Recorder::CountBarriers(Recorder::CommandClass::Draw, 2); } -void RecordStagedMerge(const Context& context, VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area) { +void RecordStagedMerge(const Context& context, VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area, + const HeapSlotOwner* targetOwner) { if (area.extent.width == 0 || area.extent.height == 0) return; RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, anyWrite, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); { std::lock_guard lock(mergesMutex()); - mergesFor(context).Merge(commands, temporary, target, mask, samples, area); + mergesFor(context).Merge(commands, temporary, target, mask, samples, area, targetOwner); } RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT, anyAccess); if (Recorder::Active() != nullptr) Recorder::CountBarriers(Recorder::CommandClass::Draw, 2); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 691462952a33..714c3bfcacbf 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" +#include "prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp" #include "prx/libSceAgcDriver/Execution/include/AsyncLog.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" @@ -17,6 +18,7 @@ #include "prx/libSceAgcDriver/Execution/include/ThreadScratch.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/MapImportGate.hpp" @@ -33,6 +35,7 @@ #include "RdnaDecoder/include/RdnaDecoder/RdnaDescriptorFormat.hpp" #include "IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/BufferFormat.hpp" #include +#include #include #include #include @@ -1547,6 +1550,7 @@ VkImageView Texture::BaseLevelView() const { } void Texture::release() noexcept { + ReleaseHeapSlots(context); upload.reset(); if (view) context.Function("vkDestroyImageView")(context.device, view, nullptr); view = VK_NULL_HANDLE; @@ -1876,20 +1880,44 @@ class PendingList { iterator end() { return textures.end(); } void push_back(StorageTexture* texture) { textures.push_back(texture); + if (LabelCandidate(texture)) labelCandidates.push_back(texture); + const auto begin = texture->Descriptor().baseAddress; + index.Insert(begin, begin + texture->GuestBytes(), texture, nextOrder++); changed(); } iterator erase(iterator it) { + unindex(*it); const auto next = textures.erase(it); changed(); return next; } void remove(const StorageTexture* texture) { - if (std::erase(textures, texture) != 0) changed(); + const auto found = std::find(textures.begin(), textures.end(), texture); + if (found == textures.end()) return; + unindex(const_cast(texture)); + textures.erase(found); + changed(); } bool MayOverlap(std::uint64_t address, std::size_t bytes) { if (indexed != version) rebuild(); return !textures.empty() && Overlaps(ranges, address, bytes); } + template + bool AnyOverlapping(std::uint64_t address, std::size_t bytes, Visit&& visit) { + return index.AnyOverlapping(address, bytes, visit); + } + template + StorageTexture* FirstOverlapping(std::uint64_t address, std::size_t bytes, Match&& match) { + const auto* entry = index.FirstByPosition(address, bytes, match); + return entry != nullptr ? entry->item : nullptr; + } + static bool LabelCandidate(const StorageTexture* texture) { + return texture->Descriptor().tileMode == TextureTileMode::kLinear || texture->GuestBytes() <= StorageTexture::OccasionalStoreBytes; + } + const std::vector& LabelCandidates() const { return labelCandidates; } + void Publish() { + if (indexed != version) rebuild(); + } bool SurelyClear(std::uint64_t address, std::size_t bytes) const { const auto current = published.load(std::memory_order_acquire); return current != nullptr && current->version == changes.load(std::memory_order_acquire) && !Overlaps(current->ranges, address, bytes); @@ -1906,6 +1934,15 @@ class PendingList { return !Overlaps(copy->ranges, address, bytes); } + bool SurelyClearAll(std::span> wanted) const { + const auto current = published.load(std::memory_order_acquire); + if (current == nullptr) return false; + for (const auto& [begin, end] : wanted) { + if (end > begin && Overlaps(current->ranges, begin, static_cast(end - begin))) return false; + } + return current->version == changes.load(std::memory_order_acquire); + } + private: struct Snapshot { std::uint64_t version = 0; @@ -1924,21 +1961,26 @@ class PendingList { changes.store(version, std::memory_order_release); } + void unindex(StorageTexture* texture) { + if (LabelCandidate(texture)) std::erase(labelCandidates, texture); + const bool found = index.Erase(texture->Descriptor().baseAddress, texture); + assert(found); + static_cast(found); + } void rebuild() { ranges.clear(); - for (const auto* texture : textures) ranges.emplace_back(texture->Descriptor().baseAddress, texture->Descriptor().baseAddress + texture->GuestBytes()); - std::sort(ranges.begin(), ranges.end()); - std::size_t merged = 0; - for (const auto& range : ranges) { - if (merged != 0 && range.first <= ranges[merged - 1].second) ranges[merged - 1].second = std::max(ranges[merged - 1].second, range.second); - else ranges[merged++] = range; - } - ranges.resize(merged); + for (const auto& entry : index.Entries()) { + if (!ranges.empty() && entry.begin <= ranges.back().second) ranges.back().second = std::max(ranges.back().second, entry.end); + else ranges.emplace_back(entry.begin, entry.end); + } indexed = version; published.store(std::make_shared(Snapshot{version, ranges}), std::memory_order_release); } std::vector textures; + std::vector labelCandidates; Ranges ranges; + PendingRangeIndex index; + std::size_t nextOrder = 0; std::uint64_t version = 0; std::uint64_t indexed = ~std::uint64_t{0}; std::atomic changes{0}; @@ -2439,6 +2481,13 @@ VkImageView StorageTexture::StorageView(std::uint32_t mip, bool firstLayer, bool return created; } +VkImageView StorageTexture::UintStorageViewOrDefault(std::uint32_t mip, bool firstLayer) { + const auto uintFormat = UintStorageViewFormat(storageFormat); + const bool available = PackedStorageViewFormat(storageFormat) == VK_FORMAT_UNDEFINED && uintFormat != VK_FORMAT_UNDEFINED && + StorageFormatOrUndefined(context, uintFormat) == uintFormat; + return StorageView(mip, firstLayer, available); +} + VkImageView StorageTexture::ElementView() { if (elementView != VK_NULL_HANDLE) return elementView; if (descriptor.dimension != TextureDimension::k2D || geometry.imageLayers != 1) return VK_NULL_HANDLE; @@ -2959,7 +3008,8 @@ bool StorageTexture::otherPendingOverlaps() const { auto& pending = Pending(); std::lock_guard lock(pending.mutex); const auto other = [&](const StorageTexture* texture) { return texture != this && texture->overlaps(descriptor.baseAddress, static_cast(guestBytes)); }; - return std::any_of(pending.textures.begin(), pending.textures.end(), other) || std::any_of(pending.flushing.begin(), pending.flushing.end(), other); + const auto pendingHere = [&](const StorageTexture* texture) { return texture != this && (texture->descriptor.dccAddress != 0 || texture->pendingUnitInside(descriptor.baseAddress, static_cast(guestBytes))); }; + return pending.textures.AnyOverlapping(descriptor.baseAddress, static_cast(guestBytes), pendingHere) || std::any_of(pending.flushing.begin(), pending.flushing.end(), other); } bool StorageTexture::refreshProved() { @@ -3572,7 +3622,7 @@ void StorageTexture::upload(const std::vector* layers) { for (std::uint32_t level = 0; level < mips.size(); ++level) { if (!geometry.HasLayer(level, layer)) continue; const auto& mip = mips[level]; - detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, import->buffer, importOffset + geometry.GuestOffset(layer, mip), elementLayerView(level, layer), mip, false, layer, {.pipeBankXor = descriptor.pipeBankXor}); + detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, import->buffer, importOffset + geometry.GuestOffset(layer, mip), elementLayerView(level, layer), mip, false, layer, {.pipeBankXor = descriptor.pipeBankXor}, this); } } recordDirectUploadDone(commands); @@ -4140,10 +4190,10 @@ std::uint64_t StorageTexture::uploadWindows(std::span segme detile.pipeBankXor = descriptor.pipeBankXor; const auto view = elementLayerView(window.level, window.layer); if (source.shadow) { - detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, source.buffer, source.offset + (window.tiledBegin - source.begin), view, mip, false, window.layer, detile); + detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, source.buffer, source.offset + (window.tiledBegin - source.begin), view, mip, false, window.layer, detile, this); } else { detile.tiledBase = 0; - detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, import.buffer, importOffset + geometry.GuestOffset(window.layer, mip), view, mip, false, window.layer, detile); + detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, import.buffer, importOffset + geometry.GuestOffset(window.layer, mip), view, mip, false, window.layer, detile, this); } } recordDirectUploadDone(commands); @@ -4506,9 +4556,9 @@ std::uint64_t StorageTexture::writeBackWindows(std::span se for (auto k = directRanges[i].first; k < directRanges[i].second; ++k) { auto piece = directPieces[k].window; piece.pipeBankXor = descriptor.pipeBankXor; - detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, directPieces[k].slab, directPieces[k].offset, elementLayerView(window.level, window.layer), mips[window.level], true, window.layer, piece); + detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, directPieces[k].slab, directPieces[k].offset, elementLayerView(window.level, window.layer), mips[window.level], true, window.layer, piece, this); } - if (directRanges[i].first == directRanges[i].second) detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, tiledScratch->Handle(), scratchPositions[i], elementLayerView(window.level, window.layer), mips[window.level], true, window.layer, retile); + if (directRanges[i].first == directRanges[i].second) detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, tiledScratch->Handle(), scratchPositions[i], elementLayerView(window.level, window.layer), mips[window.level], true, window.layer, retile, this); } singlePassMoves.fetch_add(1, std::memory_order_relaxed); } else { @@ -4756,7 +4806,8 @@ void StorageTexture::markLayersPending(std::uint32_t first, std::uint32_t count) } std::optional publication; if (!layerPending.Any()) publication.emplace(descriptor.baseAddress, guestBytes); - if (!layerPending.AllIn(first, count)) { + const bool newUnits = !layerPending.AllIn(first, count); + if (newUnits) { std::vector unsaved; bool anyUnsaved = false; const bool trims = CommitTrims(); @@ -4849,7 +4900,7 @@ void StorageTexture::markLayersPending(std::uint32_t first, std::uint32_t count) if (const auto format = ResolveTextureFormat(descriptor.format); format == VK_FORMAT_R8_UINT || format == VK_FORMAT_R8_UNORM) eightBitWrites().fetch_add(1, std::memory_order_release); const bool wasLent = std::exchange(lent, false); if (dirty) { - if (wasLent) BumpPendingSerial(); + if (wasLent || newUnits) BumpPendingSerial(); return; } dirty = true; @@ -5219,8 +5270,9 @@ bool StorageTexture::FlushPending(std::uint64_t address, std::size_t bytes, cons if (pending.flushingCount.load(std::memory_order_acquire) != 0) return false; if (!pending.textures.SurelyClear(address, bytes)) { std::lock_guard lock(pending.mutex); + pending.textures.Publish(); const auto* exempt = Refreshing::Get(); - if (pending.textures.MayOverlap(address, bytes) && std::any_of(pending.textures.begin(), pending.textures.end(), [&](const StorageTexture* texture) { return texture != except && texture != exempt && texture->overlaps(address, bytes) && texture->pendingUnitInside(address, bytes); })) return false; + if (pending.textures.AnyOverlapping(address, bytes, [&](const StorageTexture* texture) { return texture != except && texture != exempt && texture->pendingUnitInside(address, bytes); })) return false; if (pending.flushingCount.load(std::memory_order_acquire) != 0) return false; } return scope == PublishScope::None || !AnyShadowedOverlaps(address, bytes); @@ -5824,7 +5876,8 @@ void StorageTexture::StoreReadbackBeforeLabel(const char* reason, VkDevice devic return std::any_of(pending.textures.begin(), pending.textures.end(), sharesStored) || std::any_of(pending.flushing.begin(), pending.flushing.end(), shares); }; #endif - for (const auto* texture : pending.textures) { + const auto& candidates = pending.textures.LabelCandidates(); + for (const auto* texture : candidates) { if (texture->descriptor.tileMode != TextureTileMode::kLinear && texture->guestBytes > SmallStoreBytes) continue; #if defined(__APPLE__) if (trap && !sharesPage(texture) && (texture->readTrapped.load(std::memory_order_acquire) || !DirectMemoryAliased_nid_postfix(static_cast(texture->descriptor.baseAddress), static_cast(texture->guestBytes))) && GuestWriteWatch::GuestWriteWatchTrapReads_nid_postfix(static_cast(texture->descriptor.baseAddress), static_cast(texture->guestBytes))) { @@ -5834,7 +5887,7 @@ void StorageTexture::StoreReadbackBeforeLabel(const char* reason, VkDevice devic #endif ranges.emplace_back(texture->descriptor.baseAddress, static_cast(texture->guestBytes)); } - for (auto* texture : pending.textures) { + for (auto* texture : candidates) { if (texture->descriptor.tileMode == TextureTileMode::kLinear || texture->guestBytes <= SmallStoreBytes || texture->guestBytes > OccasionalStoreBytes) continue; if (device != VK_NULL_HANDLE && texture->context.device != device) continue; if (!texture->writtenOccasionally.exchange(false, std::memory_order_relaxed)) continue; @@ -5952,14 +6005,7 @@ std::shared_ptr StorageTexture::FindPendingSlice(std::uint64_t a bool PendingStorageOverlaps(std::uint64_t address, std::size_t bytes, const StorageTexture* except) { auto& pending = Pending(); std::lock_guard lock(pending.mutex); - if (!pending.textures.MayOverlap(address, bytes)) return false; - for (const auto* texture : pending.textures) { - // A free function (declared in ShaderResources.hpp): the overlap is computed from the public - // surface description rather than the private helper. - const auto begin = texture->Descriptor().baseAddress; - if (texture != except && address < begin + texture->GuestBytes() && begin < address + bytes) return true; - } - return false; + return pending.textures.AnyOverlapping(address, bytes, [&](const StorageTexture* texture) { return texture != except; }); } std::uint64_t StorageTexture::StampKeepingNewerResults(std::uint64_t address, std::size_t bytes, std::uint64_t recorded, const std::function& stamp) { @@ -6060,17 +6106,22 @@ std::uint64_t StorageTexture::StampKeepingNewerResults(std::uint64_t address, st bool StorageTexture::AnyPendingOverlaps(std::span> ranges) { if (ranges.empty()) return false; auto& pending = Pending(); + const auto surelyClear = [&] { + if (pending.flushingCount.load(std::memory_order_acquire) != 0) return false; + if (!pending.textures.SurelyClearAll(ranges)) return false; + return pending.flushingCount.load(std::memory_order_acquire) == 0; + }; + if (surelyClear()) return false; std::lock_guard lock(pending.mutex); + pending.textures.Publish(); const auto overlapsAny = [&](const StorageTexture* texture) { for (const auto& [begin, end] : ranges) { if (end > begin && texture->overlaps(begin, static_cast(end - begin))) return true; } return false; }; - if (std::any_of(ranges.begin(), ranges.end(), [&](const auto& range) { return range.second > range.first && pending.textures.MayOverlap(range.first, static_cast(range.second - range.first)); })) { - for (const auto* texture : pending.textures) { - if (overlapsAny(texture)) return true; - } + for (const auto& [begin, end] : ranges) { + if (end > begin && pending.textures.AnyOverlapping(begin, static_cast(end - begin), [](const StorageTexture*) { return true; })) return true; } for (const auto* texture : pending.flushing) { if (overlapsAny(texture)) return true; @@ -6087,14 +6138,14 @@ bool StorageTexture::AnyPendingUnitsOverlap(std::spanoverlaps(begin, bytes)) return true; } - if (!pending.textures.MayOverlap(begin, bytes)) continue; - for (const auto* texture : pending.textures) { - if (!texture->overlaps(begin, bytes)) continue; + const auto unitPending = [&](const StorageTexture* texture) { for (std::uint32_t layer = 0; layer < texture->trackedLayers; ++layer) { const auto unit = texture->layerBegin(layer); if (texture->layerPending[layer] && unit < end && begin < unit + texture->layerBytes(layer)) return true; } - } + return false; + }; + if (pending.textures.AnyOverlapping(begin, bytes, unitPending)) return true; } return false; } @@ -6312,12 +6363,8 @@ bool StorageTexture::ScanPending(std::span queries) { query.found = nullptr; if (query.end <= query.begin) continue; const auto bytes = static_cast(query.end - query.begin); - if (pending.textures.MayOverlap(query.begin, bytes)) { - for (const auto* texture : pending.textures) { - if (query.found == nullptr && texture->descriptor.baseAddress == query.begin && texture->guestBytes >= bytes) query.found = texture; - if (texture != query.except && texture->overlaps(query.begin, bytes)) query.overlaps = true; - } - } + query.found = pending.textures.FirstOverlapping(query.begin, bytes, [&](const StorageTexture* texture) { return texture->descriptor.baseAddress == query.begin && texture->guestBytes >= bytes; }); + query.overlaps = pending.textures.AnyOverlapping(query.begin, bytes, [&](const StorageTexture* texture) { return texture != query.except; }); for (const auto* texture : pending.flushing) { if (texture != query.except && texture->overlaps(query.begin, bytes)) query.overlaps = true; } @@ -7934,6 +7981,7 @@ StorageTexture::~StorageTexture() { } void StorageTexture::release() noexcept { + ReleaseHeapSlots(context); for (const auto& [mip, extra] : extraViews) context.Function("vkDestroyImageView")(context.device, extra, nullptr); extraViews.clear(); for (const auto& [mip, extra] : firstLayerViews) context.Function("vkDestroyImageView")(context.device, extra, nullptr); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 0ee6c619587e..79567f47b82f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureSwizzleEquations.hpp" @@ -6,13 +7,18 @@ #include "prx/libSceAgcDriver/Graphics/shaders/CmaskClear_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/TextureDetileImage_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/TextureRepack_spv.h" +#include "prx/libSceAgcDriver/Graphics/shaders/TextureDetileAddressed_spv.h" +#include "prx/libSceAgcDriver/Graphics/shaders/TextureRepackAddressed_spv.h" +#include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/TextureDetileImageWords_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/TextureDetileWords_spv.h" #include #include #include +#include #include #include +#include #include #include @@ -42,6 +48,45 @@ struct Push { std::uint32_t splitStride; }; +struct AddressedPush { + Push push; + std::uint64_t input; + std::uint64_t output; +}; + +struct AddressedRepackPush { + std::array push; + std::uint64_t source; + std::uint64_t destination; +}; + +struct HeapImagePush { + Push push; + std::uint64_t tiled; + std::uint32_t slot; + std::uint32_t pad; +}; + +struct HeapCmaskPush { + std::array push; + std::uint32_t pad; + std::uint64_t cmask; + std::uint64_t errors; + std::uint32_t slot; + std::uint32_t pad2; +}; + +static_assert(offsetof(HeapCmaskPush, cmask) == 32 && offsetof(HeapCmaskPush, errors) == 40 && offsetof(HeapCmaskPush, slot) == 48); + +constexpr VkSpirvResourceTypeFlagsEXT DetileImageResource = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; + +constexpr std::uint32_t DetileHeapKind = ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 27u; + +static_assert(offsetof(AddressedPush, input) == 80 && sizeof(AddressedPush) == 96); +static_assert(offsetof(HeapImagePush, tiled) == 80 && offsetof(HeapImagePush, slot) == 88 && sizeof(HeapImagePush) == 96); +static_assert(ShaderRecompiler::RuntimeAbi::GpuHeapStorageKind(DetileHeapKind)); +static_assert(offsetof(AddressedRepackPush, source) == 24 && sizeof(AddressedRepackPush) == 40); + std::uint32_t BlockBytesFor(TextureTileMode tileMode) { switch (tileMode) { case TextureTileMode::kLinear: return 0u; @@ -63,8 +108,35 @@ std::uint32_t BlockBytesFor(TextureTileMode tileMode) { throw std::runtime_error("AGC graphics: TextureDetiler encountered an unknown tile mode"); } -std::uint32_t PipelineKey(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image) { - return (image ? 1u << 18 : 0u) | (thick ? 1u << 17 : 0u) | (retile ? 1u << 16 : 0u) | (static_cast(tileMode) << 8) | elementBytes; +std::uint32_t PipelineKey(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, DetileVariant variant) { + return (variant == DetileVariant::Heap ? 1u << 20 : 0u) | (variant == DetileVariant::Addressed ? 1u << 19 : 0u) | (image ? 1u << 18 : 0u) | (thick ? 1u << 17 : 0u) | (retile ? 1u << 16 : 0u) | (static_cast(tileMode) << 8) | elementBytes; +} + +void writeBufferPair(const Context& context, VkDescriptorSet set, const VkDescriptorBufferInfo& first, const VkDescriptorBufferInfo& second) { + std::array writes{}; + for (std::uint32_t index = 0; index < writes.size(); ++index) { + writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[index].dstSet = set; + writes[index].dstBinding = index; + writes[index].descriptorCount = 1; + writes[index].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[index].pBufferInfo = index == 0 ? &first : &second; + } + context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); +} + +void writeBufferImage(const Context& context, VkDescriptorSet set, const VkDescriptorBufferInfo& buffer, const VkDescriptorImageInfo& image) { + std::array writes{}; + for (std::uint32_t index = 0; index < writes.size(); ++index) { + writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[index].dstSet = set; + writes[index].dstBinding = index; + writes[index].descriptorCount = 1; + writes[index].descriptorType = index == 0 ? VK_DESCRIPTOR_TYPE_STORAGE_BUFFER : VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + } + writes[0].pBufferInfo = &buffer; + writes[1].pImageInfo = ℑ + context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); } } @@ -97,6 +169,14 @@ TextureDetiler::TextureDetiler(const Context& context) : context(context) { Check(context.Function("vkCreateDescriptorSetLayout")(context.device, &layoutInfo, nullptr, &imageDescriptorLayout), "vkCreateDescriptorSetLayout"); pipelineLayoutInfo.pSetLayouts = &imageDescriptorLayout; Check(context.Function("vkCreatePipelineLayout")(context.device, &pipelineLayoutInfo, nullptr, &imagePipelineLayout), "vkCreatePipelineLayout"); + if (context.bufferDeviceAddress) { + pipelineLayoutInfo.setLayoutCount = 0; + pipelineLayoutInfo.pSetLayouts = nullptr; + pushRange.size = sizeof(AddressedPush); + Check(context.Function("vkCreatePipelineLayout")(context.device, &pipelineLayoutInfo, nullptr, &addressedPipelineLayout), "vkCreatePipelineLayout"); + pushRange.size = sizeof(AddressedRepackPush); + Check(context.Function("vkCreatePipelineLayout")(context.device, &pipelineLayoutInfo, nullptr, &addressedRepackLayout), "vkCreatePipelineLayout"); + } } catch (...) { release(); throw; @@ -116,12 +196,19 @@ void TextureDetiler::release() noexcept { if (readbackDescriptorLayout) context.Function("vkDestroyDescriptorSetLayout")(context.device, readbackDescriptorLayout, nullptr); for (const auto pool : cmaskDescriptorSets.pools) context.Function("vkDestroyDescriptorPool")(context.device, pool, nullptr); if (cmaskPipeline) context.Function("vkDestroyPipeline")(context.device, cmaskPipeline, nullptr); + if (cmaskHeapPipeline) context.Function("vkDestroyPipeline")(context.device, cmaskHeapPipeline, nullptr); if (cmaskPipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, cmaskPipelineLayout, nullptr); if (cmaskDescriptorLayout) context.Function("vkDestroyDescriptorSetLayout")(context.device, cmaskDescriptorLayout, nullptr); cmaskErrors.reset(); for (const auto pool : descriptorSets.pools) context.Function("vkDestroyDescriptorPool")(context.device, pool, nullptr); for (const auto pool : imageDescriptorSets.pools) context.Function("vkDestroyDescriptorPool")(context.device, pool, nullptr); if (imageModule) context.Function("vkDestroyShaderModule")(context.device, imageModule, nullptr); + if (addressedRepackPipeline) context.Function("vkDestroyPipeline")(context.device, addressedRepackPipeline, nullptr); + if (addressedRepackModule) context.Function("vkDestroyShaderModule")(context.device, addressedRepackModule, nullptr); + if (addressedModule) context.Function("vkDestroyShaderModule")(context.device, addressedModule, nullptr); + if (addressedRepackLayout) context.Function("vkDestroyPipelineLayout")(context.device, addressedRepackLayout, nullptr); + if (addressedPipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, addressedPipelineLayout, nullptr); + if (heapRepackPipeline) context.Function("vkDestroyPipeline")(context.device, heapRepackPipeline, nullptr); if (repackPipeline) context.Function("vkDestroyPipeline")(context.device, repackPipeline, nullptr); if (repackModule) context.Function("vkDestroyShaderModule")(context.device, repackModule, nullptr); if (imageWordModule) context.Function("vkDestroyShaderModule")(context.device, imageWordModule, nullptr); @@ -145,9 +232,15 @@ VkFormat TextureDetiler::ImageElementFormat(std::uint32_t elementBytes) { } } -VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image) { +VkDeviceAddress TextureDetiler::bufferAddress(VkBuffer buffer) const { + if (addressedPipelineLayout == VK_NULL_HANDLE || !BufferPool::ForceAddresses()) return 0; + return BufferDeviceAddress(context, buffer); +} + +VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, DetileVariant variant) { Require(std::has_single_bit(elementBytes) && elementBytes <= 16u, "unsupported element size for texture detiling"); - const auto key = PipelineKey(tileMode, elementBytes, retile, thick, image); + const auto key = PipelineKey(tileMode, elementBytes, retile, thick, image, variant); + const bool heap = variant == DetileVariant::Heap; for (const auto& entry : pipelines) { if (entry.first == key) return entry.second; } @@ -180,8 +273,16 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem values[2] = 2u; std::copy(equation->bits.begin(), equation->bits.end(), values.begin() + 4); } - const bool words = elementBytes < 4u && (image ? retile && values[2] != 2u : !retile || values[2] != 2u); - auto& shader = image ? (words ? imageWordModule : imageModule) : (words ? wordModule : module); + const bool descriptorWords = elementBytes < 4u && (image ? retile && values[2] != 2u : !retile || values[2] != 2u); + const bool addressed = variant == DetileVariant::Addressed || (heap && !image && descriptorWords); + if (addressed && addressedModule == VK_NULL_HANDLE) { + VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + moduleInfo.codeSize = sizeof(TEXTURE_DETILE_ADDRESSED_SPV); + moduleInfo.pCode = TEXTURE_DETILE_ADDRESSED_SPV; + Check(context.Function("vkCreateShaderModule")(context.device, &moduleInfo, nullptr, &addressedModule), "vkCreateShaderModule"); + } + const bool words = !addressed && descriptorWords; + auto& shader = addressed ? addressedModule : image ? (words ? imageWordModule : imageModule) : (words ? wordModule : module); if (shader == VK_NULL_HANDLE) { if (!image) shader = CreateShaderModule(context, TEXTURE_DETILE_WORDS_SPV, sizeof(TEXTURE_DETILE_WORDS_SPV), "vkCreateShaderModule detile words"); else if (words) shader = CreateShaderModule(context, TEXTURE_DETILE_IMAGE_WORDS_SPV, sizeof(TEXTURE_DETILE_IMAGE_WORDS_SPV), "vkCreateShaderModule detile image words"); @@ -201,11 +302,30 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem stage.pSpecializationInfo = &specialization; VkComputePipelineCreateInfo createInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; createInfo.stage = stage; - createInfo.layout = image ? imagePipelineLayout : pipelineLayout; + createInfo.layout = addressed ? addressedPipelineLayout : image ? imagePipelineLayout : pipelineLayout; + std::array mappings{}; + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + auto heapFlags = DescriptorHeapFlags(); + if (heap) { + if (image) { + mappings[0] = HeapPushAddressMapping(0, 0, offsetof(HeapImagePush, tiled)); + mappings[1] = HeapPushIndexMapping(BindlessHeap::For(context), 0, 1, DetileImageResource, offsetof(HeapImagePush, slot)); + } else if (!addressed) { + mappings[0] = HeapPushAddressMapping(0, 0, offsetof(AddressedPush, input)); + mappings[1] = HeapPushAddressMapping(0, 1, offsetof(AddressedPush, output)); + } + mappingInfo.mappingCount = addressed ? 0u : static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + createInfo.stage.pNext = &mappingInfo; + createInfo.pNext = &heapFlags; + createInfo.layout = VK_NULL_HANDLE; + } VkPipeline result = VK_NULL_HANDLE; { auto pipelineCacheLock = context.LockPipelineCacheForUse(); - Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &result), "vkCreateComputePipelines"); + const auto created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &result); + if (created != VK_SUCCESS && heap) result = VK_NULL_HANDLE; + else Check(created, "vkCreateComputePipelines"); } pipelines.emplace_back(key, result); return result; @@ -234,7 +354,7 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode Require(source != VK_NULL_HANDLE && destination != VK_NULL_HANDLE, "texture detiling requires source and destination buffers"); std::uint32_t columnEnd = 0, rowEnd = 0; checkWindow(layout, window, columnEnd, rowEnd); - const auto target = pipeline(MipTileMode(tileMode, layout), elementBytes, retile, thick && !(IsGcnThick(tileMode) && layout.gcnMicroTiled)); + const bool thickPipeline = thick && !(IsGcnThick(tileMode) && layout.gcnMicroTiled); const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); const auto sourceDescriptorOffset = sourceOffset - sourceOffset % alignment; const auto destinationDescriptorOffset = destinationOffset - destinationOffset % alignment; @@ -248,25 +368,23 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode const auto sourceRange = (sourceBase + (retile ? linearBytes : tiledBytes) + 3) / 4 * 4; const auto destinationRange = (destinationBase + (retile ? tiledBytes : linearBytes) + 3) / 4 * 4; Require(sourceRange <= context.limits.maxStorageBufferRange && destinationRange <= context.limits.maxStorageBufferRange, "texture detiling buffer range exceeds device limits"); - const auto set = allocateSet(); - const VkDescriptorBufferInfo sourceInfo{source, sourceDescriptorOffset, sourceRange}; - const VkDescriptorBufferInfo destinationInfo{destination, destinationDescriptorOffset, destinationRange}; - std::array writes{}; - writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[0].dstSet = set; - writes[0].dstBinding = 0; - writes[0].descriptorCount = 1; - writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[0].pBufferInfo = &sourceInfo; - writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[1].dstSet = set; - writes[1].dstBinding = 1; - writes[1].descriptorCount = 1; - writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[1].pBufferInfo = &destinationInfo; - context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); - context.BindComputePipeline(commands, target); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, 0, nullptr); + const auto sourceAddress = bufferAddress(source); + const auto destinationAddress = sourceAddress != 0 ? bufferAddress(destination) : 0; + const bool addressable = sourceAddress != 0 && destinationAddress != 0; + const auto tileModeOfMip = MipTileMode(tileMode, layout); + const auto heapPipeline = addressable && HeapPassesActive(context) ? pipeline(tileModeOfMip, elementBytes, retile, thickPipeline, false, DetileVariant::Heap) : VK_NULL_HANDLE; + const auto variant = heapPipeline != VK_NULL_HANDLE ? DetileVariant::Heap : addressable ? DetileVariant::Addressed : DetileVariant::Classic; + if (variant == DetileVariant::Heap) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.BindComputePipeline(commands, heapPipeline); + } else if (variant == DetileVariant::Addressed) { + context.BindComputePipeline(commands, pipeline(tileModeOfMip, elementBytes, retile, thickPipeline, false, DetileVariant::Addressed)); + } else { + const auto set = allocateSet(); + writeBufferPair(context, set, {source, sourceDescriptorOffset, sourceRange}, {destination, destinationDescriptorOffset, destinationRange}); + context.BindComputePipeline(commands, pipeline(tileModeOfMip, elementBytes, retile, thickPipeline)); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::Detiler); + } Push push{}; push.srcBase = static_cast(sourceBase); push.dstBase = static_cast(destinationBase); @@ -287,7 +405,13 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode push.rowBegin = window.rowBegin; push.pipeBankXor = window.pipeBankXor ^ layerBankXor(tileMode, elementBytes, layout, slice); push.splitStride = layout.gcnSplitStride; - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); + if (variant != DetileVariant::Classic) { + const AddressedPush pushed{push, sourceAddress + sourceDescriptorOffset, destinationAddress + destinationDescriptorOffset}; + if (variant == DetileVariant::Heap) CmdPushData(context, commands, sizeof(pushed), &pushed); + else CmdPushConstants(context, commands, addressedPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); + } else { + CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); + } const auto groupsX = (columnEnd - window.columnBegin + 7u) / 8u; const auto groupsY = (rowEnd - window.rowBegin + 7u) / 8u; context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, groupsX, groupsY, 1); @@ -305,8 +429,12 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s VkComputePipelineCreateInfo createInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; createInfo.stage = stage; createInfo.layout = pipelineLayout; - auto pipelineCacheLock = context.LockPipelineCacheForUse(); - Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &repackPipeline), "vkCreateComputePipelines repack"); + { + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &repackPipeline), "vkCreateComputePipelines repack"); + } + const std::array mappings{HeapPushAddressMapping(0, 0, offsetof(AddressedRepackPush, source)), HeapPushAddressMapping(0, 1, offsetof(AddressedRepackPush, destination))}; + heapRepackPipeline = CreateHeapComputePipeline(context, createInfo, mappings); } const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); const auto sourceDescriptorOffset = sourceOffset - sourceOffset % alignment; @@ -318,23 +446,46 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s constexpr std::uint64_t rowWords = 64u * 1024u; const auto rows = (words + rowWords - 1u) / rowWords; Require(words <= UINT32_MAX && rows <= context.limits.maxComputeWorkGroupCount[1], "a texel repack exceeds the device's dispatch limits"); + const std::array repackPush{static_cast(sourceOffset - sourceDescriptorOffset), static_cast(destinationOffset - destinationDescriptorOffset), static_cast(words), static_cast(std::min(words, rowWords)), static_cast(depthToFloat)}; + const auto sourceAddress = bufferAddress(source); + const auto destinationAddress = sourceAddress != 0 ? bufferAddress(destination) : 0; + if (sourceAddress != 0 && destinationAddress != 0 && heapRepackPipeline != VK_NULL_HANDLE && HeapPassesActive(context)) { + const AddressedRepackPush pushed{repackPush, sourceAddress + sourceDescriptorOffset, destinationAddress + destinationDescriptorOffset}; + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.BindComputePipeline(commands, heapRepackPipeline); + CmdPushData(context, commands, sizeof(pushed), &pushed); + context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, static_cast((std::min(words, rowWords) + 63u) / 64u), static_cast(rows), 1); + return; + } + if (sourceAddress != 0 && destinationAddress != 0) { + if (addressedRepackPipeline == VK_NULL_HANDLE) { + VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + moduleInfo.codeSize = sizeof(TEXTURE_REPACK_ADDRESSED_SPV); + moduleInfo.pCode = TEXTURE_REPACK_ADDRESSED_SPV; + Check(context.Function("vkCreateShaderModule")(context.device, &moduleInfo, nullptr, &addressedRepackModule), "vkCreateShaderModule repack"); + VkPipelineShaderStageCreateInfo stage{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + stage.module = addressedRepackModule; + stage.pName = "main"; + VkComputePipelineCreateInfo createInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + createInfo.stage = stage; + createInfo.layout = addressedRepackLayout; + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &addressedRepackPipeline), "vkCreateComputePipelines repack"); + } + const AddressedRepackPush pushed{repackPush, sourceAddress + sourceDescriptorOffset, destinationAddress + destinationDescriptorOffset}; + context.BindComputePipeline(commands, addressedRepackPipeline); + CmdPushConstants(context, commands, addressedRepackLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); + context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, static_cast((std::min(words, rowWords) + 63u) / 64u), static_cast(rows), 1); + return; + } const auto set = allocateSet(); const VkDescriptorBufferInfo sourceInfo{source, sourceDescriptorOffset, sourceRange}; const VkDescriptorBufferInfo destinationInfo{destination, destinationDescriptorOffset, destinationRange}; - std::array writes{}; - for (std::uint32_t index = 0; index < writes.size(); ++index) { - writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[index].dstSet = set; - writes[index].dstBinding = index; - writes[index].descriptorCount = 1; - writes[index].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[index].pBufferInfo = index == 0 ? &sourceInfo : &destinationInfo; - } - context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); + writeBufferPair(context, set, sourceInfo, destinationInfo); context.BindComputePipeline(commands, repackPipeline); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, 0, nullptr); - const std::array push{static_cast(sourceOffset - sourceDescriptorOffset), static_cast(destinationOffset - destinationDescriptorOffset), static_cast(words), static_cast(std::min(words, rowWords)), static_cast(depthToFloat)}; - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::Detiler); + CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(repackPush), repackPush.data()); context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, static_cast((std::min(words, rowWords) + 63u) / 64u), static_cast(rows), 1); } @@ -345,7 +496,7 @@ std::uint32_t TextureDetiler::CmaskErrors() { return codes; } -void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write) { +void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write, const HeapSlotOwner* owner) { Require(commands != VK_NULL_HANDLE && cmask != VK_NULL_HANDLE && view != VK_NULL_HANDLE, "a CMASK clear needs a command buffer, the CMASK buffer and the target view"); Require(elementBytes == 1 || elementBytes == 2 || elementBytes == 4 || elementBytes == 8, "a CMASK clear of this element size is not modeled"); Require(cmaskOffset % 4 == 0 && cmaskBytes % 4 == 0 && cmaskBytes != 0, "a CMASK clear needs a word-aligned CMASK"); @@ -380,30 +531,50 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask auto pipelineCacheLock = context.LockPipelineCacheForUse(); created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &cmaskPipeline); } + if (created == VK_SUCCESS && addressedPipelineLayout != VK_NULL_HANDLE && DescriptorHeapEnabled() && BindlessHeap::For(context).DescriptorHeapMode()) { + const auto& bindless = BindlessHeap::For(context); + const std::array mappings{HeapPushAddressMapping(0, 0, offsetof(HeapCmaskPush, cmask)), HeapPushAddressMapping(0, 1, offsetof(HeapCmaskPush, errors)), HeapPushIndexMapping(bindless, 0, 2, DetileImageResource, offsetof(HeapCmaskPush, slot))}; + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + mappingInfo.mappingCount = static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + auto heapFlags = DescriptorHeapFlags(); + auto heapInfo = pipelineInfo; + heapInfo.pNext = &heapFlags; + heapInfo.stage.pNext = &mappingInfo; + heapInfo.layout = VK_NULL_HANDLE; + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + if (context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &heapInfo, nullptr, &cmaskHeapPipeline) != VK_SUCCESS) + cmaskHeapPipeline = VK_NULL_HANDLE; + } context.Function("vkDestroyShaderModule")(context.device, cmaskModule, nullptr); Check(created, "vkCreateComputePipelines CMASK clear"); - cmaskErrors = std::make_unique(context, 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + cmaskErrors = std::make_unique(context, 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (cmaskHeapPipeline != VK_NULL_HANDLE ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u)); std::memset(cmaskErrors->Bytes().data(), 0, 4); } - const auto set = allocateFrom(cmaskDescriptorSets, cmaskDescriptorLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 64 * 2}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 64}}, "vkCreateDescriptorPool CMASK clear", "vkAllocateDescriptorSets CMASK clear", "vkResetDescriptorPool CMASK clear"); + const auto cmaskAddress = cmaskHeapPipeline != VK_NULL_HANDLE && owner != nullptr ? bufferAddress(cmask) : 0; + const auto errorsAddress = cmaskAddress != 0 ? bufferAddress(cmaskErrors->Handle()) : 0; + const auto slot = errorsAddress != 0 ? BindlessHeap::For(context).ViewSlot(DetileHeapKind, owner, view) : std::nullopt; + const auto set = slot ? VK_NULL_HANDLE : allocateFrom(cmaskDescriptorSets, cmaskDescriptorLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 64 * 2}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 64}}, "vkCreateDescriptorPool CMASK clear", "vkAllocateDescriptorSets CMASK clear", "vkResetDescriptorPool CMASK clear"); const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); const auto descriptorOffset = cmaskOffset - cmaskOffset % alignment; const auto base = cmaskOffset - descriptorOffset; - const VkDescriptorBufferInfo cmaskInfo{cmask, descriptorOffset, base + cmaskBytes}; - const VkDescriptorBufferInfo errorInfo{cmaskErrors->Handle(), 0, 4}; - const VkDescriptorImageInfo imageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; - std::array writes{}; - for (std::uint32_t index = 0; index < writes.size(); ++index) { - writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[index].dstSet = set; - writes[index].dstBinding = index; - writes[index].descriptorCount = 1; - writes[index].descriptorType = index == 2 ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + if (!slot) { + const VkDescriptorBufferInfo cmaskInfo{cmask, descriptorOffset, base + cmaskBytes}; + const VkDescriptorBufferInfo errorInfo{cmaskErrors->Handle(), 0, 4}; + const VkDescriptorImageInfo imageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; + std::array writes{}; + for (std::uint32_t index = 0; index < writes.size(); ++index) { + writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[index].dstSet = set; + writes[index].dstBinding = index; + writes[index].descriptorCount = 1; + writes[index].descriptorType = index == 2 ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + } + writes[0].pBufferInfo = &cmaskInfo; + writes[1].pBufferInfo = &errorInfo; + writes[2].pImageInfo = &imageInfo; + context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); } - writes[0].pBufferInfo = &cmaskInfo; - writes[1].pBufferInfo = &errorInfo; - writes[2].pImageInfo = &imageInfo; - context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); const auto barrier = [&](VkPipelineStageFlags source, VkPipelineStageFlags destination, VkAccessFlags sourceAccess, VkAccessFlags destinationAccess) { VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; memory.srcAccessMask = sourceAccess; @@ -413,25 +584,31 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask constexpr VkAccessFlags anyWrite = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT; constexpr VkAccessFlags anyAccess = anyWrite | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_HOST_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT; barrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, anyWrite, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); - context.BindComputePipeline(commands, cmaskPipeline); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set, 0, nullptr); const std::uint32_t mask = elementBytes >= 4 ? 0xffffffffu : (1u << (elementBytes * 8u)) - 1u; const std::array push{static_cast(base), width, height, (width + 1023u) / 1024u, clearWords[0] & mask, elementBytes == 8 ? clearWords[1] : 0u, write ? 1u : 0u}; - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, cmaskPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + if (slot) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.BindComputePipeline(commands, cmaskHeapPipeline); + const HeapCmaskPush pushed{push, 0u, cmaskAddress + descriptorOffset, errorsAddress, *slot, 0u}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + } else { + context.BindComputePipeline(commands, cmaskPipeline); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set, SetBindSite::Detiler); + CmdPushConstants(context, commands, cmaskPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + } context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, (width + 7u) / 8u, (height + 7u) / 8u, 1); barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT, anyAccess); context.Resolved(&DeviceFunctions::cmdFillBuffer, "vkCmdFillBuffer")(commands, cmask, cmaskOffset, cmaskBytes, 0xffffffffu); barrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, anyAccess); } -void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile, std::uint32_t slice, const DetileWindow& window) { +void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile, std::uint32_t slice, const DetileWindow& window, const HeapSlotOwner* owner) { Require(commands != VK_NULL_HANDLE, "texture detiling requires an active command buffer"); Require(window.rangeBegin < window.rangeEnd && window.tiledBase <= window.rangeBegin, "texture detiling window is empty"); Require(tiled != VK_NULL_HANDLE && view != VK_NULL_HANDLE, "texture detiling requires a tiled buffer and an image view"); Require(ImageElementFormat(elementBytes) != VK_FORMAT_UNDEFINED, "unsupported element size for texture detiling through an image"); std::uint32_t columnEnd = 0, rowEnd = 0; checkWindow(layout, window, columnEnd, rowEnd); - const auto target = pipeline(MipTileMode(tileMode, layout), elementBytes, retile, false, true); const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); const auto descriptorOffset = tiledOffset - tiledOffset % alignment; const auto base = tiledOffset - descriptorOffset; @@ -439,25 +616,6 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til const std::uint64_t tiledBytes = window.rangeEnd == 0xffffffffu ? layout.tiledSize : std::min(layout.tiledSize, window.rangeEnd) - window.tiledBase; const auto range = (base + tiledBytes + 3) / 4 * 4; Require(range <= context.limits.maxStorageBufferRange, "texture detiling buffer range exceeds device limits"); - const auto set = allocateSet(true); - const VkDescriptorBufferInfo bufferInfo{tiled, descriptorOffset, range}; - const VkDescriptorImageInfo imageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; - std::array writes{}; - writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[0].dstSet = set; - writes[0].dstBinding = 0; - writes[0].descriptorCount = 1; - writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[0].pBufferInfo = &bufferInfo; - writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[1].dstSet = set; - writes[1].dstBinding = 1; - writes[1].descriptorCount = 1; - writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - writes[1].pImageInfo = &imageInfo; - context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); - context.BindComputePipeline(commands, target); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set, 0, nullptr); Push push{}; push.srcBase = static_cast(retile ? 0 : base); push.dstBase = static_cast(retile ? base : 0); @@ -478,7 +636,24 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til push.rowBegin = window.rowBegin; push.pipeBankXor = window.pipeBankXor ^ layerBankXor(tileMode, elementBytes, layout, slice); push.splitStride = layout.gcnSplitStride; - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); + std::optional slot; + const auto tiledAddress = owner != nullptr && DescriptorHeapEnabled() ? bufferAddress(tiled) : 0; + const auto heapPipeline = tiledAddress != 0 ? pipeline(MipTileMode(tileMode, layout), elementBytes, retile, false, true, DetileVariant::Heap) : VK_NULL_HANDLE; + if (heapPipeline != VK_NULL_HANDLE) slot = BindlessHeap::For(context).ViewSlot(DetileHeapKind, owner, view); + if (slot) { + auto& bindless = BindlessHeap::For(context); + bindless.BindDescriptorHeaps(commands); + context.BindComputePipeline(commands, heapPipeline); + const HeapImagePush pushed{push, tiledAddress + descriptorOffset, *slot, 0u}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + } else { + const auto target = pipeline(MipTileMode(tileMode, layout), elementBytes, retile, false, true); + const auto set = allocateSet(true); + writeBufferImage(context, set, {tiled, descriptorOffset, range}, {VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}); + context.BindComputePipeline(commands, target); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set, SetBindSite::Detiler); + CmdPushConstants(context, commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); + } const auto groupsX = (columnEnd - window.columnBegin + 7u) / 8u; const auto groupsY = (rowEnd - window.rowBegin + 7u) / 8u; context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, groupsX, groupsY, 1); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp index 1820ce5a4dc0..0c66584d9e21 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" #include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/SlimMutex.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -221,12 +222,16 @@ std::shared_ptr makeSlab(const Context& context, std::uint64_t first VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = static_cast(units) * UnitBytes; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + const bool addressable = BufferPool::ForceAddresses() && context.bufferDeviceAddress; + if (addressable) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VkBuffer buffer = VK_NULL_HANDLE; if (context.Function("vkCreateBuffer")(context.device, &info, nullptr, &buffer) != VK_SUCCESS) return nullptr; VkMemoryRequirements requirements{}; context.Function("vkGetBufferMemoryRequirements")(context.device, buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + const VkMemoryAllocateFlagsInfo addressFlags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, nullptr, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0}; + if (addressable) allocation.pNext = &addressFlags; allocation.allocationSize = requirements.size; VkDeviceMemory memory = VK_NULL_HANDLE; try { diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp index ccf33f592a8e..82a88660b7f1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp @@ -246,6 +246,18 @@ void RunBdaContractTests() { auto unparsed = MakeBdaStoreTestShader(0x1000, 7, 32, false); unparsed[5] |= 0xffff0000u; AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(unparsed), "a module with an instruction past its end was taken for one without stores"); + RecompileResult classic; + classic.spirv = SharedSpirv(MakeBdaStoreTestShader(0x1000, 7, 32, false)); + AgcDriver::Graphics::Require(AgcDriver::Graphics::ProgramStoresThroughAddresses(classic), "a classic program's BDA store was taken from the emitter flag instead of its SPIR-V"); + classic.spirv = SharedSpirv(MakeBdaTestShader(0x1000, 32)); + classic.bdaStores = true; + AgcDriver::Graphics::Require(!AgcDriver::Graphics::ProgramStoresThroughAddresses(classic), "a classic program reading through an address was taken for one storing"); + RecompileResult heap; + heap.gpuResolvedImages = true; + heap.spirv = SharedSpirv(MakeBdaStoreTestShader(0x1000, 7, 32, false)); + AgcDriver::Graphics::Require(!AgcDriver::Graphics::ProgramStoresThroughAddresses(heap), "a heap program's stores were not taken from the emitter flag"); + heap.bdaStores = true; + AgcDriver::Graphics::Require(AgcDriver::Graphics::ProgramStoresThroughAddresses(heap), "a heap program's BDA store flag was ignored"); using AgcDriver::Graphics::SpirvFaultReportOnly; AgcDriver::Graphics::Require(SpirvFaultReportOnly(MakeBdaTestShader(0x1000, 32), 0, 1) && SpirvFaultReportOnly(MakeBdaDwordReadTestShader(0x1000, 4, false, false), 0, 1) && SpirvFaultReportOnly(MakeBdaFaultSequenceTestShader({BdaAbi::FaultReason::Unmapped, BdaAbi::FaultReason::Unaligned}), 0, 1), "a BDA read program, which writes only the fault report, was given a full fault buffer"); AgcDriver::Graphics::Require(!SpirvFaultReportOnly(MakeBdaStoreTestShader(0x1000, 7, 32, false), 0, 1) && !SpirvFaultReportOnly(MakeBdaWriteTestShader(0x1000, 7, 32, false), 0, 1), "a BDA store program, which records written pages, was given a report-only fault buffer"); diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp index 4d30663f7aa9..95f7b0e4a1ee 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp @@ -720,6 +720,9 @@ void importJoinTests(const Context& context) { Require(prefix != nullptr && prefix->base == heapBase && prefix->bytes == 3 * piece && prefixBuffer == prefix->buffer && prefixCopied == 0, "a buffer bound from the first of three pieces into the last was not imported over the pieces it crosses"); const auto* kept = HostImportFor(importing, first, 16); Require(kept != nullptr && kept->buffer == joinedBuffer && kept->bytes == 2 * large, "a registry change elsewhere re-imported the joined ranges"); + const auto [startedBuffer, startedCopied] = bind(heapBase, 2 * piece + 32); + const auto* started = HostImportFor(importing, heapBase, 2 * piece + 32); + Require(started != nullptr && started->base == heapBase && started->bytes == 3 * piece && startedBuffer == started->buffer && startedCopied == 0, "a buffer bound from the start of one piece into the next was not imported as one run"); change(guest + 2 * large, large, true); Require(HostImportFor(importing, first, 16)->buffer == joinedBuffer, "a range registered next to the joined ranges re-imported them"); const auto [grownBuffer, grownCopied] = bind(third - 16); @@ -5335,6 +5338,7 @@ void RunBdaResourceTests(const Context& context, const BdaTestAccess& access) { const std::array snapshots{{{0x7fff12340000ULL, source}}}; ShaderRecompiler::RecompileResult shader; shader.bindings = {binding(Role::BdaPagetable, 4), binding(Role::FaultBuffer, 5)}; + shader.bdaStores = true; CompiledShader compiled{ShaderRecompiler::ShaderStage::Compute, &shader, 0}; reject([&] { ShaderResources resources(context, compiled, snapshots); }, "ABI version"); shader.bdaAbiVersion = ShaderRecompiler::BdaAbi::Version; diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp new file mode 100644 index 000000000000..43641a33e2ac --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -0,0 +1,695 @@ +#include "execution/VulkanTestDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" +#include "prx/libSceAgcDriver/Graphics/include/PlaceholderImages.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "RuntimeAbi.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace AgcDriver::Graphics; +namespace Abi = ShaderRecompiler::RuntimeAbi; + +void require(bool condition, const std::string& what) { + if (!condition) throw std::runtime_error(what); +} + +struct FakeOwner : HeapSlotOwner { + FakeOwner() = default; +}; + +std::shared_ptr fakeTexture(const Context& context, std::size_t) { + VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + info.imageType = VK_IMAGE_TYPE_2D; + info.format = VK_FORMAT_R8G8B8A8_UNORM; + info.extent = {1u, 1u, 1u}; + info.mipLevels = 1u; + info.arrayLayers = 1u; + info.samples = VK_SAMPLE_COUNT_1_BIT; + info.tiling = VK_IMAGE_TILING_OPTIMAL; + info.usage = VK_IMAGE_USAGE_SAMPLED_BIT; + info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + VkImage image = VK_NULL_HANDLE; + require(context.Function("vkCreateImage")(context.device, &info, nullptr, &image) == VK_SUCCESS, "a texture fixture image is created"); + VkMemoryRequirements requirements{}; + context.Function("vkGetImageMemoryRequirements")(context.device, image, &requirements); + VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + allocation.allocationSize = requirements.size; + allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory memory = VK_NULL_HANDLE; + const auto release = [context, image, &memory] { + context.Function("vkDestroyImage")(context.device, image, nullptr); + if (memory != VK_NULL_HANDLE) context.Function("vkFreeMemory")(context.device, memory, nullptr); + }; + std::unique_ptr texture; + try { + require(context.Function("vkAllocateMemory")(context.device, &allocation, nullptr, &memory) == VK_SUCCESS, "a texture fixture image gets memory"); + require(context.Function("vkBindImageMemory")(context.device, image, memory, 0u) == VK_SUCCESS, "a texture fixture image binds its memory"); + texture = std::make_unique(context, image, info.format, VK_IMAGE_ASPECT_COLOR_BIT, VkComponentMapping{}); + } catch (...) { + release(); + throw; + } + return std::shared_ptr(texture.release(), [context, image, memory](Texture* released) { + delete released; + context.Function("vkDestroyImage")(context.device, image, nullptr); + context.Function("vkFreeMemory")(context.device, memory, nullptr); + }); +} + +void textureSlots(const Context& context, VkImageView view) { + BindlessHeap heap(context); + const auto kind = Abi::FirstImageBinding; + auto first = fakeTexture(context, 0); + const auto slot = heap.TextureSlot(kind, first.get(), view, VK_IMAGE_LAYOUT_GENERAL); + require(slot.has_value(), "the first texture takes a slot"); + require(heap.SlotTexture(kind, *slot) == first.get(), "the slot names the first texture"); + require(first.use_count() == 1, "a heap slot holds a reference to its texture"); + const auto generation = heap.SlotGeneration(*slot); + + auto second = fakeTexture(context, 1); + require(!heap.TextureSlot(kind, second.get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "the slot of a live texture is not reused"); + heap.ReleaseSlots(first.get()); + const auto reused = heap.TextureSlot(kind, second.get(), view, VK_IMAGE_LAYOUT_GENERAL); + require(reused.has_value() && *reused == *slot, "the released texture's slot is reused"); + require(heap.SlotGeneration(*slot) != generation, "a freed slot moves its generation"); + require(heap.SlotTexture(kind, *slot) == second.get(), "the reused slot names the second texture"); + const auto counts = heap.Statistics(); + require(counts.slotsFreed == 1u, "one slot freed"); + + auto shared = fakeTexture(context, 2); + const auto otherKind = kind + 1u; + require(!heap.TextureSlot(otherKind, shared.get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), + "another kind finds the capped heap's only slot taken"); + heap.ReleaseSlots(second.get()); + const auto sharedSlot = heap.TextureSlot(otherKind, shared.get(), view, VK_IMAGE_LAYOUT_GENERAL); + require(sharedSlot.has_value() && *sharedSlot == *slot, "another kind takes the slot the first kind's texture left"); + require(heap.SlotTexture(kind, *slot) == nullptr && heap.SlotTexture(otherKind, *slot) == shared.get(), + "the slot names the other kind's texture"); + const auto freedBefore = heap.Statistics().slotsFreed; + heap.ReleaseSlots(shared.get()); + heap.ReleaseSlots(shared.get()); + require(heap.Statistics().slotsFreed == freedBefore + 1u, "a texture's release frees its slot once"); +} + +void samplerSlots(const Context& context) { + auto& heap = BindlessHeap::For(context); + auto cache = std::make_unique(); + const std::array firstWords{0u, 0u, 0u, 0u}; + const std::array secondWords{0u, 0u, 0x00100000u, 0u}; + auto first = cache->Get(context, firstWords, false); + const auto uses = first.use_count(); + const auto slot = heap.SamplerSlot(first); + require(slot.has_value(), "the first sampler takes a slot"); + require(first.use_count() == uses, "a heap slot holds a reference to its sampler"); + const auto generation = heap.SamplerGeneration(*slot); + require(first->CacheKey() != nullptr, "a cached sampler carries its key"); + first.reset(); + cache.reset(); + require(heap.SamplerGeneration(*slot) != generation, "a destroyed sampler did not release its slot"); + cache = std::make_unique(); + auto second = cache->Get(context, secondWords, false); + const auto reused = heap.SamplerSlot(second); + require(reused.has_value() && *reused == *slot, "the destroyed sampler's slot is reused"); +} + +void viewSlots(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstStorageImageBinding + 27u; + FakeOwner first, second; + const auto slot = heap.ViewSlot(kind, &first, view); + require(slot.has_value() && heap.ViewSlot(kind, &first, view) == slot, "a view keeps its slot"); + require(!heap.ViewSlot(kind, &second, view).has_value(), "a full heap refuses another owner's view"); + const auto generation = heap.SlotGeneration(*slot); + heap.ReleaseSlots(&first); + require(heap.SlotGeneration(*slot) != generation, "a released view slot moves its generation"); + require(heap.ViewSlot(kind, &second, view) == slot, "a released view slot is reused"); + heap.ReleaseSlots(&second); +} + +void encodedViews(const Context& context) { + BindlessHeap heap(context); + const auto base = heap.Statistics(); + const auto encodes = [&] { return heap.Statistics().encodes - base.encodes; }; + const auto copies = [&] { return heap.Statistics().encodedCopies - base.encodedCopies; }; + VkImageView destroyed = VK_NULL_HANDLE; + const auto storageKey = static_cast(VK_IMAGE_LAYOUT_GENERAL) | 0x80000000u; + std::vector bytes(static_cast(heap.ImageHeapStride())); + { + const PlaceholderImages placeholders(context); + const auto view = placeholders.View(Abi::FirstStorageImageBinding); + heap.AbsentSlot(Abi::FirstStorageImageBinding + 2u, view); + require(encodes() == 1u && copies() == 0u, "a view's first heap slot encodes its descriptor"); + heap.AbsentSlot(Abi::FirstStorageImageBinding + 3u, view); + require(encodes() == 1u && copies() == 1u, "another slot for the same view copies the encoded descriptor"); + require(CopyEncodedImageView(context.device, view, storageKey, bytes), "a live view keeps its encoded descriptor"); + destroyed = view; + } + require(!CopyEncodedImageView(context.device, destroyed, storageKey, bytes), "a destroyed view drops its encoded descriptor"); + const PlaceholderImages again(context); + heap.AbsentSlot(Abi::FirstStorageImageBinding + 4u, again.View(Abi::FirstStorageImageBinding)); + require(encodes() == 2u && copies() == 1u, "a destroyed view's encoded descriptor is not copied to a new view"); +} + +void ownerSlots(const Context& context, VkImageView view) { + BindlessHeap heap(context); + FakeOwner image, other; + const auto slot = heap.StorageSlot(Abi::FirstStorageImageBinding, &image, view); + require(slot.has_value(), "a storage owner takes the capped heap's only slot"); + require(!heap.StorageSlot(Abi::FirstStorageImageBinding + 1u, &image, view).has_value(), "the owner's second view finds the heap full"); + heap.ReleaseSlots(&other); + require(!heap.StorageSlot(Abi::FirstStorageImageBinding, &other, view).has_value(), "another owner's release freed this owner's slot"); + heap.ReleaseSlots(&image); + require(heap.StorageSlot(Abi::FirstStorageImageBinding, &other, view) == slot, "a storage owner's release frees its slot"); + heap.ReleaseSlots(&other); +} + +void ownerViewsRelease(const Context& context, VkImageView view) { + BindlessHeap heap(context); + FakeOwner owner; + const auto firstKind = Abi::FirstStorageImageBinding, secondKind = Abi::FirstStorageImageBinding + 1u; + const auto first = heap.StorageSlot(firstKind, &owner, view); + const auto second = heap.ViewSlot(secondKind, &owner, view); + require(first.has_value() && second.has_value() && *first != *second, "one owner takes a slot for each of its two views"); + const auto before = heap.Statistics(); + const auto serial = heap.SlotSerial(); + require(heap.StorageSlot(firstKind, &owner, view) == first && heap.ViewSlot(secondKind, &owner, view) == second, "a lookup hit returns the owner's existing slots"); + const auto hit = heap.Statistics(); + require(hit.slotsFreed == before.slotsFreed && hit.encodes == before.encodes && hit.encodedCopies == before.encodedCopies, + "a lookup hit changed the counts"); + require(heap.SlotSerial() == serial, "a lookup hit moved the slot serial"); + const auto firstGeneration = heap.SlotGeneration(*first), secondGeneration = heap.SlotGeneration(*second); + heap.ReleaseSlots(&owner); + const auto released = heap.Statistics(); + require(released.slotsFreed == before.slotsFreed + 2u, "one release freed " + std::to_string(released.slotsFreed - before.slotsFreed) + " of the owner's two slots"); + require(heap.SlotGeneration(*first) != firstGeneration && heap.SlotGeneration(*second) != secondGeneration, "the release moved both slots' generations"); + require(heap.SlotSerial() != serial, "a release moved the slot serial"); + const auto releasedSerial = heap.SlotSerial(); + const auto releasedGenerations = std::array{heap.SlotGeneration(*first), heap.SlotGeneration(*second)}; + heap.ReleaseSlots(&owner); + require(heap.Statistics().slotsFreed == released.slotsFreed, "a second release of the same owner freed slots"); + require(heap.SlotSerial() == releasedSerial, "a second release moved the slot serial"); + require(heap.SlotGeneration(*first) == releasedGenerations[0] && heap.SlotGeneration(*second) == releasedGenerations[1], "a second release moved a generation"); +} + +struct SharedOwner : std::enable_shared_from_this, HeapSlotOwner { + explicit SharedOwner(const Context& context) : context(context) {} + ~SharedOwner() { ReleaseHeapSlots(context); } + Context context; +}; + +void sharedOwnerRelease(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + auto owner = std::make_shared(context); + const HeapSlotOwner* base = owner.get(); + require(static_cast(base) != static_cast(owner.get()), "the slot owner base does not sit behind another base"); + const auto slot = heap.StorageSlot(Abi::FirstStorageImageBinding, owner.get(), view); + require(slot.has_value(), "an owner behind another base takes a slot"); + const auto generation = heap.SlotGeneration(*slot); + const auto freed = heap.Statistics().slotsFreed; + owner.reset(); + require(heap.SlotGeneration(*slot) != generation && heap.Statistics().slotsFreed == freed + 1u, + "destroying an owner behind another base did not free its slot"); +} + +void writeTails(const Context& context) { + BindlessHeap heap(context); + for (const std::size_t count : {0u, 1u, 3u, 4u, 5u, 7u, 9u}) { + std::vector words(count); + for (std::size_t index = 0; index < count; ++index) words[index] = 0x1000u * static_cast(count) + static_cast(index) + 1u; + const auto span = heap.Allocate(count + 1u); + span.words[count] = 0xdeadbeefu; + BindlessHeap::Write(span, words); + require(std::equal(words.begin(), words.end(), span.words.begin()), "a GPU heap span holds other words than were written"); + require(span.words[count] == 0xdeadbeefu, "writing a GPU heap span wrote past its words"); + } +} + +void spanScope(const Context& context) { + BindlessHeap heap(context); + std::atomic allocated{false}; + std::thread other; + bool waited = false; + { + const BindlessHeap::SpanScope outer(heap); + const BindlessHeap::SpanScope inner(heap); + static_cast(heap.Allocate(16u)); + other = std::thread([&] { + static_cast(heap.Allocate(16u)); + allocated.store(true, std::memory_order_release); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + waited = !allocated.load(std::memory_order_acquire); + } + other.join(); + require(waited, "another thread's span waits while a scope holds the allocator"); + require(allocated.load(std::memory_order_acquire), "the other thread allocates once the scope ends"); + require(heap.Statistics().spansWritten == 2u, "both spans are counted"); +} + +bool dataPool(const Context& context) { + Recorder recorder(context, true); + if (!recorder.HasTimeline()) return false; + constexpr std::size_t blockWords = AgcDriver::Graphics::BindlessHeap::PoolBlockBytes / sizeof(std::uint32_t); + { + BindlessHeap heap(context); + for (int index = 0; index < 5; ++index) static_cast(heap.Allocate(blockWords / 2u)); + require(heap.Statistics().poolBlocksMade == 3u, "one batch's shader data grows into new blocks instead of waiting"); + const auto span = heap.Allocate(blockWords * 3u / 2u); + require(span.words.size() == blockWords * 3u / 2u && heap.Statistics().poolBlocksMade == 4u, "a span larger than a block gets a block of its own"); + const auto [buffer, offset] = heap.DataLocation(span.address + 64u); + require(buffer != VK_NULL_HANDLE && offset == span.offset + 64u, "a pooled address maps back to its buffer and offset"); + heap.Submitted(recorder, recorder.Submissions() + (1ull << 40u)); + const auto made = heap.Statistics().poolBlocksMade; + for (int index = 0; index < 4; ++index) static_cast(heap.Allocate(blockWords / 2u + 1u)); + const auto busy = heap.Statistics(); + require(busy.poolBlocksRecycled == 0u && busy.poolBlocksMade > made, "blocks a batch in flight still reads are not reused"); + } + { + BindlessHeap heap(context); + for (int index = 0; index < 3; ++index) static_cast(heap.Allocate(blockWords - 64u)); + heap.Submitted(recorder, 0u); + const auto made = heap.Statistics().poolBlocksMade; + static_cast(heap.Allocate(blockWords - 64u)); + const auto counts = heap.Statistics(); + require(counts.poolBlocksRecycled == 1u && counts.poolBlocksMade == made, "a completed block is reused instead of making a new one"); + } + { + BindlessHeap heap(context); + constexpr std::size_t blocks = 2u * AgcDriver::Graphics::BindlessHeap::PoolIdleBytes / AgcDriver::Graphics::BindlessHeap::PoolBlockBytes; + for (std::size_t index = 0; index < blocks; ++index) static_cast(heap.Allocate(blockWords - 64u)); + heap.Submitted(recorder, 0u); + const auto counts = heap.Statistics(); + require(counts.poolBlocksFreed != 0u && counts.poolBlockBytes <= AgcDriver::Graphics::BindlessHeap::PoolIdleBytes + AgcDriver::Graphics::BindlessHeap::PoolBlockBytes, + "idle blocks beyond the pool's budget are freed"); + } + { + BindlessHeap heap(context); + const BindlessHeap::SpanScope spans(heap); + BindlessHeap::TableMark table; + const std::vector words(40u, 0x5au); + const auto first = heap.AllocateTable(spans, words.size(), table); + require(first.has_value() && table.address == first->address && first->words.size() == words.size(), "a stage table is allocated"); + BindlessHeap::Write(*first, words); + const auto firstAddress = table.address; + heap.RetireTable(spans, table); + require(table.address == 0u, "a retired table leaves its owner"); + BindlessHeap::TableMark unsubmitted; + const auto second = heap.AllocateTable(spans, words.size(), unsubmitted); + require(second.has_value() && second->address != firstAddress, "a table retired in the open batch is not reused before the batch is submitted"); + heap.Submitted(recorder, recorder.Submissions() + (1ull << 40u)); + BindlessHeap::TableMark busy; + const auto third = heap.AllocateTable(spans, words.size(), busy); + require(third.has_value() && third->address != firstAddress, "a table a batch in flight still reads is not reused"); + heap.RetireTable(spans, unsubmitted); + heap.Submitted(recorder, 0u); + BindlessHeap::TableMark reused; + const auto fourth = heap.AllocateTable(spans, words.size(), reused); + require(fourth.has_value() && fourth->address != firstAddress, "a table waits for the batch that last read it, not a later one"); + BindlessHeap::TableMark large; + const auto big = heap.AllocateTable(spans, AgcDriver::Graphics::BindlessHeap::TableBlockBytes, large); + require(big.has_value() && big->words.size() == AgcDriver::Graphics::BindlessHeap::TableBlockBytes && heap.DataLocation(large.address).first != VK_NULL_HANDLE, "a table larger than a shared block gets a block of its own"); + } + { + BindlessHeap heap(context); + for (int index = 0; index < 3; ++index) static_cast(heap.Allocate(blockWords - 64u)); + const BindlessHeap::SpanScope spans(heap); + BindlessHeap::TableMark table; + static_cast(heap.AllocateTable(spans, 40u, table)); + const auto address = table.address; + heap.RetireTable(spans, table); + { + Recorder gone(context, true); + heap.Submitted(gone, gone.Submissions() + (1ull << 40u)); + const auto made = heap.Statistics().poolBlocksMade; + static_cast(heap.Allocate(blockWords - 64u)); + require(heap.Statistics().poolBlocksRecycled == 0u && heap.Statistics().poolBlocksMade == made + 1u, "a block a live recorder's batch still reads is not reused"); + heap.RecorderDestroyed(gone); + } + const auto made = heap.Statistics().poolBlocksMade; + static_cast(heap.Allocate(blockWords - 64u)); + require(heap.Statistics().poolBlocksRecycled == 1u && heap.Statistics().poolBlocksMade == made, "a destroyed recorder's blocks are released without dereferencing it"); + BindlessHeap::TableMark after; + require(heap.AllocateTable(spans, 40u, after).has_value() && after.address == address, "a destroyed recorder's retired table is reusable without dereferencing it"); + } + { + BindlessHeap heap(context); + const BindlessHeap::SpanScope spans(heap); + BindlessHeap::TableMark table; + static_cast(heap.AllocateTable(spans, 40u, table)); + const auto address = table.address; + heap.RetireTable(spans, table); + heap.Submitted(recorder, 0u); + BindlessHeap::TableMark next; + require(heap.AllocateTable(spans, 40u, next).has_value() && next.address == address, "a table whose batch completed is reused"); + } + return true; +} + +void heapComesBack(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstImageBinding; + std::vector> held; + for (std::size_t index = 0; index < 7u; ++index) { + held.push_back(fakeTexture(context, index)); + require(heap.TextureSlot(kind, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), + "a texture takes one of the eight capped slots"); + } + require(BindlessHeap::NearlyFull(), "one free slot of eight marks the heap nearly full"); + for (std::size_t index = 0; index < 2u; ++index) heap.ReleaseSlots(held[index].get()); + require(BindlessHeap::NearlyFull(), "three free slots of eight leave the heap nearly full"); + heap.ReleaseSlots(held[2].get()); + require(!BindlessHeap::NearlyFull(), "a release that leaves twice the margin free clears the nearly full state"); + for (std::size_t index = 3; index < held.size(); ++index) heap.ReleaseSlots(held[index].get()); + BindlessHeap::Release(context.device); +} + +bool idleSlotsEvicted(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstImageBinding; + Recorder recorder(context, true); + if (!recorder.HasTimeline()) return false; + recorder.Activate(); + const auto submit = [&] { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + recorder.Submit(); + }; + std::vector> held; + std::vector slots; + const auto take = [&](std::size_t index) { + if (held.size() <= index) held.resize(index + 1u); + if (held[index] == nullptr) held[index] = fakeTexture(context, index); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + return heap.TextureSlot(kind, held[index].get(), view, VK_IMAGE_LAYOUT_GENERAL); + }; + for (std::size_t index = 0; index < 6u; ++index) { + const auto slot = take(index); + require(slot.has_value(), "a texture takes one of the eight capped slots"); + slots.push_back(*slot); + } + const auto idleGeneration = heap.SlotGeneration(slots[0]); + submit(); + submit(); + require(take(5) == slots[5], "a texture a draw uses again keeps its slot"); + require(take(6).has_value(), "the seventh texture takes a slot"); + require(heap.Statistics().slotsEvicted == 5u, "the five slots idle for two submissions are evicted"); + require(heap.SlotTexture(kind, slots[0]) == nullptr && heap.SlotGeneration(slots[0]) != idleGeneration, + "an evicted slot names no texture and moves its generation"); + require(heap.SlotTexture(kind, slots[5]) == held[5].get(), "the slot used again stays with its texture"); + require(BindlessHeap::NearlyFull(), "evicted slots no submission covers yet do not count as free"); + require(take(7).has_value(), "the eighth texture takes the last never-used slot"); + require(!take(8).has_value(), "an evicted slot is not reused before a submission covers the draws that used it"); + submit(); + require(!BindlessHeap::NearlyFull(), "evicted slots a submission covers clear the nearly full state"); + require(recorder.WaitSerialFor(recorder.Submissions(), ~std::uint64_t{0}), "the submission completes"); + const auto reused = take(8); + require(reused.has_value() && std::find(slots.begin(), slots.begin() + 5, *reused) != slots.begin() + 5, + "an evicted slot is reused once the submission after its eviction completes"); + const auto back = take(0); + require(back.has_value() && heap.SlotTexture(kind, *back) == held[0].get(), "an evicted texture takes a slot again when a draw uses it"); + for (const auto& texture : held) heap.ReleaseSlots(texture.get()); + BindlessHeap::Release(context.device); + return true; +} + +void storageComesBack(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + std::array owners{}; + for (auto& owner : owners) { + require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), + "a storage owner takes one of the eight capped slots"); + } + require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight mark the heap nearly full"); + for (auto& owner : owners) heap.ReleaseSlots(&owner); + require(!BindlessHeap::NearlyFull(), "releasing the storage owners clears the nearly full state"); + BindlessHeap::Release(context.device); +} + +void storageViewsComeBack(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + std::array owners{}; + for (std::size_t index = 0; index < 3u; ++index) { + for (std::uint32_t kind = 0; kind < 2u; ++kind) { + require(heap.StorageSlot(Abi::FirstStorageImageBinding + kind, &owners[index], view).has_value(), + "a storage owner takes one of the eight capped slots for each of its two views"); + } + } + require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owners[3], view).has_value(), "a single-view storage owner takes the seventh slot"); + require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight mark the heap nearly full"); + const auto freed = heap.Statistics().slotsFreed; + heap.ReleaseSlots(&owners[0]); + require(heap.Statistics().slotsFreed == freed + 2u, "a storage owner's release freed " + std::to_string(heap.Statistics().slotsFreed - freed) + " of its two slots"); + require(BindlessHeap::NearlyFull(), "three free slots of eight leave the heap nearly full"); + heap.ReleaseSlots(&owners[1]); + require(!BindlessHeap::NearlyFull(), "releasing a second two-view owner clears the nearly full state"); + heap.ReleaseSlots(&owners[2]); + heap.ReleaseSlots(&owners[3]); + BindlessHeap::Release(context.device); +} + +void mixedComesBack(const Context& context, VkImageView sampledView, VkImageView storageView) { + auto& heap = BindlessHeap::For(context); + std::vector> textures; + for (std::size_t index = 0; index < 4u; ++index) { + textures.push_back(fakeTexture(context, index)); + require(heap.TextureSlot(Abi::FirstImageBinding, textures.back().get(), sampledView, VK_IMAGE_LAYOUT_GENERAL).has_value(), + "a texture takes one of the eight capped slots"); + } + require(!BindlessHeap::NearlyFull(), "four textures in eight capped slots do not mark the heap nearly full"); + std::array owners{}; + for (auto& owner : owners) { + require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owner, storageView).has_value(), + "a storage owner takes one of the slots the textures left"); + } + require(BindlessHeap::NearlyFull(), "storage owners that take the slots the textures left mark the heap nearly full"); + for (auto& owner : owners) heap.ReleaseSlots(&owner); + require(!BindlessHeap::NearlyFull(), "releasing the storage owners clears the nearly full state while the textures stay"); + for (const auto& texture : textures) heap.ReleaseSlots(texture.get()); + BindlessHeap::Release(context.device); +} + +void viewsComeBack(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstStorageImageBinding + 27u; + std::array owners{}; + for (auto& owner : owners) require(heap.ViewSlot(kind, &owner, view).has_value(), "a view takes one of the eight capped slots"); + require(BindlessHeap::NearlyFull(), "views that leave one free slot of eight mark the heap nearly full"); + for (auto& owner : owners) heap.ReleaseSlots(&owner); + require(!BindlessHeap::NearlyFull(), "releasing the views clears the nearly full state"); + BindlessHeap::Release(context.device); +} + +void twoHeapsComeBack(const Context& context, VkImageView view) { + auto first = std::make_unique(context); + auto second = std::make_unique(context); + std::array firstOwners{}, secondOwners{}; + for (auto& owner : firstOwners) require(first->ViewSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a view takes one of the first heap's eight capped slots"); + for (auto& owner : secondOwners) require(second->ViewSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a view takes one of the second heap's eight capped slots"); + require(BindlessHeap::NearlyFull(), "two nearly full heaps mark the heap nearly full"); + for (auto& owner : secondOwners) second->ReleaseSlots(&owner); + require(BindlessHeap::NearlyFull(), "room in the second heap cleared the nearly full state while the first stays nearly full"); + second.reset(); + require(BindlessHeap::NearlyFull(), "destroying the second heap cleared the nearly full state while the first stays nearly full"); + for (auto& owner : firstOwners) first->ReleaseSlots(&owner); + require(!BindlessHeap::NearlyFull(), "room in the last nearly full heap did not clear the nearly full state"); + first.reset(); +} + +bool slotPressureSubmits(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstImageBinding; + Recorder recorder(context, true); + if (!recorder.HasTimeline()) return false; + recorder.Activate(); + const auto submit = [&] { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + recorder.Submit(); + }; + std::vector> held; + std::vector slots; + for (std::size_t index = 0; index < 7u; ++index) { + held.push_back(fakeTexture(context, index)); + const auto slot = heap.TextureSlot(kind, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL); + require(slot.has_value(), "a texture takes one of the eight capped slots"); + slots.push_back(*slot); + } + require(BindlessHeap::NearlyFull(), "one free slot of eight marks the heap nearly full"); + submit(); + require(heap.Statistics().slotsEvicted == 0u && BindlessHeap::NearlyFull(), + "a submission in the middle of a draw evicts no slot the draw took in the batch it submitted"); + const auto submitsBefore = heap.Statistics().slotPressureSubmits; + const auto generation = heap.SlotGeneration(slots[0]); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + require(heap.TakeSlotPressure() && heap.Statistics().slotPressureSubmits == submitsBefore + 1u, "a nearly full heap asks the next draw to submit its batch"); + recorder.Submit(); + } + require(heap.Statistics().slotsEvicted == slots.size(), "the pressure submission evicts every slot, since no draw is being prepared at draw entry"); + require(!heap.TakeSlotPressure() && !BindlessHeap::NearlyFull(), "slots the submission covers clear the nearly full state"); + require(heap.SlotGeneration(slots[0]) != generation && heap.SlotTexture(kind, slots[0]) == nullptr, "an evicted slot moves its generation and names no texture"); + for (std::size_t index = 7; index < 12u; ++index) { + held.push_back(fakeTexture(context, index)); + const auto slot = heap.TextureSlot(kind, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL); + require(slot.has_value(), "a new texture takes a slot after the pressure submission, waiting for it when none is free"); + } + const auto back = heap.TextureSlot(kind, held[0].get(), view, VK_IMAGE_LAYOUT_GENERAL); + require(back.has_value() && heap.SlotTexture(kind, *back) == held[0].get(), "an evicted texture takes a slot again"); + for (const auto& texture : held) heap.ReleaseSlots(texture.get()); + BindlessHeap::Release(context.device); + return true; +} + +void noTimelineFails(const Context& context) { + static_cast(BindlessHeap::For(context)); + Recorder recorder(context); + recorder.Activate(); + bool failed = false; + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + try { + recorder.Submit(); + } catch (const std::runtime_error& error) { + failed = std::string(error.what()).find("without a timeline semaphore") != std::string::npos; + } + } + require(failed, "a heap batch from a recorder without a timeline, which could not wait for its slots, was accepted"); + require(recorder.Submissions() == 0u, "a heap batch from a recorder without a timeline was submitted before the failure"); + BindlessHeap::Release(context.device); +} + +bool samplersEvicted(const Context& context) { + auto& heap = BindlessHeap::For(context); + Recorder recorder(context, true); + if (!recorder.HasTimeline()) return false; + recorder.Activate(); + const auto submit = [&] { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + recorder.Submit(); + }; + SamplerCache cache(Abi::GpuSamplerHeapSlots); + const auto sampler = [&](std::uint32_t bias) { + const std::array words{0u, 0u, bias, 0u}; + return cache.Get(context, words, false); + }; + constexpr std::uint32_t Taken = Abi::GpuSamplerHeapSlots - Abi::GpuSamplerHeapSlots / 4u + 8u; + const auto pinnedSampler = sampler(Taken); + const auto pinned = heap.PinnedSamplerSlot(pinnedSampler); + require(pinned.has_value(), "a pinned sampler takes a slot"); + const auto pinnedGeneration = heap.SamplerGeneration(*pinned); + std::vector> held; + std::vector slots; + for (std::uint32_t index = 0; index < Taken; ++index) { + held.push_back(sampler(index)); + const auto slot = heap.SamplerSlot(held.back()); + require(slot.has_value(), "a sampler takes a slot"); + require(*slot > *pinned, "the pinned sampler holds a lower slot than every later sampler"); + slots.push_back(*slot); + } + require(BindlessHeap::NearlyFull(), "too few free sampler slots mark the heap nearly full"); + submit(); + const auto generation = heap.SamplerGeneration(slots[0]); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + require(heap.TakeSlotPressure(), "a heap short of sampler slots asks the next draw to submit its batch"); + recorder.Submit(); + } + require(heap.Statistics().samplersEvicted != 0u, "the pressure submission evicts samplers the new batch has not used"); + require(!BindlessHeap::NearlyFull(), "evicted sampler slots the submission covers clear the nearly full state"); + require(heap.SamplerGeneration(*pinned) == pinnedGeneration && heap.SamplerSlot(pinnedSampler) == pinned, "a pinned sampler slot is never evicted"); + require(heap.SamplerGeneration(slots[0]) != generation, "the oldest sampler's slot was evicted and moved its generation"); + require(recorder.WaitSerialFor(recorder.Submissions(), ~std::uint64_t{0}), "the submission completes"); + const auto back = heap.SamplerSlot(held[0]); + require(back.has_value(), "an evicted sampler takes a slot again"); + held.clear(); + BindlessHeap::Release(context.device); + return true; +} + +} + +int main(int argc, char** argv) { + const std::string mode = argc > 1 ? argv[1] : ""; + const bool comesBack = !mode.empty(); + try { + SetTestEnvironment("APS5_GPU_HEAP", "1"); + SetTestEnvironment("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1"); + auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!device->graphicsContext().descriptorHeap) { + std::printf("skipped, the device has no VK_EXT_descriptor_heap\n"); + return VulkanTestSkipped; + } + if (comesBack) { + { + const auto context = device->graphicsContext(); + const PlaceholderImages placeholders(context); + const auto sampled = placeholders.View(Abi::FirstImageBinding); + const auto storage = placeholders.View(Abi::FirstStorageImageBinding); + if (mode == "comes-back") heapComesBack(context, sampled); + else if (mode == "storage-comes-back") storageComesBack(context, storage); + else if (mode == "storage-views-come-back") storageViewsComeBack(context, storage); + else if (mode == "mixed-comes-back") mixedComesBack(context, sampled, storage); + else if (mode == "views-come-back") viewsComeBack(context, storage); + else if (mode == "two-heaps-come-back") twoHeapsComeBack(context, storage); + else if (mode == "owner-views-release") ownerViewsRelease(context, storage); + else if (mode == "shared-owner-release") sharedOwnerRelease(context, storage); + else if (mode == "no-timeline-fails") noTimelineFails(context); + else if (mode == "idle-slots-evicted" || mode == "pressure-submit" || mode == "samplers-evicted") { + const bool ran = mode == "idle-slots-evicted" ? idleSlotsEvicted(context, sampled) + : mode == "pressure-submit" ? slotPressureSubmits(context, sampled) + : samplersEvicted(context); + if (!ran) { + std::printf("skipped, the recorder has no timeline\n"); + return VulkanTestSkipped; + } + } + else throw std::runtime_error("unknown mode " + mode); + device->WaitIdle(); + } + device.reset(); + std::cout << "the nearly full heap recovers once released slots leave room (" << mode << ")\n"; + return 0; + } + { + const auto context = device->graphicsContext(); + const PlaceholderImages placeholders(context); + textureSlots(context, placeholders.View(Abi::FirstImageBinding)); + samplerSlots(context); + if (!dataPool(context)) std::printf("the data pool tests need the recorder timeline\n"); + spanScope(context); + writeTails(context); + viewSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); + encodedViews(context); + ownerSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); + device->WaitIdle(); + } + device.reset(); + std::cout << "bindless heap slot reuse tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "bindless heap slot reuse tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/CollectMemoGeneration.cpp b/core/libs/prx/libSceAgcDriver/tests/CollectMemoGeneration.cpp index 52e90967a8a7..f651cafd335f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/CollectMemoGeneration.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/CollectMemoGeneration.cpp @@ -4,6 +4,7 @@ #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/GuestWriteWatch.hpp" #include +#include #include #include #include @@ -269,6 +270,20 @@ void CheckThreadWithoutEpochWalksEveryTime() { Require(first && second, "a thread that never bumped its epoch reused an entry"); } +void CheckNoStampAfterCoversEveryRange() { + BumpCollectEpoch(); + const auto probe = Base + 11 * Page + 16; + const auto before = TrackerGeneration(); + Store(probe); + Require(CollectWrites(probe & ~(Page - 1), Page) != 0, "a collect failed"); + Require(NewestStamp(probe, 4) > before, "a collected store left no stamp after the generation"); + const std::array, 2> stored{{{Base + 12 * Page, Base + 12 * Page}, {probe, probe + 4}}}; + Require(!NoStampAfter(stored, before), "a range stored after the generation counted as settled"); + const std::array, 2> quiet{{{probe, probe}, {Base + 100 * Block, Base + 100 * Block + 4}}}; + Require(NoStampAfter(quiet, before), "an empty or untouched range counted as stored after the generation"); + Require(NoStampAfter({}, before), "no ranges counted as stored after the generation"); +} + void CheckStoreInNewEpochIsFound() { BumpCollectEpoch(); const auto address = Base + 7 * Page + 8; @@ -625,6 +640,7 @@ int main(int argc, char** argv) { CheckNeighbouringBlockStoreIsFound(); CheckInvalidationReachesBlockKeyedEntry(); CheckThreadWithoutEpochWalksEveryTime(); + CheckNoStampAfterCoversEveryRange(); CheckStoreInNewEpochIsFound(); CheckOwnersShareOneWalk(); CheckRunsAreWalkedOnce(); diff --git a/core/libs/prx/libSceAgcDriver/tests/ComputePipelineCaptureHeapRun.cmake b/core/libs/prx/libSceAgcDriver/tests/ComputePipelineCaptureHeapRun.cmake new file mode 100644 index 000000000000..13d4d8fc144a --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/ComputePipelineCaptureHeapRun.cmake @@ -0,0 +1,30 @@ +foreach(required IN ITEMS FIXTURE OUTPUT_ROOT) + if(NOT DEFINED ${required}) + message(FATAL_ERROR "Missing ${required}") + endif() +endforeach() +string(RANDOM LENGTH 16 ALPHABET 0123456789abcdef runId) +set(runDirectory "${OUTPUT_ROOT}/compute-capture-heap-${runId}") +set(captureDirectory "${runDirectory}/captures") +file(MAKE_DIRECTORY "${runDirectory}") +execute_process( + COMMAND "${CMAKE_COMMAND}" -E env "ANYPS5_REQUIRE_VULKAN=1" "ANYPS5_NO_SHADER_CACHE=1" "APS5_GPU_HEAP=1" "APS5_PIPELINE_STATS=0" "APS5_DUMP_COMPUTE_PIPELINES=${captureDirectory}" "APS5_DUMP_COMPUTE_MIN_WORDS=0" "${FIXTURE}" + WORKING_DIRECTORY "${runDirectory}" + RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error TIMEOUT 20 +) +file(WRITE "${runDirectory}/heap.log" "${output}\n${error}") +if(result STREQUAL "77") + message(STATUS "compute pipeline heap capture run: skipped, no usable Vulkan device") + file(REMOVE_RECURSE "${runDirectory}") + return() +endif() +if(NOT result STREQUAL "0" OR NOT output MATCHES "compute stages sampled their textures through the heap") + message(FATAL_ERROR "Heap compute fixture failed: ${result}\n${output}\n${error}") +endif() +file(GLOB captures "${captureDirectory}/compute-*/capture.aps5cp") +list(LENGTH captures count) +if(NOT count EQUAL 0) + message(FATAL_ERROR "Heap compute pipelines were captured, but a capture does not preserve their descriptor heap mappings: ${captures}") +endif() +message(STATUS "Heap compute fixture ran with no captured pipelines") +file(REMOVE_RECURSE "${runDirectory}") diff --git a/core/libs/prx/libSceAgcDriver/tests/DepthRangeRemap.cpp b/core/libs/prx/libSceAgcDriver/tests/DepthRangeRemap.cpp index 257d5b498779..0a2726b8989b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/DepthRangeRemap.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/DepthRangeRemap.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace { @@ -126,6 +127,37 @@ void preparedTransformTests(ShaderRecompiler::ShaderStage stage) { require(!PreparedShaderInvocation::TryCreate(other, handle).has_value(), "a prepared vertex shader matched a request of another depth remap mode"); } +void preparedInputValidationTests() { + using namespace ShaderRecompiler; + auto request = baseRequest(false); + request.useCache = true; + auto& vertex = *request.context.vertex; + vertex.resourcesNum = 2u; + vertex.resources[0].fields = {0x10000u, 16u << 16u, 100u, 0u}; + vertex.resources[1].fields = {0x10004u, 16u << 16u, 100u, 0u}; + vertex.resourcesDst[0] = {0, 4, 0, 0u}; + vertex.resourcesDst[1] = {4, 4, 1, 0u}; + const auto handle = PrepareShader(request); + std::vector key; + BuildPreparedShaderKey(request, key); + require(PreparedShaderInvocation::TryCreate(request, handle, key).has_value(), "the prepared vertex shader did not match its own request"); + auto disagreeing = request; + disagreeing.context.vertex->resources[1].fields[2] = 99u; + const auto rejects = [](const auto& create) { + try { + static_cast(create()); + } catch (const std::exception& error) { + return std::string_view(error.what()).find("disagree on record count") != std::string_view::npos; + } + return false; + }; + require(rejects([&] { return PreparedShaderInvocation::TryCreate(disagreeing, handle, key); }), "a copied request with merged vertex buffers of different record counts was not rejected"); + require(rejects([&] { + auto moved = disagreeing; + return PreparedShaderInvocation::TryCreate(std::move(moved), handle, key); + }), "a moved request with merged vertex buffers of different record counts was not rejected"); +} + void pushedTransformTests(ShaderRecompiler::ShaderStage stage) { using namespace ShaderRecompiler; const auto remapped = Recompile(baseRequest(true, stage)); @@ -180,6 +212,7 @@ int main() { pushedTransformTests(stage); clipDistanceCapacityTests(stage); } + preparedInputValidationTests(); std::cout << "Depth range remap tests passed\n"; return 0; } catch (const std::exception& error) { diff --git a/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp b/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp new file mode 100644 index 000000000000..9e358dcd9d1d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp @@ -0,0 +1,138 @@ +#include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" +#include +#include +#include +#include + +namespace { + +using namespace AgcDriver::Graphics; + +void Require(bool value, const char* what) { + if (value) return; + std::fprintf(stderr, "FAIL: %s\n", what); + std::abort(); +} + +struct Fake { + VkDevice device; + int createViews = 0; + int destroyViews = 0; + int createSamplers = 0; + int destroySamplers = 0; + VkDevice lastDevice = VK_NULL_HANDLE; +}; + +Fake devices[2]{Fake{reinterpret_cast(0x1000)}, Fake{reinterpret_cast(0x2000)}}; +Fake& first = devices[0]; +Fake& second = devices[1]; + +const std::uint64_t SharedView = 0x77; + +template +Fake& expect(VkDevice device) { + Require(device == devices[Index].device, "a call reached another device's function"); + return devices[Index]; +} + +template +VKAPI_ATTR VkResult VKAPI_CALL fakeCreateView(VkDevice device, const VkImageViewCreateInfo*, const VkAllocationCallbacks*, VkImageView* view) { + auto& fake = expect(device); + ++fake.createViews; + fake.lastDevice = device; + *view = reinterpret_cast(SharedView); + return VK_SUCCESS; +} + +template +VKAPI_ATTR void VKAPI_CALL fakeDestroyView(VkDevice device, VkImageView, const VkAllocationCallbacks*) { + auto& fake = expect(device); + ++fake.destroyViews; + fake.lastDevice = device; +} + +template +VKAPI_ATTR VkResult VKAPI_CALL fakeCreateSampler(VkDevice device, const VkSamplerCreateInfo*, const VkAllocationCallbacks*, VkSampler* sampler) { + auto& fake = expect(device); + ++fake.createSamplers; + fake.lastDevice = device; + *sampler = reinterpret_cast(SharedView); + return VK_SUCCESS; +} + +template +VKAPI_ATTR void VKAPI_CALL fakeDestroySampler(VkDevice device, VkSampler, const VkAllocationCallbacks*) { + auto& fake = expect(device); + ++fake.destroySamplers; + fake.lastDevice = device; +} + +template +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL fakeProc(VkDevice device, const char* name) { + Require(device == devices[Index].device, "a function was looked up through another device's loader"); + if (std::strcmp(name, "vkCreateImageView") == 0) return reinterpret_cast(&fakeCreateView); + if (std::strcmp(name, "vkDestroyImageView") == 0) return reinterpret_cast(&fakeDestroyView); + if (std::strcmp(name, "vkCreateSampler") == 0) return reinterpret_cast(&fakeCreateSampler); + if (std::strcmp(name, "vkDestroySampler") == 0) return reinterpret_cast(&fakeDestroySampler); + return nullptr; +} + +} + +int main() { + const auto createView = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc<0>, "vkCreateImageView")); + const auto destroyView = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc<0>, "vkDestroyImageView")); + const auto createSampler = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc<0>, "vkCreateSampler")); + const auto destroySampler = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc<0>, "vkDestroySampler")); + Require(createView != nullptr && destroyView != nullptr && createSampler != nullptr && destroySampler != nullptr, "the hooks resolve"); + Require(DescriptorHeapObjectFunction(second.device, fakeProc<1>, "vkCreateImageView") == reinterpret_cast(createView), "the second device resolves the same hook"); + DescriptorHeapObjectFunction(second.device, fakeProc<1>, "vkDestroyImageView"); + DescriptorHeapObjectFunction(second.device, fakeProc<1>, "vkCreateSampler"); + DescriptorHeapObjectFunction(second.device, fakeProc<1>, "vkDestroySampler"); + + VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + viewInfo.format = VK_FORMAT_R8G8B8A8_UNORM; + VkImageView view = VK_NULL_HANDLE; + Require(createView(first.device, &viewInfo, nullptr, &view) == VK_SUCCESS, "the first device creates a view"); + Require(first.createViews == 1 && second.createViews == 0 && first.lastDevice == first.device, "the first device's view goes through the first device's function"); + viewInfo.format = VK_FORMAT_B8G8R8A8_UNORM; + Require(createView(second.device, &viewInfo, nullptr, &view) == VK_SUCCESS, "the second device creates a view"); + Require(second.createViews == 1 && first.createViews == 1 && second.lastDevice == second.device, "the second device's view goes through the second device's function"); + + const auto recordFirst = FindImageView(first.device, view); + const auto recordSecond = FindImageView(second.device, view); + Require(recordFirst.has_value() && recordSecond.has_value(), "both devices keep a record for the same handle value"); + Require(recordFirst->info.format == VK_FORMAT_R8G8B8A8_UNORM && recordSecond->info.format == VK_FORMAT_B8G8R8A8_UNORM, "the records stay separate per device"); + + const std::byte bytes[4]{}; + KeepEncodedImageView(first.device, view, recordFirst->generation, 1u, bytes); + std::byte copy[4]{}; + Require(CopyEncodedImageView(first.device, view, 1u, copy), "the first device keeps its encoded view"); + Require(!CopyEncodedImageView(second.device, view, 1u, copy), "the second device's record has no encoding of the first's"); + + destroyView(second.device, view, nullptr); + Require(second.destroyViews == 1 && first.destroyViews == 0, "a destroy reaches the owning device's function"); + Require(!FindImageView(second.device, view).has_value(), "the destroyed record is gone"); + Require(FindImageView(first.device, view).has_value(), "destroying on one device keeps the other device's record"); + + VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + samplerInfo.maxLod = 3.0f; + VkSampler sampler = VK_NULL_HANDLE; + Require(createSampler(first.device, &samplerInfo, nullptr, &sampler) == VK_SUCCESS && first.createSamplers == 1, "the first device creates a sampler"); + samplerInfo.maxLod = 5.0f; + Require(createSampler(second.device, &samplerInfo, nullptr, &sampler) == VK_SUCCESS && second.createSamplers == 1, "the second device creates a sampler"); + Require(FindSampler(first.device, sampler)->info.maxLod == 3.0f && FindSampler(second.device, sampler)->info.maxLod == 5.0f, "sampler records stay separate per device"); + destroySampler(first.device, sampler, nullptr); + Require(first.destroySamplers == 1 && second.destroySamplers == 0, "a sampler destroy reaches the owning device's function"); + Require(!FindSampler(first.device, sampler).has_value() && FindSampler(second.device, sampler).has_value(), "destroying a sampler on one device keeps the other's record"); + destroySampler(second.device, sampler, nullptr); + Require(!FindSampler(second.device, sampler).has_value(), "the second device's sampler record is gone"); + VkSampler twin = VK_NULL_HANDLE; + samplerInfo.maxLod = 7.0f; + Require(createSampler(second.device, &samplerInfo, nullptr, &twin) == VK_SUCCESS && createSampler(second.device, &samplerInfo, nullptr, &twin) == VK_SUCCESS, "a device creates one sampler handle twice"); + destroySampler(second.device, twin, nullptr); + Require(FindSampler(second.device, twin).has_value() && FindSampler(second.device, twin)->info.maxLod == 7.0f, "destroying one of two creations of a sampler handle keeps its record"); + destroySampler(second.device, twin, nullptr); + Require(!FindSampler(second.device, twin).has_value(), "destroying the last creation of a sampler handle drops its record"); + std::puts("descriptor heap objects per device: ok"); +} diff --git a/core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp b/core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp new file mode 100644 index 000000000000..af6485e8930d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp @@ -0,0 +1,61 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include +#include +#include +#include +#include +#include + +namespace { + +void Check(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +void TestStopReleasesFullProducer() { + using AgcDriver::DriverDetail::DrawPipeline; + auto& pipeline = DrawPipeline::Queue0(); + const auto depth = DrawPipeline::Depth(); + Check(depth >= 2, "test requires at least two pipeline slots"); + std::binary_semaphore release{0}; + std::atomic started{false}; + pipeline.Enqueue([&] { + started.store(true, std::memory_order_release); + release.acquire(); + }, {}, 0, {}, {}, true); + while (!started.load(std::memory_order_acquire)) std::this_thread::yield(); + for (std::size_t index = 1; index < depth; ++index) pipeline.Enqueue([] {}, {}, 0, {}, {}, true); + std::atomic returned{false}; + std::thread::id ranOn; + std::thread producer([&] { + pipeline.Enqueue([&] { ranOn = std::this_thread::get_id(); }, {}, 0, {}, {}, true); + returned.store(true, std::memory_order_release); + }); + const auto producerId = producer.get_id(); + const auto waiting = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (pipeline.FullWaiters() == 0 && !returned.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < waiting) std::this_thread::yield(); + const bool waitedForRoom = pipeline.FullWaiters() != 0 && !returned.load(std::memory_order_acquire); + std::thread stopper([&] { pipeline.Stop(); }); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + while (!returned.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < deadline) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + const bool releasedByStop = returned.load(std::memory_order_acquire); + release.release(); + producer.join(); + stopper.join(); + Check(waitedForRoom, "the producer did not wait for room in a full queue"); + Check(releasedByStop, "stopping the pipeline left a producer waiting for room until the committer drained"); + Check(ranOn == producerId, "a draw enqueued while the pipeline stopped did not run on its producer"); +} + +} + +int main() { + try { + TestStopReleasesFullProducer(); + std::cout << "draw pipeline stop tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "draw pipeline stop tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index a3469b6aa2e4..54edc6d8158b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -6813,6 +6813,46 @@ void copyInputKeptBytesTests() { Require(mock.live == 0, "copy input accounting tests leaked Vulkan objects"); } +void pooledBufferAddressTests() { + using namespace AgcDriver::Graphics; + constexpr std::size_t bytes = 4096; + constexpr auto properties = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + const bool forced = BufferPool::ForceAddresses(); + mock = MockVulkan{}; + { + auto context = mockContext(); + context.device = makeHandle(); + context.bufferDeviceAddress = true; + context.memory.memoryTypes[0].propertyFlags |= properties; + context.memory.memoryHeapCount = 1; + context.memory.memoryHeaps[0] = {std::uint64_t{4} << 30u, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + context.limits.maxMemoryAllocationCount = 4096; + context.bufferPool = std::make_shared(context); + BufferPool::SetForceAddresses(true); + VkBuffer pooled = VK_NULL_HANDLE; + { + DeviceBuffer texture(context, bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); + pooled = texture.Handle(); + } + VkDeviceAddress address = 0; + VkDeviceAddress expected = 0; + { + Buffer staging(context, bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, properties); + Require(staging.Handle() == pooled, "a device-local buffer of the pooled device buffer's size and usage did not reuse its allocation"); + const VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, pooled}; + expected = mockGetBufferDeviceAddress(context.device, &info); + Require(expected != 0, "the mock device address of the pooled buffer is zero"); + try { + address = staging.DeviceAddress(); + } catch (const std::exception&) { + } + } + BufferPool::SetForceAddresses(forced); + Require(address == expected, "a buffer that reuses a pooled device buffer's allocation has no device address"); + } + Require(mock.live == 0, "pooled buffer address tests leaked Vulkan objects"); +} + void depthCopyKeptBytesTests() { using namespace AgcDriver::Graphics; constexpr std::size_t bytes = (8 * 8 + 4 * 4) * sizeof(float); @@ -14131,6 +14171,27 @@ void pipelineJournalTests(bool longPath = false, bool extended = false) { subgroup.hostSubgroupSize = 64; Require(!(subgroup.Identity() == constFirst.Identity()), "the host subgroup size did not enter the identity"); Require(ShaderRecompiler::RecompileResult{}.Identity().Empty(), "a result without a module has an identity"); + const auto embedded = [&](std::uint32_t element, std::uint32_t word) { + auto result = module(1); + auto& binding = result.bindings.emplace_back(); + binding.samplerEmbedded = {element}; + binding.samplerEmbeddedWords = {word, 1u, 2u, 3u}; + return result; + }; + Require(embedded(0u, 5u).Identity() == embedded(0u, 5u).Identity() && !(embedded(0u, 5u).Identity() == constFirst.Identity()), "an embedded sampler did not enter the identity"); + Require(!(embedded(0u, 5u).Identity() == embedded(0u, 6u).Identity()), "the embedded sampler words did not enter the identity"); + Require(!(embedded(0u, 5u).Identity() == embedded(1u, 5u).Identity()), "the embedded sampler element did not enter the identity"); + const auto flagged = [&](std::size_t flag) { + auto result = embedded(0u, 5u); + auto& binding = result.bindings.back(); + for (auto* flags : {&binding.samplerDepthCompare, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored}) flags->assign(1, false); + if (flag < 4u) (*std::array{&binding.samplerDepthCompare, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored}[flag])[0] = true; + return result; + }; + for (std::size_t flag = 0; flag < 4u; ++flag) Require(!(flagged(flag).Identity() == flagged(4u).Identity()), "an embedded sampler flag did not enter the identity"); + Require(DescribedPipelineIdentity(embedded(0u, 5u)) == embedded(0u, 5u).Identity(), "the described identity of a result with an embedded sampler differs from its identity"); + Require(!(DescribedPipelineIdentity(embedded(0u, 5u)) == DescribedPipelineIdentity(embedded(0u, 6u))), "the embedded sampler words did not enter the described identity"); + for (std::size_t flag = 0; flag < 4u; ++flag) Require(!(DescribedPipelineIdentity(flagged(flag)) == DescribedPipelineIdentity(flagged(4u))), "an embedded sampler flag did not enter the described identity"); Require(DescribedPipelineIdentity(ShaderRecompiler::RecompileResult{}).Empty(), "a result without a module has a described identity"); const auto withTable = [&](Role role, std::uint32_t elements, std::uint32_t buffers) { auto result = module(1); @@ -15082,6 +15143,11 @@ int main(int argc, char** argv) { std::cout << "GPU-copy input snapshot accounting and retention passed\n"; return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--pooled-buffer-address") { + pooledBufferAddressTests(); + std::cout << "a reused pooled allocation keeps a device address\n"; + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--depth-copy-kept-bytes") { depthCopyKeptBytesTests(); std::cout << "Depth-copy linear buffer accounting and retention passed\n"; diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp new file mode 100644 index 000000000000..133f0796cf9b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp @@ -0,0 +1,72 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include "Recompiler.hpp" +#include +#include +#include +#include + +namespace { + +using ShaderRecompiler::DescriptorRole; + +void Check(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +ShaderRecompiler::DescriptorBinding Binding(DescriptorRole role, std::vector words) { + ShaderRecompiler::DescriptorBinding binding{}; + binding.role = role; + binding.count = 1; + binding.guestDescriptor = std::move(words); + return binding; +} + +void TestTemplateWords() { + ShaderRecompiler::RecompileResult program; + program.bindings = {Binding(DescriptorRole::ShaderData, {1, 2, 3, 4}), Binding(DescriptorRole::GuestImages, {10, 11, 12, 13, 14, 15, 16, 17}), + Binding(DescriptorRole::FlattenedSrt, {20, 21}), Binding(DescriptorRole::GuestSamplers, {30, 31, 32, 33})}; + auto shared = std::make_shared(); + shared->bindings = {{9, 9, 9, 9}, {40, 41, 42, 43, 44, 45, 46, 47}, {50, 51}, {}}; + ShaderRecompiler::HeapStageWords words; + words.base = shared; + words.userData = {7}; + words.bindings.resize(program.bindings.size()); + const auto& b = program.bindings; + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[1]) == shared->bindings[1], "a resource binding without per-draw words does not read its template's"); + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[3]) == b[3].guestDescriptor, "a binding the template does not hold does not read the program's words"); + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[0]) == b[0].guestDescriptor, "shader data fell back to the template"); + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[2]) == b[2].guestDescriptor, "the flattened SRT fell back to the template"); + words.flattenedSrt = {70, 71}; + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[2]) == words.flattenedSrt, "the flattened SRT does not read the stage's own words"); + words.flattenedSrt.clear(); + words.bindings[1] = {60, 61, 62, 63, 64, 65, 66, 67}; + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[1]) == words.bindings[1], "per-draw words do not override the template's"); + words.bindings[1].clear(); + const auto patched = AgcDriver::DriverDetail::PatchedHeapResult(program, words); + Check(patched->bindings[0].guestDescriptor == std::vector({7, 2, 3, 4}), "the patched shader data does not take the draw's user data over the program's"); + Check(patched->bindings[1].guestDescriptor == shared->bindings[1], "the patched result does not take the template's resource words"); + Check(patched->bindings[2].guestDescriptor == b[2].guestDescriptor, "the patched flattened SRT took the template's words"); + Check(patched->bindings[3].guestDescriptor == b[3].guestDescriptor, "the patched result lost the program's words"); + shared->bindings[3] = {1}; + bool refused = false; + try { + static_cast(AgcDriver::DriverDetail::PatchedHeapResult(program, words)); + } catch (const std::runtime_error&) { + refused = true; + } + Check(refused, "template words of another size than the program's were taken"); +} + +} + +int main() { + try { + TestTemplateWords(); + std::cout << "heap stage template word tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "heap stage template word tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapWalkReads.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapWalkReads.cpp new file mode 100644 index 000000000000..26b41fba9f6d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/HeapWalkReads.cpp @@ -0,0 +1,67 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +void walkReadRunsTests() { + std::uint64_t state = 0x9e3779b97f4a7c15ull; + const auto next = [&] { + state ^= state << 13u; + state ^= state >> 7u; + state ^= state << 17u; + return state; + }; + for (int round = 0; round < 512; ++round) { + std::vector words; + const auto count = 1u + next() % 96u; + std::uint64_t cursor = 0x10000u + (next() % 64u) * 4u; + for (std::uint32_t index = 0; index < count; ++index) { + const auto pick = next() % 8u; + if (pick < 4u) cursor += 4u; + else if (pick == 4u) cursor = 0x10000u + (next() % 512u) * 4u; + else if (pick == 5u) cursor += 2u; + else if (pick == 6u && cursor >= 0x10008u) cursor -= 8u; + words.push_back(cursor); + } + std::vector> runs; + for (const auto word : words) AgcDriver::DriverDetail::AppendWalkRead(runs, word); + std::vector> ranges; + AgcDriver::DriverDetail::CoalesceWalkReads(runs, ranges); + auto sorted = words; + std::sort(sorted.begin(), sorted.end()); + std::vector> expected; + for (const auto word : sorted) { + if (!expected.empty() && word <= expected.back().second) { + expected.back().second = std::max(expected.back().second, word + 4u); + continue; + } + expected.emplace_back(word, word + 4u); + } + require(ranges == expected, "the heap walk's read ranges in round " + std::to_string(round) + " differ from the merged ranges of its " + std::to_string(words.size()) + " word reads"); + } + std::cout << "the heap walk's read runs merge to the same ranges as its sorted word reads\n"; +} + +} + +int main() { + try { + walkReadRunsTests(); + std::cout << "heap walk read tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "heap walk read tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/LinkedCodeDependencies.cpp b/core/libs/prx/libSceAgcDriver/tests/LinkedCodeDependencies.cpp index 2e3e94cd978f..fc8eec46c8af 100644 --- a/core/libs/prx/libSceAgcDriver/tests/LinkedCodeDependencies.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/LinkedCodeDependencies.cpp @@ -24,6 +24,9 @@ namespace AgcDriver::DriverDetail { struct DriverTestAccess { + static std::uint64_t VariantBytes(const DispatchVariant& variant) { + return Driver::variantBytes(variant); + } static std::shared_ptr Insert(const std::shared_ptr& shader, const ShaderRecompiler::RecompileRequest& request, bool disabled = false, std::vector>* dependencies = nullptr) { auto& driver = Driver::Get(); auto memory = std::make_shared(request.context.memory); @@ -313,6 +316,16 @@ void Run(const std::string& mode, std::string_view watch) { const auto footprint = Driver::Get().DispatchCacheSize(); Require(footprint.entries == 1u && footprint.variantBytes >= 16u, "cached callee snapshots were not accounted"); Require(original->linking != nullptr && original->linking->dependencies.size() == 2u, "cached direct linking did not capture both callees"); + { + const auto bare = DriverTestAccess::VariantBytes(*original); + auto ring = std::make_shared(); + ring->userData.assign(256u, 1u); + ring->bindings.assign(4u, std::vector(128u, 2u)); + original->ringTemplate = ring; + const auto held = DriverTestAccess::VariantBytes(*original); + original->ringTemplate = nullptr; + Require(held >= bare + 256u * sizeof(std::uint32_t) + 4u * 128u * sizeof(std::uint32_t), "a retained ring template was left out of the dispatch-cache byte accounting"); + } std::vector> dependencies(original->linking->dependencies.begin(), original->linking->dependencies.end()); const auto linked = original->linking->linked; DriverTestAccess::Evict(); diff --git a/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp b/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp index 53e1f7541059..c02a15035066 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "Recompiler.hpp" #include "MeshGeometryFixture.hpp" @@ -173,7 +174,8 @@ bool ReadsNumWorkgroups(std::span words) { } void DrawMesh(AgcDriver::VulkanDevice& device, const MeshDraw& setup) { - const auto target = device.Target(); + auto target = device.Target(); + target.gpuResolvedImages = AgcDriver::Graphics::DescriptorHeapEnabled(); std::vector userData(12, 0u); const auto index = AgcDriver::Graphics::MeshIndexBufferDescriptor(setup.draw); std::copy(index.begin(), index.end(), userData.begin() + ShaderRecompiler::MeshIndexBufferUserWord); @@ -190,7 +192,7 @@ void DrawMesh(AgcDriver::VulkanDevice& device, const MeshDraw& setup) { const auto meshResult = ShaderRecompiler::Recompile(geometry); Require(ReadsNumWorkgroups(meshResult.spirv), "the mesh program does not read NumWorkgroups, so RADV can keep a previous vertex pipeline's user SGPR count for its dispatch"); const auto meshPush = static_cast(meshResult.pushConstants.size()); - Require((meshPush == 0) == (setup.geometryPushBytes == 0), "the geometry program's push data does not follow its layout"); + Require(meshResult.gpuResolvedImages || (meshPush == 0) == (setup.geometryPushBytes == 0), "the geometry program's push data does not follow its layout"); ShaderRecompiler::ShaderPixelStageInfo pixel{}; pixel.interpolatorCount = 1; @@ -206,6 +208,7 @@ void DrawMesh(AgcDriver::VulkanDevice& device, const MeshDraw& setup) { std::nullopt }; const auto pixelResult = ShaderRecompiler::Recompile(fragment); + Require(meshResult.gpuResolvedImages == target.gpuResolvedImages && pixelResult.gpuResolvedImages == target.gpuResolvedImages, "the mesh draw's stages did not take GPU mode"); const std::array shaders{{ {ShaderStage::Mesh, &meshResult, 0}, {ShaderStage::Fragment, &pixelResult, PixelPushOffset(meshPush, target)} diff --git a/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp b/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp new file mode 100644 index 000000000000..f5e9b4b859ed --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp @@ -0,0 +1,142 @@ +#include "prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp" +#include +#include +#include +#include +#include +#include + +namespace { + +struct Range { + std::uint64_t begin; + std::uint64_t end; +}; + +bool Overlaps(const Range& range, std::uint64_t address, std::size_t bytes) { + return bytes != 0 && address < range.end && range.begin < address + bytes; +} + +void Require(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +void RandomAgainstScan() { + std::mt19937_64 random(0x5eed); + for (int round = 0; round < 2000; ++round) { + const auto count = static_cast(random() % 40); + std::vector ranges; + AgcDriver::Graphics::PendingRangeIndex index; + for (std::size_t item = 0; item < count; ++item) { + const auto begin = (random() % 4096) * 64; + const auto bytes = 1 + random() % (random() % 4 == 0 ? 65536 : 4096); + ranges.push_back({begin, begin + bytes}); + index.Insert(begin, begin + bytes, item, item); + } + for (int query = 0; query < 200; ++query) { + const auto address = (random() % 4200) * 64 + random() % 64; + const auto bytes = static_cast(random() % 8 == 0 ? 0 : random() % 20000); + const auto except = static_cast(random() % (count + 1)); + bool scanned = false; + std::size_t firstScanned = count; + std::vector scannedSet(count, false); + for (std::size_t item = 0; item < count; ++item) { + if (!Overlaps(ranges[item], address, bytes)) continue; + scannedSet[item] = true; + if (item == except) continue; + scanned = true; + if (firstScanned == count) firstScanned = item; + } + const bool indexed = index.AnyOverlapping(address, bytes, [&](std::size_t item) { return item != except; }); + Require(indexed == scanned, "the index and the scan disagree on whether a range overlaps"); + std::vector visited(count, false); + static_cast(index.AnyOverlapping(address, bytes, [&](std::size_t item) { + Require(!visited[item], "the index visited an item twice"); + visited[item] = true; + return false; + })); + Require(visited == scannedSet, "the index visited a different set of overlapping items than the scan"); + const auto* first = index.FirstByPosition(address, bytes, [&](std::size_t item) { return item != except; }); + Require((first == nullptr) == (firstScanned == count), "the index and the scan disagree on the first overlapping item"); + Require(first == nullptr || first->item == firstScanned, "the index named a later item than the first overlapping one"); + } + } +} + +void InsertEraseAgainstScan() { + std::mt19937_64 random(0xfeed); + struct Live { + std::uint64_t begin; + std::uint64_t end; + int item; + }; + AgcDriver::Graphics::PendingRangeIndex index; + std::vector list; + int nextItem = 0; + std::size_t order = 0; + for (int step = 0; step < 20000; ++step) { + if (list.empty() || random() % 3 != 0) { + const auto begin = (random() % 256) * 4096; + const auto end = begin + 1 + random() % (random() % 5 == 0 ? 262144 : 16384); + list.push_back({begin, end, nextItem}); + index.Insert(begin, end, nextItem++, order++); + } else { + const auto at = static_cast(random() % list.size()); + Require(index.Erase(list[at].begin, list[at].item), "the index lost an entry it was given"); + list.erase(list.begin() + static_cast(at)); + } + Require(index.Entries().size() == list.size(), "the index holds a different number of entries than the list"); + Require(!index.Erase(1u << 30, -1), "the index erased an entry it was never given"); + for (int query = 0; query < 8; ++query) { + const auto address = (random() % 300) * 4096 + random() % 4096; + const auto bytes = static_cast(random() % 70000); + int firstScanned = -1; + std::size_t overlapping = 0; + for (const auto& live : list) { + if (!Overlaps({live.begin, live.end}, address, bytes)) continue; + ++overlapping; + if (firstScanned < 0 && live.item % 2 == 0) firstScanned = live.item; + } + std::size_t visited = 0; + static_cast(index.AnyOverlapping(address, bytes, [&](int) { + ++visited; + return false; + })); + Require(visited == overlapping, "after inserts and erases the index visited a different number of overlapping entries than the scan"); + const auto* first = index.FirstByPosition(address, bytes, [](int item) { return item % 2 == 0; }); + Require((first == nullptr ? -1 : first->item) == firstScanned, "after inserts and erases the index named a different first match than the list order"); + } + const auto& entries = index.Entries(); + for (std::size_t at = 1; at < entries.size(); ++at) Require(entries[at - 1].begin <= entries[at].begin, "the index entries are out of base order"); + } +} + +void Edges() { + AgcDriver::Graphics::PendingRangeIndex index; + index.Insert(100, 200, 1, 0); + index.Insert(0, 1000, 2, 1); + index.Insert(300, 301, 3, 2); + const auto any = [&](std::uint64_t address, std::size_t bytes, int skip) { return index.AnyOverlapping(address, bytes, [&](int item) { return item != skip; }); }; + Require(any(500, 1, 0), "a long earlier range covering the query was missed"); + Require(!any(500, 1, 2), "an excluded item was reported"); + Require(any(200, 101, 2), "a one-byte range at the end of the query was missed"); + Require(!any(200, 100, 2), "a range touching the query's end was reported as overlapping"); + Require(!any(1000, 10, -1), "a range ending at the query's start was reported as overlapping"); + Require(!any(150, 0, -1), "an empty query overlapped"); + Require(any(~std::uint64_t{0} - 5, 100, -1) == false, "a query past the address space overlapped"); +} + +} + +int main() { + try { + Edges(); + RandomAgainstScan(); + InsertEraseAgainstScan(); + std::cout << "pending range index tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "pending range index test failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp index 19c55aea39a7..53dc8dd85ce6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp @@ -1,3 +1,5 @@ +#include "execution/VulkanTestDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp" #include "prx/libSceAgcDriver/Execution/include/DisplayBuffer.hpp" #include "prx/libSceAgcDriver/Execution/include/DisplayFormat.hpp" @@ -34,7 +36,6 @@ using AgcDriver::PresentationPass; using AgcDriver::PresentationScaler; using AgcDriver::PresentationUpscaler; -constexpr int VulkanTestSkipped = 77; constexpr std::uint64_t Bgra8 = 0x8000000000000000ull; constexpr std::uint64_t Rgba8 = 0x8000000022000000ull; constexpr std::uint64_t TenBit = 0x0100000000000000ull; @@ -807,7 +808,7 @@ void sourceImageOutsideDeviceMemoryTests(const Context& base) { base.Function("vkGetImageMemoryRequirements")(base.device, probe, &requirements); base.Function("vkDestroyImage")(base.device, probe, nullptr); if (!base.HostMemoryType(requirements.memoryTypeBits)) { - std::printf("presentation source in host memory: skipped, the device offers no host memory type for the image\n"); + std::printf("presentation source in host memory: skipped, the device has no host memory type for the image\n"); return; } auto context = base; @@ -1354,6 +1355,14 @@ int main(int argc, char** argv) { residentPresentTests(device->GetContext()); overlayPlaneTests(device->GetContext()); sourceImageOutsideDeviceMemoryTests(device->GetContext()); + if (GpuHeapEnabled()) { + const auto heapDevice = OpenVulkanTestDevice(); + if (!heapDevice) return VulkanTestSkipped; + if (SkipWithoutDescriptorHeap()) return VulkanTestSkipped; + const auto context = heapDevice->graphicsContext(); + Require(BindlessHeap::For(context).DescriptorHeapMode(), "the test device did not open the descriptor heap"); + residentPresentTests(context); + } std::cout << "resident present format, presentation pass, overlay plane and letterbox tests passed\n"; return 0; } catch (const std::exception& error) { diff --git a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp new file mode 100644 index 000000000000..a53b60808557 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp @@ -0,0 +1,283 @@ +#include +#include "prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include "PushDataLayout.hpp" +#include "RuntimeAbi.hpp" +#include "IntermediateRepresentation/IrMetadata/ShaderInfo.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::CompiledShader; +using AgcDriver::Graphics::PushDataPlacements; +using ShaderRecompiler::ShaderStage; +using ShaderRecompiler::StagePushPlacement; +namespace Abi = ShaderRecompiler::RuntimeAbi; +using Item = Abi::RootItem; + +void require(bool condition, const std::string& what) { + if (!condition) throw std::runtime_error(what); +} + +struct Stage { + ShaderStage stage; + std::uint32_t items; + std::size_t pushed; + std::uint32_t buffers = 0; +}; + +std::uint32_t bits(std::initializer_list items) { + std::uint32_t mask = 0; + for (const auto item : items) mask |= Abi::RootItemBit(item); + return mask; +} + +std::vector place(const std::vector& stages) { + static std::vector programs; + programs.assign(stages.size(), {}); + std::vector shaders; + for (std::size_t index = 0; index < stages.size(); ++index) { + programs[index].dataAddressPush = true; + programs[index].gpuResolvedImages = true; + programs[index].pushItems = stages[index].items; + programs[index].pushedData.resize(stages[index].pushed); + programs[index].pushedBufferCount = stages[index].buffers; + for (std::size_t dword = 0; dword < stages[index].pushed; ++dword) programs[index].pushedData[dword] = static_cast(dword); + shaders.push_back({stages[index].stage, &programs[index], 0u}); + } + return PushDataPlacements(shaders); +} + +void disjoint(const std::vector& stages, const std::vector& placements, std::uint64_t occupied, const char* what) { + std::uint64_t used = occupied; + constexpr std::uint32_t NotGlobal = ~0u; + std::array globalOwner; + globalOwner.fill(NotGlobal); + for (std::size_t index = 0; index < placements.size(); ++index) { + const auto claim = [&](std::uint32_t first, std::uint32_t width, std::uint32_t global) { + for (auto dword = first; dword < first + width; ++dword) { + require(dword < Abi::PushDataDwords, std::string("a push entry leaves the push data: ") + what); + const auto bit = 1ull << dword; + if (global != NotGlobal && globalOwner[dword] == global) continue; + require((used & bit) == 0u, std::string("two push entries share a dword: ") + what); + used |= bit; + if (global != NotGlobal) globalOwner[dword] = global; + } + }; + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + const bool wanted = (stages[index].items & (1u << item)) != 0u; + const auto position = placements[index].items[item]; + const bool optional = static_cast(item) == Item::UserData; + require(wanted == (position != Abi::NoPushPosition) || (optional && wanted), std::string("a stage's root items and its placement disagree: ") + what); + if (position == Abi::NoPushPosition) continue; + const auto kind = static_cast(item); + if (Abi::RootAddressItem(kind)) require(position % 2u == 0u, std::string("a root address is not 8-byte aligned: ") + what); + claim(position, Abi::RootAddressItem(kind) ? 2u : 1u, static_cast(kind) < static_cast(Abi::RootItem::ShaderData) ? item : NotGlobal); + } + const auto& placement = placements[index]; + require(placement.pushedBuffers == stages[index].buffers, std::string("a stage's placement does not count its buffers: ") + what); + bool overflowed = stages[index].buffers > Abi::PushedBufferLimit; + for (std::uint32_t buffer = 0; buffer < Abi::PushedBufferLimit; ++buffer) { + const auto root = placement.bufferRoots[buffer]; + if (buffer >= stages[index].buffers) require(root == Abi::NoPushPosition, std::string("a buffer the stage does not read has a root: ") + what); + overflowed = overflowed || (buffer < stages[index].buffers && root == Abi::NoPushPosition); + if (root == Abi::NoPushPosition) continue; + require(root % 2u == 0u, std::string("a pushed buffer address is not 8-byte aligned: ") + what); + claim(root, Abi::PushedBufferWords, NotGlobal); + } + require(overflowed == (placement.bufferOverflow != Abi::NoPushPosition), std::string("a stage's overflow address and its unplaced buffers disagree: ") + what); + if (placement.bufferOverflow != Abi::NoPushPosition) { + require(placement.bufferOverflow % 2u == 0u, std::string("a buffer overflow address is not 8-byte aligned: ") + what); + claim(placement.bufferOverflow, 2u, NotGlobal); + } + claim(placements[index].pushed.base, placements[index].pushed.count, NotGlobal); + require(placements[index].pushed.count <= stages[index].pushed, std::string("a stage pushes more than it asked for: ") + what); + } +} + +} + +int main() { + try { + const bool defaultCap = AgcDriver::Graphics::PushedBufferRecordCap() == Abi::PushedBufferLimit; + const auto vertexItems = bits({Item::PagetableAddress, Item::ShaderData, Item::SrtAddress}); + const auto pixelItems = bits({Item::PagetableAddress, Item::ShaderData, Item::TableMap}); + { + const std::vector stages{{ShaderStage::Vertex, vertexItems, 6}, {ShaderStage::Fragment, pixelItems, 30}}; + const auto placements = place(stages); + disjoint(stages, placements, 0, "vertex and pixel"); + require(placements[0].pushed.count == 6 && placements[1].pushed.count == 30, "stages that fit push everything they want"); + require(place({stages[1]})[0] == placements[1], "a pixel stage that fits is placed as it is alone, so its fragment library is shared"); + require(placements[0].Item(Item::PagetableAddress) == placements[1].Item(Item::PagetableAddress), "the pre-rasterization and fragment parts share their globals"); + const std::vector fault{{ShaderStage::Vertex, vertexItems | bits({Item::FaultAddress, Item::GdsAddress}), 6}, {ShaderStage::Fragment, pixelItems, 30}}; + disjoint(fault, place(fault), 0, "globals only the pre-rasterization part reads"); + require(place(fault)[1] == place({fault[1]})[0], "globals only the pre-rasterization part reads do not move the fragment part's roots"); + } + { + const auto user = Abi::RootItemBit(Item::UserData); + const std::vector stages{{ShaderStage::Vertex, vertexItems | user, 6, 4}, {ShaderStage::Fragment, pixelItems | user, 30, 4}}; + const auto placements = place(stages); + disjoint(stages, placements, 0, "vertex and pixel stages with user-data roots"); + require(placements[0].Item(Item::UserData) != Abi::NoPushPosition && placements[1].Item(Item::UserData) != Abi::NoPushPosition, "stages with room place their user-data roots"); + const std::vector without{{ShaderStage::Vertex, vertexItems, 6, 4}, {ShaderStage::Fragment, pixelItems, 30, 4}}; + const auto plain = place(without); + for (std::size_t index = 0; index < plain.size(); ++index) { + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + if (static_cast(item) != Item::UserData) require(plain[index].items[item] == placements[index].items[item], "a user-data root moves another root item"); + } + require(plain[index].bufferRoots == placements[index].bufferRoots, "a user-data root moves a pushed buffer"); + } + const auto pushedTotal = [](const std::vector& stages) { + std::size_t total = 0; + for (const auto& stage : stages) total += stage.pushed.count; + return total; + }; + require(pushedTotal(placements) + 2u * placements.size() >= pushedTotal(plain), "a user-data root takes more than its own dwords from pushed data"); + } + { + const std::vector stages{{ShaderStage::Vertex, vertexItems, 40}, {ShaderStage::Fragment, pixelItems, 40}}; + const auto placements = place(stages); + disjoint(stages, placements, 0, "stages that want too much"); + require(placements[0].pushed.count == 27 && placements[1].pushed.count == 27, "stages that want too much share the room evenly"); + } + { + const std::vector stages{{ShaderStage::Local, vertexItems, 4}, {ShaderStage::TessellationControl, bits({Item::PagetableAddress, Item::ShaderData}), 3}, {ShaderStage::TessellationEvaluation, vertexItems, 10}, {ShaderStage::Fragment, pixelItems, 48}}; + const auto placements = place(stages); + disjoint(stages, placements, ShaderRecompiler::PushFeatureDwords(false, true, false), "a tessellation pipeline"); + require(placements[0].Item(Item::PagetableAddress) == placements[1].Item(Item::PagetableAddress), "pre-rasterization stages share their part's globals"); + } + { + const std::vector stages{{ShaderStage::Mesh, vertexItems, 8}, {ShaderStage::Fragment, pixelItems, 20}}; + disjoint(stages, place(stages), ShaderRecompiler::PushFeatureDwords(true, false, false), "a mesh pipeline"); + } + { + const std::vector stages{{ShaderStage::Compute, bits({Item::PagetableAddress, Item::GdsAddress, Item::ShaderData}), 60}}; + const auto placements = place(stages); + disjoint(stages, placements, ShaderRecompiler::StagePushFeatures(ShaderStage::Compute, 0u), "a compute stage"); + require(placements[0] == ShaderRecompiler::StandalonePushPlacement(ShaderStage::Compute, stages[0].items, stages[0].pushed), "the compiler's standalone compute placement is the driver's"); + } + { + std::vector programs(2); + programs[0].dataAddressPush = true; + programs[0].gpuResolvedImages = true; + programs[0].pushItems = vertexItems; + programs[0].pushedData.resize(48); + programs[1].pushConstants.resize(12); + programs[1].stencilReferences.push_back(1u); + programs[1].stencilReferenceDword = 2u; + const std::array shaders{CompiledShader{ShaderStage::Vertex, &programs[0], 0u}, CompiledShader{ShaderStage::Fragment, &programs[1], 128u}}; + const auto placements = PushDataPlacements(shaders); + const auto stencil = 128u / 4u + programs[1].stencilReferenceDword; + const auto pushed = placements[0].pushed; + require(stencil < pushed.base || stencil >= pushed.base + pushed.count, "a pushed run covers a per-draw stage's stencil reference"); + } + { + std::vector programs(3); + for (const std::size_t index : {0u, 2u}) { + programs[index].dataAddressPush = true; + programs[index].gpuResolvedImages = true; + } + programs[0].pushItems = vertexItems; + programs[0].pushedData.resize(6); + programs[1].pushConstants.resize(8); + programs[2].pushItems = pixelItems; + programs[2].pushedData.resize(20); + const std::array shaders{CompiledShader{ShaderStage::Vertex, &programs[0], 0u}, CompiledShader{ShaderStage::TessellationControl, &programs[1], 200u}, CompiledShader{ShaderStage::Fragment, &programs[2], 0u}}; + const auto placements = PushDataPlacements(shaders); + const std::vector stages{{ShaderStage::Vertex, vertexItems, 6}, {ShaderStage::TessellationControl, 0u, 0}, {ShaderStage::Fragment, pixelItems, 20}}; + disjoint(stages, placements, ShaderRecompiler::PushBytesMask(200u, 8u) | ShaderRecompiler::PushFeatureDwords(false, true, false), "a pixel stage wider than the top free run"); + require(placements[2].pushed.count == 20, "a pixel stage wider than the top free run takes a lower run instead of being cut"); + } + { + const auto all = (1u << Abi::RootItemCount) - 1u; + const auto stencil = Abi::RootItemBit(Item::StencilReference); + const std::vector stages{{ShaderStage::Vertex, (all & ~stencil) | Abi::DepthRemapPushBit, 48, Abi::PushedBufferLimit}, {ShaderStage::Geometry, 0u, 0}, {ShaderStage::Fragment, all, 48, Abi::PushedBufferLimit}}; + const auto placements = place(stages); + disjoint(stages, placements, ShaderRecompiler::PushFeatureDwords(true, false, true), "vertex and pixel stages with every root item and the most pushed buffers"); + require(place({stages[2]})[0].bufferRoots == placements[2].bufferRoots, "a pixel stage's buffer root is placed as it is alone, so its fragment library is shared"); + } + { + const auto all = (1u << Abi::RootItemCount) - 1u; + const auto stencil = Abi::RootItemBit(Item::StencilReference); + const std::vector stages{{ShaderStage::Local, all & ~stencil, 4}, {ShaderStage::TessellationControl, all & ~stencil, 3}, {ShaderStage::TessellationEvaluation, (all & ~stencil) | Abi::DepthRemapPushBit, 10}, {ShaderStage::Fragment, all, 48, Abi::PushedBufferLimit}}; + disjoint(stages, place(stages), ShaderRecompiler::PushFeatureDwords(false, true, true), "a tessellation pipeline whose stages hold every root item and whose pixel stage pushes the most buffers"); + } + { + const auto all = (1u << Abi::RootItemCount) - 1u; + const std::vector stages{{ShaderStage::Compute, all & ~Abi::RootItemBit(Item::StencilReference), 60, Abi::PushedBufferLimit}}; + const auto placements = place(stages); + disjoint(stages, placements, ShaderRecompiler::StagePushFeatures(ShaderStage::Compute, 0u), "a compute stage with every root item and the most pushed buffers"); + require(!defaultCap || placements[0] == ShaderRecompiler::StandalonePushPlacement(ShaderStage::Compute, stages[0].items, stages[0].pushed, stages[0].buffers), "the compiler's standalone compute placement with pushed buffers is the driver's"); + } + { + namespace Ids = ShaderRecompiler::PipelineSpecialization; + for (std::uint32_t buffer = 0; buffer <= Ids::BufferRootCount; ++buffer) { + const auto id = Ids::BufferRootPosition + buffer; + require(id >= Ids::SamplerLodBiasBase + Abi::SamplerHeapCapacity && id < Ids::ImageComponentBase, "a buffer root specialization id lies inside another constant's range"); + require(Ids::IsPushPlacement(id), "a buffer root specialization id is not a push placement"); + } + for (std::uint32_t id = Ids::StoreQuantizeBase; id < Ids::DescriptorIndexBase; ++id) require(!Ids::IsPushPlacement(id), "a store quantization specialization id counts as a push placement"); + for (std::uint32_t id = Ids::HeapCountBase; id < Ids::MipCountBase + ShaderRecompiler::ShaderInfo::MaxImages; ++id) require(!Ids::IsPushPlacement(id), "a heap or mip count specialization id counts as a push placement"); + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + const auto id = Ids::RootItemPositionBase + item; + require(id >= Ids::MipCountBase + ShaderRecompiler::ShaderInfo::MaxImages && id < Ids::StoreQuantizeBase, "a root item specialization id lies inside another constant's range"); + require(Ids::IsPushPlacement(id), "a root item specialization id is not a push placement"); + } + } + { + const auto all = (1u << Abi::RootItemCount) - 1u; + const auto stencil = Abi::RootItemBit(Item::StencilReference); + for (const std::uint32_t buffers : {1u, 4u, 5u, 9u, 40u}) { + const std::vector worst{{ShaderStage::Vertex, (all & ~stencil) | Abi::DepthRemapPushBit, 48, buffers}, {ShaderStage::Geometry, all & ~stencil, 8, buffers}, {ShaderStage::Fragment, all, 48, buffers}}; + const auto placements = place(worst); + disjoint(worst, placements, ShaderRecompiler::PushFeatureDwords(true, false, true), ("stages with every root item and " + std::to_string(buffers) + " buffers each").c_str()); + const std::vector typical{{ShaderStage::Vertex, vertexItems, 6, buffers}, {ShaderStage::Fragment, pixelItems, 20, buffers}}; + const auto roomy = place(typical); + disjoint(typical, roomy, 0, ("typical stages with " + std::to_string(buffers) + " buffers each").c_str()); + const auto kept = static_cast(std::count_if(roomy[1].bufferRoots.begin(), roomy[1].bufferRoots.end(), [](std::uint32_t root) { return root != Abi::NoPushPosition; })); + require(!defaultCap || (buffers > kept) == (roomy[1].bufferOverflow != Abi::NoPushPosition), "a typical pixel stage overflows only the buffers it cannot keep in push data"); + require(!defaultCap || kept >= std::min(buffers, 8u), "a typical pixel stage keeps at least eight buffer records in push data"); + const auto alone = place({typical[1]})[0]; + require(alone.items == roomy[1].items && alone.bufferRoots == roomy[1].bufferRoots && alone.bufferOverflow == roomy[1].bufferOverflow, "a typical pixel stage with buffers is placed as it is alone, so its fragment library is shared"); + const std::vector tessellation{{ShaderStage::Local, all & ~stencil, 4, buffers}, {ShaderStage::TessellationControl, all & ~stencil, 3, buffers}, {ShaderStage::TessellationEvaluation, (all & ~stencil) | Abi::DepthRemapPushBit, 10, buffers}, {ShaderStage::Fragment, all, 48, buffers}}; + disjoint(tessellation, place(tessellation), ShaderRecompiler::PushFeatureDwords(false, true, true), ("a tessellation pipeline with " + std::to_string(buffers) + " buffers per stage").c_str()); + const std::vector compute{{ShaderStage::Compute, all & ~stencil, 60, buffers}}; + const auto computed = place(compute); + disjoint(compute, computed, ShaderRecompiler::StagePushFeatures(ShaderStage::Compute, 0u), ("a compute stage with " + std::to_string(buffers) + " buffers").c_str()); + require(!defaultCap || computed[0] == ShaderRecompiler::StandalonePushPlacement(ShaderStage::Compute, compute[0].items, compute[0].pushed, buffers), "the compiler's standalone compute placement with overflowing buffers is the driver's"); + } + } + { + namespace Ids = ShaderRecompiler::PipelineSpecialization; + ShaderRecompiler::RecompileResult module; + module.spirv = {0x07230203u, 0x00010300u, 0u, 1u, 0u}; + const auto rootItem = [](Item item) { return Ids::RootItemPositionBase + static_cast(item); }; + module.specialization = {{rootItem(Item::UserData), Abi::NoPushPosition}, {rootItem(Item::ShaderData), 0u}}; + StagePushPlacement placement; + placement.items.fill(Abi::NoPushPosition); + placement.items[static_cast(Item::ShaderData)] = 4u; + AgcDriver::Graphics::PipelineSpecialization optionalUser(module, 0u); + optionalUser.PlacePushData(placement); + placement.items[static_cast(Item::ShaderData)] = Abi::NoPushPosition; + bool refused = false; + try { + AgcDriver::Graphics::PipelineSpecialization required(module, 0u); + required.PlacePushData(placement); + } catch (const std::runtime_error&) { + refused = true; + } + require(refused, "a stage reading a root item its pipeline's push layout does not hold was accepted"); + } + std::puts("push data placements passed"); + return 0; + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/PushDataShadow.cpp b/core/libs/prx/libSceAgcDriver/tests/PushDataShadow.cpp new file mode 100644 index 000000000000..d3ee3b3f3aa3 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/PushDataShadow.cpp @@ -0,0 +1,88 @@ +#include "prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp" +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::PushDataShadow; +constexpr std::size_t Bytes = 256; +using Block = std::array; +int failures = 0; + +void Expect(bool condition, const std::string& what) { + if (condition) return; + std::fprintf(stderr, "FAILED: %s\n", what.c_str()); + ++failures; +} + +void SetWord(Block& block, std::size_t word, std::uint32_t value) { + std::memcpy(block.data() + word * 4, &value, sizeof(value)); +} + +VkCommandBuffer Commands(std::uintptr_t value) { + return reinterpret_cast(value); +} + +void testRanges() { + PushDataShadow shadow; + Block block{}; + for (std::size_t word = 0; word < Bytes / 4; ++word) SetWord(block, word, 0x1000u + static_cast(word)); + auto range = shadow.Changed(Commands(1), 7, block); + Expect(range.first == 0 && range.second == Bytes, "the first push of a command buffer covers the whole block"); + shadow.Pushed(8); + range = shadow.Changed(Commands(1), 8, block); + Expect(range.first == range.second, "an unchanged block pushes nothing"); + SetWord(block, 56, 0xbeefu); + range = shadow.Changed(Commands(1), 8, block); + Expect(range.first == 224 && range.second == 232, "a change to the low dword of an address pushes the whole address"); + shadow.Pushed(9); + SetWord(block, 5, 0x1u); + SetWord(block, 41, 0x2u); + range = shadow.Changed(Commands(1), 9, block); + Expect(range.first == 16 && range.second == 168, "two changes push one range from the first to the last changed address"); + shadow.Pushed(10); + range = shadow.Changed(Commands(1), 11, block); + Expect(range.first == 0 && range.second == Bytes, "a push by anything else since the last one pushes the whole block"); + shadow.Pushed(12); + range = shadow.Changed(Commands(2), 12, block); + Expect(range.first == 0 && range.second == Bytes, "another command buffer gets the whole block"); +} + +void testKeptBytes() { + PushDataShadow shadow; + Block block{}; + shadow.Changed(Commands(3), 1, block); + shadow.Pushed(2); + std::uint64_t mark = 2; + std::uint64_t seed = 0x9e3779b97f4a7c15ull; + Block gpu = block; + for (int round = 0; round < 4000; ++round) { + seed ^= seed << 13u; + seed ^= seed >> 7u; + seed ^= seed << 17u; + const auto changes = seed % 4u; + for (std::uint64_t change = 0; change < changes; ++change) SetWord(block, (seed >> (8u * change + 4u)) % (Bytes / 4), static_cast(seed >> 32u) + static_cast(change)); + const auto [first, end] = shadow.Changed(Commands(3), mark, block); + Expect(first % 8u == 0u && end % 8u == 0u && first <= end && end <= Bytes, "pushed ranges are whole addresses inside the block"); + std::memcpy(gpu.data() + first, block.data() + first, end - first); + if (first < end) shadow.Pushed(++mark); + if (gpu != block) { + Expect(false, "the pushed ranges rebuild the block in round " + std::to_string(round)); + return; + } + } +} + +} + +int main() { + testRanges(); + testKeptBytes(); + if (failures != 0) return EXIT_FAILURE; + std::puts("push data shadow tests passed"); + return EXIT_SUCCESS; +} diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index cb49a0c474ee..b972612c1c98 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -18,6 +18,7 @@ #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/MapImportGate.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/PlaceholderImages.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" @@ -10958,11 +10959,11 @@ void storageUploadLifetimeTests(const Device& device, Recorder& previous, bool f std::cout << "Storage upload lifetime" << (failView ? " after view failure" : " after caller release") << ": passed\n"; } -void refreshProofTests(const Device& device, Recorder& recorder) { +bool refreshProofTests(const Device& device, Recorder& recorder) { const auto& base = device.GetContext(); if (base.hostImportAlignment == 0) { std::cout << "host imports unavailable: refresh proofs not tested\n"; - return; + return false; } constexpr std::uint32_t side = 256; constexpr std::size_t surfaceBytes = side * side * 4; @@ -10971,7 +10972,7 @@ void refreshProofTests(const Device& device, Recorder& recorder) { void* block = AllocateWatched(bytes, 65536); if (block == nullptr) { std::cout << "no write watching: refresh proofs not tested\n"; - return; + return false; } auto* texels = static_cast(block); auto* keys = texels + surfaceBytes; @@ -10996,7 +10997,7 @@ void refreshProofTests(const Device& device, Recorder& recorder) { } unregister{base, block, address}; if (HostImportFor(base, address, bytes) == nullptr || !AgcDriver::GuestMemory::Watched(address, bytes)) { std::cout << "no watched host import: refresh proofs not tested\n"; - return; + return false; } TextureDetiler detiler(base); auto context = base; @@ -11079,6 +11080,47 @@ void refreshProofTests(const Device& device, Recorder& recorder) { recorder.Sync(); } recorder.Sync(); + { + std::memset(keys, 0xff, keyCount); + const auto meta = resource.dccAddress >> 8u; + const std::vector words{ + static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (((side - 1u) & 3u) << 30u), + ((side - 1u) >> 2u) | ((side - 1u) << 14u), + 0xfacu | (0x1bu << 20u) | (9u << 28u), + 0u, + 0u, + (1u << 19u) | (1u << 20u) | (1u << 21u) | (static_cast(meta & 0xffu) << 24u), + static_cast(meta >> 8u), + }; + ShaderRecompiler::RecompileResult program; + ShaderRecompiler::DescriptorBinding images{ShaderRecompiler::DescriptorKind::StorageImage, ShaderRecompiler::DescriptorRole::GuestImages, 0, ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding, 1, words}; + images.imageShape = ShaderRecompiler::DescriptorImageShape::Image2D; + images.imageWritten = {true}; + program.bindings.push_back(images); + const CompiledShader compute{ShaderRecompiler::ShaderStage::Compute, &program, 0}; + const PlaceholderImages placeholders(context); + auto imageContext = context; + imageContext.placeholderImages = &placeholders; + std::lock_guard gpu(GpuMutex()); + ShaderResources resources(imageContext, compute); + Require(resources.Reusable(), "a set writing a keyed storage image is not kept for reuse"); + ShaderResources::ProofReport report; + Require(resources.Revalidate(std::span(&compute, 1), &report), "a set over an unchanged keyed storage image did not revalidate"); + Require(resources.Revalidate(std::span(&compute, 1), &report) && report.path == ShaderResources::ProofPath::Fast, "a set over an unchanged keyed storage image left the fast proof"); + const auto image = StorageTexture::FindLive(address, surfaceBytes); + Require(image != nullptr && image->UploadedKeys() == DccKeys::Uncompressed, "the storage image was not uploaded under uncompressed keys"); + std::memset(keys, 0x00, keyCount); + Require(resources.Revalidate(std::span(&compute, 1), &report), "a set over a fast-cleared keyed storage image did not revalidate"); + Require(report.path == ShaderResources::ProofPath::OwnRefreshed, "a fast clear of a storage image's keys took the full walk instead of the image's own refresh"); + Require(image->UploadedKeys() == DccKeys::Clear0000, "the own refresh did not apply the fast clear"); + Require(resources.Revalidate(std::span(&compute, 1), &report) && report.path == ShaderResources::ProofPath::Fast, "the set did not return to the fast proof after the fast clear"); + recorder.Submit(); + device.WaitQueue(); + recorder.Sync(); + ClearCachedTextures(context.device); + } + return true; } bool pendingKeyRefreshTests(const Device& device, Recorder& recorder) { @@ -17354,6 +17396,11 @@ int main(int argc, char** argv) { unchangedCpuStampTests(device, recorder); return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--refresh-proofs-only") { + if (!refreshProofTests(device, recorder)) return 77; + std::cout << "refresh proof tests passed\n"; + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--rewritten-blocks-only") return rewrittenBlockTests(device, recorder) ? 0 : 77; if (argc == 2 && std::string_view(argv[1]) == "--rewritten-stale-units-only") return rewrittenStaleUnitTests(device, recorder) ? 0 : 77; if (argc == 2 && std::string_view(argv[1]) == "--idle-writeback-race-only") { diff --git a/core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp b/core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp new file mode 100644 index 000000000000..081c26ab2700 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp @@ -0,0 +1,117 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::DriverDetail::RecycledShared; + +void require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +void heldObjectsNotReusedTests() { + RecycledShared> pool(4, 4); + std::vector>> held; + for (std::uint32_t index = 0; index < 4; ++index) { + held.push_back(pool.Take([](std::vector& values) { values.clear(); })); + held.back()->assign(16, index); + } + auto next = pool.Take([](std::vector& values) { values.clear(); }); + for (std::size_t index = 0; index < held.size(); ++index) { + require(next.get() != held[index].get(), "the recycled pool handed out object " + std::to_string(index) + " while a draw still held it"); + require(*held[index] == std::vector(16, static_cast(index)), "the recycled pool changed object " + std::to_string(index) + " while a draw still held it"); + } + require(pool.Reused() == 0, "the recycled pool reused an object although every pooled object was held"); + std::cout << "the recycled pool never reuses an object another owner holds\n"; +} + +void releasedObjectsReusedTests() { + RecycledShared> pool(8, 8); + std::size_t resets = 0; + const void* first = nullptr; + for (std::uint32_t round = 0; round < 64; ++round) { + auto values = pool.Take([&](std::vector& reused) { + ++resets; + reused.clear(); + }); + require(values->empty(), "a recycled object kept the contents of its previous use in round " + std::to_string(round)); + values->assign(256, round); + if (first == nullptr) first = values.get(); + } + require(pool.Fresh() == 1 && pool.Reused() == 63 && resets == 63, "a pool whose objects were released after each use made " + std::to_string(pool.Fresh()) + " objects and reused " + std::to_string(pool.Reused()) + ", not 1 and 63"); + std::cout << "the recycled pool reuses released objects and resets them\n"; +} + +void fullPoolCyclesTests() { + RecycledShared> pool(2, 2); + std::vector>> heldLong; + for (int index = 0; index < 2; ++index) heldLong.push_back(pool.Take([](std::vector&) {})); + for (int index = 0; index < 6; ++index) static_cast(pool.Take([](std::vector&) {})); + require(pool.Reused() == 5, "a pool full of objects held long ago reused " + std::to_string(pool.Reused()) + " of the 6 short-lived takes after it filled, not 5"); + std::cout << "a full recycled pool replaces long-held objects with newer ones\n"; +} + +void zeroCapacityTests() { + RecycledShared> pool(0, 4); + for (std::uint32_t round = 0; round < 3; ++round) { + auto values = pool.Take([](std::vector& reused) { reused.clear(); }); + require(values != nullptr, "a zero-capacity pool returned no object"); + } + require(pool.Fresh() == 3 && pool.Reused() == 0, "a zero-capacity pool retained an object"); + std::cout << "a zero-capacity recycled pool hands out unretained objects\n"; +} + +void stageWordsResetTests() { + ShaderRecompiler::HeapStageWords words; + words.userData = {1, 2, 3}; + words.flattenedSrt = {4, 5}; + words.vertexAttributes.resize(2); + words.bindings = {{6}, {7, 8}}; + words.base = std::make_shared(); + words.dataOrigin = 9; + words.drawKeyMemo.words.store(std::make_shared>(1, 10u), std::memory_order_relaxed); + words.memoizeKey = false; + AgcDriver::DriverDetail::ResetHeapStageWords(words); + const ShaderRecompiler::HeapStageWords fresh; + require(words.userData.empty() && words.flattenedSrt.empty() && words.vertexAttributes.empty() && words.bindings.empty(), "a recycled heap stage record kept its previous draw's words"); + require(words.base == nullptr, "a recycled heap stage record kept its previous draw's ring template"); + require(words.dataOrigin == fresh.dataOrigin, "a recycled heap stage record kept its previous data origin"); + require(words.drawKeyMemo.words.load(std::memory_order_relaxed) == nullptr, "a recycled heap stage record kept its previous draw key"); + require(words.memoizeKey == fresh.memoizeKey, "a recycled heap stage record kept its previous key memo switch"); + words.userData.assign(64u << 10u, 1u); + words.flattenedSrt.assign(16, 2u); + words.vertexAttributes.resize(64u << 10u); + words.bindings.resize(4096); + const auto smallCapacity = words.flattenedSrt.capacity(); + AgcDriver::DriverDetail::ResetHeapStageWords(words); + require(words.userData.capacity() == 0u, "a recycled heap stage record kept a 256 KiB buffer in the pool"); + require(words.vertexAttributes.capacity() == 0u, "a recycled heap stage record kept a large vertex attribute buffer in the pool"); + require(words.bindings.capacity() == 0u, "a recycled heap stage record kept a large binding list in the pool"); + require(words.flattenedSrt.capacity() == smallCapacity, "a recycled heap stage record dropped a small buffer it should reuse"); + std::cout << "a recycled heap stage record is reset to a new record's state\n"; +} + +} + +int main() { + try { + heldObjectsNotReusedTests(); + releasedObjectsReusedTests(); + fullPoolCyclesTests(); + zeroCapacityTests(); + stageWordsResetTests(); + std::cout << "recycled stage record tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "recycled stage record tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp index ca7b65b6fbb5..bf7363e86031 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp @@ -199,7 +199,7 @@ void CheckAbi() { Require(bindings.insert(BindingNumber(static_cast(stage), static_cast(binding))).second, "runtime ABI bindings overlap"); } } - Require(BindingNumber(Stage::Main, Binding::ShaderData) == 62u && BindingNumber(Stage::Fragment, Binding::ShaderData) == 127u, "runtime ABI binding numbers changed"); + Require(BindingNumber(Stage::Main, Binding::ShaderData) == 62u && BindingNumber(Stage::Fragment, Binding::ShaderData) == 128u, "runtime ABI binding numbers changed"); Require(BindingNumber(Stage::Main, Binding::ImageTable) == ShaderRecompiler::RuntimeAbi::ImageTableBinding && BindingNumber(Stage::TessellationEvaluation, Binding::ImageTable) == ShaderRecompiler::RuntimeAbi::ImageTableBinding && !bindings.contains(ShaderRecompiler::RuntimeAbi::ImageTableBinding), "the shared image table binding overlaps a stage binding"); for (std::uint32_t stage = 0u; stage < ShaderRecompiler::RuntimeAbi::StageCount; ++stage) { for (std::uint32_t binding = 0u; binding < static_cast(Binding::Count); ++binding) { diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp index 377033d7c0ba..98abbdc3bf24 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp @@ -401,6 +401,7 @@ CompiledVariant sampleVariant() { info.bindings.memoryOffsetDword = 1; info.bindings.memoryOffsetCount = 5; info.bindings.stencilReferenceDword = 23u; + info.bindings.dataAddress = true; info.bindings.userDataRegisters = {4, 5, 9}; info.bindings.descriptors = {{DescriptorBindingKind::Buffers, {0, 1}}, {DescriptorBindingKind::FlattenedSrt, {}}}; variant.bindings.layout = info.bindings; @@ -2511,7 +2512,12 @@ void verifyPlanRoundTrip() { const auto registeredHandle = PrepareShader(registeredRequest); const auto registeredPlan = GetResourcePlan(registeredRequest); ShaderDiskCache::Flush(); + const auto registeredInvocation = PreparedShaderInvocation::TryCreate(registeredRequest, registeredHandle); + require(registeredInvocation.has_value(), "the registered shader has no prepared invocation"); + const auto& heldPlan = registeredInvocation->Plan(); + require(heldPlan != nullptr, "a registered shader with a held plan returned none"); ReleaseUndrawnResourcePlan(*registeredHandle); + require(heldPlan != nullptr, "a plan returned by an invocation was cleared when its source released the plan"); const auto beforeReload = ShaderDiskCache::Totals(); const auto reloadedPlan = GetResourcePlan(registeredRequest); require(ShaderDiskCache::Totals().planHits == beforeReload.planHits + 1u, "a released registration plan was not reloaded from the disk cache"); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 8fd552c57540..8e2794012b92 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -46,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -445,6 +446,35 @@ void verifySpecializedModuleRelease() { require(shared.spirv.data() == again.spirv.data(), "specialized module release: a second result of a live module copied its words"); } +void verifyRebuiltModuleKeepsWords() { + using namespace ShaderRecompiler; + const std::array color{0x3f800000u}; + const std::vector code{0xbf800003u, 0x7e000200u, 0xf800180fu, 0u, 0xbf810000u}; + auto pixel = FrontendRequest(code, color); + pixel.shader.stage = ShaderStage::Fragment; + pixel.context.compute.reset(); + pixel.context.pixel = ShaderPixelStageInfo{}; + pixel.context.pixel->wave32 = true; + pixel.context.pixel->targetOutputMode[0] = 9u; + pixel.context.pixel->dualSourceBlend = true; + pixel.context.waveSize = 32u; + pixel.useCache = true; + { + const auto built = Recompile(pixel); + require(built.specializationId != 0u, "rebuilt module: the pixel fixture was not specialized"); + } + SharedSpirv::Weak rebuilt; + const std::uint32_t* words = nullptr; + { + const auto again = Recompile(pixel); + rebuilt = again.spirv.Weaken(); + words = again.spirv.data(); + } + require(!rebuilt.Expired(), "rebuilt module: a module needed again after its release dropped its words a second time"); + const auto third = Recompile(pixel); + require(third.spirv.data() == words, "rebuilt module: a kept module was specialized again"); +} + void verifyLayerSpecializationRelease() { using namespace ShaderRecompiler; const std::array code{ @@ -8243,6 +8273,28 @@ void verifySingleLaneVertexWave() { require(withoutKey != withKey, "single-lane vertex wave: vertex subgroup support did not change the cache key"); } +void verifyExtensionKey() { + using namespace ShaderRecompiler; + RecompileRequest request{}; + request.shader.stage = ShaderStage::Compute; + const std::array first{"VK_KHR_a", "VK_KHR_bb"}; + const std::string copied[2] = {"VK_KHR_a", "VK_KHR_bb"}; + const std::array same{copied[0], copied[1]}; + const std::array second{"VK_KHR_a", "VK_KHR_bc"}; + std::vector firstKey, againKey, sameKey, secondKey, backKey; + request.target.supportedExtensions = first; + RecompileCacheKey::BuildInterface(request, firstKey); + RecompileCacheKey::BuildInterface(request, againKey); + request.target.supportedExtensions = same; + RecompileCacheKey::BuildInterface(request, sameKey); + request.target.supportedExtensions = second; + RecompileCacheKey::BuildInterface(request, secondKey); + request.target.supportedExtensions = first; + RecompileCacheKey::BuildInterface(request, backKey); + require(firstKey == againKey && firstKey == sameKey && firstKey == backKey, "extension key: the same extension names built different keys"); + require(firstKey != secondKey, "extension key: a changed extension name kept the key"); +} + void verifySingleLaneElectedAtomicMax() { using namespace ShaderRecompiler; static constexpr std::array capabilities{spv::CapabilityGroupNonUniform, spv::CapabilityGroupNonUniformBallot, spv::CapabilityGroupNonUniformShuffle, spv::CapabilityGroupNonUniformArithmetic, spv::CapabilityGroupNonUniformShuffleRelative, spv::CapabilityClipDistance, spv::CapabilityInt64}; @@ -8915,7 +8967,7 @@ void verifyPixelRequestSerialization() { minimal.context.pixel->layerExported = true; minimal.context.pixel->ditheredAlphaToCoverage = true; const auto encoded = serializer.Serialize(minimal); - require(requestPrefix(encoded, 8u) == "NVNQQT4AAAA=", "new requests did not use serialization version 62"); + require(requestPrefix(encoded, 8u) == "NVNQQT8AAAA=", "new requests did not use serialization version 63"); auto withBarycentric = minimal; withBarycentric.target.fragmentBarycentricBuiltins = true; require(serializer.Deserialize(serializer.Serialize(withBarycentric)).request.target.fragmentBarycentricBuiltins && !serializer.Deserialize(encoded).request.target.fragmentBarycentricBuiltins, "barycentric built-ins were lost in serialization"); @@ -9036,7 +9088,7 @@ void verifyPixelRequestSerialization() { for (std::size_t bytes = 0; bytes < 45u; ++bytes) { expectFailure([&] { static_cast(serializer.Deserialize(requestPrefix(encoded, mappingOffset + bytes))); }, "truncated data", "a truncated pixel mapping, packing, dual-source, alpha-to-coverage, stencil reference export flag, primitive class, layer export, dither or front-face flag, quad pixel mask or quad sample mask was accepted"); } - for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQToAAAA=", "NVNQQT0AAAA=", "NVNQQT8AAAA="}) { + for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQToAAAA=", "NVNQQTwAAAA=", "NVNQQT0AAAA=", "NVNQQUAAAAA="}) { expectFailure([&] { static_cast(serializer.Deserialize(unsupported)); }, "serialization version", "an unsupported request version was accepted"); } static constexpr std::string_view version18Request{ @@ -9090,6 +9142,11 @@ std::vector decodeBase64(std::string_view text) { bytes.push_back(static_cast((chunk >> bits) & 0xffu)); } } + if (bytes.size() > 26u && bytes[4] == 63u) { + require(std::all_of(bytes.end() - 19, bytes.end() - 6, [](std::uint8_t value) { return value == 0u; }), "a version 63 request in these checks set a GPU heap target field"); + bytes.erase(bytes.end() - 19, bytes.end() - 6); + bytes[4] = 62u; + } return bytes; } @@ -9100,7 +9157,11 @@ std::vector version56Bytes(std::vector bytes) { return bytes; } -std::string encodeBase64(const std::vector& bytes) { +std::string encodeBase64(std::vector bytes) { + if (bytes.size() > 13u && bytes[4] == 62u) { + bytes[4] = 63u; + bytes.insert(bytes.end() - 6, 13u, 0u); + } constexpr std::string_view alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string text; for (std::size_t index = 0; index < bytes.size(); index += 3u) { @@ -10363,7 +10424,7 @@ void verifyCoherentGds() { require(std::ranges::find(decorations[gds], static_cast(spv::DecorationCoherent)) != decorations[gds].end(), "coherent GDS: the gds buffer is not Coherent"); } -void verifyCoherentBufferAccesses() { +auto recompileCoherent(const std::vector& code, std::uint32_t address, std::span capabilities) { using namespace ShaderRecompiler; alignas(256) static std::array input{}; alignas(256) static std::array output{}; @@ -10373,6 +10434,26 @@ void verifyCoherentBufferAccesses() { static_cast(inputAddress), static_cast((inputAddress >> 32u) & 0xffffu), 256u, 0x31016facu, static_cast(outputAddress), static_cast((outputAddress >> 32u) & 0xffffu), 256u, 0x31016facu}; const std::array extensions{"SPV_KHR_physical_storage_buffer", "SPV_KHR_8bit_storage"}; + RecompileRequest request{}; + request.shader = {ShaderStage::Compute, address, code, 0, {}}; + request.context.waveSize = 32; + request.context.userDataBaseRegister = 0; + request.context.userData = userData; + request.context.compute = ShaderComputeStageInfo{{32u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; + request.target.vulkanVersion = 0x00401000u; + request.target.spirvVersion = 0x00010300u; + request.target.subgroupSize = 32; + request.target.bdaAbiVersion = BdaAbi::Version; + request.target.supportedCapabilities = capabilities; + request.target.supportedExtensions = extensions; + request.target.fragmentShaderBarycentricEnabled = false; + request.layout.pushConstantSizeBytes = 128; + request.useCache = false; + return Recompile(request).spirv; +} + +void verifyCoherentBufferAccesses() { + using namespace ShaderRecompiler; const std::array capabilities{spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess}; struct Module { std::map names; @@ -10384,22 +10465,7 @@ void verifyCoherentBufferAccesses() { std::vector code{0x34020082u}; if (invalidate) code.insert(code.end(), {0xe1c40000u, 0u}); code.insert(code.end(), {0xe0301000u | (glcLoad ? 0x4000u : 0u), 0x80000201u, 0xbf8c3f70u, 0xe0701000u | (glcStore ? 0x4000u : 0u), 0x80010201u, 0xbf810000u}); - RecompileRequest request{}; - request.shader = {ShaderStage::Compute, 0x5a000u, code, 0, {}}; - request.context.waveSize = 32; - request.context.userDataBaseRegister = 0; - request.context.userData = userData; - request.context.compute = ShaderComputeStageInfo{{32u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; - request.target.vulkanVersion = 0x00401000u; - request.target.spirvVersion = 0x00010300u; - request.target.subgroupSize = 32; - request.target.bdaAbiVersion = BdaAbi::Version; - request.target.supportedCapabilities = capabilities; - request.target.supportedExtensions = extensions; - request.target.fragmentShaderBarycentricEnabled = false; - request.layout.pushConstantSizeBytes = 128; - request.useCache = false; - const auto words = Recompile(request).spirv; + const auto words = recompileCoherent(code, 0x5a000u, capabilities); Module module; std::map bases; const auto base = [&](std::uint32_t pointer) { @@ -13005,6 +13071,122 @@ void verifyRuntimeImageSwitchDeduplication() { require(mipTargets.at(0u) != mipTargets.at(1u), "runtime image switch deduplication: storage image modes with different mip modes shared an OpSwitch target"); } +void verifyRegistrationStorageMipSlots() { + using namespace ShaderRecompiler; + constexpr std::uint32_t MetadataDword = 200u; + IrProgram program; + program.SetWaveSize(32u); + program.Resources().stage = IrShaderStage::Compute; + program.Resources().srtPlanComplete = true; + program.Resources().resourceTrackingComplete = true; + program.Metadata().shaderInfoComplete = true; + program.Metadata().bindingLayoutComplete = true; + auto& block = program.CreateBlock(); + program.SetEntryBlock(block); + program.BlockOrder().push_back(&block); + program.Metadata().blockInfo.emplace_back(); + auto& zero = program.CreateValue(IrOpcode::Void, IrType::U32); + zero.SetImmediateU32(0u); + auto& enabled = program.CreateValue(IrOpcode::Void, IrType::Bool); + enabled.SetImmediateBool(true); + auto& handle = program.CreateValue(IrOpcode::GetImageResource, IrType::ImageResource, 0u); + for (std::uint32_t i = 0u; i < 8u; ++i) handle.AddArgument(&zero); + block.AppendInstruction(&handle); + auto& address = program.CreateValue(IrOpcode::MakeImageAddress, IrType::ImageAddress); + for (std::uint32_t i = 0u; i < 13u; ++i) address.AddArgument(&zero); + block.AppendInstruction(&address); + MemoryInfo memory{}; + memory.kind = ResourceKind::Image; + memory.resource = 0u; + memory.imageDimension = RdnaImageDimension::Dim2D; + memory.imageAddressComponents = 2u; + memory.dmask = 0xfu; + memory.dataBits = 32u; + memory.dataDwords = 4u; + memory.componentCount = 4u; + program.Resources().memoryInfo.push_back(memory); + ImageResource image{}; + image.resourceClass = ImageResourceClass::Storage; + image.numericClass = IrTextureNumericClass::Float; + image.dimension = RdnaImageDimension::Dim2D; + image.mipMode = ImageMipMode::DynamicStorage; + image.mipCount = 3u; + image.written = true; + image.fmaskCompatible = false; + const auto modes = ResourceMaterializer::RuntimeImageModes(image); + const auto Mips = std::ranges::max(modes, {}, &ImageResource::mipCount).mipCount; + require(Mips > 1u, "registration slot words: a dynamic-mip storage image has no mip chain"); + program.Info().images.push_back(image); + program.Info().runtimeImageModes.push_back(modes); + auto& layout = program.Metadata().bindings; + layout.gpuResolvedImages = true; + layout.heapStorageImages = true; + layout.dataAddress = true; + layout.runtimeImageCount = 1u; + layout.memoryOffsetDword = MetadataDword; + for (const auto& mode : modes) { + const auto kind = DescriptorBindingForImage(mode); + if (std::ranges::none_of(layout.descriptors, [&](const IrDescriptorBinding& entry) { return entry.kind == kind; })) layout.descriptors.push_back({kind, std::vector(Mips, 0u)}); + } + for (const auto& descriptor : layout.descriptors) { + require(layout.HeapSlotWordKind(descriptor.kind), "registration slot words: a storage image kind has no slot words in a registration layout"); + layout.imageSlotDwords += static_cast(descriptor.resources.size()); + } + require(!layout.HeapSlotWordKind(static_cast(RuntimeAbi::FirstImageBinding)), "registration slot words: a sampled image kind has slot words in a registration layout"); + auto plain = layout; + plain.runtimeImageCount = 0u; + require(plain.HeapSlotWordKind(static_cast(RuntimeAbi::FirstImageBinding)), "registration slot words: a sampled image kind has no slot words outside a registration layout"); + ShaderComputeInputInfo compute{}; + compute.threadsNum[0] = 32u; + compute.threadsNum[1] = 1u; + compute.threadsNum[2] = 1u; + compute.hostSubgroupSize = 32u; + compute.waveSize = 32u; + ShaderStageInputInfo inputs{}; + inputs.compute = &compute; + auto& texel = program.CreateValue(IrOpcode::CompositeConstructU32x4, IrType::U32x4); + for (std::uint32_t i = 0u; i < 4u; ++i) texel.AddArgument(&zero); + block.AppendInstruction(&texel); + auto& store = program.CreateValue(IrOpcode::ImageWrite, IrType::Void); + store.AddArgument(&handle); + store.AddArgument(&address); + store.AddArgument(&texel); + store.AddArgument(&enabled); + block.AppendInstruction(&store); + CompiledBindingLayout bindings{}; + bindings.layout = layout; + SpirvTargetOptions target{}; + target.vulkanVersion = 0x00401000u; + target.spirvVersion = 0x00010300u; + target.subgroupSize = 32u; + target.registrationModules = true; + target.gpuResolvedImages = true; + const std::array capabilities{spv::CapabilityStorageImageArrayDynamicIndexing, spv::CapabilitySampledImageArrayDynamicIndexing, spv::CapabilityStorageImageWriteWithoutFormat}; + target.supportedCapabilities = capabilities; + const auto words = SpirvEmitter().Emit(program, inputs, bindings, target); + std::map definitions; + std::vector writes; + for (std::size_t cursor = 5u; cursor < words.size(); cursor += words[cursor] >> 16u) { + const auto count = words[cursor] >> 16u; + require(count != 0u && count <= words.size() - cursor, "registration slot words: truncated SPIR-V instruction"); + const auto opcode = words[cursor] & 0xffffu; + if (opcode == spv::OpImageWrite) writes.push_back(cursor); + if ((opcode == spv::OpLoad || opcode == spv::OpAccessChain) && count >= 4u) definitions[words[cursor + 2u]] = cursor; + } + const auto operandOf = [&](std::uint32_t id, std::uint32_t opcode, std::size_t operand) { + const auto found = definitions.find(id); + require(found != definitions.end() && (words[found->second] & 0xffffu) == opcode, "registration slot words: a storage image write does not take its descriptor through the image array"); + return words[found->second + operand]; + }; + std::set slotVariables; + for (const auto write : writes) { + const auto pointer = operandOf(words[write + 1u], spv::OpLoad, 3u); + const auto index = operandOf(pointer, spv::OpAccessChain, 4u); + slotVariables.insert(operandOf(index, spv::OpLoad, 3u)); + } + require(writes.size() >= Mips && slotVariables.size() >= Mips, "registration slot words: the storage image writes of a dynamic mip chain do not each read their own heap slot word"); +} + void verifyTableKeep() { using namespace ShaderRecompiler; std::vector code{0xf40c0200u, 0xfa000000u, 0xf4080500u, 0xfa000020u, 0xf4080600u, 0xfa000040u, 0xf4000400u, 0xfa000050u, 0xf4080a00u, 0xfa000080u, 0xbf8cc07fu, 0xf42c0814u, 0xfa000000u, 0xbf8cc07fu, 0xbf068010u, 0xbf850008u}; @@ -13338,6 +13520,7 @@ int main(int argc, char** argv) { verifyImageTables(); verifyImageTableKeyBounds(); verifySpecializedModuleRelease(); + verifyRebuiltModuleKeepsWords(); verifyLayerSpecializationRelease(); verifyImageTableRegistration(); verifyImageTableUintStorage(); @@ -13360,6 +13543,7 @@ int main(int argc, char** argv) { verifyNarrowVertexWave(); verifySingleLaneCrossLaneReads(); verifySingleLaneVertexWave(); + verifyExtensionKey(); verifySingleLaneElectedAtomicMax(); verifySingleLaneDomainWave(); verifyMeshConfiguration(); @@ -13411,6 +13595,7 @@ int main(int argc, char** argv) { verifyGcnDimensionQueries(); verifySrgbDepthCompareModes(); verifyRuntimeImageSwitchDeduplication(); + verifyRegistrationStorageMipSlots(); verifyQuadMaskNeighbourReads(); verifyPixelQuadPermReads(); verifyCoherentGds(); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderReplayRequests.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderReplayRequests.cpp index e34aeeb6faf9..3293ff101a72 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderReplayRequests.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderReplayRequests.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include int main(int argc, char** argv) try { @@ -75,6 +76,27 @@ int main(int argc, char** argv) try { file << RequestSerializer{}.Serialize(lds); if (!file) throw std::runtime_error("cannot write synthetic replay request"); } + for (const auto& [name, dwords] : {std::pair{"heap-addressed.req", 0u}, std::pair{"heap-4096.req", 4096u}}) { + auto heap = lds; + heap.target.gpuResolvedImages = true; + heap.target.descriptorMemory = true; + heap.target.heapDataUniformDwords = dwords; + std::ofstream file(directory / name, std::ios::binary); + file << RequestSerializer{}.Serialize(heap); + if (!file) throw std::runtime_error("cannot write synthetic replay request"); + } + srt[20] = 0u; + const std::array dataCapabilities{spv::CapabilityImageGatherExtended, spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess, spv::CapabilitySampledImageArrayDynamicIndexing, spv::CapabilityStorageImageArrayDynamicIndexing}; + for (const auto& [name, dwords] : {std::pair{"heap-data-addressed.req", 0u}, std::pair{"heap-data-4096.req", 4096u}}) { + auto heap = request; + heap.target.supportedCapabilities = dataCapabilities; + heap.target.gpuResolvedImages = true; + heap.target.descriptorMemory = true; + heap.target.heapDataUniformDwords = dwords; + std::ofstream file(directory / name, std::ios::binary); + file << RequestSerializer{}.Serialize(heap); + if (!file) throw std::runtime_error("cannot write synthetic replay request"); + } std::puts("synthetic guarded replay requests written"); return 0; } catch (const std::exception& error) { diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake b/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake index 2696a4c3e54c..4652362aa1d6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake @@ -85,3 +85,71 @@ foreach(mode IN ITEMS --prepare --materialize) message(FATAL_ERROR "${mode} ignored --wave-lds-memory-barriers\n${baseline}") endif() endforeach() + +function(expect_heap_profile description profile) + execute_process(COMMAND "${TOOL}" ${ARGN} RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE errors) + if(NOT code STREQUAL "0" OR NOT output MATCHES "heap profile ${profile}\n") + message(FATAL_ERROR "${description}: expected heap profile ${profile}: ${code}\n${output}${errors}") + endif() +endfunction() + +expect_heap_profile("captured heap off" "\\(captured\\): no heap, gpuResolvedImages 0, descriptorMemory 0, data uniform dwords 0" "${CAPTURE}/lds.req") +expect_heap_profile("captured heap with limit 0" "\\(captured\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 0" "${CAPTURE}/heap-addressed.req") +expect_heap_profile("captured heap with limit 4096" "\\(captured\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 4096" "${CAPTURE}/heap-4096.req") +expect_heap_profile("--gpu-heap on a heap-off capture" "\\(override\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 16384" --gpu-heap "${CAPTURE}/lds.req") +expect_heap_profile("--gpu-heap on a limit 0 capture" "\\(override\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 16384" --gpu-heap "${CAPTURE}/heap-addressed.req") +expect_heap_profile("--gpu-heap with a limit" "\\(override\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 8192" --gpu-heap --heap-data-uniform-dwords 8192 "${CAPTURE}/lds.req") +expect_heap_profile("--no-gpu-heap on a heap capture" "\\(override\\): no heap, gpuResolvedImages 0, descriptorMemory 0, data uniform dwords 0" --no-gpu-heap "${CAPTURE}/heap-4096.req") +expect_heap_profile("--heap-data-uniform-dwords alone keeps the captured heap" "\\(override\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 0" --heap-data-uniform-dwords 0 "${CAPTURE}/heap-4096.req") + +execute_process(COMMAND "${TOOL}" --heap-data-uniform-dwords x "${CAPTURE}/lds.req" RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE errors) +if(NOT code STREQUAL "2") + message(FATAL_ERROR "a malformed --heap-data-uniform-dwords value was accepted: ${code}\n${output}${errors}") +endif() + +function(expect_usage_error description message) + execute_process(COMMAND "${TOOL}" ${ARGN} RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE errors) + if(NOT code STREQUAL "2" OR NOT errors MATCHES "${message}") + message(FATAL_ERROR "${description}: expected exit 2 with '${message}': ${code}\n${output}${errors}") + endif() +endfunction() + +expect_usage_error("--gpu-heap then --no-gpu-heap" "--gpu-heap and --no-gpu-heap conflict" --gpu-heap --no-gpu-heap "${CAPTURE}/lds.req") +expect_usage_error("--no-gpu-heap then --gpu-heap" "--gpu-heap and --no-gpu-heap conflict" --no-gpu-heap --gpu-heap "${CAPTURE}/lds.req") +expect_usage_error("--no-gpu-heap with a limit" "--no-gpu-heap conflicts with --heap-data-uniform-dwords 4096" --no-gpu-heap --heap-data-uniform-dwords 4096 "${CAPTURE}/lds.req") +expect_usage_error("a limit then --no-gpu-heap" "--no-gpu-heap conflicts with --heap-data-uniform-dwords 4096" --heap-data-uniform-dwords 4096 --no-gpu-heap "${CAPTURE}/lds.req") +expect_usage_error("a limit hidden by a later zero" "--no-gpu-heap conflicts with --heap-data-uniform-dwords 4096" --heap-data-uniform-dwords 4096 --no-gpu-heap --heap-data-uniform-dwords 0 "${CAPTURE}/lds.req") +expect_usage_error("a missing limit" "needs an unsigned 32-bit number" --heap-data-uniform-dwords) +expect_usage_error("an overflowing limit" "needs an unsigned 32-bit number" --heap-data-uniform-dwords 99999999999 "${CAPTURE}/lds.req") +expect_usage_error("a negative limit" "needs an unsigned 32-bit number" --heap-data-uniform-dwords -1 "${CAPTURE}/lds.req") +expect_heap_profile("--no-gpu-heap with limit 0" "\\(override\\): no heap, gpuResolvedImages 0, descriptorMemory 0, data uniform dwords 0" --no-gpu-heap --heap-data-uniform-dwords 0 "${CAPTURE}/heap-4096.req") +expect_heap_profile("--gpu-heap replaces a captured limit" "\\(override\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 16384" --gpu-heap "${CAPTURE}/heap-4096.req") + +execute_process(COMMAND "${TOOL}" --robust2 --lds-lock-fences "${CAPTURE}/lds.req" RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE errors) +if(NOT code STREQUAL "0" OR NOT output MATCHES "target flags forced on: robust2, lds-lock-fences\n" OR NOT output MATCHES "heap profile \\(captured\\)") + message(FATAL_ERROR "forced target flags were not reported next to the captured heap profile: ${code}\n${output}${errors}") +endif() + +function(replay_spv result) + execute_process(COMMAND "${TOOL}" --spv ${ARGN} RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE errors) + if(NOT code STREQUAL "0" OR NOT output MATCHES "recompiled: [0-9]+ SPIR-V words") + message(FATAL_ERROR "--spv ${ARGN} failed: ${code}\n${output}${errors}") + endif() + string(FIND "${output}" "\n" firstLine) + math(EXPR firstLine "${firstLine} + 1") + string(SUBSTRING "${output}" ${firstLine} -1 output) + string(REGEX REPLACE "[^\n]*heap profile[^\n]*\n" "" output "${output}") + set(${result} "${output}" PARENT_SCOPE) +endfunction() + +replay_spv(addressed "${CAPTURE}/heap-data-addressed.req") +replay_spv(uniform "${CAPTURE}/heap-data-4096.req") +replay_spv(addressedAgain --heap-data-uniform-dwords 0 "${CAPTURE}/heap-data-addressed.req") +replay_spv(uniformOverride --heap-data-uniform-dwords 4096 "${CAPTURE}/heap-data-addressed.req") +replay_spv(addressedOverride --heap-data-uniform-dwords 0 "${CAPTURE}/heap-data-4096.req") +if(addressed STREQUAL uniform) + message(FATAL_ERROR "the captured limits 0 and 4096 replayed to the same SPIR-V\n${addressed}") +endif() +if(NOT addressed STREQUAL addressedAgain OR NOT uniform STREQUAL uniformOverride OR NOT addressed STREQUAL addressedOverride) + message(FATAL_ERROR "--heap-data-uniform-dwords did not reproduce the captured limit's SPIR-V\n${addressed}\n${addressedAgain}\n${uniform}\n${uniformOverride}\n${addressedOverride}") +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_compute_pipeline_capture_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_compute_pipeline_capture_tests.cmake index 2367926617c5..9361457b1440 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_compute_pipeline_capture_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_compute_pipeline_capture_tests.cmake @@ -27,3 +27,11 @@ if(BUILD_TESTING AND ANYPS5_ENABLE_SPIRV_TOOLS) -P ${CMAKE_CURRENT_SOURCE_DIR}/tests/ComputePipelineCaptureRun.cmake) set_tests_properties(agc_compute_pipeline_capture_run PROPERTIES TIMEOUT 30 SKIP_REGULAR_EXPRESSION "compute pipeline capture run: skipped, no usable Vulkan device") endif() + +if(BUILD_TESTING) + add_test(NAME agc_compute_pipeline_capture_heap_run COMMAND ${CMAKE_COMMAND} + -DFIXTURE=$ + -DOUTPUT_ROOT=${CMAKE_CURRENT_BINARY_DIR}/capture-tests + -P ${CMAKE_CURRENT_SOURCE_DIR}/tests/ComputePipelineCaptureHeapRun.cmake) + set_tests_properties(agc_compute_pipeline_capture_heap_run PROPERTIES TIMEOUT 30 SKIP_REGULAR_EXPRESSION "compute pipeline heap capture run: skipped") +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_descriptor_heap_object_devices_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_descriptor_heap_object_devices_tests.cmake new file mode 100644 index 000000000000..66368de709bc --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_descriptor_heap_object_devices_tests.cmake @@ -0,0 +1,12 @@ +add_test_executable(agc_descriptor_heap_object_devices_tests EXCLUDE_FROM_ALL tests/DescriptorHeapObjectDevices.cpp) +target_include_directories(agc_descriptor_heap_object_devices_tests PRIVATE + ${LIBS_INCLUDE_DIR} + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} +) +target_link_libraries(agc_descriptor_heap_object_devices_tests PRIVATE libSceAgcDriver libc) +set_target_properties(agc_descriptor_heap_object_devices_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_descriptor_heap_object_devices_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_descriptor_heap_object_devices_tests) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake index 2df2f73414e8..bdc278eebb27 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake @@ -31,4 +31,10 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_address_draw_space_reuse_held PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + agc_add_env_test(agc_driver_address_draw_space_reuse_heap agc_driver_address_draw_space_reuse_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 TIMEOUT 60 NO_WORKING_DIRECTORY) + agc_add_env_test(agc_driver_address_draw_space_reuse_heap_stages agc_driver_address_draw_space_reuse_tests + ARGS --heap-stages ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 TIMEOUT 60 NO_WORKING_DIRECTORY) + agc_add_env_test(agc_driver_address_draw_space_reuse_heap_transitions agc_driver_address_draw_space_reuse_tests + ARGS --transitions ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_DRAW_TRANSITIONS=1 TIMEOUT 60 NO_WORKING_DIRECTORY) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_passes_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_passes_tests.cmake index 9208eaf2d256..c8e637395a5f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_passes_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_passes_tests.cmake @@ -12,3 +12,7 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_address_passes) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bda_span_reads_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bda_span_reads_tests.cmake index a04e3566680a..76823a0a095d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bda_span_reads_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bda_span_reads_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_bda_span_reads) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_bda_span_reads) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bindless_images_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bindless_images_tests.cmake new file mode 100644 index 000000000000..3892cefc3235 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bindless_images_tests.cmake @@ -0,0 +1,7 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_bindless_images) +endif() +if(BUILD_TESTING AND TARGET agc_driver_bindless_images_tests) + agc_add_env_test(agc_driver_bindless_images_heap agc_driver_bindless_images_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 NO_WORKING_DIRECTORY) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_buffer_atomics_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_buffer_atomics_tests.cmake new file mode 100644 index 000000000000..bd2fde5c5e7d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_buffer_atomics_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_buffer_atomics) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_buffer_format_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_buffer_format_tests.cmake new file mode 100644 index 000000000000..d73e107870ad --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_buffer_format_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_buffer_format) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_buffer_load_store_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_buffer_load_store_tests.cmake index 6657a149501c..59e092a61eb2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_buffer_load_store_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_buffer_load_store_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_buffer_load_store) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_buffer_load_store) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_compute_table_calls_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_compute_table_calls_tests.cmake new file mode 100644 index 000000000000..3a5f7014a351 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_compute_table_calls_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_compute_table_calls) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_copied_writer_copy_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_copied_writer_copy_tests.cmake index 86b69033ad36..fac8a17c07e5 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_copied_writer_copy_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_copied_writer_copy_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_copied_writer_copy) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_copied_writer_copy) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_partial_store_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_partial_store_tests.cmake index 471edcce294c..f6fa9b2308d4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_partial_store_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_partial_store_tests.cmake @@ -1,4 +1,11 @@ if(BUILD_TESTING) + add_test(NAME agc_driver_depth_plane_proof_under_other_pending COMMAND agc_driver_depth_plane_partial_store_tests --proof-under-other-pending) + set_tests_properties(agc_driver_depth_plane_proof_under_other_pending PROPERTIES + ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_depth_plane_proof_under_other_pending PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test(NAME agc_driver_depth_plane_cpu_write_after_page_unwatch COMMAND agc_driver_depth_plane_partial_store_tests --cpu-write-after-page-unwatch) set_tests_properties(agc_driver_depth_plane_cpu_write_after_page_unwatch PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_storage_dispatch_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_storage_dispatch_tests.cmake new file mode 100644 index 000000000000..85967a92e666 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_storage_dispatch_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_depth_storage_dispatch) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_storage_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_storage_reuse_tests.cmake index ae4b99b882dc..06ed98cdd187 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_storage_reuse_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_storage_reuse_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_depth_storage_reuse) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_depth_storage_reuse) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_move_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_move_tests.cmake new file mode 100644 index 000000000000..401ae774dfbe --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_move_tests.cmake @@ -0,0 +1,4 @@ +if(BUILD_TESTING AND TARGET agc_driver_dispatch_move_tests) + agc_add_env_test(agc_driver_dispatch_move_gpu_heap agc_driver_dispatch_move_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_overlap_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_overlap_tests.cmake index 669a81003495..bd369d9903f7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_overlap_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_overlap_tests.cmake @@ -6,4 +6,8 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_dispatch_overlap_off PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + agc_add_env_test(agc_driver_dispatch_overlap_recipe_verify agc_driver_dispatch_overlap_tests TIMEOUT 60 + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_VERIFY_RECIPE=1) + agc_add_env_test(agc_driver_dispatch_overlap_recipe_verify_gpu_heap agc_driver_dispatch_overlap_tests TIMEOUT 60 + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_VERIFY_RECIPE=1) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_relocation_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_relocation_tests.cmake index 75ebf972361a..2650cc7e6319 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_relocation_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_relocation_tests.cmake @@ -17,3 +17,11 @@ if(BUILD_TESTING) endif() agc_add_draw_pipeline_test(agc_driver_draw_cache_relocation) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_draw_cache_relocation) + agc_add_env_test(agc_driver_draw_cache_relocation_entries_verify agc_driver_draw_cache_relocation_tests TIMEOUT 60 + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_VERIFY_DRAW_ENTRIES=1) + agc_add_env_test(agc_driver_draw_cache_relocation_data_hits_verify_gpu_heap agc_driver_draw_cache_relocation_tests TIMEOUT 60 + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_VERIFY_DRAW_DATA_HITS=1) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_reuse_tests.cmake index a125e04bee22..48d67e9de5da 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_reuse_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_reuse_tests.cmake @@ -15,11 +15,16 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_draw_cache_reuse_inline PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_PIPELINED_DRAWS=0;APS5_VERIFY_DRAW_RECIPE=1;APS5_VERIFY_REGISTER_KEYS=1" SKIP_RETURN_CODE 77) add_test(NAME agc_driver_draw_cache_reuse_indirect COMMAND agc_driver_draw_cache_reuse_tests) set_tests_properties(agc_driver_draw_cache_reuse_indirect PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_CACHE_INDIRECT=1;APS5_PROFILE_DRAW=1" SKIP_RETURN_CODE 77) + agc_add_env_test(agc_driver_draw_cache_reuse_indirect_gpu_heap agc_driver_draw_cache_reuse_tests NO_WORKING_DIRECTORY + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_DRAW_CACHE_INDIRECT=1 APS5_PROFILE_DRAW=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) + set_tests_properties(agc_driver_draw_cache_reuse_indirect_gpu_heap PROPERTIES FAIL_REGULAR_EXPRESSION "FATAL:") add_test(NAME agc_driver_draw_cache_reuse_push_word COMMAND agc_driver_draw_cache_reuse_tests) set_tests_properties(agc_driver_draw_cache_reuse_push_word PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_CACHE_INDIRECT=1;APS5_DRAW_CACHE_PUSH_WORD=1;APS5_PROFILE_DRAW=1" SKIP_RETURN_CODE 77) add_test(NAME agc_driver_draw_cache_reuse_push_word_verify COMMAND agc_driver_draw_cache_reuse_tests) set_tests_properties(agc_driver_draw_cache_reuse_push_word_verify PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_CACHE_INDIRECT=1;APS5_DRAW_CACHE_PUSH_WORD=1;APS5_VERIFY_DRAW_PUSH_WORD=1;APS5_PROFILE_DRAW=1" SKIP_RETURN_CODE 77) - set_tests_properties(agc_driver_draw_cache_reuse agc_driver_draw_cache_reuse_off agc_driver_draw_cache_reuse_verify agc_driver_draw_cache_reuse_inline agc_driver_draw_cache_reuse_indirect agc_driver_draw_cache_reuse_push_word agc_driver_draw_cache_reuse_push_word_verify PROPERTIES FAIL_REGULAR_EXPRESSION "FATAL:") + agc_add_env_test(agc_driver_draw_cache_reuse_push_word_gpu_heap agc_driver_draw_cache_reuse_tests NO_WORKING_DIRECTORY + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_DRAW_CACHE_INDIRECT=1 APS5_DRAW_CACHE_PUSH_WORD=1 APS5_VERIFY_DRAW_PUSH_WORD=1 APS5_PROFILE_DRAW=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) + set_tests_properties(agc_driver_draw_cache_reuse agc_driver_draw_cache_reuse_off agc_driver_draw_cache_reuse_verify agc_driver_draw_cache_reuse_inline agc_driver_draw_cache_reuse_indirect agc_driver_draw_cache_reuse_push_word agc_driver_draw_cache_reuse_push_word_verify agc_driver_draw_cache_reuse_indirect_gpu_heap agc_driver_draw_cache_reuse_push_word_gpu_heap PROPERTIES FAIL_REGULAR_EXPRESSION "FATAL:") set_property(TEST agc_driver_draw_cache_reuse agc_driver_draw_cache_reuse_off APPEND PROPERTY ENVIRONMENT "APS5_VERIFY_DRAW_RECIPE=1" "APS5_VERIFY_REGISTER_KEYS=1") add_test(NAME agc_driver_draw_cache_reuse_pass_attachments_verify COMMAND agc_driver_draw_cache_reuse_tests) set_tests_properties(agc_driver_draw_cache_reuse_pass_attachments_verify PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1;APS5_VERIFY_PASS_ATTACHMENTS=1" SKIP_RETURN_CODE 77 FAIL_REGULAR_EXPRESSION "FATAL:;differ from the full lookup") @@ -36,6 +41,7 @@ if(BUILD_TESTING) endif() if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_draw_cache_reuse) foreach(dumpMode graphics filtered disabled) set(dumpTest agc_driver_graphics_dump_${dumpMode}) add_test(NAME ${dumpTest} COMMAND agc_driver_draw_cache_reuse_tests --dump-${dumpMode}) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_data_hit_user_words_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_data_hit_user_words_tests.cmake new file mode 100644 index 000000000000..959f90b10a4a --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_data_hit_user_words_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_draw_data_hit_user_words) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_offset_indices_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_offset_indices_tests.cmake index 5267a2cde3b3..824560157a5a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_offset_indices_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_offset_indices_tests.cmake @@ -26,4 +26,12 @@ if(BUILD_TESTING) endif() endforeach() endforeach() + add_test(NAME agc_driver_draw_heap_attributes_compact_restart COMMAND agc_driver_draw_offset_indices_tests heap-attributes) + set_tests_properties(agc_driver_draw_heap_attributes_compact_restart PROPERTIES + ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 45 SKIP_RETURN_CODE 77 + WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_draw_heap_attributes_compact_restart PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_pushed_user_values_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_pushed_user_values_tests.cmake new file mode 100644 index 000000000000..195b460d7279 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_pushed_user_values_tests.cmake @@ -0,0 +1,5 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_draw_pushed_user_values) + agc_add_env_test(agc_driver_draw_pushed_user_values_gpu_heap_unverified agc_driver_draw_pushed_user_values_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recapture_on_change_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recapture_on_change_tests.cmake index 37bf0863a7be..d857de723cbe 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recapture_on_change_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recapture_on_change_tests.cmake @@ -1,6 +1,8 @@ if(BUILD_TESTING) add_test(NAME agc_driver_draw_recapture_on_change_inline COMMAND agc_driver_draw_recapture_on_change_tests) set_tests_properties(agc_driver_draw_recapture_on_change_inline PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_PIPELINED_DRAWS=0" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + agc_add_env_test(agc_driver_draw_recapture_on_change_gpu_heap agc_driver_draw_recapture_on_change_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) add_test(NAME agc_driver_draw_recapture_on_change_finisher COMMAND agc_driver_draw_recapture_on_change_tests) set_tests_properties(agc_driver_draw_recapture_on_change_finisher PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") add_test(NAME agc_driver_dispatch_recapture_on_change_items COMMAND agc_driver_dispatch_recapture_on_change_tests) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake new file mode 100644 index 000000000000..96a1ed2653d0 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake @@ -0,0 +1,7 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_draw_recipe_moved_buffer) + agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_overflow agc_driver_draw_recipe_moved_buffer_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PUSHED_BUFFER_RECORDS=0) + agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_unverified agc_driver_draw_recipe_moved_buffer_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_relocate_user_values_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_relocate_user_values_tests.cmake new file mode 100644 index 000000000000..a7861b87515a --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_relocate_user_values_tests.cmake @@ -0,0 +1,4 @@ +if(BUILD_TESTING) + agc_add_env_test(agc_driver_draw_relocate_user_values_gpu_heap agc_driver_draw_relocate_user_values_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_VERIFY_DRAW_ENTRIES=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_unsupported_buffer_type_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_unsupported_buffer_type_tests.cmake index 8a28aad7c163..c088a54f5081 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_unsupported_buffer_type_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_unsupported_buffer_type_tests.cmake @@ -14,3 +14,7 @@ if(BUILD_TESTING) endif() agc_add_draw_pipeline_test(agc_driver_draw_unsupported_buffer_type) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_draw_unsupported_buffer_type) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_write_ranges_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_write_ranges_tests.cmake index 230d88b1669c..5eb2f7eb1d70 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_write_ranges_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_write_ranges_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_draw_write_ranges) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_draw_write_ranges) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_dispatch_order_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_dispatch_order_tests.cmake new file mode 100644 index 000000000000..ab71ab726682 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_dispatch_order_tests.cmake @@ -0,0 +1,7 @@ +if(BUILD_TESTING) + agc_add_draw_pipeline_test(agc_driver_finisher_dispatch_order) +endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_finisher_dispatch_order) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_hit_lookup_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_hit_lookup_tests.cmake new file mode 100644 index 000000000000..e5b9cccef45e --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_hit_lookup_tests.cmake @@ -0,0 +1,4 @@ +if(BUILD_TESTING) + agc_add_draw_pipeline_test(agc_driver_finisher_hit_lookup) + agc_add_gpu_heap_test(agc_driver_finisher_hit_lookup) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_label_order_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_label_order_tests.cmake index 889a5ae09ccc..f0bcb3e2d923 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_label_order_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_label_order_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_finisher_label_order) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_finisher_label_order) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_fragment_user_data_tail_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_fragment_user_data_tail_tests.cmake new file mode 100644 index 000000000000..6b01e6f504e5 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_fragment_user_data_tail_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_fragment_user_data_tail) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_gated_dispatch_capture_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_gated_dispatch_capture_tests.cmake index d933f3070ddd..2a50895389de 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_gated_dispatch_capture_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_gated_dispatch_capture_tests.cmake @@ -9,3 +9,7 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_gated_dispatch_capture) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_gpu_indirect_arguments_misaligned_writer_ahead_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_gpu_indirect_arguments_misaligned_writer_ahead_tests.cmake new file mode 100644 index 000000000000..79bc85e76449 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_gpu_indirect_arguments_misaligned_writer_ahead_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_gpu_indirect_arguments_misaligned_writer_ahead) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_gpu_indirect_arguments_written_ahead_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_gpu_indirect_arguments_written_ahead_tests.cmake new file mode 100644 index 000000000000..ab633bf75e25 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_gpu_indirect_arguments_written_ahead_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_gpu_indirect_arguments_written_ahead) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_graphics_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_graphics_tests.cmake index d31f89f72b7b..e46829706c22 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_graphics_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_graphics_tests.cmake @@ -118,7 +118,8 @@ if(BUILD_TESTING) endif() add_test(NAME agc_copy_input_kept_bytes COMMAND agc_driver_graphics_tests --copy-input-kept-bytes) add_test(NAME agc_depth_copy_kept_bytes COMMAND agc_driver_graphics_tests --depth-copy-kept-bytes) - set_tests_properties(agc_copy_input_kept_bytes agc_depth_copy_kept_bytes PROPERTIES + add_test(NAME agc_pooled_buffer_address COMMAND agc_driver_graphics_tests --pooled-buffer-address) + set_tests_properties(agc_copy_input_kept_bytes agc_depth_copy_kept_bytes agc_pooled_buffer_address PROPERTIES TIMEOUT 30 ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" ENVIRONMENT_MODIFICATION "APS5_CPU_COPIES=unset:;APS5_GPU_COPY_MAX_KIB=unset:;APS5_CAPTURE_GPU_COPIES=unset:;APS5_BUFFER_POOL_SLOTS=unset:;APS5_BUFFER_POOL_SHARED=unset:;APS5_NO_BUFFER_CLASSES=unset:;APS5_STAGING_POOL_MIB=unset:") if(WIN32) @@ -126,6 +127,8 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") set_property(TEST agc_depth_copy_kept_bytes APPEND PROPERTY ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_property(TEST agc_pooled_buffer_address APPEND PROPERTY ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") endif() set_tests_properties(agc_sparse_buffer_holes PROPERTIES TIMEOUT 30) add_test(NAME agc_pipeline_journal COMMAND agc_driver_graphics_tests --pipeline-journal) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake new file mode 100644 index 000000000000..a9d4ef8d3cbb --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake @@ -0,0 +1,8 @@ +if(BUILD_TESTING AND TARGET agc_driver_heap_compute_sample_tests) + agc_add_env_test(agc_driver_heap_compute_sample_heap_pipelined agc_driver_heap_compute_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PIPELINE_DISPATCH=1 APS5_PIPELINED_DRAWS=32) + agc_add_env_test(agc_driver_heap_compute_sample_heap agc_driver_heap_compute_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) + agc_add_env_test(agc_driver_heap_compute_sample_full_heap agc_driver_heap_compute_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=4) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake new file mode 100644 index 000000000000..95898aa8ec11 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake @@ -0,0 +1,24 @@ +if(BUILD_TESTING AND TARGET agc_driver_heap_draw_sample_tests) + agc_add_env_test(agc_driver_heap_draw_sample_heap agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) + agc_add_env_test(agc_driver_heap_draw_sample_full_heap agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5) + agc_add_env_test(agc_driver_heap_draw_sample_full_heap_pipelined agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) + agc_add_env_test(agc_driver_heap_draw_sample_full_heap_unverified agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5) + agc_add_env_test(agc_driver_heap_draw_sample_heap_excluded agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_GPU_HEAP_EXCLUDE=sampled) + agc_add_env_test(agc_driver_heap_draw_sample_no_timeline agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_NO_TIMELINE=1) + set_tests_properties(agc_driver_heap_draw_sample_no_timeline PROPERTIES PASS_REGULAR_EXPRESSION "APS5_NO_TIMELINE cannot be used with APS5_GPU_HEAP" + SKIP_REGULAR_EXPRESSION "skipped, the device lacks VK_EXT_descriptor_heap") + agc_add_env_test(agc_driver_heap_draw_sample_heap_async agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_ASYNC_DRAW_COMPILE=1) + agc_add_env_test(agc_driver_heap_draw_sample_heap_async_pipelined agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_ASYNC_DRAW_COMPILE=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) + agc_add_env_test(agc_driver_heap_draw_sample_nogpl agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_GPL=1) + agc_add_env_test(agc_driver_heap_draw_sample_nogpl_heap agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_GPL=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake new file mode 100644 index 000000000000..d87a35c63b02 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake @@ -0,0 +1,6 @@ +if(BUILD_TESTING AND TARGET agc_driver_heap_embedded_sampler_tests) + agc_add_env_test(agc_driver_heap_embedded_sampler_heap agc_driver_heap_embedded_sampler_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) + agc_add_env_test(agc_driver_heap_embedded_sampler_heap_capped agc_driver_heap_embedded_sampler_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_EMBEDDED_SAMPLER_CAP=0) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_finisher_queued_write_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_finisher_queued_write_tests.cmake new file mode 100644 index 000000000000..1c0259461511 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_finisher_queued_write_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_heap_finisher_queued_write) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake new file mode 100644 index 000000000000..c72737e907db --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake @@ -0,0 +1,6 @@ +if(BUILD_TESTING) + agc_add_draw_pipeline_test(agc_driver_heap_ring_draw_key) + agc_add_gpu_heap_test(agc_driver_heap_ring_draw_key) + agc_add_env_test(agc_driver_heap_ring_draw_key_gpu_heap_fixed_buffers agc_driver_heap_ring_draw_key_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1 APS5_NO_MOVED_BUFFER_TEMPLATES=1) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake new file mode 100644 index 000000000000..1d23196afc8e --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake @@ -0,0 +1,28 @@ +add_test_executable(agc_driver_heap_slots_tests EXCLUDE_FROM_ALL + tests/BindlessHeapSlots.cpp +) + +target_include_directories(agc_driver_heap_slots_tests PRIVATE + ${LIBS_INCLUDE_DIR} + ${CMAKE_SOURCE_DIR}/core/shader/recompiler + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} +) + +target_link_libraries(agc_driver_heap_slots_tests PRIVATE + libSceAgcDriver + SDL2-static + libc +) + +set_target_properties(agc_driver_heap_slots_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_driver_heap_slots_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_driver_heap_slots_tests) + foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release idle-slots-evicted pressure-submit samplers-evicted no-timeline-fails) + string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") + agc_add_env_test(agc_driver_heap_slots_${agcHeapSlotsName} agc_driver_heap_slots_tests + ARGS ${agcHeapSlotsMode} ENV ANYPS5_NO_SHADER_CACHE=1) + endforeach() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake new file mode 100644 index 000000000000..6def7e94b48c --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake @@ -0,0 +1,13 @@ +if(BUILD_TESTING) + add_test_executable(agc_driver_heap_stage_words_tests tests/HeapStageWordsBase.cpp) + target_include_directories(agc_driver_heap_stage_words_tests PRIVATE ${LIBS_INCLUDE_DIR} ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR}) + target_link_libraries(agc_driver_heap_stage_words_tests PRIVATE libSceAgcDriver) + set_target_properties(agc_driver_heap_stage_words_tests PROPERTIES CXX_EXTENSIONS OFF) + configure_windows_unwind(agc_driver_heap_stage_words_tests) + add_test(NAME agc_driver_heap_stage_words COMMAND agc_driver_heap_stage_words_tests) + set_tests_properties(agc_driver_heap_stage_words PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(agc_driver_heap_stage_words PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$;PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake new file mode 100644 index 000000000000..d282888850bf --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake @@ -0,0 +1,9 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_heap_table_walk_reuse) + if(TARGET agc_driver_heap_table_walk_reuse_tests) + agc_add_env_test(agc_driver_heap_table_walk_reuse_heap agc_driver_heap_table_walk_reuse_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1) + agc_add_env_test(agc_driver_heap_table_walk_reuse_async agc_driver_heap_table_walk_reuse_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_ASYNC_DRAW_COMPILE=1) + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake new file mode 100644 index 000000000000..dc7bba88a614 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_heap_walk_capture_failure) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_reads_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_reads_tests.cmake new file mode 100644 index 000000000000..49e761c6ca0b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_reads_tests.cmake @@ -0,0 +1,24 @@ +add_test_executable(agc_driver_heap_walk_reads_tests EXCLUDE_FROM_ALL + tests/HeapWalkReads.cpp +) + +target_include_directories(agc_driver_heap_walk_reads_tests PRIVATE + ${LIBS_INCLUDE_DIR} + $ + ${CMAKE_SOURCE_DIR}/core/shader/recompiler + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} +) + +target_link_libraries(agc_driver_heap_walk_reads_tests PRIVATE + libSceAgcDriver + SDL2-static + libc +) + +set_target_properties(agc_driver_heap_walk_reads_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_driver_heap_walk_reads_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_driver_heap_walk_reads_tests) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_threads_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_threads_tests.cmake new file mode 100644 index 000000000000..e2e2f0ceb11c --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_threads_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_heap_walk_threads) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics64_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics64_tests.cmake new file mode 100644 index 000000000000..1906060b5d14 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics64_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_atomics64) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics_bitwise_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics_bitwise_tests.cmake new file mode 100644 index 000000000000..ffa07becb676 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics_bitwise_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_atomics_bitwise) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics_float_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics_float_tests.cmake new file mode 100644 index 000000000000..7e2d6ef5b4fd --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics_float_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_atomics_float) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics_tests.cmake new file mode 100644 index 000000000000..4d1590c46853 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_atomics_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_atomics) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_cache_bits_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_cache_bits_tests.cmake new file mode 100644 index 000000000000..e1ad2f4b0be2 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_cache_bits_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_cache_bits) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_converted_unorm_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_converted_unorm_tests.cmake index 8375c9978b50..d07dd8a62f90 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_converted_unorm_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_converted_unorm_tests.cmake @@ -29,3 +29,7 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_image_depth24_float PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_converted_unorm) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_gather_one_dimensional_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_gather_one_dimensional_tests.cmake new file mode 100644 index 000000000000..70324af9eab4 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_gather_one_dimensional_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_gather_one_dimensional) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_load_packed_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_load_packed_tests.cmake new file mode 100644 index 000000000000..1a1d9b83a008 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_load_packed_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_load_packed) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_border_color_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_border_color_tests.cmake new file mode 100644 index 000000000000..6adc925a198f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_border_color_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_sample_border_color) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_derivatives_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_derivatives_tests.cmake new file mode 100644 index 000000000000..6e94552f53e9 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_derivatives_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_sample_derivatives) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_lod_clamp_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_lod_clamp_tests.cmake index 4cf0a2069597..9a6913007160 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_lod_clamp_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_lod_clamp_tests.cmake @@ -1,4 +1,5 @@ if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_sample_lod_clamp) add_test(NAME agc_driver_image_sample_lod_clamp_shader_lane COMMAND agc_driver_image_sample_lod_clamp_tests --shader-lane) set_tests_properties(agc_driver_image_sample_lod_clamp_shader_lane PROPERTIES ENVIRONMENT "APS5_NO_IMAGE_VIEW_MIN_LOD=1;APS5_NO_GPL=1;ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 60) if(WIN32) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_shared_sampler_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_shared_sampler_tests.cmake new file mode 100644 index 000000000000..15964a4cfc42 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sample_shared_sampler_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_sample_shared_sampler) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sint8_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sint8_tests.cmake index bed7782429b6..7d5efc453113 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sint8_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_sint8_tests.cmake @@ -9,4 +9,5 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_image_sint8_gather_constant_one agc_driver_image_sint8_gather_constant_all_bits PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + agc_add_gpu_heap_test(agc_driver_image_sint8) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_srgb_load_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_srgb_load_tests.cmake new file mode 100644 index 000000000000..6e2bbe454302 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_srgb_load_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_srgb_load) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_array_through_volume_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_array_through_volume_tests.cmake new file mode 100644 index 000000000000..8d54dc08f592 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_array_through_volume_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_store_array_through_volume) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_face_on_cube_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_face_on_cube_tests.cmake new file mode 100644 index 000000000000..0ab9fe54fdbc --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_face_on_cube_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_store_face_on_cube) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_float_rounding_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_float_rounding_tests.cmake new file mode 100644 index 000000000000..3d16cb85557c --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_float_rounding_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_store_float_rounding) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_line_through_plane_array_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_line_through_plane_array_tests.cmake new file mode 100644 index 000000000000..342b19006c96 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_line_through_plane_array_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_store_line_through_plane_array) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_line_through_plane_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_line_through_plane_tests.cmake new file mode 100644 index 000000000000..3fab0a37b350 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_line_through_plane_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_store_line_through_plane) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_packed_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_packed_tests.cmake new file mode 100644 index 000000000000..942cc404cb0b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_packed_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_store_packed) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_sint_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_sint_tests.cmake new file mode 100644 index 000000000000..6179aa7e5991 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_sint_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_store_sint) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_unorm_rounding_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_unorm_rounding_tests.cmake new file mode 100644 index 000000000000..a72eed6ae44f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_unorm_rounding_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_store_unorm_rounding) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_volume_through_array_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_volume_through_array_tests.cmake new file mode 100644 index 000000000000..f45dde563ae9 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_store_volume_through_array_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_store_volume_through_array) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_cache_bounds_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_cache_bounds_tests.cmake new file mode 100644 index 000000000000..f84b019c2489 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_cache_bounds_tests.cmake @@ -0,0 +1,9 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_table_cache_bounds) + agc_add_env_test(agc_driver_image_table_atomics agc_driver_image_table_cache_bounds_tests + ARGS --atomic-table ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 60) + agc_add_env_test(agc_driver_image_table_atomics_gpu_heap agc_driver_image_table_cache_bounds_tests + ARGS --atomic-table ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 TIMEOUT 60) + agc_add_env_test(agc_driver_image_table_store_gpu_heap agc_driver_image_table_cache_bounds_tests + ARGS --store-table ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 TIMEOUT 60) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_reuse_tests.cmake index 2615fa3fbc21..48b9f52a3983 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_reuse_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_reuse_tests.cmake @@ -28,3 +28,7 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_image_table_reuse_records agc_driver_image_table_reuse_records_narrow PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_table_reuse) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_variants_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_variants_tests.cmake new file mode 100644 index 000000000000..ef34a6f33f6d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_variants_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_table_variants) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_texel_status_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_texel_status_tests.cmake new file mode 100644 index 000000000000..dd91b04aa2b4 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_texel_status_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_texel_status) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_arguments_written_ahead_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_arguments_written_ahead_tests.cmake new file mode 100644 index 000000000000..8c80cbfe825e --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_arguments_written_ahead_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_indirect_arguments_written_ahead) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_patched_stage_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_patched_stage_tests.cmake new file mode 100644 index 000000000000..fdc74f343c1f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_patched_stage_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_indirect_patched_stage) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_thread_dimensions_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_thread_dimensions_tests.cmake index e1e265cfd939..9173a6930ae8 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_thread_dimensions_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_indirect_thread_dimensions_tests.cmake @@ -6,3 +6,7 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_indirect_thread_dimensions) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_lds_beyond_device_limit_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_lds_beyond_device_limit_tests.cmake new file mode 100644 index 000000000000..441dfc8499c6 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_lds_beyond_device_limit_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_lds_beyond_device_limit) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_draw_relocation_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_draw_relocation_tests.cmake new file mode 100644 index 000000000000..1168df7bb5ae --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_draw_relocation_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_mesh_draw_relocation) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_index_cache_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_index_cache_tests.cmake new file mode 100644 index 000000000000..5db5e725cd88 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_index_cache_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_mesh_index_cache) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_provoking_vertex_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_provoking_vertex_tests.cmake new file mode 100644 index 000000000000..dc8ecfc0f1a3 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_provoking_vertex_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_mesh_provoking_vertex) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_tests.cmake index 2f26ed8c15dd..d26f10a7ef5a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_mesh_tests.cmake @@ -12,3 +12,7 @@ configure_windows_unwind(agc_driver_mesh_tests) if(BUILD_TESTING) agc_add_default_test(agc_driver_mesh_tests) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_mesh) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_oversized_dispatch_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_oversized_dispatch_tests.cmake new file mode 100644 index 000000000000..ffbee6f42891 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_oversized_dispatch_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_oversized_dispatch) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_journal_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_journal_tests.cmake index c6a43bcb2950..f22bd06f0091 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_journal_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_journal_tests.cmake @@ -6,4 +6,6 @@ if(BUILD_TESTING) if(WIN32) set_tests_properties(agc_driver_pipeline_journal_undecodable_module PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + agc_add_env_test(agc_driver_pipeline_journal_gpu_heap agc_driver_pipeline_journal_tests + ARGS --gpu-heap ENV APS5_GPU_HEAP=1 TIMEOUT 30) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_stop_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_stop_tests.cmake new file mode 100644 index 000000000000..f89abafd2978 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_stop_tests.cmake @@ -0,0 +1,13 @@ +if(BUILD_TESTING) + add_test_executable(agc_driver_pipeline_stop_tests tests/DrawPipelineStop.cpp) + target_include_directories(agc_driver_pipeline_stop_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(agc_driver_pipeline_stop_tests PRIVATE libSceAgcDriver) + set_target_properties(agc_driver_pipeline_stop_tests PROPERTIES CXX_EXTENSIONS OFF) + configure_windows_unwind(agc_driver_pipeline_stop_tests) + add_test(NAME agc_driver_pipeline_stop COMMAND agc_driver_pipeline_stop_tests) + set_tests_properties(agc_driver_pipeline_stop PROPERTIES TIMEOUT 20 ENVIRONMENT "APS5_PIPELINED_DRAWS=4") + if(WIN32) + set_tests_properties(agc_driver_pipeline_stop PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_dma_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_dma_tests.cmake index 63a078aa117a..6b60fe164558 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_dma_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_dma_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_pipelined_dma) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_pipelined_dma) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_fill_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_fill_tests.cmake index 38a274318427..42f881e669ff 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_fill_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_fill_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_pipelined_fill) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_pipelined_fill) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_metadata_pass_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_metadata_pass_tests.cmake index b4df42c2ced8..716726765017 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_metadata_pass_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_metadata_pass_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_pipelined_metadata_pass) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_pipelined_metadata_pass) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_predicated_label_order_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_predicated_label_order_tests.cmake index f80d0d69b445..74273173b184 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_predicated_label_order_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_predicated_label_order_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_pipelined_predicated_label_order) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_pipelined_predicated_label_order) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_predication_read_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_predication_read_tests.cmake index 59f85e5bf0b1..2b8b222f1bbe 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_predication_read_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipelined_predication_read_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_pipelined_predication_read) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_pipelined_predication_read) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pixel_barycentric_emulation_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pixel_barycentric_emulation_tests.cmake new file mode 100644 index 000000000000..4912dbdf62ba --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pixel_barycentric_emulation_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_pixel_barycentric_emulation) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_prepared_graphics_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_prepared_graphics_tests.cmake index 47e76a68790b..1ae6f19fa991 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_prepared_graphics_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_prepared_graphics_tests.cmake @@ -17,3 +17,7 @@ if(BUILD_TESTING) set_tests_properties(${prebuildPolicyTest} PROPERTIES ENVIRONMENT_MODIFICATION "${prebuildPolicyEnvironment}") endforeach() endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_prepared_graphics) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_presentation_pass_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_presentation_pass_tests.cmake index 65f85c2bdfc1..0bd5687ed2e2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_presentation_pass_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_presentation_pass_tests.cmake @@ -6,6 +6,7 @@ target_include_directories(agc_driver_presentation_pass_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/core/shader/recompiler ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} ) target_link_libraries(agc_driver_presentation_pass_tests PRIVATE @@ -22,8 +23,10 @@ if(BUILD_TESTING) set_target_properties(agc_driver_presentation_pass_tests PROPERTIES EXCLUDE_FROM_ALL OFF) add_test(NAME agc_driver_presentation_pass COMMAND agc_driver_presentation_pass_tests) set_tests_properties(agc_driver_presentation_pass PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + add_test(NAME agc_driver_presentation_pass_gpu_heap COMMAND agc_driver_presentation_pass_tests) + set_tests_properties(agc_driver_presentation_pass_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") if(WIN32) - set_tests_properties(agc_driver_presentation_pass PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(agc_driver_presentation_pass agc_driver_presentation_pass_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() add_test(NAME agc_driver_presentation_fsr COMMAND agc_driver_presentation_pass_tests --fsr) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_provoking_vertex_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_provoking_vertex_tests.cmake index 023e8c55df76..c3e9092bdafb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_provoking_vertex_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_provoking_vertex_tests.cmake @@ -19,3 +19,7 @@ target_include_directories(agc_driver_provoking_vertex_tests PRIVATE ${agcTestSh if(BUILD_TESTING) set_tests_properties(agc_driver_provoking_vertex PROPERTIES TIMEOUT 30) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_provoking_vertex) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_push_data_placements_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_push_data_placements_tests.cmake new file mode 100644 index 000000000000..d21b0671b563 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_push_data_placements_tests.cmake @@ -0,0 +1,23 @@ +add_test_executable(agc_driver_push_data_placements_tests EXCLUDE_FROM_ALL + tests/PushDataPlacements.cpp +) + +target_include_directories(agc_driver_push_data_placements_tests PRIVATE + ${LIBS_INCLUDE_DIR} + ${CMAKE_SOURCE_DIR}/core/shader/recompiler + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} +) + +target_link_libraries(agc_driver_push_data_placements_tests PRIVATE + libSceAgcDriver + SDL2-static + libc +) + +set_target_properties(agc_driver_push_data_placements_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_driver_push_data_placements_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_driver_push_data_placements_tests) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_push_only_heap_passes_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_push_only_heap_passes_tests.cmake new file mode 100644 index 000000000000..df3f856331fe --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_push_only_heap_passes_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_push_only_heap_passes) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorded_draw_staging_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorded_draw_staging_tests.cmake new file mode 100644 index 000000000000..8ae69dded719 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorded_draw_staging_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_recorded_draw_staging) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake index be40dae89637..feff681684ea 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake @@ -183,6 +183,11 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() add_test(NAME agc_storage_kept_unit_settle COMMAND agc_driver_recorder_tests --kept-unit-settle-only) + add_test(NAME agc_storage_refresh_proofs COMMAND agc_driver_recorder_tests --refresh-proofs-only) + set_tests_properties(agc_storage_refresh_proofs PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + if(WIN32) + set_tests_properties(agc_storage_refresh_proofs PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() add_test(NAME agc_storage_idle_writeback_race COMMAND agc_driver_recorder_tests --idle-writeback-race-only) set_tests_properties(agc_storage_idle_writeback_race PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) set_tests_properties(agc_storage_kept_unit_settle PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_rect_list_indirect_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_rect_list_indirect_tests.cmake new file mode 100644 index 000000000000..1867b03a37e7 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_rect_list_indirect_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_rect_list_indirect) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recycled_shared_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recycled_shared_tests.cmake new file mode 100644 index 000000000000..eb4799c28ea6 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recycled_shared_tests.cmake @@ -0,0 +1,24 @@ +add_test_executable(agc_driver_recycled_shared_tests EXCLUDE_FROM_ALL + tests/RecycledShared.cpp +) + +target_include_directories(agc_driver_recycled_shared_tests PRIVATE + ${LIBS_INCLUDE_DIR} + $ + ${CMAKE_SOURCE_DIR}/core/shader/recompiler + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} +) + +target_link_libraries(agc_driver_recycled_shared_tests PRIVATE + libSceAgcDriver + SDL2-static + libc +) + +set_target_properties(agc_driver_recycled_shared_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_driver_recycled_shared_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_driver_recycled_shared_tests) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_same_queue_label_wait_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_same_queue_label_wait_tests.cmake index 2740681a9589..249fa785b3a9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_same_queue_label_wait_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_same_queue_label_wait_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_same_queue_label_wait) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_same_queue_label_wait) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sample_multisample_target_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sample_multisample_target_tests.cmake index 5cb16f77866c..1f6b0d89989b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sample_multisample_target_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sample_multisample_target_tests.cmake @@ -25,6 +25,7 @@ if(BUILD_TESTING) endif() if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_sample_multisample_target) foreach(initialMode IN ITEMS nonuniform nonuniform_lifetime nonuniform_capabilities nonuniform_hook) add_test(NAME agc_driver_native_color_initial_${initialMode} COMMAND agc_driver_sample_multisample_target_tests --initial-${initialMode}) set_tests_properties(agc_driver_native_color_initial_${initialMode} 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/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake index 62579748a9f4..bc9888b04088 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake @@ -1,6 +1,8 @@ if(BUILD_TESTING) add_test(NAME agc_driver_sampled_cache_budget_memory COMMAND agc_driver_sampled_cache_budget_tests memory) set_tests_properties(agc_driver_sampled_cache_budget_memory PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77) + agc_add_env_test(agc_driver_sampled_cache_budget_heap_view agc_driver_sampled_cache_budget_tests + ARGS heap-view ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_IMAGE_SLABS=1 APS5_RELEASE_UNDER_LOCK=1) add_test(NAME agc_driver_sampled_cache_budget_without_storage_image_multisample COMMAND agc_driver_sampled_cache_budget_tests without-storage-image-multisample) set_tests_properties(agc_driver_sampled_cache_budget_without_storage_image_multisample PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30) add_test(NAME agc_sampled_cache_device_selection COMMAND agc_driver_sampled_cache_budget_tests device-selection-cpu) @@ -48,3 +50,7 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_sampled_cache_budget) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_scratch_pool_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_scratch_pool_tests.cmake new file mode 100644 index 000000000000..73356a9c5815 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_scratch_pool_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_scratch_pool) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_staged_clear_sampled_read_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_staged_clear_sampled_read_tests.cmake index f982191576a9..f37fcc32f203 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_staged_clear_sampled_read_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_staged_clear_sampled_read_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_staged_clear_sampled_read) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_staged_clear_sampled_read) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_cache_budget_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_cache_budget_tests.cmake index dd6b8580b053..d6efb30d33e6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_cache_budget_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_cache_budget_tests.cmake @@ -20,4 +20,8 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_storage_cache_retained_batch agc_driver_storage_cache_entries_unlimited agc_driver_storage_cache_entries_profile PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + agc_add_env_test(agc_driver_storage_cache_budget_heap_slots agc_driver_storage_cache_budget_tests + ARGS --heap-slots ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_IMAGE_SLABS=1 TIMEOUT 30) + agc_add_env_test(agc_driver_storage_cache_retained_batch_heap_slots agc_driver_storage_cache_budget_tests + ARGS --retained-batch-heap-slots ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 30) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_flush_ordering_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_flush_ordering_tests.cmake index b3997c3aec7a..f656fa908fe0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_flush_ordering_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_flush_ordering_tests.cmake @@ -1,4 +1,5 @@ if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_storage_flush_ordering) add_test(NAME agc_driver_storage_flush_ordering_no_import COMMAND agc_driver_storage_flush_ordering_tests --stored-again) set_tests_properties(agc_driver_storage_flush_ordering_no_import PROPERTIES ENVIRONMENT "APS5_NO_HOST_IMPORT=1" SKIP_RETURN_CODE 77 TIMEOUT 60) if(WIN32) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_one_slice_alias_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_one_slice_alias_tests.cmake new file mode 100644 index 000000000000..ae27a3bdfeef --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_one_slice_alias_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_storage_one_slice_alias) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_write_back_overhang_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_write_back_overhang_tests.cmake index 688fd4820eab..862745ecb13b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_write_back_overhang_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_write_back_overhang_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_storage_write_back_overhang) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_storage_write_back_overhang) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_submit_progress_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_submit_progress_tests.cmake index eb7c0a6323a7..5553b418b7eb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_submit_progress_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_submit_progress_tests.cmake @@ -8,10 +8,10 @@ if(BUILD_TESTING) endif() add_test(NAME agc_submit_progress_no_timeline COMMAND agc_driver_submit_progress_tests --fallback-only) set_tests_properties(agc_submit_progress_no_timeline PROPERTIES - ENVIRONMENT "APS5_SUBMIT_PROGRESS=1;APS5_NO_TIMELINE=1" + ENVIRONMENT "APS5_SUBMIT_PROGRESS=1;APS5_NO_TIMELINE=1" ENVIRONMENT_MODIFICATION "APS5_GPU_HEAP=unset:" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") if(WIN32) set_tests_properties(agc_submit_progress_no_timeline PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$;PATH=path_list_prepend:$") + "APS5_GPU_HEAP=unset:;PATH=path_list_prepend:$;PATH=path_list_prepend:$") endif() endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_submit_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_submit_tests.cmake new file mode 100644 index 000000000000..7c5e93e4d111 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_submit_tests.cmake @@ -0,0 +1,6 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_tessellation_submit) + agc_add_env_test(agc_driver_tessellation_submit_geometry agc_driver_tessellation_submit_tests ARGS --geometry) + agc_add_env_test(agc_driver_tessellation_submit_geometry_gpu_heap agc_driver_tessellation_submit_tests ARGS --geometry + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_tests.cmake index f616a8f244b2..8a7f8e593836 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_tests.cmake @@ -7,3 +7,7 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_tessellation) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_unimported_label_order_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_unimported_label_order_tests.cmake index fe6fd86b0953..409dbf893501 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_unimported_label_order_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_unimported_label_order_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_unimported_label_order) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_unimported_label_order) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_view_past_last_mip_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_view_past_last_mip_tests.cmake new file mode 100644 index 000000000000..8a1e081e24de --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_view_past_last_mip_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_view_past_last_mip) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_write_data_written_ahead_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_write_data_written_ahead_tests.cmake index 46785e7b7461..2eb60cce0d6d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_write_data_written_ahead_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_write_data_written_ahead_tests.cmake @@ -1,3 +1,7 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_write_data_written_ahead) endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_write_data_written_ahead) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake new file mode 100644 index 000000000000..b2770b22610b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake @@ -0,0 +1,15 @@ +if(BUILD_TESTING) + add_test_executable(agc_pending_range_index_tests + tests/PendingRangeIndex.cpp + ) + target_include_directories(agc_pending_range_index_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(agc_pending_range_index_tests PRIVATE libc) + set_target_properties(agc_pending_range_index_tests PROPERTIES CXX_EXTENSIONS OFF) + configure_windows_unwind(agc_pending_range_index_tests) + add_test(NAME agc_pending_range_index COMMAND agc_pending_range_index_tests) + set_tests_properties(agc_pending_range_index PROPERTIES TIMEOUT 30) + if(WIN32) + set_tests_properties(agc_pending_range_index PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pipeline_cache_allocation_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pipeline_cache_allocation_tests.cmake index ef7a969e695e..c6f734beea4f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pipeline_cache_allocation_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pipeline_cache_allocation_tests.cmake @@ -1,5 +1,5 @@ add_test_executable(agc_pipeline_cache_allocation_tests EXCLUDE_FROM_ALL tests/PipelineCacheFailures.cpp - Graphics/src/PipelineCache.cpp tests/AllocationFailure.cpp) + Graphics/src/PipelineCache.cpp Graphics/src/DescriptorHeapObjects.cpp tests/AllocationFailure.cpp) target_include_directories(agc_pipeline_cache_allocation_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/core/shader/recompiler ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR}) target_link_libraries(agc_pipeline_cache_allocation_tests PRIVATE shader_recompiler_agc_driver libc) set_target_properties(agc_pipeline_cache_allocation_tests PROPERTIES CXX_EXTENSIONS OFF) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake new file mode 100644 index 000000000000..e8252ab14f8d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake @@ -0,0 +1,8 @@ +add_test_executable(agc_push_data_shadow_tests EXCLUDE_FROM_ALL tests/PushDataShadow.cpp) +target_include_directories(agc_push_data_shadow_tests PRIVATE ${LIBS_INCLUDE_DIR} ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR}) +set_target_properties(agc_push_data_shadow_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_host_test_executable(agc_push_data_shadow_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_push_data_shadow_tests) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp index bebcd0cdd5e5..d24b2f75e17e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -2,12 +2,14 @@ #include "prx/libSceAgcDriver/Execution/include/Recipe.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/GuestArena.hpp" @@ -38,6 +40,7 @@ #include #include #include +#include #include namespace AgcDriver { @@ -63,6 +66,8 @@ constexpr std::size_t PixelCodeOffset = 256; constexpr std::size_t IndirectCodeOffset = 512; constexpr std::size_t PointerSlots = 1024; constexpr std::size_t MovedVerticesOffset = 32768; +constexpr std::size_t ShiftedVerticesOffset = MovedVerticesOffset + 4100; +constexpr std::size_t ShiftedAgainVerticesOffset = ShiftedVerticesOffset + 4096; constexpr std::size_t RingSlotBytes = 256; constexpr std::size_t RingSlots = 8; constexpr std::uint32_t PinWaitMs = 4000; @@ -326,6 +331,8 @@ class Outcomes { AgcDriver::Graphics::AddressDrawReuseCounts before = AgcDriver::Graphics::AddressDrawReuseCounters(); }; +bool HeapStages = false; + std::uint64_t Builds() { const auto counters = AgcDriver::Graphics::BdaResources::TableCacheCounters(); return counters.hits + counters.misses - AgcDriver::Graphics::AddressDrawReuseVerifications(); @@ -355,6 +362,8 @@ struct Scene { pixels.Register(true); std::memcpy(vertices.Data(), Triangle.data(), sizeof(Triangle)); std::memcpy(vertices.Data() + MovedVerticesOffset, Triangle.data(), sizeof(Triangle)); + std::memcpy(vertices.Data() + ShiftedVerticesOffset, Triangle.data(), sizeof(Triangle)); + std::memcpy(vertices.Data() + ShiftedAgainVerticesOffset, Triangle.data(), sizeof(Triangle)); vertices.Register(false); std::memcpy(code.Data() + VertexCodeOffset, VertexCode.data(), sizeof(VertexCode)); std::memcpy(code.Data() + PixelCodeOffset, PixelCode.data(), sizeof(PixelCode)); @@ -394,7 +403,7 @@ struct Scene { ShaderRecompiler::RecompileRequest vertex{ {ShaderStage::Vertex, code.Address(VertexCodeOffset), VertexCode, 0, {}}, {64, 0, userData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory}, - device.Target(), + Target(), {0, 0, 0, 64} }; vertex.useCache = cachedVertex; @@ -404,8 +413,14 @@ struct Scene { shaders[0] = {ShaderStage::Vertex, &vertexResults.back(), 0}; } + ShaderRecompiler::SpirvTarget Target() const { + auto target = device.Target(); + target.gpuResolvedImages = HeapStages; + return target; + } + void Point(std::uint64_t slot, std::span program = PixelCode, std::size_t offset = PixelCodeOffset, std::span resources = {}) { - const auto target = device.Target(); + const auto target = Target(); ShaderRecompiler::ShaderPixelStageInfo pixel{}; pixel.inputAddr = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionX) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionY); pixel.posX = true; @@ -497,8 +512,13 @@ void CpuWrite(Scene& scene) { Require(scene.DrawnColor() == 120, "address draw space reuse: the draw before the CPU write did not read the guest constant"); scene.Store(scene.constants, 0, 40); const auto before = Builds(); + const auto copies = AgcDriver::Graphics::DrawInputCopies(); const auto color = scene.DrawnColor(); Require(color == 40, "address draw space reuse: a draw after a CPU write into its constant read " + std::to_string(color) + " instead of the written 40"); + if (HeapStages) { + const auto taken = AgcDriver::Graphics::DrawInputCopies() - copies; + Require(taken == 0, "address draw space reuse: heap stages of an address draw read " + std::to_string(taken) + " per-draw copies instead of guest memory in place"); + } Require(Builds() == before, "address draw space reuse: a CPU write into memory the draw reads in place made it build its resources again (" + std::to_string(Builds() - before) + " builds)"); } @@ -780,15 +800,41 @@ void RingRefusals(Scene& scene) { { const Outcomes outcomes; scene.Fetch(MovedVerticesOffset); + const auto copies = AgcDriver::Graphics::DrawInputCopies(); const auto color = scene.DrawnColor(); Require(color == 170, "address draw space reuse: the draw after its read-only vertex buffer moved read " + std::to_string(color) + " instead of 170"); + if (HeapStages) { + const auto taken = AgcDriver::Graphics::DrawInputCopies() - copies; + Require(taken == 0, "address draw space reuse: heap stages read " + std::to_string(taken) + " copies of a vertex buffer that moved inside the space instead of the buffer in place"); + } Require(outcomes[AddressDrawReuse::Reused] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose read-only vertex buffer moved inside the space counted " + outcomes.Text() + ", expected one reuse with the buffer bound anew"); } + if (HeapStages) { + { + const Outcomes outcomes; + scene.Fetch(ShiftedVerticesOffset); + const auto copies = AgcDriver::Graphics::DrawInputCopies(); + const auto color = scene.DrawnColor(); + Require(color == 170, "address draw space reuse: the draw after its vertex buffer moved off its view's alignment read " + std::to_string(color) + " instead of 170"); + Require(outcomes[AddressDrawReuse::Built] == 1 && outcomes.Total() == 1, "address draw space reuse: a heap-stage draw whose vertex buffer moved off its view's alignment counted " + outcomes.Text() + ", expected one build for the new alignment"); + Require(AgcDriver::Graphics::DrawInputCopies() == copies, "address draw space reuse: heap stages read a copy of a vertex buffer that moved off its view's alignment"); + } + const Outcomes outcomes; + const auto copies = AgcDriver::Graphics::DrawInputCopies(); + for (const auto offset : {ShiftedAgainVerticesOffset, MovedVerticesOffset, ShiftedVerticesOffset}) { + scene.Fetch(offset); + const auto color = scene.DrawnColor(); + Require(color == 170, "address draw space reuse: a draw whose vertex buffer moved between two view alignments read " + std::to_string(color) + " instead of 170"); + } + Require(outcomes[AddressDrawReuse::Reused] == 3 && outcomes.Total() == 3, "address draw space reuse: heap-stage draws whose vertex buffer moved between two view alignments counted " + outcomes.Text() + ", expected each alignment's build reused with the buffer read in place"); + Require(AgcDriver::Graphics::DrawInputCopies() == copies, "address draw space reuse: heap stages read a copy of a vertex buffer that moved between two view alignments"); + } { std::memcpy(scene.spare.Data(), Triangle.data(), sizeof(Triangle)); constexpr std::size_t Filled = 64; const std::array pattern{}; const Outcomes outcomes; + const auto behindBefore = AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites(); scene.Fetch(scene.spare, 0); { std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); @@ -798,7 +844,12 @@ void RingRefusals(Scene& scene) { } const auto color = scene.Color(); Require(color == 170, "address draw space reuse: the draw whose moved vertex buffer a pending fill overlaps read " + std::to_string(color) + " instead of 170"); - Require(outcomes[inPlace ? AddressDrawReuse::Reused : AddressDrawReuse::MovedBuffer] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose moved read-only vertex buffer a pending GPU write overlaps counted " + outcomes.Text() + (inPlace ? ", expected one reuse with the buffer read in place" : ", expected one refusal for a moved GuestBuffers element")); + if (HeapStages) { + Require(outcomes[AddressDrawReuse::Reused] == 1 && outcomes.Total() == 1, "address draw space reuse: a heap-stage draw whose moved read-only vertex buffer a pending GPU write overlaps counted " + outcomes.Text() + ", expected one reuse reading the buffer in place"); + Require(AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites() > behindBefore, "address draw space reuse: a heap-stage draw whose moved vertex buffer a pending GPU write overlaps was not read in place behind the write"); + } else { + Require(outcomes[inPlace ? AddressDrawReuse::Reused : AddressDrawReuse::MovedBuffer] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose moved read-only vertex buffer a pending GPU write overlaps counted " + outcomes.Text() + ", expected one refusal for a moved GuestBuffers element"); + } } { constexpr std::size_t Offset = 4096; @@ -818,7 +869,8 @@ void RingRefusals(Scene& scene) { } const auto color = scene.Color(); Require(color == 110, "address draw space reuse: the draw whose moved vertex buffer a pending fill completes read " + std::to_string(color) + " instead of 110: it did not see the vertex the GPU wrote"); - Require(outcomes[inPlace ? AddressDrawReuse::Reused : AddressDrawReuse::MovedBuffer] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose moved vertex buffer a pending fill completes counted " + outcomes.Text() + (inPlace ? ", expected one reuse with the buffer read in place" : ", expected one refusal for a moved GuestBuffers element")); + const bool reused = HeapStages || inPlace; + Require(outcomes[reused ? AddressDrawReuse::Reused : AddressDrawReuse::MovedBuffer] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose moved vertex buffer a pending fill completes counted " + outcomes.Text() + (reused ? ", expected one reuse with the buffer read in place" : ", expected one refusal for a moved GuestBuffers element")); } scene.Fetch(0); scene.cachedVertex = false; @@ -1091,20 +1143,27 @@ constexpr std::array TransitionCases{{ int main(int argc, char** argv) { try { - const std::string mode = argc > 1 ? argv[1] : ""; - const std::string only = mode == "--case" && argc > 2 ? argv[2] : ""; - Require(mode.empty() || mode == "--off" || mode == "--transitions" || mode == "--verify" || mode == "--held" || !only.empty(), "usage: [--off | --transitions | --verify | --held | --case ]"); + HeapStages = argc > 1 && std::string_view(argv[1]) == "--heap-stages"; + const int first = HeapStages ? 2 : 1; + const std::string mode = argc > first ? argv[first] : HeapStages ? "--heap-stages" : ""; + const std::string only = mode == "--case" && argc > first + 1 ? argv[first + 1] : ""; + Require(mode.empty() || mode == "--off" || mode == "--transitions" || mode == "--verify" || mode == "--held" || mode == "--heap-stages" || !only.empty(), "usage: [--off | --transitions | --verify | --held | --heap-stages [--case ] | --case ]"); Require(mode != "--verify" || std::getenv("APS5_VERIFY_ADDRESS_DRAW_REUSE") != nullptr, "address draw space reuse: --verify needs APS5_VERIFY_ADDRESS_DRAW_REUSE=1"); Require(mode != "--held" || std::getenv("APS5_RELEASE_ON_UNLOCK") != nullptr, "address draw space reuse: --held needs APS5_RELEASE_ON_UNLOCK=1"); LimitPinWait(); const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; + if (HeapStages && !AgcDriver::Graphics::DescriptorHeapEnabled()) { + std::puts("skipped, the device has no VK_EXT_descriptor_heap, which --heap-stages needs"); + return VulkanTestSkipped; + } { Scene scene(*device); if (!Imported(scene)) { std::puts("skipped, host imports are unavailable: the cached address space needs one"); return VulkanTestSkipped; } + if (HeapStages) Require(std::all_of(scene.shaders.begin(), scene.shaders.end(), [](const AgcDriver::Graphics::CompiledShader& shader) { return AgcDriver::Graphics::HeapShader(shader); }), "address draw space reuse: --heap-stages built a stage that is not a heap stage"); const Outcomes outcomes; const auto verifiedBefore = AgcDriver::Graphics::AddressDrawReuseVerifications(); if (mode == "--off") { @@ -1114,6 +1173,7 @@ int main(int argc, char** argv) { bool ran = false; for (const auto& entry : cases) { if (!only.empty() && only != entry.name) continue; + if (HeapStages && std::string_view(entry.name) == "fault-per-use") continue; entry.run(scene); ran = true; } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressPasses.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressPasses.cpp index bc4e3ffab8e9..5c9abaf2908f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressPasses.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressPasses.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -213,9 +214,12 @@ std::string Counts(const AgcDriver::Graphics::DrawPassCounts& before, const AgcD void ReadersShareAPass(const GuestBlock& vertices, const GuestBlock& data, const GuestBlock& target) { const auto before = AddressDraws(); + const auto heapBinds = AgcDriver::Graphics::DescriptorHeapBinds(); Submit(vertices, target, {{PixelRead.data(), data.At(0)}, {PixelRead.data(), data.At(0)}}); const auto after = AddressDraws(); - std::printf("two draws reading through the table: %s\n", Counts(before, after).c_str()); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds() - heapBinds; + std::printf("two draws reading through the table: %s, %llu heap binds\n", Counts(before, after).c_str(), static_cast(binds)); + Expect(!AgcDriver::Graphics::DescriptorHeapEnabled() || binds == 1, "two heap draws in one command buffer bound the descriptor heaps " + std::to_string(binds) + " times"); Expect(after.draws - before.draws == 2 && after.passesContinued - before.passesContinued == 1, "a draw reading through the table after another did not continue its pass: " + Counts(before, after)); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/BindlessImages.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/BindlessImages.cpp index 3268ff39d811..cfeefcbba3ba 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/BindlessImages.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/BindlessImages.cpp @@ -1,9 +1,11 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" #include "ImageTableAbi.hpp" #include "VulkanTestDevice.hpp" #include #include +#include #include #include @@ -56,8 +58,12 @@ void Run(AgcDriver::VulkanDevice& device) { const auto output = Buffer(data.output.data(), 0u, 256u); std::copy(output.begin(), output.end(), data.srt.begin() + 12u); const ShaderComputeStageInfo compute{{threads, 1u, 1u}, 0u, {false, false, false}, false, 1u}; - RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, regions}, device.Target(), {0u, 0u, 0u, 128u}}; + const bool heap = AgcDriver::Graphics::DescriptorHeapEnabled(); + auto target = device.Target(); + target.gpuResolvedImages = heap; + RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, regions}, target, {0u, 0u, 0u, 128u}}; const auto shader = Recompile(request); + Require(shader.gpuResolvedImages == heap, heap ? "the compute heap did not take the table stage" : "a table stage took the heap without it"); if (artifact.variantId == 0u) artifact = shader; else Require(shader.cacheHit && shader.variantId == artifact.variantId, "bindless table changed the compiled artifact"); if (iteration == 1u) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/BufferAtomics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/BufferAtomics.cpp index 550cbd7f0bea..88c1230b46b7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/BufferAtomics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/BufferAtomics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" @@ -77,11 +78,12 @@ void Run(AgcDriver::VulkanDevice& device) { ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(32), {0, 0, 0, 128} }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == AgcDriver::Graphics::DescriptorHeapEnabled(), "the compute heap did not take the buffer stage"); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/BufferFormat.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/BufferFormat.cpp index 7394269e39b1..3067384aad32 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/BufferFormat.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/BufferFormat.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" @@ -155,11 +156,12 @@ void Run(AgcDriver::VulkanDevice& device) { ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(32), {0, 0, 0, 128} }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == AgcDriver::Graphics::DescriptorHeapEnabled(), "the compute heap did not take the buffer stage"); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/BufferLoadStore.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/BufferLoadStore.cpp index da69c6d9d0b6..0932f742a89f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/BufferLoadStore.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/BufferLoadStore.cpp @@ -304,7 +304,7 @@ void CheckRuntimeDescriptors(AgcDriver::VulkanDevice& device, std::uint32_t wave const auto output = BufferDescriptor(Output.data(), threads * 4u); std::copy(output.begin(), output.end(), userData.begin() + 4); const ShaderRecompiler::ShaderComputeStageInfo compute{{threads, 1u, 1u}, 0u, {false, false, false}, false, 1u}; - ShaderRecompiler::RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {waveSize, 0u, userData, compute, std::nullopt, std::nullopt, {}}, device.Target(), {0u, 0u, 0u, 128u}}; + ShaderRecompiler::RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {waveSize, 0u, userData, compute, std::nullopt, std::nullopt, {}}, device.ComputeTarget(waveSize), {0u, 0u, 0u, 128u}}; ShaderRecompiler::RecompileResult first; for (const auto& value : cases) { auto input = BufferDescriptor(Input.data(), value.records); @@ -345,9 +345,9 @@ int main() { try { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - Run(*device, Wave32Code, 32, device->Target()); + Run(*device, Wave32Code, 32, device->ComputeTarget(32)); Check(Expected32, Names, "wave32"); - Run(*device, Wave64Code, 64, device->Target()); + Run(*device, Wave64Code, 64, device->ComputeTarget(64)); Check(Expected64, Names, "wave64"); Run(*device, Wave64Code, 64, device->ComputeTarget(32)); Check(Expected64, Names, "wave64 split"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp index 41c41b320f21..3ecd51769880 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp @@ -236,7 +236,7 @@ void RecordedMasks(AgcDriver::VulkanDevice& device, const Shaders& compiled, VkC const auto context = device.graphicsContext(); const auto shaders = Stages(device, compiled); const std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); - Recorder recorder(context); + Recorder recorder(context, device.TimelineSemaphores()); recorder.Activate(); const MaskTrace trace(context); const auto continued = [] { return DrawPassTotals()[0].passesContinued; }; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp index 7425d8269b13..4aa730492930 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp @@ -69,7 +69,7 @@ PFN_vkVoidFunction VKAPI_CALL Resolve(VkDevice device, const char* name) { return originalProc(device, name); } -void Scenario(Graphics::Context context, bool fail) { +void Scenario(Graphics::Context context, bool fail, bool timeline) { constexpr std::size_t blockBytes = 65536; constexpr auto usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; constexpr auto properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; @@ -94,7 +94,7 @@ void Scenario(Graphics::Context context, bool fail) { bool caught = false; bool earlyReuse = false; { - Graphics::Recorder recorder(context); + Graphics::Recorder recorder(context, timeline); recorder.Activate(); try { Graphics::GuestBufferMemory memory(context); @@ -151,8 +151,8 @@ int main() { originalFree = context.Function("vkFreeMemory"); originalCopy = context.Function("vkCmdCopyBuffer"); originalBarrier = context.Function("vkCmdPipelineBarrier"); - Scenario(context, false); - Scenario(context, true); + Scenario(context, false, device->TimelineSemaphores()); + Scenario(context, true, device->TimelineSemaphores()); return 0; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp index 07073f1b706e..102d215b0df0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp @@ -365,14 +365,14 @@ void RecreatedRecorderReadsHtile(AgcDriver::VulkanDevice& device, bool clearSurf auto& htile = NewBlock(); const DepthTarget target{NewBlock().Address(), 0, {64, 32}, VK_FORMAT_D32_SFLOAT, 1.0f, 0, htile.Address(), false}; std::optional recorder; - recorder.emplace(context); + recorder.emplace(context, device.TimelineSemaphores()); const auto* address = &*recorder; RecordHtileWords(context, *recorder, htile, 0xf0u); const auto note = recorder->NewestWriteNote(htile.Address(), HtileBytes); NoteHtileMaskOnGpu(context, {htile.Address(), HtileBytes, 0x3f0u, 0u}); recorder.reset(); if (clearSurfaces) ClearDepthSurfaces(context.device); - recorder.emplace(context); + recorder.emplace(context, device.TimelineSemaphores()); Require(&*recorder == address, "the replacement recorder did not reuse the original storage"); RecordHtileWords(context, *recorder, htile, 0xfu); Require(recorder->NewestWriteNote(htile.Address(), HtileBytes) == note, "the replacement recorder did not reuse the original note"); @@ -411,8 +411,8 @@ void LiveRecorderMaskIsolation(AgcDriver::VulkanDevice& device) { auto* previous = Recorder::Active(); { auto& htile = NewBlock(); - Recorder first(context); - Recorder second(context); + Recorder first(context, device.TimelineSemaphores()); + Recorder second(context, device.TimelineSemaphores()); RecordHtileWords(context, first, htile, 0xf0u); NoteHtileMaskOnGpu(context, {htile.Address(), HtileBytes, 0x3f0u, 0u}); RecordHtileWords(context, second, htile, 0xfu); @@ -437,8 +437,8 @@ void MaskCleanupIsolation(AgcDriver::VulkanDevice& device, AgcDriver::VulkanDevi auto& firstHtile = NewBlock(); auto& secondHtile = NewBlock(); std::optional first; - first.emplace(context); - Recorder second(context); + first.emplace(context, device.TimelineSemaphores()); + Recorder second(context, device.TimelineSemaphores()); RecordHtileWords(context, *first, firstHtile, 0xf0u); NoteHtileMaskOnGpu(context, {firstHtile.Address(), HtileBytes, 0x3f0u, 0u}); RecordHtileWords(context, second, secondHtile, 0xf0u); @@ -450,9 +450,9 @@ void MaskCleanupIsolation(AgcDriver::VulkanDevice& device, AgcDriver::VulkanDevi auto& firstHtile = NewBlock(); auto& secondHtile = NewBlock(); auto& otherHtile = NewBlock(); - Recorder first(context); - Recorder second(context); - Recorder other(otherContext); + Recorder first(context, device.TimelineSemaphores()); + Recorder second(context, device.TimelineSemaphores()); + Recorder other(otherContext, otherDevice.TimelineSemaphores()); RecordHtileWords(context, first, firstHtile, 0xf0u); NoteHtileMaskOnGpu(context, {firstHtile.Address(), HtileBytes, 0x3f0u, 0u}); RecordHtileWords(context, second, secondHtile, 0xf0u); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlanePartialStore.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlanePartialStore.cpp index 4002536e95f9..060335f180be 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlanePartialStore.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlanePartialStore.cpp @@ -269,6 +269,56 @@ int main(int argc, char** argv) { return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--proof-under-other-pending") { + auto* arrayBlocks = static_cast(AllocateBlocks(3u * PlaneBytes, true)); + if (!AgcDriver::GuestMemory::WriteWatched() || !AgcDriver::GuestMemory::Watched(reinterpret_cast(arrayBlocks), 3u * PlaneBytes)) return VulkanTestSkipped; + AgcDriver::Graphics::GuestTextureResource array{}; + array.baseAddress = reinterpret_cast(arrayBlocks); + array.width = PlaneWidth; + array.height = PlaneHeight; + array.depthOrLastArray = 2; + array.mipCount = 1; + array.tileMode = AgcDriver::Graphics::TextureTileMode::kR64KBX; + array.dimension = AgcDriver::Graphics::TextureDimension::k2DArray; + array.format = 22; + array.dstSelX = 4; + array.dstSelY = 5; + array.dstSelZ = 6; + array.dstSelW = 7; + auto last = array; + last.baseAddress = array.baseAddress + 2u * PlaneBytes; + last.depthOrLastArray = 0; + last.dimension = AgcDriver::Graphics::TextureDimension::k2D; + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(*device); + const auto lookup = [&](const AgcDriver::Graphics::GuestTextureResource& resource, std::uint32_t count) { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + return AgcDriver::Graphics::CachedStorageLayers(context, resource, 0, count); + }; + for (std::size_t layer = 0; layer < 3u; ++layer) Fill(reinterpret_cast(arrayBlocks + layer * PlaneBytes), 1.0f); + const auto whole = lookup(array, 3); + const auto single = lookup(last, 1); + Require(whole != nullptr && single != nullptr && whole != single, "the array and the image over its last layer did not get two cached images"); + device->WaitIdle(); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + whole->MarkSliceDirty(0, 1); + } + static_cast(lookup(last, 1)); + auto proved = AgcDriver::Graphics::StorageTexture::RefreshesProved(); + Require(lookup(last, 1) == single, "a lookup of the image over the last layer replaced its cached image"); + Require(AgcDriver::Graphics::StorageTexture::RefreshesProved() != proved, "an array pending only on its first layer kept the image over its last layer from proving its refresh"); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + whole->MarkSliceDirty(2, 1); + } + proved = AgcDriver::Graphics::StorageTexture::RefreshesProved(); + static_cast(lookup(last, 1)); + Require(AgcDriver::Graphics::StorageTexture::RefreshesProved() == proved, "an image kept its refresh proof after the array under it gained a pending write over its bytes"); + device->WaitIdle(); + std::puts("depth plane partial store tests passed (refresh proof under another pending image)"); + return 0; + } + Fill(plane, 1.0f); Require(draw(depth, writeHalf) == PlaneTexels, "the draw writing depth 0.5 did not cover the plane"); Require(AgcDriver::Graphics::DepthPlanesStale(), "the draw writing depth left the plane unregistered"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageDispatch.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageDispatch.cpp index 54abd98d1fb7..b2f3520b954e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageDispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageDispatch.cpp @@ -141,7 +141,7 @@ ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, std:: ShaderRecompiler::RecompileRequest request{ {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageReuse.cpp index dbd774f671a8..1f44d1771099 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageReuse.cpp @@ -45,7 +45,7 @@ void Read(AgcDriver::VulkanDevice& device, std::uint32_t format, std::uint32_t w const ShaderRecompiler::ShaderComputeStageInfo compute{{32, 1, 1}, 0u, {false, false, false}, false, 1}; ShaderRecompiler::RecompileRequest request{ {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, - {32, 0, data, compute, std::nullopt, std::nullopt, memory}, device.Target(), {0, 0, 0, 128}, + {32, 0, data, compute, std::nullopt, std::nullopt, memory}, device.ComputeTarget(64), {0, 0, 0, 128}, }; request.useCache = false; const auto shader = ShaderRecompiler::Recompile(request); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DeviceFunctionCache.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DeviceFunctionCache.cpp new file mode 100644 index 000000000000..4df226b5bf5c --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DeviceFunctionCache.cpp @@ -0,0 +1,51 @@ +#include "VulkanTestDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Context.hpp" + +#include +#include + +namespace { + +PFN_vkGetDeviceProcAddr realProc = nullptr; +int countedCalls = 0; + +PFN_vkVoidFunction VKAPI_CALL countingProc(VkDevice device, const char* name) { + ++countedCalls; + return realProc(device, name); +} + +void require(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +constexpr char DispatchName[] = "vkCmdDispatch"; + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + auto context = device->graphicsContext(); + require(context.functions != nullptr && context.functionCache != nullptr, "the device context carries its function cache"); + const auto first = context.Function(DispatchName); + const auto lookups = AgcDriver::Graphics::DeviceProcLookups(); + require(context.Function(DispatchName) == first && AgcDriver::Graphics::DeviceProcLookups() == lookups, + "a repeated lookup is served from the device's cache"); + realProc = context.deviceProc; + context.deviceProc = countingProc; + require(context.Function(DispatchName) == first && countedCalls == 1, "another resolver is not served from the cache"); + context.deviceProc = realProc; + require(context.Function(DispatchName) == first && AgcDriver::Graphics::DeviceProcLookups() == lookups + 1u, + "the device's resolver is still served from the cache"); + context.deviceProc = countingProc; + context.functions = nullptr; + static_cast(context.Function(DispatchName)); + require(countedCalls == 2, "a context without the device's table looks up every time"); + std::printf("device function cache tests passed\n"); + return 0; + } catch (const std::exception& error) { + std::printf("device function cache tests failed: %s\n", error.what()); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp index a25294cadc31..6a86c07117d9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp @@ -134,6 +134,10 @@ std::vector DrawFrom(std::initializer_list sources, return commands; } +std::uint64_t EntryInserts(const AgcDriver::DriverDetail::DrawEntryCounters& counters) { + return counters.inserts - (std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr ? counters.verifyHits : 0u); +} + void MovedDataHitsTheCache(bool libraries) { Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); Registered(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); @@ -151,7 +155,7 @@ void MovedDataHitsTheCache(bool libraries) { for (std::size_t i = 0; i < 4; ++i) counters = draw({same[i].data()}); Require(counters.lookups == 4 && counters.hits == 0 && counters.inserts == 2, mode + ": the draws that teach the moved pointer and its contents made " + std::to_string(counters.hits) + " hits and " + std::to_string(counters.inserts) + " inserts, expected 0 and 2"); for (std::size_t i = 4; i < same.size(); ++i) counters = draw({same[i].data()}); - Require(counters.lookups == 8 && counters.hits == 4 && counters.inserts == 2, mode + ": draws whose data moved again did not reuse the cached draw (" + std::to_string(counters.hits) + " hits in " + std::to_string(counters.lookups) + " lookups)"); + Require(counters.lookups == 8 && counters.hits == 4 && EntryInserts(counters) == 2 && counters.verifyMismatches == 0, mode + ": draws whose data moved again did not reuse the cached draw (" + std::to_string(counters.hits) + " hits in " + std::to_string(counters.lookups) + " lookups)"); const auto other = draw({Other.data()}); Require(other.lookups == 9 && other.hits == 4, mode + ": a draw whose moved data holds another value reused the cached draw"); const auto again = draw({same[0].data()}); @@ -295,6 +299,10 @@ void RelocatedDrawsReuseTheirRecipe(bool libraries) { const auto recipeHits = AgcDriver::VulkanDevice::DrawRecipeHits() - recipesBefore; const auto hits = counters.hits - start.hits; Require(hits == moved.size() - 4, mode + ": draws whose data moved again made " + std::to_string(hits) + " draw-cache hits, expected " + std::to_string(moved.size() - 4)); + if (std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr) { + Require(recipeHits == 0, mode + ": " + std::to_string(recipeHits) + " draws served by a relocated entry were recorded from a recipe while entry verification records every hit afresh"); + return; + } Require(recipeHits == hits, mode + ": " + std::to_string(recipeHits) + " of " + std::to_string(hits) + " draws served by a relocated entry were recorded from the cached draw's recipe, expected all"); } @@ -321,7 +329,7 @@ void UnrelocatedAliasesStayOut(bool libraries) { for (const auto& entry : pair) draw(entry.data()); counters = draw(repeated.data()); } - const auto inserts = counters.inserts - start.inserts; + const auto inserts = EntryInserts(counters) - EntryInserts(start); Require(inserts <= AgcDriver::DriverDetail::DrawRelocationTrial::ProbationAdmissions, mode + ": draws whose alias repeats but never relocates were cached (" + std::to_string(inserts) + " inserts for " + std::to_string(twice.size()) + " aliases)"); Require(counters.hits - start.hits == twice.size(), mode + ": the exact key of a repeated draw lost its hits next to draws whose alias never relocates (" + std::to_string(counters.hits - start.hits) + " hits in " + std::to_string(twice.size()) + " draws)"); } @@ -384,7 +392,8 @@ void MovedForwardedWordReachesStageDataHit(bool libraries) { AgcDriver::DriverDetail::Driver::SetCaptureCheckHook(nullptr); Require(!RestartArmed.load(), mode + ": the capture check did not run for the relocated draw"); const bool pipelined = DrawFinisher::Enabled() && DrawPipeline::Depth() != 0; - Require(!pipelined || RestartChecked.load(), mode + ": the pipelined relocated draw was checked on the queue worker, not the draw finisher, so its restart patch and skip count were not exercised"); + const bool dataHitsVerified = std::getenv("APS5_VERIFY_DRAW_DATA_HITS") != nullptr; + Require(!pipelined || dataHitsVerified || RestartChecked.load(), mode + ": the pipelined relocated draw was checked on the queue worker, not the draw finisher, so its restart patch and skip count were not exercised"); if (RestartChecked.load()) { const auto skipped = restartedCounters.restartPatchSkipped - counters.restartPatchSkipped; const auto expected = std::getenv("APS5_VERIFY_DRAW_RECIPE") != nullptr ? 1u : 0u; @@ -402,7 +411,8 @@ void MovedForwardedWordReachesStageDataHit(bool libraries) { SecondOffsetTable[2] = data; const auto moved2 = draw(&SecondOffsetTable[2]); std::printf("%s: a draw through a second moved table at the same alignment: %llu lookups, %llu hits, %llu stage data hits, %llu inserts\n", mode.c_str(), static_cast(moved2.lookups - again.lookups), static_cast(moved2.hits - again.hits), static_cast(moved2.stageDataHits - again.stageDataHits), static_cast(moved2.inserts - again.inserts)); - Require(moved2.hits == again.hits + 1 && moved2.inserts == again.inserts, mode + ": a draw through a second moved table was not a relocated hit after its alias's entry was recaptured (" + std::to_string(moved2.hits - again.hits) + " hits, " + std::to_string(moved2.inserts - again.inserts) + " inserts)"); + const auto capturedAgain = std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr || std::getenv("APS5_VERIFY_DRAW_DATA_HITS") != nullptr; + Require(moved2.hits == again.hits + 1 && (capturedAgain ? moved2.inserts == again.inserts + 1 : moved2.inserts == again.inserts), mode + ": a draw through a second moved table was not a relocated hit after its alias's entry was recaptured (" + std::to_string(moved2.hits - again.hits) + " hits, " + std::to_string(moved2.inserts - again.inserts) + " inserts)"); const auto second = pixels({64, 255, 255, 64}); Require(second.empty(), mode + ": a draw through a second moved table drew wrong pixels: " + second); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheReuse.cpp index 345cbb6cda84..9d3048f878eb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheReuse.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" #include "VulkanTestDevice.hpp" @@ -326,7 +327,8 @@ void RecordsKeepThePacketsFragmentWord(bool libraries) { void RecordWordsReachTheShader(bool libraries) { const auto mode = std::string(libraries ? "with" : "without") + " graphics pipeline libraries"; const bool cached = std::getenv("APS5_DRAW_CACHE_INDIRECT") != nullptr; - const bool forwarded = std::getenv("APS5_DRAW_CACHE_PUSH_WORD") != nullptr; + const bool pushWord = std::getenv("APS5_DRAW_CACHE_PUSH_WORD") != nullptr; + const bool forwarded = pushWord && !AgcDriver::Graphics::GpuHeapEnabled(); const bool verify = forwarded && std::getenv("APS5_VERIFY_DRAW_PUSH_WORD") != nullptr; Registered(OffsetTriangleVertexHeader, OffsetTriangleVertexCode.data(), sizeof(OffsetTriangleVertexCode), 2); ColorMemory.fill(std::byte{0}); @@ -356,6 +358,7 @@ void RecordWordsReachTheShader(bool libraries) { const auto refused = after.recordWordsRefused - before.recordWordsRefused; const auto verified = after.recordWordsVerified - before.recordWordsVerified; if (forwarded) Require(wordsForwarded == 4 && stagesRecompiled == 0 && refused == 0, mode + ": with APS5_DRAW_CACHE_PUSH_WORD, four records forwarded " + std::to_string(wordsForwarded) + " patched words as push data, re-materialized " + std::to_string(stagesRecompiled) + " stages and refused " + std::to_string(refused) + " words, expected 4, 0 and 0"); + else if (pushWord) Require(wordsForwarded == 0 && stagesRecompiled == 4 && refused == 4, mode + ": with APS5_DRAW_CACHE_PUSH_WORD in GPU heap mode, four records forwarded " + std::to_string(wordsForwarded) + " patched words, re-materialized " + std::to_string(stagesRecompiled) + " stages and refused " + std::to_string(refused) + " words, expected 0, 4 and 4"); else Require(wordsForwarded == 0 && stagesRecompiled == 4, mode + ": without APS5_DRAW_CACHE_PUSH_WORD, four records forwarded " + std::to_string(wordsForwarded) + " words and re-materialized " + std::to_string(stagesRecompiled) + " stages, expected 0 and 4"); Require(verified == (verify ? 4u : 0u), mode + ": " + std::to_string(verified) + " forwarded words were verified against a full build, expected " + std::to_string(verify ? 4 : 0)); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp index c42969cfe818..7688aa86378f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp @@ -398,7 +398,7 @@ class Fixture { return state; } - void Draw(const ShaderRecompiler::RecompileResult& vertex, const AgcDriver::Pm4::DrawParameters& draw, bool restartStrip = false, bool compactRestart = false, bool quadList = false) { + void Draw(const ShaderRecompiler::RecompileResult& vertex, const AgcDriver::Pm4::DrawParameters& draw, bool restartStrip = false, bool compactRestart = false, bool quadList = false, const ShaderRecompiler::HeapStageWords* heap = nullptr) { const auto vertexPush = static_cast(vertex.pushConstants.size()); ShaderRecompiler::ShaderPixelStageInfo pixelInfo{}; pixelInfo.wave32 = true; @@ -407,7 +407,7 @@ class Fixture { ShaderRecompiler::RecompileRequest pixelRequest{{ShaderStage::Fragment, reinterpret_cast(PixelCode.data()), PixelCode, 0, {}}, {32u, 0u, {}, std::nullopt, pixelInfo, std::nullopt, {}}, device->Target(), PixelPushLayout(vertexPush, device->Target())}; pixelRequest.useCache = false; const auto pixel = ShaderRecompiler::Recompile(pixelRequest); - const std::array shaders{{{ShaderStage::Vertex, &vertex, 0u}, {ShaderStage::Fragment, &pixel, PixelPushOffset(vertexPush, device->Target())}}}; + const std::array shaders{{{ShaderStage::Vertex, &vertex, 0u, nullptr, heap}, {ShaderStage::Fragment, &pixel, PixelPushOffset(vertexPush, device->Target())}}}; Output.fill(Unwritten); if (compactRestart) { auto context = device->graphicsContext(); @@ -479,8 +479,8 @@ std::string PathName(const std::optional& path) { return path ? "the CPU path (" + std::string(AgcDriver::Graphics::IndirectDrawPathName(*path)) + ")" : std::string("the GPU"); } -std::string Classified(Fixture& fixture, const std::string& what, const ShaderRecompiler::RecompileResult& vertex, const std::vector& userData, AgcDriver::Pm4::DrawParameters& draw, std::optional expectedPath, Rule expectedRule, bool rectList = false) { - const auto path = AgcDriver::DriverDetail::Driver::ClassifyIndirectDraw(vertex, fixture.State(rectList), Program(userData), fixture.device, draw, false); +std::string Classified(Fixture& fixture, const std::string& what, const ShaderRecompiler::RecompileResult& vertex, const std::vector& userData, AgcDriver::Pm4::DrawParameters& draw, std::optional expectedPath, Rule expectedRule, bool rectList = false, const ShaderRecompiler::HeapStageWords* heap = nullptr) { + const auto path = AgcDriver::DriverDetail::Driver::ClassifyIndirectDraw(vertex, fixture.State(rectList), Program(userData), fixture.device, draw, false, heap); const auto& indirect = *draw.indirect; const bool rules = expectedPath || (indirect.vertexRule == expectedRule && indirect.instanceRule == expectedRule); std::cout << what << ": classified to " << PathName(path) << '\n'; @@ -540,6 +540,28 @@ std::string RuntimeFetch(Fixture& fixture, std::uint32_t index, bool compactRest return std::equal(expected.begin(), expected.end(), Output.begin()) ? "" : "runtime-fetched VertexIndex was changed\n"; } +std::string HeapAttributes(Fixture& fixture) { + const auto userData = fixture.UserData(0, 0); + const auto perDraw = fixture.Vertex(VertexCode, userData); + const auto records = BufferTable[2]; + BufferTable[2] = 1u; + const auto shared = fixture.Vertex(VertexCode, userData); + BufferTable[2] = records; + Require(!perDraw.vertexAttributes.empty() && shared.vertexAttributes.size() == perDraw.vertexAttributes.size(), "the vertex buffers did not become fixed vertex attributes"); + ShaderRecompiler::HeapStageWords words; + words.vertexAttributes = perDraw.vertexAttributes; + const auto index = static_cast(VertexSlots.size() - 1u); + const std::array fetched{index}; + fixture.Place(0, fetched, 0); + alignas(256) static std::array indices{}; + indices = {0xffffffffu, index, index, index, 0xffffffffu}; + const AgcDriver::Pm4::DrawParameters draw{reinterpret_cast(indices.data()), 5, 4, 1, 0, true, 0, 0}; + fixture.Draw(shared, draw, false, true, false, &words); + std::cout << "heap vertex attributes, index " << index << ", compact restart: readback " << Output[0] << ' ' << Output[1] << ' ' << Output[2] << ' ' << Output[3] << '\n'; + const std::array expected{index, 0, index, 0}; + return std::equal(expected.begin(), expected.end(), Output.begin()) ? "" : "a compacted index inside the draw's own vertex buffer was clamped by the shared program's buffer size\n"; +} + std::string Run(Fixture& fixture) { std::string failures = Analysis(fixture); const std::array autoIndices{0, 1, 2}; @@ -709,6 +731,13 @@ std::string Run(Fixture& fixture) { AgcDriver::Pm4::DrawParameters draw{indexAddress, static_cast(Indices.size()), 2, 0, 0, true, 0, 0}; draw.indirect = indexedIndirect; failures += Classified(fixture, what, vertex, staleUserData, draw, std::nullopt, Rule::InPlace); + if (code == &PostAddCode) { + ShaderRecompiler::HeapStageWords words; + words.vertexAttributes = vertex.vertexAttributes; + for (auto& attribute : words.vertexAttributes) attribute.resource.fields[2] = 0x2000000u; + auto heapDraw = draw; + failures += Classified(fixture, what + ", with a 128 MiB vertex buffer in its heap words", vertex, staleUserData, heapDraw, Path::VertexRange, Rule::InPlace, false, &words); + } fixture.Place(indexedRecord[3], bufferIndices, indexedRecord[4]); fixture.Draw(vertex, draw); failures += fixture.Check(what + ", drawn in place on the GPU", bufferIndices, indexedRecord[3], indexedRecord[4], false); @@ -750,6 +779,7 @@ int main(int argc, char** argv) { Fixture fixture(device); std::string failures; if (argc == 1) failures = Run(fixture); + else if (argc == 2 && std::string(argv[1]) == "heap-attributes") failures = HeapAttributes(fixture); else { Require(argc == 3 || argc == 4, "expected runtime-fetch INDEX [compact-restart]"); Require(std::string(argv[1]) == "runtime-fetch", "unknown case"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawPushedUserValues.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawPushedUserValues.cpp new file mode 100644 index 000000000000..49e0f8c8090f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawPushedUserValues.cpp @@ -0,0 +1,223 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::byte Kept{0x40}; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array UserPixelCode{0x7e00020cu, 0x7e02020du, 0x7e04020eu, 0x7e06020fu, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; + +alignas(256) std::array ColorMemory{}; + +std::span MergedTarget(std::size_t index) { + constexpr std::size_t Bytes = 65536; + static std::array data{}; + if (data.at(index) == nullptr) data[index] = [] { + std::byte* block = nullptr; +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); + GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); +#else + void* raw = mmap(nullptr, 2u * Bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the merged color target"); + const auto begin = reinterpret_cast(raw); + block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); +#endif + GuestAllocations::Mutation mutation; + mutation.Add(block, Bytes, true, true, true); + return block; + }(); + return {data[index], ColorMemory.size()}; +} +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(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); +} + +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); +} + +std::vector Frame(std::span alphas) { + const auto color = reinterpret_cast(MergedTarget(0).data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {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}, + {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}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x292, 2}, + }; + + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + const auto vertex = reinterpret_cast(VertexCode.data()); + Append(commands, 0x76, {0xc8, static_cast(vertex >> 8u)}); + Append(commands, 0x76, {0xc9, static_cast(vertex >> 40u)}); + Append(commands, 0x76, {0x8b, 1u << 1u}); + Append(commands, 0x76, {0x8c, 0}); + const auto pixel = reinterpret_cast(UserPixelCode.data()); + for (const auto alpha : alphas) { + const std::array words{std::bit_cast(0.25f), std::bit_cast(0.5f), std::bit_cast(0.75f), std::bit_cast(alpha)}; + Append(commands, 0x76, {0x008, static_cast(pixel >> 8u)}); + Append(commands, 0x76, {0x009, static_cast(pixel >> 40u)}); + Append(commands, 0x76, {0x00b, 16u << 1u}); + for (std::uint32_t index = 0; index < 12u; ++index) Append(commands, 0x76, {0x00cu + index, 0u}); + for (std::uint32_t index = 0; index < 4u; ++index) Append(commands, 0x76, {0x018u + index, words[index]}); + Append(commands, 0x2d, {3, 2}); + } + return commands; +} + +unsigned Submit(std::span alphas) { + std::ranges::fill(MergedTarget(0), Kept); + auto commands = Frame(alphas); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + const auto color = MergedTarget(0); + for (std::size_t offset = 0; offset < color.size(); offset += 4) { + if (std::all_of(color.begin() + static_cast(offset), color.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) continue; + return static_cast(color[offset + 3]); + } + throw std::runtime_error("the draws covered no pixel"); +} + +unsigned Byte(float value) { + return static_cast(value * 255.0f + 0.5f); +} + +} + +int main() { + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + Registered(PixelHeader, UserPixelCode.data(), sizeof(UserPixelCode), 1); + const auto keepsBefore = AgcDriver::Graphics::PushedUserDataKeeps(); + const std::vector> frames{{0.2f, 0.6f}, {0.6f, 0.2f}, {0.2f, 0.2f}, {0.8f}, {0.8f, 0.4f, 0.8f}, {0.4f}, {0.4f}}; + for (const auto& frame : frames) { + const auto drawn = Submit(frame); + Require(drawn == Byte(frame.back()), "a draw whose only change was a user word read from push data drew alpha " + std::to_string(drawn) + ", expected " + std::to_string(Byte(frame.back()))); + } + if (AgcDriver::Graphics::DescriptorHeapEnabled()) + Require(AgcDriver::Graphics::PushedUserDataKeeps() > keepsBefore, "heap draws whose user words all fit push data did not take the pushed user-data path"); + std::puts("draws whose only change was a pushed user word read the new word"); + AgcDriverShutdown_nid_postfix(); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp new file mode 100644 index 000000000000..8601c576cc28 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -0,0 +1,445 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::byte Kept{0x40}; +constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, + 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array ConstantSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BorderSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array WrapSamplerPixelCode{ + 0xbe8803ffu, 0u, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BufferPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array GdsPixelCode{ + 0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array StoragePixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, + 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array LdsPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e080280u, 0xd8344400u, 0x00000004u, + 0xbf8cc07fu, 0xd8d84400u, 0x00000004u, 0xbf8cc07fu, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(4096) std::array StorageMemory{}; +alignas(256) constexpr std::array SamplingVertexCode{ + 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, + 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, + 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array InterpolantPixelCode{0xc8020002u, 0xc8060102u, 0xc80a0202u, 0xc80e0302u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BdaPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0x7e08020cu, 0x7e0a020du, 0xdc308000u, 0x067d0004u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0x7e060306u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TablePixelCode{ + 0xf4200404u, 0xfa000000u, 0xbf8cc07fu, 0x8f108510u, 0xf42c0500u, 0x20000000u, 0xbf8cc07fu, 0x7e0002f0u, + 0x7e0202f0u, 0xf09c0f08u, 0x00250000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TableVertexCode{ + 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, + 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, + 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) std::array TableMemory{}; +alignas(256) std::array FreshVertexCode{}; +alignas(256) std::array FreshPixelCode{}; +alignas(256) std::array MaterialMemory{}; +alignas(256) std::array OtherTextureMemory{}; +constexpr float BufferAlpha = 0.2f; +constexpr std::uint8_t BufferAlphaByte = 51u; +constexpr float SecondAlpha = 0.6f; +constexpr std::uint8_t SecondAlphaByte = 153u; +constexpr float FilledAlpha = 0.8f; +constexpr std::uint8_t FilledAlphaByte = 204u; +constexpr std::size_t FillSource = 512; +alignas(4096) std::array BufferMemory{}; +alignas(4096) std::array OtherMemory{}; +constexpr std::size_t OtherSlices = 1024; + +float* SliceAt(std::size_t slice) { + return slice >= OtherSlices ? OtherMemory.data() + (slice - OtherSlices) : BufferMemory.data() + slice; +} + +std::size_t SliceBytes(std::size_t slice) { + return (slice >= OtherSlices ? sizeof(OtherMemory) - (slice - OtherSlices) * sizeof(float) : sizeof(BufferMemory) - slice * sizeof(float)); +} +alignas(256) std::array ColorMemory{}; + +std::span MergedTarget(std::size_t index) { + constexpr std::size_t Bytes = 65536; + static std::array data{}; + if (data.at(index) == nullptr) data[index] = [] { + std::byte* block = nullptr; +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); + GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); +#else + void* raw = mmap(nullptr, 2u * Bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the merged color target"); + const auto begin = reinterpret_cast(raw); + block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); +#endif + GuestAllocations::Mutation mutation; + mutation.Add(block, Bytes, true, true, true); + return block; + }(); + return {data[index], ColorMemory.size()}; +} +alignas(256) std::array TextureMemory{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(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); +} + +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); +} + +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler, BorderSampler, WrapSampler, MergedBlend, MergedBlendOther }; + +const std::uint32_t* VertexProgram(Mode mode) { + if (mode == Mode::VertexTable) return TableVertexCode.data(); + if (mode == Mode::Vertex) return SamplingVertexCode.data(); + return VertexCode.data(); +} + +std::uint32_t PixelUserWords(Mode mode, bool vertexSampling) { + switch (mode) { + case Mode::Storage: + return 24u; + case Mode::Buffer: + case Mode::MovedBuffer: + return 16u; + case Mode::Bda: + return 14u; + default: + return vertexSampling ? 0u : 12u; + } +} + +unsigned ExpectedChannel(Mode mode, bool buffer, std::size_t channel) { + if (mode == Mode::MovedTexture) return 0x33u; + if ((mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3) return SecondAlphaByte; + if (buffer && channel == 3) return BufferAlphaByte; + if (mode == Mode::BorderSampler) return 0xffu; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return std::min(2u * Texel[channel] + static_cast(Kept), 0xffu); + return Texel[channel]; +} + +const char* DrawnWhat(Mode mode, bool buffer) { + if (mode == Mode::Bda) return " (texture and BDA)"; + if (mode == Mode::MovedBuffer) return " (texture and a buffer moved between two draws)"; + if (mode == Mode::MovedTexture) return " (a texture changed between two draws)"; + if (buffer) return " (texture and buffer)"; + if (mode == Mode::Table) return " (image table)"; + if (mode == Mode::ConstantSampler) return " (texture with a constant sampler)"; + if (mode == Mode::BorderSampler) return " (constant border-clamp sampler outside the texture)"; + if (mode == Mode::WrapSampler) return " (constant wrapping sampler outside the texture, after a border-clamp draw of the same shader)"; + if (mode == Mode::MergedBlend) return " (texture blended unclamped into the color target)"; + if (mode == Mode::MergedBlendOther) return " (texture blended unclamped into a second color target)"; + return " (texture)"; +} + +const char* TakenWhat(Mode mode, bool buffer) { + if (buffer) return " reading a buffer"; + if (mode == Mode::Vertex) return " (vertex stage)"; + if (mode == Mode::Bda) return " loading through BDA"; + if (mode == Mode::Table) return " reading an image table"; + if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; + if (mode == Mode::ConstantSampler || mode == Mode::BorderSampler || mode == Mode::WrapSampler) return " sampling with a constant sampler"; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return " merging into its color target"; + return ""; +} + +std::array ImageDescriptor(const void* memory) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; +} + +std::array BufferDescriptor(const void* memory, std::size_t bytes) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), static_cast(bytes), + 0xfacu}; +} + + +alignas(256) std::array SampledTexture{}; + +std::vector Frame(std::span slices, std::optional filled = std::nullopt, std::optional stored = std::nullopt) { + const auto color = reinterpret_cast(MergedTarget(0).data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {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}, + {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}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x292, 2}, + }; + + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + const auto vertex = reinterpret_cast(VertexCode.data()); + Append(commands, 0x76, {0xc8, static_cast(vertex >> 8u)}); + Append(commands, 0x76, {0xc9, static_cast(vertex >> 40u)}); + Append(commands, 0x76, {0x8b, 1u << 1u}); + Append(commands, 0x76, {0x8c, 0}); + const auto pixel = reinterpret_cast(BufferPixelCode.data()); + for (const auto slice : slices) { + if (filled.has_value() && slice == *filled) { + const auto source = reinterpret_cast(BufferMemory.data() + FillSource); + const auto destination = reinterpret_cast(SliceAt(slice)); + Append(commands, 0x50, {0u, static_cast(source), static_cast(source >> 32u), static_cast(destination), static_cast(destination >> 32u), 16u}); + } + if (stored.has_value() && slice == *stored) { + const auto label = reinterpret_cast(SliceAt(slice)); + commands.insert(commands.end(), {0xc0033700u, 0x00100200u, static_cast(label), static_cast(label >> 32u), std::bit_cast(FilledAlpha)}); + } + std::array words{}; + const auto image = ImageDescriptor(SampledTexture.data()); + std::copy(image.begin(), image.end(), words.begin()); + const auto descriptor = BufferDescriptor(SliceAt(slice), SliceBytes(slice)); + std::copy(descriptor.begin(), descriptor.end(), words.begin() + 12); + Append(commands, 0x76, {0x008, static_cast(pixel >> 8u)}); + Append(commands, 0x76, {0x009, static_cast(pixel >> 40u)}); + Append(commands, 0x76, {0x00b, 16u << 1u}); + for (std::uint32_t index = 0; index < 16u; ++index) Append(commands, 0x76, {0x00cu + index, words[index]}); + Append(commands, 0x2d, {3, 2}); + } + return commands; +} + +unsigned DrawnAlpha() { + const auto color = MergedTarget(0); + for (std::size_t offset = 0; offset < color.size(); offset += 4) { + if (std::all_of(color.begin() + static_cast(offset), color.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) continue; + return static_cast(color[offset + 3]); + } + throw std::runtime_error("the draws covered no pixel"); +} + +unsigned Submit(std::span slices, std::optional filled = std::nullopt, std::optional stored = std::nullopt) { + std::ranges::fill(MergedTarget(0), Kept); + auto commands = Frame(slices, filled, stored); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + return DrawnAlpha(); +} + +} + +int main() { + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (AgcDriver::Graphics::GpuHeapEnabled() && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; + } + { + GuestAllocations::Mutation mutation; + mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); + mutation.Add(OtherMemory.data(), sizeof(OtherMemory), true, true, true); + } + for (std::size_t offset = 0; offset < SampledTexture.size(); offset += Texel.size()) std::memcpy(SampledTexture.data() + offset, Texel.data(), Texel.size()); + BufferMemory.fill(0.0f); + constexpr std::size_t First = 1, Moved = 9; + BufferMemory[First] = BufferAlpha; + BufferMemory[Moved] = SecondAlpha; + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + Registered(PixelHeader, BufferPixelCode.data(), sizeof(BufferPixelCode), 1); + const std::array slices{First, Moved}; + const auto keepsBefore = AgcDriver::Graphics::PushedUserDataKeeps(); + for (int round = 0; round < 2; ++round) Require(Submit(slices) == SecondAlphaByte, "the draw of the moved buffer did not read it"); + const auto keeps = AgcDriver::Graphics::PushedUserDataKeeps() - keepsBefore; + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) Require(keeps == 0u, "draws without the GPU heap kept a pushed user-data block " + std::to_string(keeps) + " times"); + else Require(keeps >= 2u, "heap draws whose only change was the moved buffer's pushed user words kept their user-data block " + std::to_string(keeps) + " times, expected at least 2"); + + const auto hitsBefore = AgcDriver::VulkanDevice::DrawRecipeHits(); + const auto pathsBefore = AgcDriver::Graphics::HeapBufferPaths(); + Require(Submit(slices) == SecondAlphaByte, "the repeated draw of the moved buffer did not read it"); + const auto hits = AgcDriver::VulkanDevice::DrawRecipeHits() - hitsBefore; + const auto paths = AgcDriver::Graphics::HeapBufferPaths(); + if (AgcDriver::Graphics::DrawRecipes() && std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) { + Require(hits == slices.size(), "a repeated draw whose read-only buffer moved from its template's did not replay a recipe (" + std::to_string(hits) + " recipe hits for " + std::to_string(slices.size()) + " draws)"); + if (AgcDriver::Graphics::DescriptorHeapEnabled()) { + Require(paths.pushedStages - pathsBefore.pushedStages >= hits, "recipe hits over a moved buffer pushed the buffer addresses of " + std::to_string(paths.pushedStages - pathsBefore.pushedStages) + " stages for " + std::to_string(hits) + " hits"); + if (AgcDriver::Graphics::PushedBufferRecordCap() == 0u) Require(paths.overflowStages - pathsBefore.overflowStages >= hits, "recipe hits whose buffers all overflow the push data wrote the overflow block of " + std::to_string(paths.overflowStages - pathsBefore.overflowStages) + " stages for " + std::to_string(hits) + " hits"); + } + } + BufferMemory[Moved] = BufferAlpha; + Require(Submit(slices) == BufferAlphaByte, "a recipe over a moved buffer drew the buffer's old contents after they changed"); + BufferMemory[Moved] = SecondAlpha; + const std::array unmoved{First}; + for (int round = 0; round < 3; ++round) Require(Submit(unmoved) == BufferAlphaByte, "the draw of the template's own buffer did not read it"); + const std::array movedOnly{Moved}; + for (int round = 0; round < 3; ++round) Require(Submit(movedOnly) == SecondAlphaByte, "a draw whose buffer moved after a recipe without moves was recorded did not read the moved buffer"); + std::fill(BufferMemory.begin() + FillSource, BufferMemory.begin() + FillSource + 4, FilledAlpha); + const auto behindBefore = AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites(); + constexpr std::size_t Aligned = First + 64; + const std::array alignedSlices{First, Aligned}; + BufferMemory[Aligned] = SecondAlpha; + const auto cpuAlpha = Submit(alignedSlices); + Require(cpuAlpha == SecondAlphaByte, "a draw whose buffer moved by a whole number of 256-byte blocks drew another buffer's contents (alpha " + std::to_string(cpuAlpha) + ")"); + BufferMemory[Aligned] = 0.0f; + const auto alignedAlpha = Submit(alignedSlices, Aligned); + Require(alignedAlpha == FilledAlphaByte, "a draw whose buffer moved onto a range a GPU copy wrote earlier in its batch did not read the copied value (alpha " + std::to_string(alignedAlpha) + ")"); + if (AgcDriver::Graphics::DescriptorHeapEnabled()) + Require(AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites() > behindBefore, "a heap draw whose buffer moved onto a range with a pending GPU write did not reuse its template by reading the buffer in place"); + std::fill(BufferMemory.begin() + Aligned, BufferMemory.begin() + Aligned + 4, 0.0f); + constexpr std::size_t Elsewhere = OtherSlices + First; + const std::array elsewhereSlices{First, Elsewhere}; + const auto elsewhereBefore = AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites(); + const auto elsewhereAlpha = Submit(elsewhereSlices, Elsewhere); + Require(elsewhereAlpha == FilledAlphaByte, "a draw whose buffer moved into other guest memory a GPU copy wrote earlier in its batch did not read the copied value (alpha " + std::to_string(elsewhereAlpha) + ")"); + if (AgcDriver::Graphics::DescriptorHeapEnabled()) + Require(AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites() > elsewhereBefore, "a heap draw whose buffer moved into other guest memory with a pending GPU write did not reuse its template by reading the buffer in place"); + OtherMemory.fill(0.0f); + constexpr std::size_t Shifted = Elsewhere + 1; + const std::array shiftedSlices{First, Shifted}; + const auto shiftedBefore = AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites(); + const auto shiftedAlpha = Submit(shiftedSlices, Shifted); + Require(shiftedAlpha == FilledAlphaByte, "a draw whose buffer moved to another view alignment behind a GPU copy did not read the copied value (alpha " + std::to_string(shiftedAlpha) + ")"); + Require(AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites() == shiftedBefore, "a draw whose buffer moved to another view alignment was read in place through its template's view"); + OtherMemory.fill(0.0f); + constexpr std::size_t Stored = First + 128; + BufferMemory[Stored] = 0.0f; + const std::array storedSlices{First, Stored}; + const auto storedAlpha = Submit(storedSlices, std::nullopt, Stored); + Require(storedAlpha == FilledAlphaByte, "a draw whose buffer moved onto a range a label store queued earlier in its batch did not read the stored value (alpha " + std::to_string(storedAlpha) + ")"); + BufferMemory[Stored] = 0.0f; + OtherMemory.fill(0.0f); + std::puts("draws whose read-only buffer moved from their template's replayed recipes that read the buffer's current contents"); + AgcDriverShutdown_nid_postfix(); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp index 1c2407762fac..7a1f605e6e03 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" @@ -9,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -163,6 +165,30 @@ void BufferValueWordsArePatchedInTheirBinding() { Require(sharedCount->valueSlots.size() == 1u && sharedCount->valueSlots[0] == std::array{4u, 0u, 0u}, "a V# whose record count builds a second descriptor recorded a record-count patch"); const auto ownCount = shared(descriptor[2] + 1u); Require((ownCount->valueWords >> 6u & 1u) != 0u, "a record count used by one descriptor only was not tagged next to an independent second descriptor"); + + const auto tagged = [&](bool forwardedAsPushData, bool shaderDataCopy, bool heapMode) { + auto compiled = result(false); + if (!shaderDataCopy) { + compiled->pushConstants.resize(sizeof(std::uint32_t)); + std::memcpy(compiled->pushConstants.data(), &descriptor[0], sizeof(std::uint32_t)); + } + if (forwardedAsPushData) compiled->shaderDataUserWords = {4u}; + const std::vector userWords(program.userData.begin(), program.userData.end()); + if (shaderDataCopy) compiled->bindings.push_back(ShaderRecompiler::DescriptorBinding{ShaderRecompiler::DescriptorKind::UniformBuffer, ShaderRecompiler::DescriptorRole::ShaderData, 1, 0, 1, heapMode ? std::vector(userWords.size(), 0u) : userWords}); + const auto variant = Variant(compiled); + ShaderRecompiler::HeapStageWords words; + words.userData = userWords; + words.bindings = {descriptor, {}}; + Driver::tagUserValueWords(*variant, program, heapMode ? &words : nullptr); + return variant->valueWords; + }; + for (const auto forwardedAsPushData : {false, true}) { + const auto expected = forwardedAsPushData ? std::uint64_t {(1u << 4u) | (1u << 6u)} : std::uint64_t {0}; + Require(tagged(forwardedAsPushData, false, false) == expected, std::string("default: a V# base ") + (forwardedAsPushData ? "forwarded as push data from its own user word" : "also present in push data but not forwarded from it") + " was tagged as " + std::to_string(tagged(forwardedAsPushData, false, false))); + Require(tagged(forwardedAsPushData, false, true) == tagged(forwardedAsPushData, false, false), std::string("heap and default disagree on a V# base ") + (forwardedAsPushData ? "forwarded as push data" : "that is not forwarded") + " (heap " + std::to_string(tagged(forwardedAsPushData, false, true)) + ", default " + std::to_string(tagged(forwardedAsPushData, false, false)) + ")"); + } + Require(tagged(false, true, false) == 0u, "default: a V# base copied into a shader data binding was tagged"); + Require(tagged(false, true, true) == ((1u << 4u) | (1u << 6u)), "heap: the user-word copy in shader data hid a V# from tagging (mask " + std::to_string(tagged(false, true, true)) + ")"); } alignas(256) constexpr std::array VertexCode{ @@ -177,6 +203,10 @@ alignas(256) constexpr std::array OwnCountPixelCode{ 0xbe880304u, 0xbe890305u, 0xbe8a0306u, 0xbe8b0307u, 0xf4200300u, 0xfa000000u, 0xf4200344u, 0xfa000004u, 0xbf8cc07fu, 0x7e00020cu, 0x7e02020du, 0x7e040280u, 0x7e0602f2u, 0xf800180fu, 0x03020100u, 0xbf810000u, }; +alignas(256) constexpr std::array ForwardedBasePixelCode{ + 0xbe880304u, 0xbe890305u, 0xbe8a0306u, 0xbe8b0307u, 0xf4200300u, 0xfa000000u, 0xf4200344u, 0xfa000004u, + 0xbf8cc07fu, 0x7e00020cu, 0x7e02020du, 0x7e040280u, 0x7e062200u, 0xf800180fu, 0x03020100u, 0xbf810000u, +}; alignas(256) std::array ColorMemory{}; struct Header { @@ -187,6 +217,7 @@ struct Header { alignas(8) Header VertexHeader{}; alignas(8) Header SharedCountHeader{}; alignas(8) Header OwnCountHeader{}; +alignas(8) Header ForwardedBaseHeader{}; void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { header.shader.file_header = 0x34333231u; @@ -266,12 +297,22 @@ void MovedRecordCountsReachEveryDescriptor(bool sharedCount) { return std::array{Low(first[i].data()), High(first[i].data()), sharedCount ? records : 12u, 0x20077facu, Low(second[i].data()), High(second[i].data()), sharedCount ? 4u : records, 0x20077facu}; }; const auto start = Driver::Get().DrawCacheCounters(); + const auto heapStart = AgcDriver::DriverDetail::HeapStagesTaken(); + const auto ringStart = AgcDriver::DriverDetail::HeapRingHitsVerified(); for (std::size_t i = 0; i < 5; ++i) { const auto pixel = DrawWithUserData(pixelCode, userData(i, 4u)); Require(pixel == std::array{255, 0, 0, 255}, mode + ": a draw whose second descriptor holds one dword drew " + std::to_string(pixel[0]) + "," + std::to_string(pixel[1]) + "," + std::to_string(pixel[2]) + "," + std::to_string(pixel[3])); + first[i] = {0.0f, 0.0f, 1.0f, 0.0f}; + second[i] = {1.0f, 0.0f, 1.0f, 0.0f}; } const auto taught = Driver::Get().DrawCacheCounters(); Require(taught.hits > start.hits, mode + ": draws whose descriptors moved to equal contents never reused the cached draw (" + std::to_string(taught.lookups - start.lookups) + " lookups)"); + if (std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr) { + Require(AgcDriver::DriverDetail::HeapStagesTaken() > heapStart, mode + ": the draws never reached the GPU heap"); + if (std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr) + Require(AgcDriver::DriverDetail::HeapRingHitsVerified() > ringStart, mode + ": no relocated ring hit was compared with a fresh capture"); + Require(AgcDriver::DriverDetail::HeapRingHitsDiffering() == 0, mode + ": a relocated ring hit's rebuilt words differ from a fresh capture"); + } const auto pixel = DrawWithUserData(pixelCode, userData(5, 8u)); Require(pixel == std::array{255, 255, 0, 255}, mode + ": after the record count grew to two dwords, the second descriptor's second dword drew " + std::to_string(pixel[1]) + " (a reused draw kept the earlier count)"); if (!sharedCount) { @@ -280,6 +321,39 @@ void MovedRecordCountsReachEveryDescriptor(bool sharedCount) { } } +struct alignas(256) Block { + std::array, 16> entries{}; +}; + +void ForwardedBaseWordsFollowRelocatedDraws() { + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + Registered(ForwardedBaseHeader, ForwardedBasePixelCode.data(), sizeof(ForwardedBasePixelCode), 1); + static std::array blocks{}; + alignas(16) static std::array, 8> other{}; + for (auto& block : blocks) { + for (auto& entry : block.entries) entry = {1.0f, 0.0f, 0.0f, 0.0f}; + } + for (auto& entry : other) entry = {0.0f, 1.0f, 0.0f, 0.0f}; + const auto ringStart = AgcDriver::DriverDetail::HeapRingHitsVerified(); + const auto start = Driver::Get().DrawCacheCounters(); + for (std::size_t i = 0; i < blocks.size(); ++i) { + const bool lowByteSet = i % 2 == 1; + const auto* first = blocks[i].entries[lowByteSet ? 1 : 0].data(); + const auto* second = other[i % other.size()].data(); + const std::array words{Low(first), High(first), 4u, 0x20077facu, Low(second), High(second), 4u, 0x20077facu}; + const auto pixel = DrawWithUserData(ForwardedBasePixelCode.data(), words); + const std::array expected{255, 0, 0, static_cast(lowByteSet ? 255 : 0)}; + Require(pixel == expected, "draw " + std::to_string(i) + " read a stale forwarded V# base word: drew " + std::to_string(pixel[0]) + "," + std::to_string(pixel[1]) + "," + std::to_string(pixel[2]) + "," + std::to_string(pixel[3]) + ", expected alpha " + std::to_string(expected[3])); + } + const auto after = Driver::Get().DrawCacheCounters(); + Require(after.hits > start.hits, "draws that moved only their first V# never reused the cached draw, so the forwarded base word was never rebuilt for a hit"); + if (std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr) { + if (std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr) + Require(AgcDriver::DriverDetail::HeapRingHitsVerified() > ringStart, "no relocated ring hit of the forwarded-base draws was compared with a fresh capture"); + Require(AgcDriver::DriverDetail::HeapRingHitsDiffering() == 0, "a relocated ring hit of the forwarded-base draws differs from a fresh capture"); + } +} + void BufferValueWordsKeyByNothing() { const RelocatableUserWord word{4u, {}, true, 0u}; bool readable = true; @@ -301,6 +375,7 @@ int main() { } MovedRecordCountsReachEveryDescriptor(true); MovedRecordCountsReachEveryDescriptor(false); + ForwardedBaseWordsFollowRelocatedDraws(); AgcDriverShutdown_nid_postfix(); std::cout << "User-data V# values and fetch subroutine pointers relocate\n"; return 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawUnsupportedBufferType.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawUnsupportedBufferType.cpp index 61a0e679ee22..ceb237477d67 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawUnsupportedBufferType.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawUnsupportedBufferType.cpp @@ -93,7 +93,7 @@ void NamesShaderAndDescriptor() { Require(message.find("buffer descriptor uses an unsupported type") != std::string::npos, "draw failed for another reason: " + message); Require(message.find(shader) != std::string::npos, std::string("draw error does not name ") + shader + ": " + message); Require(message.find(words) != std::string::npos, std::string("draw error does not name ") + words + ": " + message); - if (std::getenv("APS5_DRAW_PIPELINE") != nullptr) Require(message.find("draw at submission ") != std::string::npos && message.find("(finished on the draw finisher)") != std::string::npos, "a draw finished on the draw finisher does not name its submission and offset: " + message); + if (std::getenv("APS5_DRAW_PIPELINE") != nullptr && std::getenv("APS5_VERIFY_DRAW_DATA_HITS") == nullptr) Require(message.find("draw at submission ") != std::string::npos && message.find("(finished on the draw finisher)") != std::string::npos, "a draw finished on the draw finisher does not name its submission and offset: " + message); return; } throw std::runtime_error("a pixel shader read a buffer through a descriptor of type 2"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawWriteRanges.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawWriteRanges.cpp index a9be10492ecc..fcca54218bba 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawWriteRanges.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawWriteRanges.cpp @@ -104,6 +104,32 @@ int main() { Require(typedBounded && Contains(typedRanges, written, written + surfaceBytes), "a dispatch whose written images are a real one and a TYPE 0 or 1 one lost the real one"); Require(!Touches(typedRanges, base, base + surfaceBytes), "a TYPE 0 or 1 storage image is a dispatch write range"); } + { + constexpr std::uint64_t heapWritten = 0x600000000ull; + constexpr std::uint64_t heapReadOnly = 0x700000000ull; + ShaderRecompiler::RecompileResult heapProgram; + heapProgram.gpuResolvedImages = true; + ShaderRecompiler::DescriptorBinding heapImages; + heapImages.kind = ShaderRecompiler::DescriptorKind::StorageImage; + heapImages.role = ShaderRecompiler::DescriptorRole::GuestImages; + heapImages.count = 2; + heapImages.imageWritten = {true, false}; + heapProgram.bindings.push_back(heapImages); + ShaderRecompiler::HeapStageWords heapWords; + heapWords.bindings.resize(1); + for (const auto base : {heapWritten, heapReadOnly}) { + const auto words = ImageWords(base, 256, 128); + heapWords.bindings[0].insert(heapWords.bindings[0].end(), words.begin(), words.end()); + } + const std::array heapStages{{{ShaderRecompiler::ShaderStage::Fragment, &heapProgram, 0, nullptr, &heapWords}}}; + const std::array bareStages{{{ShaderRecompiler::ShaderStage::Fragment, &heapProgram, 0}}}; + for (const bool exact : {false, true}) { + const auto ranges = DrawWriteRanges(state, heapStages, exact); + Require(Contains(ranges, heapWritten, heapWritten + surfaceBytes), "a heap-backed storage image the draw stores to is not a write range"); + Require(!Touches(ranges, heapReadOnly, heapReadOnly + surfaceBytes), "a heap-backed storage image the draw only reads is a write range"); + Require(!Touches(DrawWriteRanges(state, bareStages, exact), heapWritten, heapWritten + surfaceBytes), "a heap-backed stage's ranges came from somewhere other than its heap words"); + } + } AgcDriver::Graphics::State targets{}; targets.hasColorTarget = true; auto& color = targets.color; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp new file mode 100644 index 000000000000..8a2430e93be1 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp @@ -0,0 +1,179 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "HeapSampleKernel.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0xf4000100u, 0xfa000000u, 0xbf8cc07fu, 0x7e000204u, 0x06000002u, 0x7e020280u, 0xf800180fu, 0x00010100u, 0xbf810000u, 0xbf810000u}; +alignas(256) std::array PixelConstant{}; +alignas(256) std::array ColorMemory{}; +constexpr std::uint32_t Rounds = 8; +alignas(4096) std::array, Rounds> Outputs{}; +alignas(256) std::array SampleMemory{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(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); +} + +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); +} + +std::vector Setup() { + const auto color = reinterpret_cast(ColorMemory.data()); + const auto vertex = reinterpret_cast(VertexCode.data()); + const auto pixel = reinterpret_cast(PixelCode.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, 3u << 1u}, + }; + std::vector commands; + 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}); + const auto table = reinterpret_cast(PixelConstant.data()); + Append(commands, 0x76, {0x00c, static_cast(table)}); + Append(commands, 0x76, {0x00d, static_cast(table >> 32u)}); + Append(commands, 0x76, {0x00e, std::bit_cast(0.25f)}); + return commands; +} + +void SetShaderRegister(std::vector& commands, std::uint32_t offset, std::uint32_t value) { + Append(commands, 0x76, {offset, value}); +} + +void Sample(std::vector& commands, float* output) { + const auto address = static_cast(reinterpret_cast(SampleCode.data())); + SetShaderRegister(commands, 0x20c, static_cast(address >> 8u)); + SetShaderRegister(commands, 0x20d, static_cast(address >> 40u) & 0xffu); + for (const std::uint32_t offset : {0x207u, 0x208u, 0x209u}) SetShaderRegister(commands, offset, 1); + SetShaderRegister(commands, 0x212, 0); + SetShaderRegister(commands, 0x213, 16u << 1u); + std::uint32_t offset = 0x240; + for (const auto value : SampleUserData(ColorMemory.data(), output)) SetShaderRegister(commands, offset++, value); + Append(commands, 0x15, {1, 1, 1, 0x8041u}); +} + +void DumpSamples(std::vector& commands, std::uint32_t round) { + const auto address = reinterpret_cast(SampleMemory.data() + 32u * round); + Append(commands, 0x46, {AgcDriver::Pm4::SampleDumpEvent | (1u << 8u), static_cast(address), static_cast(address >> 32u)}); +} + +} + +int main() { + try { + bool libraries = false; + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + libraries = device->GraphicsPipelineLibraries(); + } + if (!libraries && std::getenv("APS5_NO_GPL") == nullptr) return VulkanTestSkipped; + using AgcDriver::DriverDetail::DrawFinisher; + const bool finisher = DrawFinisher::Enabled() && DrawFinisher::Overlap(); + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + Registered(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); + PixelConstant[0] = 0.25f; + for (auto& output : Outputs) output.fill(-1.0f); + constexpr std::array Constants{0.25f, 0.125f}; + unsigned expected = 0; + for (std::uint32_t pass = 0; pass < 2; ++pass) { + PixelConstant[0] = Constants[pass]; + expected = static_cast((Constants[pass] + 0.25f) * 255.0f + 0.5f); + static_cast(DrawFinisher::DrainText()); + auto commands = Setup(); + for (std::uint32_t round = 0; round < Rounds; ++round) { + Append(commands, 0x2d, {3, 2}); + Sample(commands, Outputs[round].data()); + Append(commands, 0x2d, {3, 2}); + DumpSamples(commands, round); + } + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + const auto drains = DrawFinisher::DrainText(); + const auto passLabel = "pass " + std::to_string(pass) + ": "; + if (finisher) Require(drains.find(" 0x15 x") == std::string::npos, passLabel + "a pipelined dispatch after a draw handed to the finisher drained the finisher:" + drains); + if (finisher) Require(drains.find(" 0x46 x") == std::string::npos, passLabel + "a sample dump after a draw handed to the finisher drained the finisher:" + drains); + AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(Outputs.data()), sizeof(Outputs)); + for (std::uint32_t round = 0; round < Rounds; ++round) { + const auto where = "pass " + std::to_string(pass) + " round " + std::to_string(round); + const auto texel = [&](std::size_t channel) { return static_cast(Outputs[round][channel] * 255.0f + 0.5f); }; + Require(texel(0) + 1 >= expected && texel(0) <= expected + 1 && texel(3) + 1 >= expected && texel(3) <= expected + 1 && texel(1) == 0u && texel(2) == 0u, + "the dispatch after the draw in " + where + " sampled " + std::to_string(texel(0)) + "," + std::to_string(texel(1)) + "," + std::to_string(texel(2)) + "," + std::to_string(texel(3)) + " from the draw's target, expected " + std::to_string(expected) + ",0,0," + std::to_string(expected)); + } + } + AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(ColorMemory.data()), ColorMemory.size()); + unsigned brightest = 0; + for (const auto value : ColorMemory) brightest = std::max(brightest, static_cast(std::to_integer(value))); + Require(brightest + 2 >= expected && brightest <= expected + 2, "the draws around the dispatches wrote " + std::to_string(brightest) + ", expected " + std::to_string(expected)); + AgcDriverShutdown_nid_postfix(); + std::cout << "dispatches and sample dumps after finisher draws " << (finisher ? "queued through the finisher" : "run in order") << "\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp new file mode 100644 index 000000000000..fe1fb6604bac --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp @@ -0,0 +1,150 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0xf4000100u, 0xfa000000u, 0xbf8cc07fu, 0x7e000204u, 0x06000002u, 0x7e020280u, 0xf800180fu, 0x00010100u, 0xbf810000u, 0xbf810000u}; +alignas(256) std::array PixelConstant{}; +alignas(256) std::array ColorMemory{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(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); +} + +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); +} + +std::vector Setup() { + const auto color = reinterpret_cast(ColorMemory.data()); + const auto vertex = reinterpret_cast(VertexCode.data()); + const auto pixel = reinterpret_cast(PixelCode.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, 3u << 1u}, + }; + std::vector commands; + 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}); + const auto table = reinterpret_cast(PixelConstant.data()); + Append(commands, 0x76, {0x00c, static_cast(table)}); + Append(commands, 0x76, {0x00d, static_cast(table >> 32u)}); + Append(commands, 0x76, {0x00e, std::bit_cast(0.25f)}); + return commands; +} + +} + +namespace { + +std::uint64_t LookupDrains(const std::string& drains) { + const auto at = drains.find(" lookup "); + Require(at != std::string::npos, "the finisher's drain text has no lookup site: " + drains); + return std::strtoull(drains.c_str() + at + 8, nullptr, 10); +} + +void SubmitDraws(std::uint32_t draws) { + auto commands = Setup(); + for (std::uint32_t draw = 0; draw < draws; ++draw) Append(commands, 0x2d, {3, 2}); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); +} + +} + +int main() { + try { + bool libraries = false; + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + libraries = device->GraphicsPipelineLibraries(); + } + if (!libraries && std::getenv("APS5_NO_GPL") == nullptr) return VulkanTestSkipped; + using AgcDriver::DriverDetail::DrawFinisher; + const bool finisher = DrawFinisher::Enabled() && DrawFinisher::Overlap(); + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + Registered(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); + PixelConstant[0] = 0.25f; + SubmitDraws(8); + static_cast(DrawFinisher::DrainText()); + const auto cacheBefore = AgcDriver::DriverDetail::Driver::Get().DrawCacheCounters(); + SubmitDraws(64); + const auto cacheAfter = AgcDriver::DriverDetail::Driver::Get().DrawCacheCounters(); + const auto drains = DrawFinisher::DrainText(); + Require(cacheAfter.hits > cacheBefore.hits, "the measured submission's repeated draws never hit the draw cache (" + std::to_string(cacheAfter.lookups - cacheBefore.lookups) + " lookups)"); + AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(ColorMemory.data()), ColorMemory.size()); + unsigned brightest = 0; + for (const auto value : ColorMemory) brightest = std::max(brightest, static_cast(std::to_integer(value))); + Require(brightest + 2 >= 128 && brightest <= 130, "the repeated draws wrote " + std::to_string(brightest) + ", expected 128"); + if (finisher) Require(LookupDrains(drains) == 0u, "a draw-cache lookup drained the finisher for held draws of its key that hit the cache and insert nothing:" + drains); + AgcDriverShutdown_nid_postfix(); + std::cout << "repeated draw-cache hits " << (finisher ? "looked up beside the finisher" : "drawn without the finisher") << "\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp new file mode 100644 index 000000000000..983e8a6130a1 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp @@ -0,0 +1,178 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Submit/include/Acb.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "Recompiler.hpp" +#include "HeapSampleKernel.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void Require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +constexpr std::array OtherTexel{0xf0u, 0x20u, 0x00u, 0x40u}; + +alignas(256) constexpr std::array LdsSampleCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0x7e080280u, 0xbf8c0000u, 0xd8340000u, 0x00000004u, + 0xbf8c0000u, 0xd8d80000u, 0x00000004u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u, 0xbf810000u}; + +alignas(256) std::array TextureMemory{}; +alignas(256) std::array OtherTextureMemory{}; +alignas(4096) std::array, 4> Outputs{}; +constexpr std::size_t FullHeapTextures = 16; +alignas(256) std::array, FullHeapTextures> ManyTextures{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header SampleHeader{}; + +void Registered(Header& header, const std::uint32_t* code, std::size_t bytes) { + 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 = 0; + header.shader.user_data = &header.userData; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +void SetShaderRegister(std::vector& words, std::uint32_t offset, std::uint32_t value) { + words.insert(words.end(), {0xc0017600u, offset, value}); +} + +void Sample(std::vector& words, const void* image, float* output) { + const auto address = static_cast(reinterpret_cast(SampleCode.data())); + SetShaderRegister(words, 0x20c, static_cast(address >> 8u)); + SetShaderRegister(words, 0x20d, static_cast(address >> 40u) & 0xffu); + for (const std::uint32_t offset : {0x207u, 0x208u, 0x209u}) SetShaderRegister(words, offset, 1); + SetShaderRegister(words, 0x212, 0); + SetShaderRegister(words, 0x213, 16u << 1u); + const auto userData = SampleUserData(image, output); + std::uint32_t offset = 0x240; + for (const auto value : userData) SetShaderRegister(words, offset++, value); + words.insert(words.end(), {0xc0031500u, 1, 1, 1, 0x8041u}); +} + +void Submit(std::vector& words) { + Packet packet{words.data(), static_cast(words.size()), 0, {}}; + Require(sceAgcDriverSubmitAcb(0x20, &packet) == 0, "the compute submission failed"); + AgcDriverWaitIdle_nid_postfix(); +} + +void DriverSample(bool heap) { + Outputs[0].fill(-1.0f); + const auto before = AgcDriver::Graphics::HeapComputeStages(); + std::vector words; + Sample(words, TextureMemory.data(), Outputs[0].data()); + Sample(words, TextureMemory.data(), Outputs[0].data()); + Submit(words); + RequireSampled(Outputs[0].data(), SampleTexel, "the sampled texture", heap); + if (heap) Require(AgcDriver::Graphics::HeapComputeStages() > before, "the heap did not take the sampling compute stage"); +} + +void FullHeapSample() { + Outputs[0].fill(-1.0f); + const auto stagesBefore = AgcDriver::Graphics::HeapComputeStages(); + const auto submitsBefore = AgcDriver::Graphics::BindlessHeap::TotalStatistics().slotPressureSubmits; + std::vector words; + for (std::size_t index = 0; index < FullHeapTextures; ++index) Sample(words, ManyTextures[index].data(), Outputs[0].data() + 4u * index); + Submit(words); + for (std::size_t index = 0; index < FullHeapTextures; ++index) + RequireSampled(Outputs[0].data() + 4u * index, SampleTexel, "texture " + std::to_string(index) + " of a heap with too few image slots", true); + Require(AgcDriver::Graphics::BindlessHeap::TotalStatistics().slotPressureSubmits > submitsBefore, "the capped heap never submitted a batch early to free image slots"); + Require(AgcDriver::Graphics::HeapComputeStages() - stagesBefore == FullHeapTextures, "a compute stage left the heap while it ran short of image slots"); +} + +void DeviceSample(AgcDriver::VulkanDevice& device, bool heap) { + for (std::size_t index = 1; index < Outputs.size(); ++index) Outputs[index].fill(-1.0f); + const auto first = CompileSampleKernel(device, OtherTextureMemory.data(), Outputs[1].data(), false); + const auto second = CompileSampleKernel(device, TextureMemory.data(), Outputs[2].data(), false); + Require(first.gpuResolvedImages == heap && second.gpuResolvedImages == heap, + heap ? "a sampling compute stage is not GPU mode" : "a compute stage took the heap without it"); + const auto before = AgcDriver::Graphics::HeapComputeStages(); + const auto pushesBefore = AgcDriver::Graphics::DataAddressPushes(); + device.Dispatch(first, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); + device.Dispatch(second, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); + device.WaitIdle(); + RequireSampled(Outputs[1].data(), OtherTexel, "the first of two textures in one batch", heap); + RequireSampled(Outputs[2].data(), SampleTexel, "the second of two textures in one batch", heap); + if (heap) { + Require(AgcDriver::Graphics::HeapComputeStages() >= before + 2u, "the heap did not take both sampling compute stages"); + Require(AgcDriver::Graphics::DataAddressPushes() >= pushesBefore + 2u, + "a heap dispatch did not read its shader data through pushed addresses"); + } + const auto again = CompileSampleKernel(device, TextureMemory.data(), Outputs[3].data(), false); + device.Dispatch(again, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); + device.WaitIdle(); + RequireSampled(Outputs[3].data(), SampleTexel, "the first texture again in a later batch", heap); + Outputs[1].fill(-1.0f); + const auto lds = CompileSampleKernel(device, TextureMemory.data(), Outputs[1].data(), false, LdsSampleCode, + (device.ComputeTarget(32u).maxWorkgroupSharedMemoryBytes + 4096u) / 4u); + Require(lds.workgroupMemoryDwords != 0u && lds.gpuResolvedImages == heap, + "the LDS sampling stage did not get workgroup memory in the expected mode"); + const auto heapPipelines = device.DescriptorHeapComputePipelines(); + device.Dispatch(lds, 1u, 1u, 1u, {}, reinterpret_cast(LdsSampleCode.data())); + device.WaitIdle(); + RequireSampled(Outputs[1].data(), SampleTexel, "the texture sampled through workgroup memory", heap); + if (heap) + Require(device.DescriptorHeapComputePipelines() > heapPipelines, "the LDS sampling stage did not take the descriptor heap"); +} + +} + +int main() { + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + const bool heap = AgcDriver::Graphics::GpuHeapEnabled(); + if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; + FillTexels(TextureMemory, SampleTexel); + FillTexels(OtherTextureMemory, OtherTexel); + for (auto& texture : ManyTextures) FillTexels(texture, SampleTexel); + Registered(SampleHeader, SampleCode.data(), sizeof(SampleCode)); + if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) { + FullHeapSample(); + AgcDriverShutdown_nid_postfix(); + std::cout << "compute stages sampled every texture after the heap ran short of image slots\n"; + return 0; + } + DriverSample(heap); + AgcDriverShutdown_nid_postfix(); + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + DeviceSample(*device, heap); + } + std::cout << "compute stages sampled their textures" << (heap ? " through the heap" : "") << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + try { + AgcDriverShutdown_nid_postfix(); + } catch (const std::exception& shutdownError) { + std::cerr << shutdownError.what() << '\n'; + } + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp new file mode 100644 index 000000000000..e7d5e1d74d9a --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp @@ -0,0 +1,268 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, + 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BufferPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +constexpr float BufferAlpha = 0.2f; +alignas(4096) std::array BufferMemory{}; +alignas(256) std::array ColorMemory{}; + +std::span MergedTarget(std::size_t index) { + constexpr std::size_t Bytes = 65536; + static std::array data{}; + if (data.at(index) == nullptr) data[index] = [] { + std::byte* block = nullptr; + const bool watched = AgcDriver::GuestMemory::WriteWatched(); +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); + GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); +#else + void* raw = mmap(nullptr, 2u * Bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the merged color target"); + const auto begin = reinterpret_cast(raw); + block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); +#endif + Require(!watched || AgcDriver::GuestMemory::Watched(reinterpret_cast(block), Bytes), "the merged color target is not write-watched"); + GuestAllocations::Mutation mutation; + mutation.Add(block, Bytes, true, true, true); + return block; + }(); + return {data[index], ColorMemory.size()}; +} + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(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); +} + +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); +} + +std::array ImageDescriptor(const void* memory) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; +} + +std::array BufferDescriptor(const void* memory, std::size_t bytes) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), static_cast(bytes), + 0xfacu}; +} + +constexpr std::size_t Textures = 16; +constexpr std::size_t Buffers = 32; +alignas(256) std::array, Textures> BenchTextures{}; + +std::vector Frame(std::size_t draws, std::size_t salt) { + const auto color = reinterpret_cast(MergedTarget(0).data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {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}, + {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}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x292, 2}, + }; + + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + const auto vertex = reinterpret_cast(VertexCode.data()); + Append(commands, 0x76, {0xc8, static_cast(vertex >> 8u)}); + Append(commands, 0x76, {0xc9, static_cast(vertex >> 40u)}); + Append(commands, 0x76, {0x8b, 1u << 1u}); + Append(commands, 0x76, {0x8c, 0}); + for (std::size_t draw = 0; draw < draws; ++draw) { + const bool buffer = draw % 2u == 1u; + const auto pixel = reinterpret_cast(buffer ? BufferPixelCode.data() : PixelCode.data()); + std::array words{}; + const auto image = ImageDescriptor(BenchTextures[(draw + salt) % Textures].data()); + std::copy(image.begin(), image.end(), words.begin()); + const auto slice = 1u + (draw * 7u + salt) % Buffers; + const auto descriptor = BufferDescriptor(BufferMemory.data() + slice, sizeof(BufferMemory) - slice * sizeof(float)); + std::copy(descriptor.begin(), descriptor.end(), words.begin() + 12); + const std::uint32_t userWords = buffer ? 16u : 12u; + Append(commands, 0x76, {0x008, static_cast(pixel >> 8u)}); + Append(commands, 0x76, {0x009, static_cast(pixel >> 40u)}); + Append(commands, 0x76, {0x00b, userWords << 1u}); + for (std::uint32_t index = 0; index < userWords; ++index) Append(commands, 0x76, {0x00cu + index, words[index]}); + Append(commands, 0x2d, {3, 2}); + } + return commands; +} + +} + +int main(int argc, char** argv) { + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + const bool heap = AgcDriver::Graphics::GpuHeapEnabled(); + if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; + const std::size_t draws = argc > 1 ? std::strtoull(argv[1], nullptr, 10) : 4000u; + const std::size_t rounds = argc > 2 ? std::strtoull(argv[2], nullptr, 10) : 12u; + Require(draws > 0 && rounds >= 3, "the bench needs at least one draw and three rounds, the first two of which warm up"); + { + GuestAllocations::Mutation mutation; + mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); + } + for (auto& texture : BenchTextures) + for (std::size_t offset = 0; offset < texture.size(); offset += Texel.size()) std::memcpy(texture.data() + offset, Texel.data(), Texel.size()); + BufferMemory.fill(BufferAlpha); + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + static Header TexturePixel{}, BufferPixel{}; + Registered(TexturePixel, PixelCode.data(), sizeof(PixelCode), 1); + Registered(BufferPixel, BufferPixelCode.data(), sizeof(BufferPixelCode), 1); + const auto takenBefore = AgcDriver::DriverDetail::HeapStagesTaken(); + const auto hitsBefore = AgcDriver::VulkanDevice::DrawRecipeHits(); + std::vector perDraw; + for (std::size_t round = 0; round < rounds; ++round) { + auto commands = Frame(draws, round); + const auto start = std::chrono::steady_clock::now(); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the bench submission failed"); + AgcDriverWaitIdle_nid_postfix(); + const auto us = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + if (round >= 2) perDraw.push_back(us / static_cast(draws)); + } + std::sort(perDraw.begin(), perDraw.end()); + const bool tookHeap = AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore; + Require(tookHeap == heap, heap ? "the bench draws did not take the GPU heap" : "the bench draws took the GPU heap with it off"); + const auto hits = AgcDriver::VulkanDevice::DrawRecipeHits() - hitsBefore; + if (AgcDriver::Graphics::DrawRecipes() && std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) + Require(hits >= (rounds - 2) * draws, "the bench's repeated draws replayed " + std::to_string(hits) + " recipes, fewer than the " + std::to_string((rounds - 2) * draws) + " draws of its repeated rounds"); + std::printf("bench %s: %zu draws x %zu rounds: min %.3f us/draw, median %.3f us/draw, heap stages taken %s\n", heap ? "heap" : "per-draw", draws, + perDraw.size(), perDraw.front(), perDraw[perDraw.size() / 2], tookHeap ? "yes" : "no"); + AgcDriverShutdown_nid_postfix(); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp new file mode 100644 index 000000000000..9be65b23d241 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -0,0 +1,595 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::byte Kept{0x40}; +constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, + 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array ConstantSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BorderSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array WrapSamplerPixelCode{ + 0xbe8803ffu, 0u, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BufferPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array GdsPixelCode{ + 0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array StoragePixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, + 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array LdsPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e080280u, 0xd8344400u, 0x00000004u, + 0xbf8cc07fu, 0xd8d84400u, 0x00000004u, 0xbf8cc07fu, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(4096) std::array StorageMemory{}; +alignas(256) constexpr std::array SamplingVertexCode{ + 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, + 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, + 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array InterpolantPixelCode{0xc8020002u, 0xc8060102u, 0xc80a0202u, 0xc80e0302u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BdaPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0x7e08020cu, 0x7e0a020du, 0xdc308000u, 0x067d0004u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0x7e060306u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TablePixelCode{ + 0xf4200404u, 0xfa000000u, 0xbf8cc07fu, 0x8f108510u, 0xf42c0500u, 0x20000000u, 0xbf8cc07fu, 0x7e0002f0u, + 0x7e0202f0u, 0xf09c0f08u, 0x00250000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TableVertexCode{ + 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, + 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, + 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) std::array TableMemory{}; +alignas(256) std::array FreshVertexCode{}; +alignas(256) std::array FreshPixelCode{}; +alignas(256) std::array MaterialMemory{}; +alignas(256) std::array OtherTextureMemory{}; +constexpr float BufferAlpha = 0.2f; +constexpr std::uint8_t BufferAlphaByte = 51u; +constexpr float SecondAlpha = 0.6f; +constexpr std::uint8_t SecondAlphaByte = 153u; +alignas(4096) std::array BufferMemory{}; +alignas(256) std::array ColorMemory{}; + +std::span MergedTarget(std::size_t index) { + constexpr std::size_t Bytes = 65536; + static std::array data{}; + if (data.at(index) == nullptr) data[index] = [] { + std::byte* block = nullptr; + const bool watched = AgcDriver::GuestMemory::WriteWatched(); +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); + GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); +#else + void* raw = mmap(nullptr, 2u * Bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the merged color target"); + const auto begin = reinterpret_cast(raw); + block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); +#endif + Require(!watched || AgcDriver::GuestMemory::Watched(reinterpret_cast(block), Bytes), "the merged color target is not write-watched"); + GuestAllocations::Mutation mutation; + mutation.Add(block, Bytes, true, true, true); + return block; + }(); + return {data[index], ColorMemory.size()}; +} +alignas(256) std::array TextureMemory{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(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); +} + +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); +} + +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler, BorderSampler, WrapSampler, MergedBlend, MergedBlendOther }; + +const std::uint32_t* VertexProgram(Mode mode) { + if (mode == Mode::VertexTable) return TableVertexCode.data(); + if (mode == Mode::Vertex) return SamplingVertexCode.data(); + return VertexCode.data(); +} + +std::uint32_t PixelUserWords(Mode mode, bool vertexSampling) { + switch (mode) { + case Mode::Storage: + return 24u; + case Mode::Buffer: + case Mode::MovedBuffer: + return 16u; + case Mode::Bda: + return 14u; + default: + return vertexSampling ? 0u : 12u; + } +} + +unsigned ExpectedChannel(Mode mode, bool buffer, std::size_t channel) { + if (mode == Mode::MovedTexture) return 0x33u; + if ((mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3) return SecondAlphaByte; + if (buffer && channel == 3) return BufferAlphaByte; + if (mode == Mode::BorderSampler) return 0xffu; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return std::min(2u * Texel[channel] + static_cast(Kept), 0xffu); + return Texel[channel]; +} + +const char* DrawnWhat(Mode mode, bool buffer) { + if (mode == Mode::Bda) return " (texture and BDA)"; + if (mode == Mode::MovedBuffer) return " (texture and a buffer moved between two draws)"; + if (mode == Mode::MovedTexture) return " (a texture changed between two draws)"; + if (buffer) return " (texture and buffer)"; + if (mode == Mode::Table) return " (image table)"; + if (mode == Mode::ConstantSampler) return " (texture with a constant sampler)"; + if (mode == Mode::BorderSampler) return " (constant border-clamp sampler outside the texture)"; + if (mode == Mode::WrapSampler) return " (constant wrapping sampler outside the texture, after a border-clamp draw of the same shader)"; + if (mode == Mode::MergedBlend) return " (texture blended unclamped into the color target)"; + if (mode == Mode::MergedBlendOther) return " (texture blended unclamped into a second color target)"; + return " (texture)"; +} + +const char* TakenWhat(Mode mode, bool buffer) { + if (buffer) return " reading a buffer"; + if (mode == Mode::Vertex) return " (vertex stage)"; + if (mode == Mode::Bda) return " loading through BDA"; + if (mode == Mode::Table) return " reading an image table"; + if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; + if (mode == Mode::ConstantSampler || mode == Mode::BorderSampler || mode == Mode::WrapSampler) return " sampling with a constant sampler"; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return " merging into its color target"; + return ""; +} + +std::array ImageDescriptor(const void* memory) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; +} + +std::array BufferDescriptor(const void* memory, std::size_t bytes) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), static_cast(bytes), + 0xfacu}; +} + +std::vector Draw(const std::uint32_t* pixelCode, Mode mode, const std::uint32_t* vertexCode = nullptr) { + const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; + const auto vertex = reinterpret_cast(vertexCode != nullptr ? vertexCode : VertexProgram(mode)); + const auto pixel = reinterpret_cast(pixelCode); + const auto color = reinterpret_cast(mode == Mode::MergedBlend ? MergedTarget(0).data() : mode == Mode::MergedBlendOther ? MergedTarget(1).data() : ColorMemory.data()); + std::array descriptors{}; + const auto textureImage = ImageDescriptor(TextureMemory.data()); + const auto bufferDescriptor = BufferDescriptor(BufferMemory.data() + 1, sizeof(BufferMemory) - sizeof(float)); + const auto storageImage = ImageDescriptor(StorageMemory.data()); + std::copy(textureImage.begin(), textureImage.end(), descriptors.begin()); + std::copy(bufferDescriptor.begin(), bufferDescriptor.end(), descriptors.begin() + 12); + std::copy(storageImage.begin(), storageImage.end(), descriptors.begin() + 16); + const auto userWords = PixelUserWords(mode, vertexSampling); + const auto otherImage = ImageDescriptor(OtherTextureMemory.data()); + std::copy(otherImage.begin(), otherImage.end(), TableMemory.begin()); + std::copy(descriptors.begin(), descriptors.begin() + 8, TableMemory.begin() + 8); + MaterialMemory = {1u, 0u, 0u, 0u}; + std::array tableWords{}; + const auto table = BufferDescriptor(TableMemory.data(), sizeof(TableMemory)); + const auto material = BufferDescriptor(MaterialMemory.data(), sizeof(MaterialMemory)); + std::copy(table.begin(), table.end(), tableWords.begin()); + std::copy(material.begin(), material.end(), tableWords.begin() + 8); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {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}, + {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}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x292, 2}, + }; + std::vector> shader{ + {0xc8, static_cast(vertex >> 8u)}, + {0xc9, static_cast(vertex >> 40u)}, + {0x8b, 1u << 1u}, + {0x8c, 0}, + {0x008, static_cast(pixel >> 8u)}, + {0x009, static_cast(pixel >> 40u)}, + {0x00b, userWords << 1u}, + }; + const auto userWord = [&](std::uint32_t index) -> std::uint32_t { + if (mode == Mode::Table) return tableWords[index]; + if (mode == Mode::Bda && index >= 12u) + return static_cast(reinterpret_cast(BufferMemory.data() + 1) >> (index == 12u ? 0u : 32u)); + return descriptors[index]; + }; + for (std::uint32_t index = 0; index < userWords; ++index) shader.emplace_back(0x00cu + index, userWord(index)); + if (vertexSampling) { + shader.emplace_back(0x8bu, 12u << 1u); + for (std::uint32_t index = 0; index < 12u; ++index) + shader.emplace_back(0x08cu + index, mode == Mode::VertexTable ? tableWords[index] : descriptors[index]); + shader.emplace_back(0x00bu, 0u); + } + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) { + Append(commands, 0x69, {0x1e0, (1u << 30u) | (1u << 8u) | 1u}); + Append(commands, 0x69, {0x31c, 0x28028u & ~0x8000u}); + } + if (vertexSampling) { + Append(commands, 0x69, {0x1b6, 1}); + Append(commands, 0x69, {0x191, 1u << 10u}); + Append(commands, 0x69, {0x1b1, 0}); + } + for (const auto& [offset, value] : shader) Append(commands, 0x76, {offset, value}); + Append(commands, 0x2d, {3, 2}); + if (mode == Mode::Bda) { + const auto second = static_cast(reinterpret_cast(BufferMemory.data() + 2)); + Append(commands, 0x76, {0x00cu + 12u, static_cast(second)}); + Append(commands, 0x76, {0x00cu + 13u, static_cast(second >> 32u)}); + } + if (mode == Mode::MovedBuffer) { + const auto moved = BufferDescriptor(BufferMemory.data() + 3, sizeof(BufferMemory) - 3 * sizeof(float)); + for (std::uint32_t index = 0; index < 4u; ++index) Append(commands, 0x76, {0x00cu + 12u + index, moved[index]}); + } + if (mode == Mode::MovedTexture) { + for (std::uint32_t index = 0; index < 8u; ++index) Append(commands, 0x76, {0x00cu + index, otherImage[index]}); + } + Append(commands, 0x2d, {3, 2}); + return commands; +} + +std::span PixelProgram(Mode mode, bool buffer, bool vertexSampling) { + switch (mode) { + case Mode::PixelLds: + return LdsPixelCode; + case Mode::Table: + return TablePixelCode; + case Mode::Gds: + return GdsPixelCode; + case Mode::Storage: + return StoragePixelCode; + case Mode::Bda: + return BdaPixelCode; + case Mode::ConstantSampler: + return ConstantSamplerPixelCode; + case Mode::BorderSampler: + return BorderSamplerPixelCode; + case Mode::WrapSampler: + return WrapSamplerPixelCode; + default: + break; + } + if (buffer) return BufferPixelCode; + if (vertexSampling) return InterpolantPixelCode; + return PixelCode; +} + +template +void SubmitUntilDrawn(std::vector& commands, std::span colorMemory, const char* failure, Reset&& reset) { + const bool async = AgcDriver::DriverDetail::AsyncDrawCompile(); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60); + while (true) { + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, failure); + AgcDriverWaitIdle_nid_postfix(); + const bool covered = std::any_of(colorMemory.begin(), colorMemory.end(), [](std::byte value) { return value != Kept; }); + if (covered || !async || std::chrono::steady_clock::now() >= deadline) return; + reset(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } +} + +void DrawSamplesTheTexture(bool heap, Mode mode, bool repeated = false) { + const bool buffer = mode == Mode::Buffer || mode == Mode::Bda || mode == Mode::MovedBuffer; + const auto colorMemory = mode == Mode::MergedBlend ? MergedTarget(0) : mode == Mode::MergedBlendOther ? MergedTarget(1) : std::span(ColorMemory); + std::ranges::fill(colorMemory, Kept); + StorageMemory.fill(0u); + BufferMemory.fill(0.0f); + BufferMemory[1] = BufferAlpha; + BufferMemory[2] = SecondAlpha; + BufferMemory[3] = SecondAlpha; + for (std::size_t offset = 0; offset < TextureMemory.size(); offset += Texel.size()) + std::memcpy(TextureMemory.data() + offset, Texel.data(), Texel.size()); + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + for (std::size_t offset = 0; offset < OtherTextureMemory.size(); offset += 4) + OtherTextureMemory[offset] = OtherTextureMemory[offset + 1] = OtherTextureMemory[offset + 2] = OtherTextureMemory[offset + 3] = + 0x33u; + const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; + const auto program = PixelProgram(mode, buffer, vertexSampling); + const auto* code = program.data(); + const auto bytes = program.size_bytes(); + if (mode == Mode::Vertex) Registered(VertexHeader, SamplingVertexCode.data(), sizeof(SamplingVertexCode), 2); + if (mode == Mode::VertexTable) Registered(VertexHeader, TableVertexCode.data(), sizeof(TableVertexCode), 2); + Registered(PixelHeader, code, bytes, 1); + const auto takenBefore = AgcDriver::DriverDetail::HeapStagesTaken(); + const auto tablesBefore = AgcDriver::Graphics::ImageTableBuilds(); + const auto pushesBefore = AgcDriver::Graphics::DataAddressPushes(); + const auto embeddedBefore = AgcDriver::Graphics::EmbeddedSamplerMappings(); + const auto templatesBefore = ShaderRecompiler::HeapTemplateCounts().entries; + auto* gdsCounter = reinterpret_cast(AgcDriver::Pm4::GdsAddress() + 0x10u); + if (mode == Mode::Gds) *gdsCounter = 0u; + auto commands = Draw(code, mode); + SubmitUntilDrawn(commands, colorMemory, "the draw submission failed", [&] { + StorageMemory.fill(0u); + if (mode == Mode::Gds) *gdsCounter = 0u; + }); + std::size_t drawn = 0; + for (std::size_t offset = 0; offset < colorMemory.size(); offset += 4) { + if (std::all_of(colorMemory.begin() + static_cast(offset), + colorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) + continue; + for (std::size_t channel = 0; channel < 4; ++channel) { + const auto value = static_cast(colorMemory[offset + channel]); + const unsigned expected = ExpectedChannel(mode, buffer, channel); + Require(value == expected, "pixel " + std::to_string(offset / 4) + " channel " + std::to_string(channel) + " is " + + std::to_string(value) + ", expected " + std::to_string(expected) + DrawnWhat(mode, buffer) + + (heap ? " through the heap" : "")); + } + ++drawn; + } + Require(drawn != 0, "the draw covered no pixel"); + if ((mode == Mode::Table || mode == Mode::VertexTable) && !repeated) + Require(AgcDriver::Graphics::ImageTableBuilds() > tablesBefore, + std::string("the table draw's ") + (mode == Mode::Table ? "fragment" : "vertex") + " stage bound no image table"); + if (mode == Mode::Gds) Require(*gdsCounter != 0u, "the GDS append did not count the drawn lanes"); + if (mode == Mode::Storage) { + for (std::size_t channel = 0; channel < 4; ++channel) + Require(StorageMemory[channel] == Texel[channel], "storage texel (0, 0) channel " + std::to_string(channel) + " is " + + std::to_string(StorageMemory[channel]) + ", expected the sampled " + + std::to_string(Texel[channel]) + (heap ? " through the heap" : "")); + } + if (!heap || repeated) return; + if (mode == Mode::Vertex || mode == Mode::VertexTable) + Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, + "the heap did not take the sampling vertex stage with descriptor memory"); + else + Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, + std::string("the heap did not take the fragment stage") + TakenWhat(mode, buffer)); + Require(AgcDriver::Graphics::DataAddressPushes() > pushesBefore, + "the heap stages did not read their shader data through pushed addresses"); + if (mode == Mode::ConstantSampler || mode == Mode::BorderSampler || mode == Mode::WrapSampler) + Require(AgcDriver::Graphics::EmbeddedSamplerMappings() > embeddedBefore, "the fragment stage's constant sampler was not embedded in its pipeline"); + if (mode == Mode::MergedBlendOther) + Require(ShaderRecompiler::HeapTemplateCounts().entries == templatesBefore, + "merging into a second color target built another heap template instead of reusing the first target's"); +} + +void UnpreparedPairTakesTheHeap() { + using AgcDriver::Graphics::HeapExcluded; + using AgcDriver::Graphics::HeapExcludedCount; + using AgcDriver::Graphics::HeapStageReason; + using AgcDriver::Graphics::HeapStageReasons; + FreshVertexCode = SamplingVertexCode; + FreshPixelCode = InterpolantPixelCode; + for (std::size_t offset = 0; offset < TextureMemory.size(); offset += Texel.size()) + std::memcpy(TextureMemory.data() + offset, Texel.data(), Texel.size()); + Registered(VertexHeader, FreshVertexCode.data(), sizeof(FreshVertexCode), 2); + Registered(PixelHeader, FreshPixelCode.data(), sizeof(FreshPixelCode), 1); + const auto heapBefore = HeapStageReasons(HeapStageReason::Heap); + const auto takenBefore = AgcDriver::DriverDetail::HeapStagesTaken(); + const auto offHeapBefore = HeapStageReasons(HeapStageReason::Disabled) + HeapStageReasons(HeapStageReason::Excluded); + const auto excludedBefore = HeapExcludedCount(HeapExcluded::Draw); + ColorMemory.fill(Kept); + auto commands = Draw(FreshPixelCode.data(), Mode::Vertex, FreshVertexCode.data()); + SubmitUntilDrawn(commands, ColorMemory, "the unprepared pair's draw submission failed", [] {}); + std::size_t drawn = 0; + for (std::size_t offset = 0; offset < ColorMemory.size(); offset += 4) { + if (std::all_of(ColorMemory.begin() + static_cast(offset), + ColorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) + continue; + for (std::size_t channel = 0; channel < 4; ++channel) + Require(static_cast(ColorMemory[offset + channel]) == Texel[channel], + "the unprepared pair: pixel " + std::to_string(offset / 4) + " channel " + std::to_string(channel) + " is " + + std::to_string(static_cast(ColorMemory[offset + channel])) + ", expected " + std::to_string(Texel[channel])); + ++drawn; + } + Require(drawn != 0, "the unprepared pair's draw covered no pixel"); + Require(HeapStageReasons(HeapStageReason::Heap) - heapBefore >= 2u && AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, + "the first draw of an unprepared vertex and pixel pair did not put both stages on the heap"); + Require(HeapStageReasons(HeapStageReason::Disabled) + HeapStageReasons(HeapStageReason::Excluded) == offHeapBefore, + "a stage of the unprepared pair's first draw was decided off the heap"); + Require(HeapExcludedCount(HeapExcluded::Draw) == excludedBefore, "the unprepared pair's draw took the per-draw path"); +} + +void UnmappableStageFails() { + constexpr std::uint32_t Decorate = 4u << 16u | 71u; + ShaderRecompiler::RecompileResult result; + result.variantId = ~std::uint64_t{0} - 2u; + result.spirv = {0x07230203u, 0x00010000u, 0u, 2u, 0u, Decorate, 1u, 34u, 0u, Decorate, 1u, 33u, 4000u}; + try { + AgcDriver::DriverDetail::RequireHeapStageMappable(result); + } catch (const std::runtime_error& error) { + Require(std::string(error.what()).find("descriptor set 0 binding 4000") != std::string::npos, + std::string("an unmappable heap stage failed for another reason: ") + error.what()); + Require(!AgcDriver::DriverDetail::HeapStageFits(result), "an unmappable heap stage was reported as fitting"); + return; + } + Require(false, "a stage whose module keeps a binding the heap does not map was mapped onto the heap"); +} + +void OversizedStageFails() { + const auto capacity = AgcDriver::Graphics::BindlessHeap::ImageSlotCapacity(); + ShaderRecompiler::RecompileResult result; + result.variantId = ~std::uint64_t{0} - 1u; + result.bindings.push_back({ShaderRecompiler::DescriptorKind::SampledImage, ShaderRecompiler::DescriptorRole::GuestImages, 1u, 0u, capacity + 1u}); + try { + AgcDriver::DriverDetail::RequireHeapStageMappable(result); + } catch (const std::runtime_error& error) { + Require(std::string(error.what()).find("image slots") != std::string::npos, std::string("an oversized heap stage failed for another reason: ") + error.what()); + Require(!AgcDriver::DriverDetail::HeapStageFits(result), "an oversized heap stage was reported as fitting"); + return; + } + Require(false, "a stage needing more image slots than the heap holds was mapped onto the heap"); +} + +} + +int main() { + SetTestEnvironment("APS5_EAGER_WRITEBACK", "1"); + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + const bool excluded = std::getenv("APS5_GPU_HEAP_EXCLUDE") != nullptr; + const bool heapMode = AgcDriver::Graphics::GpuHeapEnabled(); + const bool heap = heapMode && !excluded; + if (heapMode && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; + { + GuestAllocations::Mutation mutation; + mutation.Add(StorageMemory.data(), StorageMemory.size(), true, true, true); + mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); + } + for (const auto mode : {Mode::Texture, Mode::Buffer, Mode::Storage, Mode::Gds, Mode::Vertex, Mode::Bda, Mode::Table, Mode::VertexTable, + Mode::MovedBuffer, Mode::MovedTexture, Mode::PixelLds, Mode::ConstantSampler, Mode::BorderSampler, Mode::WrapSampler, Mode::MergedBlend, Mode::MergedBlendOther, Mode::Texture}) + DrawSamplesTheTexture(heap, mode); + for (const auto mode : {Mode::Table, Mode::VertexTable}) DrawSamplesTheTexture(heap, mode, true); + const bool capped = heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr; + if (heap && !capped) UnpreparedPairTakesTheHeap(); + if (heap && AgcDriver::DriverDetail::AsyncDrawCompile() && ShaderRecompiler::HeapTemplateCounts().entries != 0u) + Require(AgcDriver::DriverDetail::HeapTemplatesBuiltInBackground() != 0u, "no heap draw waited for its template to be built in the background"); + if (heap) { + OversizedStageFails(); + UnmappableStageFails(); + const auto mark = AgcDriver::Graphics::PushDataMark(); + AgcDriver::Graphics::NoteCommandBufferBegun(VK_NULL_HANDLE); + Require(AgcDriver::Graphics::PushDataMark() != mark, "beginning a command buffer kept the push data recorded before it"); + } + if (excluded) + Require(AgcDriver::Graphics::HeapExcludedCount(AgcDriver::Graphics::HeapExcluded::Draw) != 0u, + "no draw took the per-draw path for its excluded heap class"); + if (capped) { + const auto totals = AgcDriver::Graphics::BindlessHeap::TotalStatistics(); + Require(totals.slotsEvicted + totals.samplersEvicted != 0u, "the capped heap evicted no image slot"); + } + AgcDriverShutdown_nid_postfix(); + if (heap && !capped) + Require(AgcDriver::Graphics::EmptyResourceSets() != 0, "no heap draw bound without a per-draw resource set"); + std::cout << "A sampled texture reached the drawn pixels" << (heap ? " through the heap" : "") << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp new file mode 100644 index 000000000000..19ea2cfb3863 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp @@ -0,0 +1,131 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "Recompiler.hpp" +#include "RuntimeAbi.hpp" +#include "HeapSampleKernel.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void Require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +constexpr std::uint32_t BorderClamp = 6u | (6u << 3u) | (6u << 6u); +constexpr std::uint32_t OpaqueWhiteBorder = 2u << 30u; + +alignas(256) constexpr std::array ConstantSamplerCode{ + 0xbe8803ffu, BorderClamp, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, OpaqueWhiteBorder, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +alignas(256) constexpr std::array WrapSamplerCode{ + 0xbe8803ffu, 0u, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, OpaqueWhiteBorder, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +alignas(256) constexpr std::array MirrorSamplerCode{ + 0xbe8803ffu, 1u | (1u << 3u) | (1u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, OpaqueWhiteBorder, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +alignas(256) constexpr std::array UserSamplerCode{0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +constexpr std::array White{0xffu, 0xffu, 0xffu, 0xffu}; + +alignas(256) std::array TextureMemory{}; +alignas(4096) std::array, 4> Outputs{}; + +ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, float* output, std::span code, bool userSampler) { + auto userData = SampleUserData(TextureMemory.data(), output); + if (userSampler) { + userData[8] = BorderClamp; + userData[11] = OpaqueWhiteBorder; + } + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{1u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; + ShaderRecompiler::RecompileRequest request{ + {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, + {32u, 0u, userData, compute, std::nullopt, std::nullopt, memory}, + device.ComputeTarget(32u), + {0u, 0u, 0u, 128u}}; + request.useCache = false; + return ShaderRecompiler::Recompile(request); +} + +std::size_t EmbeddedElements(const ShaderRecompiler::RecompileResult& result) { + std::size_t count = 0; + for (const auto& binding : result.bindings) { + if (binding.role != ShaderRecompiler::DescriptorRole::GuestSamplers) continue; + count += static_cast(std::ranges::count_if(binding.samplerEmbedded, [](std::uint32_t value) { return value != ShaderRecompiler::RuntimeAbi::NoEmbeddedSampler; })); + } + return count; +} + +bool DecoratesEmbeddedSet(const ShaderRecompiler::RecompileResult& result) { + const auto& spirv = result.spirv; + for (std::size_t at = 5u; at < spirv.size();) { + const auto count = spirv[at] >> 16u; + if (count == 0u) break; + if ((spirv[at] & 0xffffu) == 71u && count >= 4u && spirv[at + 2u] == 34u && spirv[at + 3u] == ShaderRecompiler::RuntimeAbi::EmbeddedSamplerSet) return true; + at += count; + } + return false; +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + const bool heap = AgcDriver::Graphics::GpuHeapEnabled(); + if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; + const bool embedding = heap; + FillTexels(TextureMemory, SampleTexel); + for (auto& output : Outputs) output.fill(-1.0f); + const auto constant = Compile(*device, Outputs[0].data(), ConstantSamplerCode, false); + const auto user = Compile(*device, Outputs[1].data(), UserSamplerCode, true); + const auto wrap = Compile(*device, Outputs[2].data(), WrapSamplerCode, false); + const auto mirror = Compile(*device, Outputs[3].data(), MirrorSamplerCode, false); + Require(constant.gpuResolvedImages == heap, "the constant-sampler stage is not in the expected mode"); + Require((EmbeddedElements(constant) != 0u) == embedding, embedding ? "a constant sampler was not embedded" : "a sampler was embedded outside heap mode"); + Require(DecoratesEmbeddedSet(constant) == embedding, "the stage's SPIR-V does not match its embedded samplers"); + Require(EmbeddedElements(user) == 0u && !DecoratesEmbeddedSet(user), "a sampler read from user data was embedded"); + Require((EmbeddedElements(wrap) != 0u) == embedding, "the wrapping constant sampler was not embedded like the clamping one"); + Require(!embedding || wrap.Identity() != constant.Identity(), + "two compute stages differing only in an embedded sampler share one pipeline identity"); + Require(!embedding || mirror.Identity() != wrap.Identity(), + "two compute stages whose embedded samplers differ only in their first word share one pipeline identity"); + const auto* existing = AgcDriver::Graphics::BindlessHeap::Existing(device->graphicsContext()); + const auto embeddedBefore = existing != nullptr ? existing->EmbeddedSamplerCount() : 0u; + device->Dispatch(constant, 1u, 1u, 1u, {}, reinterpret_cast(ConstantSamplerCode.data())); + device->Dispatch(user, 1u, 1u, 1u, {}, reinterpret_cast(UserSamplerCode.data())); + device->Dispatch(wrap, 1u, 1u, 1u, {}, reinterpret_cast(WrapSamplerCode.data())); + device->Dispatch(mirror, 1u, 1u, 1u, {}, reinterpret_cast(MirrorSamplerCode.data())); + device->WaitIdle(); + RequireSampled(Outputs[0].data(), White, "the constant sampler's opaque white border", heap); + RequireSampled(Outputs[1].data(), White, "the user-data sampler's opaque white border", heap); + RequireSampled(Outputs[2].data(), SampleTexel, "the wrapping constant sampler's texel", heap); + RequireSampled(Outputs[3].data(), SampleTexel, "the mirroring constant sampler's texel", heap); + if (embedding) { + const char* capText = std::getenv("APS5_EMBEDDED_SAMPLER_CAP"); + const bool capped = capText != nullptr; + const auto cap = capped ? static_cast(std::strtoul(capText, nullptr, 10)) : ~0u; + const auto* heapObject = AgcDriver::Graphics::BindlessHeap::Existing(device->graphicsContext()); + Require(heapObject != nullptr, "the heap dispatch left no descriptor heap"); + const auto count = heapObject->EmbeddedSamplerCount(); + Require(count <= cap, "a capped device embedded a sampler past its limit"); + Require(cap == 0u || count > embeddedBefore, "the pipeline did not embed the constant sampler"); + } + const bool capped = std::getenv("APS5_EMBEDDED_SAMPLER_CAP") != nullptr; + std::cout << "constant samplers sampled " << (!embedding ? "through descriptors" : capped ? "from sampler heap slots past the embedded sampler limit" : "as embedded samplers") << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapFinisherQueuedWrite.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapFinisherQueuedWrite.cpp new file mode 100644 index 000000000000..6dfaaeffa396 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapFinisherQueuedWrite.cpp @@ -0,0 +1,141 @@ +#include "HeapStageSettled.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; +using namespace ShaderRecompiler; + +constexpr std::uint32_t Entries = 1024; +constexpr std::size_t BlockBytes = 65536; +constexpr std::array Code{0xbf068002u, 0xbf850013u, 0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x7e200500u, 0x93109010u, + 0xf4200406u, 0x20000004u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0xf09c0f08u, 0x00450000u, 0xe0700000u, 0x80070000u, 0xbf810000u, 0xbf800000u}; +alignas(256) std::array, 3> Textures{}; +alignas(256) std::array Output{}; +alignas(256) std::array Srt{}; + +std::array Buffer(const void* pointer, std::uint32_t stride, std::uint32_t records) { + const auto address = reinterpret_cast(pointer); + return {static_cast(address), static_cast(address >> 32u) | (stride << 16u), records, stride == 0u ? 0x31016facu : 0x01016facu}; +} + +std::array Texture(std::uint32_t texture) { + const auto address = reinterpret_cast(Textures[texture].data()); + return {static_cast(address >> 8u), static_cast(address >> 40u) | ((texture == 1u ? 22u : 20u) << 20u) | (3u << 30u), 7u, 0x90000facu, 0u, 0u, 0u, 0u}; +} + +std::uint8_t* WatchedPages(std::size_t bytes) { +#ifdef _WIN32 + auto* data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, BlockBytes)); + Require(data != nullptr, "heap finisher queued write: cannot allocate the table pages"); + GuestArena::GuestArenaCommit_nid_postfix(data, bytes, PAGE_READWRITE, bytes); + return data; +#else + void* mapped = mmap(nullptr, bytes + BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(mapped != MAP_FAILED, "heap finisher queued write: cannot map the table pages"); + auto* data = reinterpret_cast((reinterpret_cast(mapped) + BlockBytes - 1u) & ~std::uintptr_t{BlockBytes - 1u}); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, bytes); + return data; +#endif +} + +void Run(AgcDriver::VulkanDevice& device) { + using namespace AgcDriver::DriverDetail; + constexpr std::size_t TableBytes = BlockBytes; + auto* base = WatchedPages(TableBytes * 2u); + auto* table = reinterpret_cast(base); + auto* material = reinterpret_cast(base + TableBytes); + for (std::uint32_t entry = 0; entry < Entries; ++entry) { + const auto descriptor = Texture(entry % 2u); + std::copy(descriptor.begin(), descriptor.end(), table + entry * 8u); + material[entry * 4u + 1u] = entry; + } + const auto tableBuffer = Buffer(table, 32u, Entries); + const auto materialBuffer = Buffer(material, 16u, Entries); + const auto output = Buffer(Output.data(), 0u, 256u); + std::copy(tableBuffer.begin(), tableBuffer.end(), Srt.begin()); + std::copy(materialBuffer.begin(), materialBuffer.end(), Srt.begin() + 8u); + std::copy(output.begin(), output.end(), Srt.begin() + 12u); + const auto srtAddress = reinterpret_cast(Srt.data()); + const std::vector userData{static_cast(srtAddress), static_cast(srtAddress >> 32u), 1u}; + const std::array regions{MemoryRegion{reinterpret_cast(Code.data()), std::as_bytes(std::span(Code))}}; + const ShaderComputeStageInfo compute{{std::min(32u, device.Target().subgroupSize), 1u, 1u}, 0u, {false, false, false}, false, 1u}; + auto target = device.Target(); + target.gpuResolvedImages = true; + std::vector prepared(regions.begin(), regions.end()); + RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(Code.data()), Code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, prepared}, target, {0u, 0u, 0u, 128u}}; + const auto handle = PrepareShader(request); + const auto invocation = PreparedShaderInvocation::TryCreate(request, handle); + Require(invocation.has_value(), "heap finisher queued write: the prepared table shader refused its own request"); + const auto walk = [&] { return MaterializeHeapStageSettled(*invocation, userData, regions, request.shader.codeAddress); }; + + const auto settled = walk(); + Require(settled.result != nullptr && settled.reads.complete, "heap finisher queued write: the heap walk declined the table stage with nothing queued"); + + const auto tableBegin = reinterpret_cast(table); + std::promise release; + const auto released = release.get_future().share(); + DrawPipeline::Queue0().Enqueue([released] { released.wait(); }, {{tableBegin + 5u * 8u * sizeof(std::uint32_t), tableBegin + 6u * 8u * sizeof(std::uint32_t)}}); + Require(DrawPipeline::Queue0().OverlapsAny(std::array{std::pair{tableBegin, tableBegin + TableBytes}}), "heap finisher queued write: the queued descriptor table write is not listed"); + + HeapStageMaterialized onFinisher; + bool ranOnFinisher = false; + std::exception_ptr failure; + DrawFinisher::Get().Enqueue([&] { + ranOnFinisher = DrawFinisher::OnFinisherThread(); + try { + onFinisher = walk(); + } catch (...) { + failure = std::current_exception(); + } + }); + DrawFinisher::Get().Drain(); + release.set_value(); + DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet); + if (failure != nullptr) std::rethrow_exception(failure); + Require(ranOnFinisher, "heap finisher queued write: the walk did not run on the finisher thread"); + Require(onFinisher.result == nullptr, "heap finisher queued write: a finisher walk read a descriptor table that a queued write overlaps"); + + const auto after = walk(); + Require(after.result != nullptr && after.reads.complete, "heap finisher queued write: the heap walk declined the table stage once the write retired"); +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) return VulkanTestSkipped; + Run(*device); + std::cout << "heap finisher queued write tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp new file mode 100644 index 000000000000..a81a54749de9 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp @@ -0,0 +1,324 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, + 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BufferPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array SamplingVertexCode{ + 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, + 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, + 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array TableVertexCode{ + 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, + 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, + 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array SrtPixelCode{ + 0xf40c0506u, 0xfa000000u, 0xf40c0706u, 0xfa000020u, 0xbf8cc07fu, 0xf420090au, 0xfa000000u, 0xf420094cu, + 0xfa000000u, 0xf420098eu, 0xfa000000u, 0xf42009d0u, 0xfa000000u, 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, + 0x00400000u, 0xbf8c0000u, 0x06060624u, 0x06060625u, 0x06060626u, 0x06060627u, 0xf800180fu, 0x03020100u, + 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array SrtVertexCode{ + 0xf40c0504u, 0xfa000000u, 0xf40c0704u, 0xfa000020u, 0xbf8cc07fu, 0xf420090au, 0xfa000000u, 0xf420094cu, + 0xfa000000u, 0xf420098eu, 0xfa000000u, 0xf42009d0u, 0xfa000000u, 0xbf8cc07fu, 0x7e000d05u, 0x080200f4u, + 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, + 0x06060624u, 0x06060625u, 0x06060626u, 0x06060627u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u}; +constexpr float BufferAlpha = 0.2f; +alignas(4096) std::array BufferMemory{}; +alignas(256) std::array ColorMemory{}; + +std::span MergedTarget(std::size_t index) { + constexpr std::size_t Bytes = 65536; + static std::array data{}; + if (data.at(index) == nullptr) data[index] = [] { + std::byte* block = nullptr; + const bool watched = AgcDriver::GuestMemory::WriteWatched(); +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); + GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); +#else + void* raw = mmap(nullptr, 2u * Bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the merged color target"); + const auto begin = reinterpret_cast(raw); + block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); +#endif + Require(!watched || AgcDriver::GuestMemory::Watched(reinterpret_cast(block), Bytes), "the merged color target is not write-watched"); + GuestAllocations::Mutation mutation; + mutation.Add(block, Bytes, true, true, true); + return block; + }(); + return {data[index], ColorMemory.size()}; +} + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; + +void Registered(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); +} + +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); +} + +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler, BorderSampler, WrapSampler, MergedBlend, MergedBlendOther }; + +const std::uint32_t* VertexProgram(Mode mode) { + if (mode == Mode::VertexTable) return TableVertexCode.data(); + if (mode == Mode::Vertex) return SamplingVertexCode.data(); + return VertexCode.data(); +} + +std::array ImageDescriptor(const void* memory) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; +} + +std::array BufferDescriptor(const void* memory, std::size_t bytes) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), static_cast(bytes), + 0xfacu}; +} + + +constexpr std::size_t Textures = 16; +constexpr std::size_t Buffers = 32; +constexpr std::size_t SrtTables = 256; +alignas(256) std::array, Textures> BenchTextures{}; +alignas(4096) std::array, SrtTables> SrtTableMemory{}; + +void FillSrtTables(std::size_t salt = 0) { + for (std::size_t table = 0; table < SrtTables; ++table) + for (std::size_t entry = 0; entry < 4u; ++entry) { + const auto slice = 1u + (table * 5u + entry * 11u + salt) % Buffers; + const auto descriptor = BufferDescriptor(BufferMemory.data() + slice, sizeof(BufferMemory) - slice * sizeof(float)); + std::copy(descriptor.begin(), descriptor.end(), SrtTableMemory[table].begin() + static_cast(entry * 4u)); + } +} + +std::vector Frame(std::size_t draws, std::size_t salt, bool srt) { + const auto color = reinterpret_cast(MergedTarget(0).data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {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}, + {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}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x292, 2}, + }; + + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + const auto vertex = reinterpret_cast(srt ? SrtVertexCode.data() : VertexCode.data()); + Append(commands, 0x76, {0xc8, static_cast(vertex >> 8u)}); + Append(commands, 0x76, {0xc9, static_cast(vertex >> 40u)}); + Append(commands, 0x76, {0x8b, (srt ? 2u : 1u) << 1u}); + Append(commands, 0x76, {0x8c, 0}); + for (std::size_t draw = 0; draw < draws; ++draw) { + const bool buffer = !srt && draw % 2u == 1u; + const auto pixel = reinterpret_cast(srt ? SrtPixelCode.data() : buffer ? BufferPixelCode.data() : PixelCode.data()); + std::array words{}; + const auto image = ImageDescriptor(BenchTextures[(draw + salt) % Textures].data()); + std::copy(image.begin(), image.end(), words.begin()); + const auto slice = 1u + (draw * 7u + salt) % Buffers; + const auto descriptor = BufferDescriptor(BufferMemory.data() + slice, sizeof(BufferMemory) - slice * sizeof(float)); + std::copy(descriptor.begin(), descriptor.end(), words.begin() + 12); + if (srt) { + const auto table = reinterpret_cast(SrtTableMemory[(draw + salt) % SrtTables].data()); + words[12] = static_cast(table); + words[13] = static_cast(static_cast(table) >> 32u); + const auto vertexTable = reinterpret_cast(SrtTableMemory[((draw + salt) * 3u + 1u) % SrtTables].data()); + Append(commands, 0x76, {0x8c, static_cast(vertexTable)}); + Append(commands, 0x76, {0x8d, static_cast(static_cast(vertexTable) >> 32u)}); + } + const std::uint32_t userWords = srt ? 14u : buffer ? 16u : 12u; + Append(commands, 0x76, {0x008, static_cast(pixel >> 8u)}); + Append(commands, 0x76, {0x009, static_cast(pixel >> 40u)}); + Append(commands, 0x76, {0x00b, userWords << 1u}); + for (std::uint32_t index = 0; index < userWords; ++index) Append(commands, 0x76, {0x00cu + index, words[index]}); + Append(commands, 0x2d, {3, 2}); + } + return commands; +} + +} + +int main() { + SetTestEnvironment("APS5_NO_DRAW_RECIPE", "1"); + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + const bool heap = AgcDriver::Graphics::GpuHeapEnabled(); + constexpr std::size_t Draws = 256, Rounds = 8; + { + GuestAllocations::Mutation mutation; + mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); + mutation.Add(SrtTableMemory.data(), sizeof(SrtTableMemory), true, true, true); + } + FillSrtTables(); + for (auto& texture : BenchTextures) + for (std::size_t offset = 0; offset < texture.size(); offset += Texel.size()) std::memcpy(texture.data() + offset, Texel.data(), Texel.size()); + BufferMemory.fill(BufferAlpha); + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + static Header TexturePixel{}, BufferPixel{}; + Registered(TexturePixel, PixelCode.data(), sizeof(PixelCode), 1); + Registered(BufferPixel, BufferPixelCode.data(), sizeof(BufferPixelCode), 1); + static Header SrtPixel{}, SrtVertex{}; + Registered(SrtPixel, SrtPixelCode.data(), sizeof(SrtPixelCode), 1); + Registered(SrtVertex, SrtVertexCode.data(), sizeof(SrtVertexCode), 2); + std::uint64_t keysBefore = 0, keysBuilt = 0, setsBefore = 0; + for (std::size_t round = 0; round < Rounds; ++round) { + if (round == 2) keysBefore = AgcDriver::Graphics::DrawContentKeysBuilt(); + if (round == 4) { + keysBuilt = AgcDriver::Graphics::DrawContentKeysBuilt() - keysBefore; + setsBefore = AgcDriver::Graphics::DescriptorCache::RewrittenSets(); + } + auto commands = Frame(Draws, round, true); + if (round >= 4) FillSrtTables(round); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + } + const auto built = keysBuilt; + const auto repeated = 2u * Draws; + const auto sets = AgcDriver::Graphics::DescriptorCache::RewrittenSets() - setsBefore; + const bool heapDraws = heap && AgcDriver::Graphics::DescriptorHeapEnabled(); + Require(heapDraws || sets != 0, "walked draws without the heap allocated no rewritten descriptor sets, so they did not relocate"); + if (heapDraws) + Require(sets == 0, "walked heap draws allocated " + std::to_string(sets) + " rewritten descriptor sets that a descriptor heap pipeline never binds"); + std::printf("walked draws allocated %llu rewritten descriptor sets\n", static_cast(sets)); + if (heap && AgcDriver::Graphics::DescriptorHeapEnabled()) + { + if (std::getenv("APS5_NO_MOVED_BUFFER_TEMPLATES") != nullptr) + Require(built * 2u >= repeated, "with moved-buffer templates off, repeated heap draws built only " + std::to_string(built) + " content keys over " + std::to_string(repeated) + " draws, so a ring stage's key was shared across draws that carry different ShaderData words"); + else if (std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) + Require(built * 8u < repeated, "repeated heap draws built " + std::to_string(built) + " resource-cache content keys over " + std::to_string(repeated) + " draws instead of reusing their stages' keys"); + } + std::printf("repeated draws built %llu content keys over %zu draws\n", static_cast(built), repeated); + AgcDriverShutdown_nid_postfix(); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapSampleKernel.hpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapSampleKernel.hpp new file mode 100644 index 000000000000..f256baf2b6c6 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapSampleKernel.hpp @@ -0,0 +1,69 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_TESTS_EXECUTION_HEAPSAMPLEKERNEL_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_TESTS_EXECUTION_HEAPSAMPLEKERNEL_HPP + +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +alignas(256) inline constexpr std::array SampleCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +inline constexpr std::array SampleTexel{0x10u, 0x80u, 0xc0u, 0xffu}; + +inline std::array SampleUserData(const void* image, const float* output) { + const auto imageAddress = static_cast(reinterpret_cast(image)); + const auto outputAddress = static_cast(reinterpret_cast(output)); + return {static_cast(imageAddress >> 8u), + static_cast((imageAddress >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u, + 0u, + 0u, + 0u, + 0u, + static_cast(outputAddress), + static_cast(outputAddress >> 32u) & 0xffffu, + static_cast(4u * sizeof(float)), + 0x31016facu}; +} + +inline void FillTexels(std::span memory, const std::array& texel) { + for (std::size_t offset = 0; offset < memory.size(); offset += texel.size()) std::memcpy(memory.data() + offset, texel.data(), texel.size()); +} + +inline void RequireSampled(const float* output, const std::array& expected, const std::string& what, bool heap = false) { + for (std::size_t channel = 0; channel < 4; ++channel) { + const float wanted = static_cast(expected[channel]) / 255.0f; + if (!(std::fabs(output[channel] - wanted) < 1e-6f)) + throw std::runtime_error(what + ": channel " + std::to_string(channel) + " is " + std::to_string(output[channel]) + ", expected " + + std::to_string(wanted) + (heap ? " through the heap" : "")); + } +} + +inline ShaderRecompiler::RecompileResult CompileSampleKernel(AgcDriver::VulkanDevice& device, const void* image, const float* output, + bool useCache = true, std::span code = SampleCode, + std::uint32_t ldsDwords = 0u) { + const auto userData = SampleUserData(image, output); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{1u, 1u, 1u}, ldsDwords, {false, false, false}, false, 1u}; + ShaderRecompiler::RecompileRequest request{ + {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, + {32u, 0u, userData, compute, std::nullopt, std::nullopt, memory}, + device.ComputeTarget(32u), + {0u, 0u, 0u, 128u}}; + request.useCache = useCache; + return ShaderRecompiler::Recompile(request); +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapStageSettled.hpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapStageSettled.hpp new file mode 100644 index 000000000000..087c60c1b1b1 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapStageSettled.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" + +#include +#include + +inline AgcDriver::DriverDetail::HeapStageMaterialized MaterializeHeapStageSettled(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + ShaderRecompiler::MemoryRegionView memory, std::uint64_t shaderBase) { + for (;;) { + try { + return AgcDriver::DriverDetail::MaterializeHeapStage(invocation, userData, memory, shaderBase); + } catch (const AgcDriver::DriverDetail::DrawCompilePending&) { + AgcDriver::DriverDetail::AwaitLibraryPrebuilds(); + } + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp new file mode 100644 index 000000000000..fdfb11756340 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp @@ -0,0 +1,277 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Recompiler.hpp" +#include "RuntimeAbi.hpp" +#include "ImageTableAbi.hpp" +#include "VulkanTestDevice.hpp" +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver { + +struct VulkanDeviceTestAccess { + static Graphics::Context ContextOf(const VulkanDevice& device) { return device.graphicsContext(); } +}; + +} + +namespace { + +using AgcDriver::Graphics::CompiledShader; +using AgcDriver::Graphics::Require; +using AgcDriver::Graphics::ShaderResources; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Lanes = 64; +constexpr std::uint32_t Textures = 4; +constexpr std::uint32_t Stride = 32; +constexpr std::size_t SurfaceBytes = 256; +constexpr std::uint32_t Format8888UNorm = 56; +constexpr std::uint32_t Type2D = 9; +constexpr std::size_t SrtOffset = 4096; +constexpr std::size_t InputOffset = 8192; +constexpr std::size_t OutputOffset = 12288; +constexpr std::size_t HeapOffset = 65536; +constexpr std::size_t BlockBytes = (HeapOffset + std::size_t{Textures} * Stride + 65535u) & ~std::size_t{65535}; +constexpr std::size_t SurfaceBlockBytes = (std::size_t{Textures} * SurfaceBytes + 65535u) & ~std::size_t{65535}; + +constexpr std::array Code{ + 0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, + 0x34080082u, 0x7e200500u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0xbf8cc07fu, + 0xe0301000u, 0x80030504u, 0xf09c0f08u, 0x00450000u, 0xbf8c3f70u, 0x4a000105u, + 0xe0701000u, 0x80070004u, 0xbf810000u, 0u, 0u}; + +class GuestBlock { +public: + GuestBlock(std::size_t bytes, bool gpu) { +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, 65536)); + if (block != nullptr) GuestArena::GuestArenaCommit_nid_postfix(block, bytes, PAGE_READWRITE, bytes); +#else + constexpr std::uintptr_t alignment = 65536; + void* mapped = mmap(nullptr, bytes + alignment, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (mapped != MAP_FAILED) { + const auto begin = reinterpret_cast(mapped); + const auto aligned = (begin + alignment - 1) & ~(alignment - 1); + if (aligned != begin) munmap(mapped, aligned - begin); + if (aligned + bytes != begin + bytes + alignment) munmap(reinterpret_cast(aligned + bytes), begin + alignment - aligned); + block = reinterpret_cast(aligned); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, bytes); + } +#endif + Require(block != nullptr, "heap table stage reuse: cannot allocate a guest block"); + std::memset(block, 0, bytes); + GuestAllocations::Mutation().Add(block, bytes, true, true, gpu); + AgcDriver::GuestMemory::CollectWritesUncached(reinterpret_cast(block), bytes); + } + + GuestBlock(const GuestBlock&) = delete; + GuestBlock& operator=(const GuestBlock&) = delete; + + std::uint64_t At(std::size_t offset) const { return reinterpret_cast(block + offset); } + std::uint8_t* Bytes(std::size_t offset) const { return block + offset; } + std::uint32_t* Words(std::size_t offset) const { return reinterpret_cast(block + offset); } + +private: + std::uint8_t* block = nullptr; +}; + +std::array BufferDescriptor(std::uint64_t address, std::uint32_t stride, std::uint32_t records) { + return {static_cast(address), static_cast((address >> 32u) & 0xffffu) | (stride << 16u), records, stride == 0u ? 0x31016facu : 0x01016facu}; +} + +void Prepare(const GuestBlock& block, const GuestBlock& surfaces) { + std::memcpy(block.Words(0), Code.data(), sizeof(Code)); + for (std::uint32_t texture = 0; texture < Textures; ++texture) { + const auto offset = static_cast(texture) * SurfaceBytes; + std::memset(surfaces.Bytes(offset), static_cast(texture & 0xffu), SurfaceBytes); + const auto surface = surfaces.At(offset); + const std::array words{static_cast(surface >> 8u), static_cast((surface >> 40u) & 0xffu) | (Format8888UNorm << 20u) | (3u << 30u), 1u | (7u << 14u), 0xfacu | (Type2D << 28u), 0u, 0u, 0u, 0u}; + std::memcpy(block.Words(HeapOffset + static_cast(texture) * Stride), words.data(), sizeof(words)); + } + auto* srt = block.Words(SrtOffset); + const auto heap = BufferDescriptor(block.At(HeapOffset), Stride, Textures); + const auto input = BufferDescriptor(block.At(InputOffset), 0u, Lanes * 4u); + const auto output = BufferDescriptor(block.At(OutputOffset), 0u, Lanes * 4u); + std::copy(heap.begin(), heap.end(), srt); + std::copy(input.begin(), input.end(), srt + 8); + std::copy(output.begin(), output.end(), srt + 12); + AgcDriver::GuestMemory::CollectWritesUncached(block.At(0), BlockBytes); + AgcDriver::GuestMemory::CollectWritesUncached(surfaces.At(0), SurfaceBlockBytes); +} + +ShaderRecompiler::RecompileResult Compile(const AgcDriver::VulkanDevice& device, const GuestBlock& block, std::optional withoutCapability = std::nullopt) { + const auto srt = block.At(SrtOffset); + const std::array userData{static_cast(srt), static_cast(srt >> 32u)}; + const std::span code(block.Words(0), Code.size()); + const std::array memory{{ + {block.At(0), std::as_bytes(code)}, + {srt, std::as_bytes(std::span(block.Words(SrtOffset), 64))}, + {block.At(HeapOffset), std::as_bytes(std::span(block.Words(HeapOffset), static_cast(Textures) * Stride / 4u))}, + }}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Lanes, 1, 1}, 0u, {false, false, false}, false, 1}; + auto target = device.ComputeTarget(Lanes); + std::vector capabilities(target.supportedCapabilities.begin(), target.supportedCapabilities.end()); + if (withoutCapability) capabilities.erase(std::remove(capabilities.begin(), capabilities.end(), *withoutCapability), capabilities.end()); + target.supportedCapabilities = capabilities; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, block.At(0), code, 0, {}}, + {Lanes, 0, userData, compute, std::nullopt, std::nullopt, memory}, + target, + {0, 0, 0, 128} + }; + if (withoutCapability) request.useCache = false; + return ShaderRecompiler::Recompile(request); +} + +void RequireHeapTable(const ShaderRecompiler::RecompileResult& result) { + const auto has = [&](ShaderRecompiler::DescriptorRole role) { + return std::any_of(result.bindings.begin(), result.bindings.end(), [&](const auto& binding) { return binding.role == role; }); + }; + Require(result.gpuResolvedImages && result.dataAddressPush, "heap table stage reuse: the program is not in the heap's GPU-resolved form"); + Require(has(ShaderRecompiler::DescriptorRole::ImageTable) && has(ShaderRecompiler::DescriptorRole::ImageTableMap), "heap table stage reuse: the program does not bind an image table and its map"); +} + +std::uint64_t TableMapRoot(const ShaderResources& resources, const CompiledShader& shader) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + std::array bytes{}; + const auto placements = AgcDriver::Graphics::PushDataPlacements(std::span(&shader, 1)); + resources.PatchDataAddresses(bytes, std::span(&shader, 1), placements, nullptr); + std::uint64_t value = 0; + const auto position = placements.front().Item(Abi::RootItem::TableMap); + Require(position != Abi::NoPushPosition, "heap table stage reuse: the stage's push layout holds no table map"); + std::memcpy(&value, bytes.data() + position * sizeof(std::uint32_t), sizeof(value)); + return value; +} + +void RefreshAfterOriginalDestroyed(const AgcDriver::VulkanDevice& device, const GuestBlock& block, bool sameAddress) { + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + const char* what = sameAddress ? "an equal-content program at the destroyed program's address" : "an equal-content program at another address"; + std::optional slot; + slot.emplace(Compile(device, block)); + RequireHeapTable(*slot); + const auto* original = &*slot; + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(AgcDriver::Graphics::BindlessHeap::For(context).Allocate(64)); + const CompiledShader built{ShaderStage::Compute, original, 0}; + auto resources = std::make_shared(context, built); + Require(resources->HeapStage(), "heap table stage reuse: the set was not built on the heap"); + const auto builtMap = TableMapRoot(*resources, built); + Require(builtMap != 0u, "heap table stage reuse: the build left the table map unset"); + const auto bindingBytes = slot->bindings.capacity() * sizeof(ShaderRecompiler::DescriptorBinding); + std::optional other; + std::vector> squatters; + if (sameAddress) { + slot.reset(); + for (int i = 0; i < 16; ++i) { + squatters.push_back(std::make_unique(bindingBytes)); + std::memset(squatters.back().get(), 0xff, bindingBytes); + } + slot.emplace(Compile(device, block)); + Require(&*slot == original, "heap table stage reuse: the reused slot moved"); + } else { + other.emplace(Compile(device, block)); + slot.reset(); + } + const auto& current = sameAddress ? *slot : *other; + RequireHeapTable(current); + const CompiledShader shader{ShaderStage::Compute, ¤t, 0}; + resources->RefreshHeapStage(std::span(&shader, 1)); + const auto refreshed = TableMapRoot(*resources, shader); + Require(refreshed != 0u, std::string("heap table stage reuse: refreshing for ") + what + " left the table map unset"); + Require(refreshed == builtMap, std::string("heap table stage reuse: refreshing for ") + what + " wrote a table map that differs from the build's"); + std::printf("the heap table map refreshed for %s\n", what); +} + +void RefreshAfterSlotReleased(const AgcDriver::VulkanDevice& device, const GuestBlock& block) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + namespace TableAbi = ShaderRecompiler::ImageTableAbi; + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + const auto program = Compile(device, block); + RequireHeapTable(program); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + const CompiledShader shader{ShaderStage::Compute, &program, 0}; + auto resources = std::make_shared(context, shader); + Require(resources->HeapStage(), "heap table slot release: the set was not built on the heap"); + auto& heap = AgcDriver::Graphics::BindlessHeap::For(context); + const auto sampledSlot = [&](std::uint64_t root) -> std::pair { + const auto header = heap.DataWords(root, TableAbi::HeaderElementBase + 1u); + const auto base = header[TableAbi::HeaderElementBase]; + const auto slot = heap.DataWords(root, base + 1u)[base]; + return {slot, heap.SlotTexture(Abi::FirstImageBinding, slot)}; + }; + const auto [slot, texture] = sampledSlot(TableMapRoot(*resources, shader)); + Require(texture != nullptr, "heap table slot release: the table's first element holds no texture"); + heap.ReleaseSlots(texture); + Require(heap.SlotTexture(Abi::FirstImageBinding, slot) == nullptr, "heap table slot release: releasing the texture's slots left its slot held"); + resources->RefreshHeapStage(std::span(&shader, 1)); + const auto [refreshedSlot, refreshedTexture] = sampledSlot(TableMapRoot(*resources, shader)); + Require(refreshedTexture == texture, "heap table slot release: after the texture's slot was released the stage's table map still names slot " + std::to_string(refreshedSlot) + ", which no longer holds the texture"); + std::puts("the heap table map was rebuilt after its texture's slot was released"); +} + +void SamplerHeapNeedsDynamicIndexing(const AgcDriver::VulkanDevice& device, const GuestBlock& block) { + const auto supported = Compile(device, block); + RequireHeapTable(supported); + std::string failure; + try { + static_cast(Compile(device, block, spv::CapabilitySampledImageArrayDynamicIndexing)); + } catch (const std::runtime_error& error) { + failure = error.what(); + } + Require(failure.find("the sampler heap needs sampler array dynamic indexing") != std::string::npos && failure.find("binding_kind=57") != std::string::npos, + "heap table stage reuse: a device without sampled image array dynamic indexing did not fail naming the sampler heap: " + failure); + std::puts("a sampler heap on a device without dynamic indexing failed at emission"); +} + +} + +int main() { + SetTestEnvironment("APS5_GPU_HEAP", "1"); + SetTestEnvironment("APS5_VERIFY_GPU_HEAP", "1"); + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + GuestBlock block(BlockBytes, true); + GuestBlock surfaces(SurfaceBlockBytes, false); + Prepare(block, surfaces); + RefreshAfterOriginalDestroyed(*device, block, false); + RefreshAfterOriginalDestroyed(*device, block, true); + RefreshAfterSlotReleased(*device, block); + SamplerHeapNeedsDynamicIndexing(*device, block); + std::puts("heap table stage reuse tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp new file mode 100644 index 000000000000..a08c791c8001 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp @@ -0,0 +1,175 @@ +#include "HeapStageSettled.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Optimization/ResourceMaterializer.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; +using namespace ShaderRecompiler; + +constexpr std::uint32_t Entries = 1024; +constexpr std::size_t BlockBytes = 65536; +constexpr std::array Code{0xbf068002u, 0xbf850013u, 0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x7e200500u, 0x93109010u, + 0xf4200406u, 0x20000004u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0xf09c0f08u, 0x00450000u, 0xe0700000u, 0x80070000u, 0xbf810000u, 0xbf800000u}; +alignas(256) std::array, 3> Textures{}; +alignas(256) std::array Output{}; +alignas(256) std::array Srt{}; + +std::array Buffer(const void* pointer, std::uint32_t stride, std::uint32_t records) { + const auto address = reinterpret_cast(pointer); + return {static_cast(address), static_cast(address >> 32u) | (stride << 16u), records, stride == 0u ? 0x31016facu : 0x01016facu}; +} + +std::array Texture(std::uint32_t texture) { + const auto address = reinterpret_cast(Textures[texture].data()); + return {static_cast(address >> 8u), static_cast(address >> 40u) | ((texture == 1u ? 22u : 20u) << 20u) | (3u << 30u), 7u, 0x90000facu, 0u, 0u, 0u, 0u}; +} + +std::uint8_t* WatchedPages(std::size_t bytes) { +#ifdef _WIN32 + auto* data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, BlockBytes)); + Require(data != nullptr, "heap table walk reuse: cannot allocate the table pages"); + GuestArena::GuestArenaCommit_nid_postfix(data, bytes, PAGE_READWRITE, bytes); + return data; +#else + void* mapped = mmap(nullptr, bytes + BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(mapped != MAP_FAILED, "heap table walk reuse: cannot map the table pages"); + auto* data = reinterpret_cast((reinterpret_cast(mapped) + BlockBytes - 1u) & ~std::uintptr_t{BlockBytes - 1u}); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, bytes); + return data; +#endif +} + +const std::byte* NoAccessPage() { +#ifdef _WIN32 + void* page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS); + Require(page != nullptr, "heap table walk reuse: cannot reserve a no-access page"); +#else + void* page = mmap(nullptr, 4096, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(page != MAP_FAILED, "heap table walk reuse: cannot map a no-access page"); +#endif + return static_cast(page); +} + +std::vector> Descriptors(const RecompileResult& result) { + std::vector> descriptors; + for (const auto& binding : result.bindings) descriptors.push_back(binding.guestDescriptor); + return descriptors; +} + +std::vector> StageDescriptors(const AgcDriver::DriverDetail::HeapStageMaterialized& stage) { + if (stage.words != nullptr && stage.result->heapTemplateId != 0u) return Descriptors(*AgcDriver::DriverDetail::PatchedHeapResult(*stage.result, *stage.words)); + return Descriptors(*stage.result); +} + +std::uint32_t RecordedWord(const AgcDriver::DriverDetail::HeapStageMaterialized& stage, std::uint64_t address) { + std::size_t cursor = 0; + for (const auto& [begin, end] : *stage.reads.ranges) { + if (address >= begin && address < end) return (*stage.reads.values)[cursor + static_cast((address - begin) / sizeof(std::uint32_t))]; + cursor += static_cast((end - begin) / sizeof(std::uint32_t)); + } + throw std::runtime_error("heap table walk reuse: the walk did not record the table word"); +} + +void Run(AgcDriver::VulkanDevice& device) { + constexpr std::size_t TableBytes = BlockBytes; + auto* base = WatchedPages(TableBytes * 2u); + auto* table = reinterpret_cast(base); + auto* material = reinterpret_cast(base + TableBytes); + for (std::uint32_t entry = 0; entry < Entries; ++entry) { + const auto descriptor = Texture(entry % 2u); + std::copy(descriptor.begin(), descriptor.end(), table + entry * 8u); + material[entry * 4u + 1u] = entry; + } + const auto tableBuffer = Buffer(table, 32u, Entries); + const auto materialBuffer = Buffer(material, 16u, Entries); + const auto output = Buffer(Output.data(), 0u, 256u); + std::copy(tableBuffer.begin(), tableBuffer.end(), Srt.begin()); + std::copy(materialBuffer.begin(), materialBuffer.end(), Srt.begin() + 8u); + std::copy(output.begin(), output.end(), Srt.begin() + 12u); + const auto srtAddress = reinterpret_cast(Srt.data()); + const std::vector userData{static_cast(srtAddress), static_cast(srtAddress >> 32u), 1u}; + const std::array regions{MemoryRegion{reinterpret_cast(Code.data()), std::as_bytes(std::span(Code))}}; + const ShaderComputeStageInfo compute{{std::min(32u, device.Target().subgroupSize), 1u, 1u}, 0u, {false, false, false}, false, 1u}; + auto target = device.Target(); + target.gpuResolvedImages = true; + std::vector prepared(regions.begin(), regions.end()); + RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(Code.data()), Code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, prepared}, target, {0u, 0u, 0u, 128u}}; + const auto handle = PrepareShader(request); + const auto invocation = PreparedShaderInvocation::TryCreate(request, handle); + Require(invocation.has_value(), "heap table walk reuse: the prepared table shader refused its own request"); + const auto walk = [&] { + auto stage = MaterializeHeapStageSettled(*invocation, userData, regions, request.shader.codeAddress); + Require(stage.result != nullptr && stage.reads.complete, "heap table walk reuse: the heap walk declined the table stage"); + return stage; + }; + const auto expected = [&] { + AgcDriver::ShaderMemory memory({}); + const auto capture = memory.Capture(*invocation); + const auto result = invocation->Materialize(*capture); + Require(result != nullptr, "heap table walk reuse: the full capture declined the table stage"); + return Descriptors(*result); + }; + const auto changed = reinterpret_cast(table + 5u * 8u); + + prepared[0] = MemoryRegion{prepared[0].guestAddress, std::span(NoAccessPage(), prepared[0].bytes.size())}; + const auto first = walk(); + prepared[0] = regions[0]; + const auto before = ResourceMaterializer::TableReuse(); + const auto second = walk(); + const auto reused = ResourceMaterializer::TableReuse(); + Require(reused.unwritten > before.unwritten, "heap table walk reuse: a walk over an unwritten table did not reuse its column"); + Require(StageDescriptors(first) == expected(), "heap table walk reuse: the first walk differs from a full capture"); + Require(*second.reads.ranges == *first.reads.ranges && *second.reads.values == *first.reads.values, "heap table walk reuse: a reused table recorded other words than the walk that read it"); + Require(StageDescriptors(second) == StageDescriptors(first), "heap table walk reuse: a reused table produced other descriptors"); + + const auto replacement = Texture(2u); + std::copy(replacement.begin(), replacement.end(), table + 5u * 8u); + const auto written = ResourceMaterializer::TableReuse(); + const auto third = walk(); + const auto after = ResourceMaterializer::TableReuse(); + Require(after.columns + after.compared > written.columns + written.compared, "heap table walk reuse: a walk did not re-read a table the guest wrote since"); + Require(RecordedWord(third, changed) == replacement[0], "heap table walk reuse: the walk recorded a stale table word"); + const auto current = expected(); + Require(StageDescriptors(third) == current, "heap table walk reuse: the walk after a table write differs from a full capture"); + Require(current != StageDescriptors(first), "heap table walk reuse: the table write did not change the stage's descriptors"); +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) return VulkanTestSkipped; + Run(*device); + std::cout << "heap table walk reuse tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp new file mode 100644 index 000000000000..15bb81f5db6c --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp @@ -0,0 +1,121 @@ +#include "HeapStageSettled.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "Optimization/RequestMemoryView.hpp" +#include "Optimization/ResourceProgram.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Lanes = 32; +constexpr std::uint32_t Format32UInt = 20; +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; +alignas(256) constexpr std::array Code{0x34020082u, 0xe0001000u, 0x80000201u, 0xe0301000u, 0x80000301u, 0xbf8c0000u, + 0xe0101000u, 0x80000201u, 0xe0701000u, 0x80000301u, + 0xe0701000u, 0x80010201u, 0xe0701080u, 0x80010301u, 0xbf800000u, 0xbf810000u}; + +std::array Descriptor(const void* data, std::uint32_t bytes, std::uint32_t type) { + const auto address = reinterpret_cast(data); + const auto word3 = (((0x01016facu & ~(0x7fu << 12u)) | (Format32UInt << 12u) | (3u << 28u)) & ~(3u << 30u)) | (type << 30u); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, word3}; +} + +ShaderRecompiler::RecompileRequest Request(AgcDriver::VulkanDevice& device, std::vector& userData) { + static const std::array memory{{{reinterpret_cast(Code.data()), std::as_bytes(std::span(Code))}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Lanes, 1, 1}, 0u, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(Code.data()), Code, 0, {}}, + {Lanes, 0, userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128} + }; + return request; +} + +std::vector UserData(std::uint32_t inputType) { + std::vector userData; + const auto input = Descriptor(Input.data(), sizeof(Input), inputType); + const auto output = Descriptor(Output.data(), sizeof(Output), 0u); + userData.insert(userData.end(), input.begin(), input.end()); + userData.insert(userData.end(), output.begin(), output.end()); + return userData; +} + +void UnsupportedTypeDeclines(AgcDriver::VulkanDevice& device) { + auto userData = UserData(2u); + const auto request = Request(device, userData); + const auto handle = ShaderRecompiler::PrepareShader(request); + const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, handle); + Require(invocation.has_value(), "the prepared shader refused its own request"); + AgcDriver::DriverDetail::HeapStageMaterialized materialized; + try { + materialized = MaterializeHeapStageSettled(*invocation, userData, request.context.memory, request.shader.codeAddress); + } catch (const std::exception& error) { + Require(false, std::string("a heap walk that read words it cannot capture threw instead of leaving the stage to the synchronized capture: ") + error.what()); + } + Require(materialized.result == nullptr, "a heap walk over an unsupported buffer type produced a stage"); + ShaderRecompiler::RequestMemoryView memoryView(request.context.memory); + const auto runtime = memoryView.MakeRuntime(request.context.userData, request.shader.codeAddress); + std::string message; + try { + static_cast(invocation->Materialize(*invocation->Capture(runtime))); + } catch (const std::exception& error) { + message = error.what(); + } + Require(message.find("buffer descriptor uses an unsupported type") != std::string::npos, "the synchronized capture of an unsupported buffer type did not reject it: " + message); +} + +void ValidTypeYieldsStage(AgcDriver::VulkanDevice& device) { + auto userData = UserData(0u); + const auto request = Request(device, userData); + const auto handle = ShaderRecompiler::PrepareShader(request); + const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, handle); + Require(invocation.has_value(), "the prepared shader refused its own request"); + const auto materialized = MaterializeHeapStageSettled(*invocation, userData, request.context.memory, request.shader.codeAddress); + Require(materialized.result != nullptr, "a heap walk over valid buffer descriptors declined its stage"); +} + +void RepeatedWalksYieldStages(AgcDriver::VulkanDevice& device) { + auto userData = UserData(0u); + userData[6] -= 16u; + const auto request = Request(device, userData); + const auto handle = ShaderRecompiler::PrepareShader(request); + const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, handle); + Require(invocation.has_value(), "the prepared shader refused its own request"); + for (int walk = 0; walk < 3; ++walk) { + const auto materialized = MaterializeHeapStageSettled(*invocation, userData, request.context.memory, request.shader.codeAddress); + Require(materialized.result != nullptr && materialized.words != nullptr, "a repeated heap walk over valid buffer descriptors declined its stage"); + } +} + +} + +int main() { + SetTestEnvironment("APS5_PROFILE_DRAW", "1"); + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + UnsupportedTypeDeclines(*device); + ValidTypeYieldsStage(*device); + RepeatedWalksYieldStages(*device); + std::puts("heap walk capture failure tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp new file mode 100644 index 000000000000..71f577ae5bea --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp @@ -0,0 +1,164 @@ +#include "HeapStageSettled.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#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 +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Lanes = 32; +constexpr std::uint32_t Format32UInt = 20; +constexpr std::size_t Variants = 1024; +constexpr std::size_t Rounds = 3; +constexpr std::size_t Held = 48; +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; +alignas(256) constexpr std::array Code{0x34020082u, 0xe0001000u, 0x80000201u, 0xe0301000u, 0x80000301u, 0xbf8c0000u, + 0xe0101000u, 0x80000201u, 0xe0701000u, 0x80000301u, + 0xe0701000u, 0x80010201u, 0xe0701080u, 0x80010301u, 0xbf800000u, 0xbf810000u}; + +std::array Descriptor(const void* data, std::uint32_t bytes) { + const auto address = reinterpret_cast(data); + const auto word3 = (((0x01016facu & ~(0x7fu << 12u)) | (Format32UInt << 12u) | (3u << 28u)) & ~(3u << 30u)); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, word3}; +} + +struct Variant { + std::vector userData; + ShaderRecompiler::RecompileRequest request; + std::optional invocation; +}; + +std::vector> Prepare(AgcDriver::VulkanDevice& device) { + static const std::array memory{{{reinterpret_cast(Code.data()), std::as_bytes(std::span(Code))}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Lanes, 1, 1}, 0u, {false, false, false}, false, 1}; + std::vector> variants; + for (std::size_t index = 0; index < Variants; ++index) { + auto variant = std::make_unique(); + const auto inputBytes = static_cast(sizeof(Input) - 4u * (index % 64u)); + const auto outputBytes = static_cast(sizeof(Output) - 4u * (index / 64u)); + const auto input = Descriptor(Input.data(), inputBytes); + const auto output = Descriptor(Output.data(), outputBytes); + variant->userData.insert(variant->userData.end(), input.begin(), input.end()); + variant->userData.insert(variant->userData.end(), output.begin(), output.end()); + variant->request = ShaderRecompiler::RecompileRequest{ + {ShaderStage::Compute, reinterpret_cast(Code.data()), Code, 0, {}}, + {Lanes, 0, variant->userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128}}; + const auto handle = ShaderRecompiler::PrepareShader(variant->request); + variant->invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(variant->request, handle); + Require(variant->invocation.has_value(), "the prepared shader refused its own request"); + variants.push_back(std::move(variant)); + } + return variants; +} + +struct Inbox { + std::mutex mutex; + std::condition_variable ready; + std::deque stages; +}; + +std::size_t Touch(const AgcDriver::DriverDetail::HeapStageMaterialized& stage) { + std::size_t sum = stage.result->spirv.size() + stage.words->userData.size() + stage.words->bindings.size(); + if (stage.reads.capture != nullptr) sum += stage.reads.capture->userDataUse.reads.size(); + if (stage.reads.values != nullptr) sum += stage.reads.values->size(); + return sum; +} + +void Work(const std::vector>& variants, std::size_t first, Inbox& own, Inbox& peer, std::atomic& failed, std::string& error) { + try { + std::deque held; + std::size_t touched = 0; + for (std::size_t round = 0; round < Rounds; ++round) { + for (std::size_t step = 0; step < variants.size(); ++step) { + const auto& variant = *variants[(first + step * 7u) % variants.size()]; + auto stage = MaterializeHeapStageSettled(*variant.invocation, variant.userData, variant.request.context.memory, variant.request.shader.codeAddress); + Require(stage.result != nullptr && stage.words != nullptr, "a heap walk over valid buffer descriptors declined its stage"); + { + std::lock_guard lock(peer.mutex); + peer.stages.push_back(std::move(stage)); + } + peer.ready.notify_one(); + std::deque received; + { + std::lock_guard lock(own.mutex); + received.swap(own.stages); + } + for (auto& item : received) { + touched += Touch(item); + held.push_back(std::move(item)); + } + while (held.size() > Held) held.pop_front(); + if (failed.load(std::memory_order_acquire)) return; + } + } + while (touched == 0) { + std::deque received; + { + std::unique_lock lock(own.mutex); + own.ready.wait_for(lock, std::chrono::seconds(60), [&] { return !own.stages.empty() || failed.load(std::memory_order_acquire); }); + received.swap(own.stages); + } + if (failed.load(std::memory_order_acquire)) return; + Require(!received.empty(), "a heap walk thread received no stage from the other thread"); + for (auto& item : received) touched += Touch(item); + } + } catch (const std::exception& caught) { + error = caught.what(); + failed.store(true, std::memory_order_release); + for (auto* inbox : {&own, &peer}) { + std::lock_guard lock(inbox->mutex); + inbox->ready.notify_all(); + } + } +} + +void TwoThreadsShareWalks(AgcDriver::VulkanDevice& device) { + const auto variants = Prepare(device); + Inbox first, second; + std::atomic failed{false}; + std::string firstError, secondError; + std::thread one(Work, std::cref(variants), std::size_t{0}, std::ref(first), std::ref(second), std::ref(failed), std::ref(firstError)); + std::thread two(Work, std::cref(variants), variants.size() / 2u, std::ref(second), std::ref(first), std::ref(failed), std::ref(secondError)); + one.join(); + two.join(); + Require(firstError.empty() && secondError.empty(), "a heap walk thread failed: " + firstError + secondError); + std::puts("two heap walk threads exchanged their stages"); +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + TwoThreadsShareWalks(*device); + std::puts("heap walk thread tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp index 1b8cf8e771c5..9dde4f7b16d4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" @@ -124,11 +125,12 @@ void Run(AgcDriver::VulkanDevice& device, std::uint32_t format) { ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(32), {0, 0, 0, 128} }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == AgcDriver::Graphics::DescriptorHeapEnabled(), "the compute heap did not take the image atomic stage"); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); } @@ -159,7 +161,7 @@ void Check(std::uint32_t format) { } } -void DispatchContention(AgcDriver::VulkanDevice& device, std::span code, std::uint32_t waveSize, std::uint32_t groups) { +void DispatchContention(AgcDriver::VulkanDevice& device, const ShaderRecompiler::SpirvTarget& target, std::span code, std::uint32_t waveSize, std::uint32_t groups) { std::vector userData(16, 0u); const auto input = BufferDescriptor(ContentionInput.data(), static_cast(ContentionInput.size() * 4u)); const auto output = BufferDescriptor(ContentionOutput.data(), static_cast(ContentionOutput.size() * 4u)); @@ -172,32 +174,33 @@ void DispatchContention(AgcDriver::VulkanDevice& device, std::span(code.data()), code, 0, {}}, {waveSize, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + target, {0, 0, 0, 128} }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == target.gpuResolvedImages, "the contended image atomic stage did not take its target's mode"); device.Dispatch(result, groups, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); } -std::uint32_t Contend(AgcDriver::VulkanDevice& device, std::span code, std::uint32_t waveSize, std::uint32_t initial) { +std::uint32_t Contend(AgcDriver::VulkanDevice& device, const ShaderRecompiler::SpirvTarget& target, std::span code, std::uint32_t waveSize, std::uint32_t initial) { ContentionOutput.fill(0xdeadbeefu); ContentionTexels.fill(0u); ContentionTexels[0] = initial; - DispatchContention(device, code, waveSize, ContentionGroups); + DispatchContention(device, target, code, waveSize, ContentionGroups); const auto returned = ContentionOutput; ContentionOutput.fill(0xdeadbeefu); - DispatchContention(device, ReadBack, waveSize, 1u); + DispatchContention(device, target, ReadBack, waveSize, 1u); const auto final = ContentionOutput[0]; ContentionOutput = returned; return final; } -void CheckContendedAdd(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) { +void CheckContendedAdd(AgcDriver::VulkanDevice& device, const ShaderRecompiler::SpirvTarget& target, std::uint32_t waveSize) { const auto name = "image_atomic_add contended by " + std::to_string(ContentionValues) + " wave" + std::to_string(waveSize) + " threads on one texel"; ContentionInput.fill(1u); - const auto final = Contend(device, ContentionAdd, waveSize, 0u); + const auto final = Contend(device, target, ContentionAdd, waveSize, 0u); std::vector seen(ContentionValues, false); for (std::uint32_t thread = 0; thread < ContentionValues; ++thread) { const auto returned = ContentionOutput[thread]; @@ -207,7 +210,7 @@ void CheckContendedAdd(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) Require(final == ContentionValues, name + ": the texel holds " + std::to_string(final) + ", expected " + std::to_string(ContentionValues)); } -void CheckContendedUMax(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) { +void CheckContendedUMax(AgcDriver::VulkanDevice& device, const ShaderRecompiler::SpirvTarget& target, std::uint32_t waveSize) { const auto name = "image_atomic_umax contended by " + std::to_string(ContentionValues) + " wave" + std::to_string(waveSize) + " threads on one texel"; constexpr std::uint32_t initial = 5u; std::uint64_t state = 0x2545f4914f6cdd1dull + waveSize; @@ -219,7 +222,7 @@ void CheckContendedUMax(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) values.insert(value); expected = std::max(expected, value); } - const auto final = Contend(device, ContentionUMax, waveSize, initial); + const auto final = Contend(device, target, ContentionUMax, waveSize, initial); for (std::uint32_t thread = 0; thread < ContentionValues; ++thread) { const auto returned = ContentionOutput[thread]; Require(values.contains(returned) && returned <= expected, name + ": thread " + std::to_string(thread) + " returned " + std::to_string(returned) + ", which no thread stored"); @@ -239,8 +242,15 @@ int main() { Check(format); } for (const auto waveSize : {32u, 64u}) { - CheckContendedAdd(*device, waveSize); - CheckContendedUMax(*device, waveSize); + const auto heapTarget = device->ComputeTarget(waveSize); + Require(heapTarget.gpuResolvedImages == AgcDriver::Graphics::DescriptorHeapEnabled(), "the compute target does not follow the descriptor heap"); + CheckContendedAdd(*device, heapTarget, waveSize); + CheckContendedUMax(*device, heapTarget, waveSize); + } + { + const auto plainTarget = device->Target(); + CheckContendedAdd(*device, plainTarget, 32u); + CheckContendedUMax(*device, plainTarget, 32u); } std::puts("image atomics tests passed"); return 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics64.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics64.cpp index 776d137cd422..64ae5b080348 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics64.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics64.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" @@ -148,11 +149,12 @@ void Run(AgcDriver::VulkanDevice& device, std::uint32_t format) { ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(32), {0, 0, 0, 128} }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == AgcDriver::Graphics::DescriptorHeapEnabled(), "the compute heap did not take the image atomic stage"); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsBitwise.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsBitwise.cpp index ca6796d7a2c5..98f8b9c08264 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsBitwise.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsBitwise.cpp @@ -127,9 +127,9 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; FillInput(); - Run(*device, 32, device->Target()); + Run(*device, 32, device->ComputeTarget(32)); Check("wave32"); - Run(*device, 64, device->Target()); + Run(*device, 64, device->ComputeTarget(64)); Check("wave64"); Run(*device, 64, device->ComputeTarget(32)); Check("wave64 split"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsFloat.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsFloat.cpp index 78b36356c7db..b4e269aadbbd 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsFloat.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsFloat.cpp @@ -544,8 +544,8 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; for (const auto format : {Format32UInt, Format32SInt, Format32Float}) { - Run(*device, 32, device->Target(), "wave32", format); - Run(*device, 64, device->Target(), "wave64", format); + Run(*device, 32, device->ComputeTarget(32), "wave32", format); + Run(*device, 64, device->ComputeTarget(64), "wave64", format); Run(*device, 64, device->ComputeTarget(32), "wave64 split", format); } bool refused = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageCacheBits.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageCacheBits.cpp index f321df600250..7f60148977e6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageCacheBits.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageCacheBits.cpp @@ -224,7 +224,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::span co ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp index eea18da65d0b..251b5e1a4f55 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp @@ -247,7 +247,7 @@ void Run(AgcDriver::VulkanDevice& device, std::span code, c ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; @@ -621,7 +621,7 @@ void CheckConvertedPreparation(AgcDriver::VulkanDevice& device, const std::uint8 ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; auto converted = request; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageMemory.cpp index 4a729b32aee6..95c89dfc72d4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageMemory.cpp @@ -359,7 +359,7 @@ bool SampledImages(const Context& context, TextureDetiler& detiler, Hooks& nativ std::vector> textures; bool covered = true; { - Recorder recorder(context); + Recorder recorder(context, true); recorder.Activate(); for (std::size_t i = 0; i < ImageCount; ++i) { auto texture = std::make_unique(context, detiler, resource, identity, snapshot); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageSint8.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageSint8.cpp index 99f99d6ca5a4..c84c4aad4111 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageSint8.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageSint8.cpp @@ -116,7 +116,7 @@ void Run(AgcDriver::VulkanDevice& device, std::span code, s ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageSrgbLoad.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageSrgbLoad.cpp index eafabe0d7c87..898a73421caf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageSrgbLoad.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageSrgbLoad.cpp @@ -188,7 +188,7 @@ std::vector Run(AgcDriver::VulkanDevice& device, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = useCache; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreArrayThroughVolume.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreArrayThroughVolume.cpp index b410321d5cd0..24cafee2007e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreArrayThroughVolume.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreArrayThroughVolume.cpp @@ -126,7 +126,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::size_t ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFaceOnCube.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFaceOnCube.cpp index 148b6e45c74d..d58e1b29b6ff 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFaceOnCube.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFaceOnCube.cpp @@ -140,7 +140,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, const Forma ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp index e94e7543b795..8418351001d4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp @@ -313,7 +313,7 @@ void Store(AgcDriver::VulkanDevice& device, std::uint8_t* texels, const Format& } } } - const auto result = Recompile(device.Target(), format, d16, mixed, texels); + const auto result = Recompile(device.ComputeTarget(64), format, d16, mixed, texels); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); AgcDriver::Graphics::StorageTexture::FlushPending(reinterpret_cast(texels), TexelBytes, nullptr, "test"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlane.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlane.cpp index 6f6e1cfb2dbb..0b29350010ca 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlane.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlane.cpp @@ -146,7 +146,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlaneArray.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlaneArray.cpp index 26d3e4d1ff99..5327471762b9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlaneArray.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlaneArray.cpp @@ -138,7 +138,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStorePacked.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStorePacked.cpp index 427ebc94b078..93262be4318a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStorePacked.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStorePacked.cpp @@ -177,7 +177,7 @@ void Run(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; const auto result = ShaderRecompiler::Recompile(request); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreSint.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreSint.cpp index 8daddabd90c8..670081b62ca1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreSint.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreSint.cpp @@ -238,7 +238,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreUnormRounding.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreUnormRounding.cpp index bb6c6f25cf17..ffbcd129b4cb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreUnormRounding.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreUnormRounding.cpp @@ -207,7 +207,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreVolumeThroughArray.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreVolumeThroughArray.cpp index b82fa4ba0725..acd2e7530f40 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreVolumeThroughArray.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreVolumeThroughArray.cpp @@ -126,7 +126,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::size_t ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp index 552994ca1788..aa0006019a46 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp @@ -7,6 +7,7 @@ #include "Optimization/ResourceMaterializer.hpp" #include "Optimization/SrtWalker.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/GuestArena.hpp" @@ -73,6 +74,17 @@ constexpr std::size_t WideKernelOffset = 2048; constexpr std::size_t WideHeapOffset = 65536; constexpr std::array WideSlots{SrtSlots - 1u, SrtSlots - 2u, SrtSlots - 3u}; constexpr std::array WideTableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x7e200500u, 0x9310b010u, 0xf42c0502u, 0x20000000u, 0xf09c0f08u, 0x00450000u, 0xe0700000u, 0x80070000u, 0xbf810000u}; +constexpr std::uint32_t Format32UInt = 20; +constexpr std::uint32_t AtomicRecords = 16; +constexpr std::uint32_t AtomicWidth = 64; +constexpr std::size_t AtomicKernelOffset = 1024; +constexpr std::size_t AtomicSurfaceBytes = AtomicWidth * 4u; +constexpr std::uint32_t AtomicElement = 5; +constexpr std::uint32_t Format16x4Float = 71; +constexpr std::size_t StoreSurfaceBytes = AtomicWidth * 8u; +constexpr std::uint64_t StoredTexel = 0x3c00ull | 0x3800ull << 16u | 0x4000ull << 32u | 0xbc00ull << 48u; +constexpr std::array StoreTableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x2c240086u, 0x4a222485u, 0x7e200511u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0x7e020280u, 0x7e0402f2u, 0x7e0602f0u, 0x7e0802f4u, 0x7e0a02f3u, 0xbf8c3f70u, 0xf0200f08u, 0x00050200u, 0xbf810000u}; +constexpr std::array AtomicTableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x2c240086u, 0x4a222485u, 0x7e200511u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0x7e020280u, 0x7e040281u, 0x34060082u, 0xbf8c3f70u, 0xf0442108u, 0x00050200u, 0xbf8c3f70u, 0xe0701000u, 0x80070203u, 0xbf8c3f70u, 0xbf810000u}; constexpr std::array TableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x7e200500u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0xf09c0f08u, 0x00450000u, 0xe0700000u, 0x80070000u, 0xbf810000u}; constexpr std::size_t VertexOffset = 256; @@ -241,12 +253,17 @@ void Prepare(const GuestBlock& block) { void TablesChangingPerDispatch(const GuestBlock& block) { auto& cache = AgcDriver::Graphics::SharedResourceCache(); + const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); std::uint64_t most = 0; for (std::uint32_t dispatch = 0; dispatch < 6; ++dispatch) { SetRecord(block, dispatch * 977u % Records, Elements + dispatch % Spare); Dispatch(block, 0); most = std::max(most, cache.TableElements()); } + if (AgcDriver::Graphics::DescriptorHeapEnabled()) { + Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table cache bounds: the dispatches did not take the descriptor heap"); + return; + } Require(most >= Elements, "image table cache bounds: no dispatch kept its table in the resource cache"); Require(most <= AgcDriver::Graphics::ResourceCache::TableElementBudget(), "image table cache bounds: tables that changed every dispatch kept " + std::to_string(most) + " table elements in the resource cache, over its budget of " + std::to_string(AgcDriver::Graphics::ResourceCache::TableElementBudget())); } @@ -442,6 +459,68 @@ void VouchedLookups(const GuestBlock& block) { std::puts("image table vouched lookups passed"); } +std::uint32_t AtomicStart(std::uint32_t texel) { return texel * 7u + 3u; } + +template +void PrepareAtomicRecords(const GuestBlock& block, const void* kernel, std::size_t kernelBytes, std::uint32_t format, std::size_t surfaceBytes, FillSurface&& fillSurface) { + std::memcpy(block.Bytes(AtomicKernelOffset), kernel, kernelBytes); + for (std::uint32_t record = 0; record < AtomicRecords; ++record) { + const auto surface = TexturesOffset + static_cast(record) * surfaceBytes; + fillSurface(record, block.Bytes(surface)); + const auto address = block.At(surface); + const std::array words{static_cast(address >> 8u), static_cast((address >> 40u) & 0xffu) | (format << 20u) | (((AtomicWidth - 1u) & 3u) << 30u), (AtomicWidth - 1u) >> 2u, 0xfacu | (Type2D << 28u), 0u, 0u, 0u, 0u}; + std::memcpy(block.Bytes(HeapOffset + static_cast(record) * Stride), words.data(), sizeof(words)); + } + auto* srt = reinterpret_cast(block.Bytes(SrtOffset)); + std::fill(srt, srt + SrtBytes / 4u, 0u); + const auto heap = V(block.At(HeapOffset), Stride, AtomicRecords); + const auto output = V(block.At(OutputOffset), 0u, 4096u); + std::copy(heap.begin(), heap.end(), srt); + std::copy(output.begin(), output.end(), srt + 12); +} + +void AtomicTable(const GuestBlock& block) { + PrepareAtomicRecords(block, AtomicTableCode.data(), sizeof(AtomicTableCode), Format32UInt, AtomicSurfaceBytes, [](std::uint32_t record, std::uint8_t* surface) { + auto* texels = reinterpret_cast(surface); + for (std::uint32_t texel = 0; texel < AtomicWidth; ++texel) texels[texel] = AtomicStart(texel) + record * 1000u; + }); + const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); + for (std::uint32_t dispatch = 0; dispatch < 2; ++dispatch) { + std::memset(block.Bytes(OutputOffset), 0xee, AtomicWidth * 4u); + Dispatch(block, 0, AtomicKernelOffset); + std::array returned{}; + AgcDriver::GuestMemory::Read(block.At(OutputOffset), std::as_writable_bytes(std::span(returned))); + for (std::uint32_t texel = 0; texel < AtomicWidth; ++texel) { + const auto expected = AtomicStart(texel) + AtomicElement * 1000u + dispatch; + Require(returned[texel] == expected, "image table atomics: dispatch " + std::to_string(dispatch) + " texel " + std::to_string(texel) + " returned " + std::to_string(returned[texel]) + ", expected " + std::to_string(expected)); + } + } + if (AgcDriver::Graphics::DescriptorHeapEnabled()) Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table atomics: the dispatches did not take the descriptor heap"); + std::puts("image table atomics passed"); +} + +bool StoreTable(const GuestBlock& block) { + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) { + std::puts("image table store skipped: per-dispatch image tables have no uint storage view (docs/dev/debt/libSceAgcDriver.md)"); + return false; + } + PrepareAtomicRecords(block, StoreTableCode.data(), sizeof(StoreTableCode), Format16x4Float, StoreSurfaceBytes, + [](std::uint32_t, std::uint8_t* surface) { std::memset(surface, 0, StoreSurfaceBytes); }); + const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); + Dispatch(block, 0, AtomicKernelOffset); + std::array texels{}; + AgcDriver::GuestMemory::Read(block.At(TexturesOffset + static_cast(AtomicElement) * StoreSurfaceBytes), std::as_writable_bytes(std::span(texels))); + for (std::uint32_t texel = 0; texel < AtomicWidth; ++texel) { + char text[160]; + std::snprintf(text, sizeof(text), "image table store: texel %u of a 16_16_16_16_FLOAT table element holds 0x%016llx, expected 0x%016llx", texel, + static_cast(texels[texel]), static_cast(StoredTexel)); + Require(texels[texel] == StoredTexel, text); + } + Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table store: the dispatch did not take the descriptor heap"); + std::puts("image table store passed"); + return true; +} + struct QueuedDraw { std::atomic release{false}; @@ -584,6 +663,16 @@ int main(int argc, char** argv) { AgcDriverShutdown_nid_postfix(); return 0; } + if (argc == 2 && std::string(argv[1]) == "--store-table") { + const bool ran = StoreTable(block); + AgcDriverShutdown_nid_postfix(); + return ran ? 0 : VulkanTestSkipped; + } + if (argc == 2 && std::string(argv[1]) == "--atomic-table") { + AtomicTable(block); + AgcDriverShutdown_nid_postfix(); + return 0; + } if (argc == 2 && std::string(argv[1]) == "--queued-draws") { VouchUnderQueuedDraws(block); AgcDriverShutdown_nid_postfix(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableVariants.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableVariants.cpp index 374108a89986..d3ca5ae2ee65 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableVariants.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableVariants.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestTextureResource.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" @@ -186,7 +187,7 @@ void FillTable(const GuestBlock& block) { } } -ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const GuestBlock& table, std::span code = TableCode) { +ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const GuestBlock& table, std::span code = TableCode, bool heap = false) { const auto srtAddress = AddressOf(Srt.data()); const std::array userData{static_cast(srtAddress), static_cast(srtAddress >> 32u)}; const std::span words(table.Table(), Records * Stride / 4u); @@ -197,12 +198,16 @@ ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const {AddressOf(Keys.data()), std::as_bytes(std::span(Keys))}, }}; const ShaderRecompiler::ShaderComputeStageInfo compute{{Lanes, 1, 1}, 0u, {true, false, false}, false, 1}; - const ShaderRecompiler::RecompileRequest request{ + ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, AddressOf(code.data()), code, 0, {}}, {64, 0, userData, compute, std::nullopt, std::nullopt, memory}, device.Target(), {0, 0, 0, 128} }; + if (heap) { + request.target.gpuResolvedImages = true; + request.useCache = false; + } auto result = ShaderRecompiler::Recompile(request); const auto binding = std::find_if(result.bindings.begin(), result.bindings.end(), [](const ShaderRecompiler::DescriptorBinding& candidate) { return candidate.role == ShaderRecompiler::DescriptorRole::ImageTable; }); Require(binding != result.bindings.end() && binding->guestDescriptor.size() == static_cast(Records) * 8u, "image table variants: the shader does not bind the whole table"); @@ -412,6 +417,38 @@ void RunRejected(AgcDriver::VulkanDevice& device, const GuestBlock& block) { AgcDriver::Graphics::ClearDepthSurfaces(device.Device()); } +const std::vector& TableWords(const ShaderRecompiler::RecompileResult& result) { + const auto binding = std::find_if(result.bindings.begin(), result.bindings.end(), [](const ShaderRecompiler::DescriptorBinding& candidate) { return candidate.role == ShaderRecompiler::DescriptorRole::ImageTable; }); + return binding->guestDescriptor; +} + +void HeapStageWithOtherWords(AgcDriver::VulkanDevice& device, const GuestBlock& block, bool templateVariants, std::uint64_t substituted, const std::string& what) { + Prepare(block); + SetRecord(block, 1, templateVariants ? block.Texels(0) : block.Texels(1), templateVariants ? Narrow : Wide); + const auto shared = Compile(device, block, TableCode, true); + Require(shared.gpuResolvedImages, "image table variants: the heap compile did not make a GPU-mode program"); + SetRecord(block, 1, templateVariants ? block.Texels(1) : block.Texels(0), templateVariants ? Wide : Narrow); + const auto own = Compile(device, block); + Require(TableWords(shared) != TableWords(own), "image table variants: the template and the stage read the same image table words"); + ShaderRecompiler::HeapStageWords words; + words.bindings.resize(shared.bindings.size()); + const auto table = std::find_if(shared.bindings.begin(), shared.bindings.end(), [](const ShaderRecompiler::DescriptorBinding& candidate) { return candidate.role == ShaderRecompiler::DescriptorRole::ImageTable; }); + words.bindings[static_cast(table - shared.bindings.begin())] = TableWords(own); + const AgcDriver::Graphics::CompiledShader stage{ShaderStage::Compute, &shared, 0, nullptr, &words}; + AgcDriver::GuestMemory::BumpCollectEpoch(); + const auto before = AgcDriver::Graphics::ImageTableReuses(); + { + AgcDriver::Graphics::ShaderResources resources(device.graphicsContext(), stage); + } + Expect(before, substituted, substituted, 0, what); +} + +void RunHeapWords(AgcDriver::VulkanDevice& device, const GuestBlock& block) { + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) return; + HeapStageWithOtherWords(device, block, false, 1, "a heap stage whose own image table words make an entry a variant, built from a template whose words keep them apart"); + HeapStageWithOtherWords(device, block, true, 0, "a heap stage whose own image table words keep two entries apart, built from a template whose words made one a variant"); +} + ShaderRecompiler::RecompileResult ProofProgram(const float* variants, const float* other) { namespace Abi = ShaderRecompiler::ImageTableAbi; using ShaderRecompiler::DescriptorKind; @@ -486,6 +523,7 @@ void RunTests(AgcDriver::VulkanDevice& device, const GuestBlock& block) { RunSize(device, block); RunDepth(device, block); RunRejected(device, block); + RunHeapWords(device, block); } } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTexelStatus.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTexelStatus.cpp index 319faa1a0675..2c333ba4a6f0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTexelStatus.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTexelStatus.cpp @@ -231,7 +231,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::span co ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp index 2b8f919a072f..7e5616b7a2c8 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp @@ -3,6 +3,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/ShaderPreparationScope.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/GuestArena.hpp" @@ -560,10 +561,11 @@ void LazyResolution(const Layout& layout, const std::filesystem::path& reference Require(unmatched.firstUses - start.firstUses == Drawn && unmatched.own - start.own == Drawn && unmatched.found == start.found, "lazy resolved ABI: draws whose state differs from the resolved ABI did not count as preparing their own artifact (before: " + Uses(start) + "; after: " + Uses(unmatched) + ")"); Require(unmatched.entries > start.entries && unmatched.unmatchedEntries - start.unmatchedEntries == unmatched.entries - start.entries, "lazy resolved ABI: entries prepared for an ABI no draw used do not count as unmatched (before: " + Uses(start) + "; after: " + Uses(unmatched) + ")"); Require(matched.firstUses == unmatched.firstUses + 1 && matched.found == unmatched.found + 1 && matched.own == unmatched.own, "lazy resolved ABI: a draw whose state matches the resolved ABI did not count as finding its artifact (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); - Require(matched.entries > unmatched.entries && matched.unmatchedEntries == unmatched.unmatchedEntries + (matched.entries - unmatched.entries) - 1, "lazy resolved ABI: the entry a matching draw used still counts as unmatched (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); + constexpr std::uint64_t drawVariants = 1u; + Require(matched.entries > unmatched.entries && matched.unmatchedEntries == unmatched.unmatchedEntries + (matched.entries - unmatched.entries) - drawVariants, "lazy resolved ABI: the entry a matching draw used still counts as unmatched (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); for (const auto index : {Matching, Twice, Replaced}) Require(eager.at("drawn " + std::to_string(index)) == eager.at("resolved " + std::to_string(index)), "lazy resolved ABI: shader " + std::to_string(index) + ", drawn with its resolved ABI's state, did not find the ABI's entries with eager preparation"); - for (std::uint32_t index = 0; index < Drawn; ++index) Require(Count(eager.at("drawn " + std::to_string(index))) == Count(eager.at("resolved " + std::to_string(index))) + 1, "lazy resolved ABI: a draw whose state differs from its resolved ABI did not prepare its own entry with eager preparation"); - Require(Count(eager.at("drawn " + std::to_string(Replacement))) == Count(eager.at("registered " + std::to_string(Replacement))) + 1, "lazy resolved ABI: the header registered over a resolved one did not prepare its own entry at its draw with eager preparation"); + for (std::uint32_t index = 0; index < Drawn; ++index) Require(Count(eager.at("drawn " + std::to_string(index))) == Count(eager.at("resolved " + std::to_string(index))) + drawVariants, "lazy resolved ABI: a draw whose state differs from its resolved ABI did not prepare its own entry with eager preparation (shader " + std::to_string(index) + ": drawn " + std::to_string(Count(eager.at("drawn " + std::to_string(index)))) + ", resolved " + std::to_string(Count(eager.at("resolved " + std::to_string(index)))) + ", expected " + std::to_string(drawVariants) + " more)"); + Require(Count(eager.at("drawn " + std::to_string(Replacement))) == Count(eager.at("registered " + std::to_string(Replacement))) + drawVariants, "lazy resolved ABI: the header registered over a resolved one did not prepare its own entry at its draw with eager preparation"); Require(lazy.at("libraries drawn") == eager.at("libraries drawn"), "lazy resolved ABI: the pipeline libraries built differ from eager preparation (eager " + eager.at("libraries drawn") + "; lazy " + lazy.at("libraries drawn") + ")"); Require(first == expected, "lazy resolved ABI: the shader prepared at its first draw drew other bytes than with eager preparation"); AgcDriverWaitIdle_nid_postfix(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MemoryAccounting.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MemoryAccounting.cpp index 23b07da10799..4444184ad7da 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MemoryAccounting.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MemoryAccounting.cpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Execution/include/PqToSdr.hpp" #include "prx/libSceAgcDriver/Graphics/include/DeferredDestruction.hpp" #include "prx/libSceAgcDriver/Execution/include/PresentationScaler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp" @@ -159,6 +160,7 @@ int main() { auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; auto context = device->graphicsContext(); + if (context.descriptorHeap) static_cast(BindlessHeap::For(context)); context.bufferPool = std::make_shared(context); drain(context); const auto baseline = MemoryAccounting::Read(context.device).allocations.size(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MeshDrawRelocation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MeshDrawRelocation.cpp index c0a23b47af4b..db3ccc573109 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MeshDrawRelocation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MeshDrawRelocation.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" #include "../MeshGeometryFixture.hpp" #include "VulkanTestDevice.hpp" @@ -103,6 +104,7 @@ std::vector Setup(const std::array& descriptor) AgcDriver::DriverDetail::DrawEntryCounters Draw(const std::array& descriptor) { Pixels.fill(std::byte{0}); + const auto pushes = AgcDriver::Graphics::DataAddressPushes(); auto commands = Setup(descriptor); const auto address = reinterpret_cast(Indices.data()); commands.insert(commands.end(), {0xc0042700u, 3u, static_cast(address), static_cast(address >> 32u), 3u, 0u}); @@ -110,6 +112,7 @@ AgcDriver::DriverDetail::DrawEntryCounters Draw(const std::array(Pixels[(24u * Width + 16u) * 4u]) > 200u, "the mesh draw did not cover its triangle"); + Require(!AgcDriver::Graphics::DescriptorHeapEnabled() || AgcDriver::Graphics::DataAddressPushes() > pushes, "the submitted mesh draw did not take the descriptor heap"); return AgcDriver::DriverDetail::Driver::Get().DrawCacheCounters(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleReadback.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleReadback.cpp index 1ba693131dbb..9f720b70cbb8 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleReadback.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleReadback.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -17,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +33,21 @@ struct VulkanDeviceTestAccess { namespace { +template +void RecordStayingOnHeap(const AgcDriver::Graphics::Context& context, VkCommandBuffer commands, const std::string& what, Record&& record) { + if (!AgcDriver::Graphics::HeapPassesActive(context)) { + record(); + return; + } + auto& heap = AgcDriver::Graphics::BindlessHeap::For(context); + heap.BindDescriptorHeaps(commands); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds(); + record(); + heap.BindDescriptorHeaps(commands); + if (AgcDriver::Graphics::DescriptorHeapBinds() != binds) throw std::runtime_error(what + " put its command buffer back in classic descriptor mode, so the heaps were bound again"); +} + + using namespace AgcDriver::Graphics; PFN_vkGetDeviceProcAddr originalDeviceProc = nullptr; @@ -81,7 +98,7 @@ bool SurfaceSupported(const Context& context, VkFormat format, std::uint32_t sam return false; } -struct Surface { +struct Surface : AgcDriver::Graphics::HeapSlotOwner { Context context; VkFormat format; std::uint32_t elementBytes; @@ -235,6 +252,7 @@ struct Surface { Surface& operator=(const Surface&) = delete; void Release() noexcept { + ReleaseHeapSlots(context); if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); if (pipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, pipelineLayout, nullptr); for (const auto module : modules) if (module) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); @@ -297,7 +315,7 @@ std::vector CheckReadback(TextureDetiler& reader, const Surface& surf CommandBatch batch(surface.context); RecordMemoryBarrier(surface.context, batch.Handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); for (std::uint32_t repeat = 0u; repeat < repetitions; ++repeat) { - reader.DispatchMultisampleReadback(batch.Handle(), surface.format, output.Handle(), offset, bytes, surface.arrayView, surface.width, surface.height, surface.layers, surface.samples, first, elements); + RecordStayingOnHeap(surface.context, batch.Handle(), "the multisample readback", [&] { reader.DispatchMultisampleReadback(batch.Handle(), surface.format, output.Handle(), offset, bytes, surface.arrayView, surface.width, surface.height, surface.layers, surface.samples, first, elements, &surface); }); if (repeat + 1u < repetitions) RecordMemoryBarrier(surface.context, batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); } RecordMemoryBarrier(surface.context, batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); @@ -376,7 +394,7 @@ void CheckRefusals(TextureDetiler& reader, const Surface& surface) { Buffer output(surface.context, 4096u, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); CommandBatch batch(surface.context); const auto call = [&](VkFormat format, std::uint64_t offset, std::uint64_t bytes, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t first, std::uint32_t elements) { - reader.DispatchMultisampleReadback(batch.Handle(), format, output.Handle(), offset, bytes, surface.arrayView, width, height, layers, fragments, first, elements); + RecordStayingOnHeap(surface.context, batch.Handle(), "the multisample readback", [&] { reader.DispatchMultisampleReadback(batch.Handle(), format, output.Handle(), offset, bytes, surface.arrayView, width, height, layers, fragments, first, elements, &surface); }); }; for (auto format : {VK_FORMAT_UNDEFINED, VK_FORMAT_R32_SFLOAT, VK_FORMAT_D16_UNORM, VK_FORMAT_D32_SFLOAT_S8_UINT}) Refused([&] { call(format, 0u, 4u, 1u, 1u, 1u, 4u, 0u, 1u); }, "requires an unsigned element view or D32 depth"); for (auto fragments : {0u, 1u, 3u, 16u}) Refused([&] { call(surface.format, 0u, 4u, 1u, 1u, 1u, fragments, 0u, 1u); }, "fragment count is unsupported"); @@ -409,7 +427,7 @@ std::vector Upload(TextureDetiler& transfer, TextureDetiler& reader, for (std::uint32_t repeat = 0; repeat < repetitions; ++repeat) { for (std::size_t done = 0; done < bytes; done += stride) { const auto count = std::min(stride, bytes - done); - transfer.DispatchMultisampleImage(batch.Handle(), surface.elementBytes, source.Handle(), offset + done, (count + 3u) & ~std::size_t{3}, surface.arrayView, surface.width, surface.height, surface.layers, surface.samples, first + static_cast(done / surface.elementBytes), static_cast(count / surface.elementBytes)); + RecordStayingOnHeap(surface.context, batch.Handle(), "the multisample upload", [&] { transfer.DispatchMultisampleImage(batch.Handle(), surface.elementBytes, source.Handle(), offset + done, (count + 3u) & ~std::size_t{3}, surface.arrayView, surface.width, surface.height, surface.layers, surface.samples, first + static_cast(done / surface.elementBytes), static_cast(count / surface.elementBytes), &surface); }); } RecordMemoryBarrier(surface.context, batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp index 1c4e69601c0c..9954f091c88f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp @@ -299,8 +299,8 @@ class Run { realCreateImage = context.Function("vkCreateImage"); realDestroyImage = context.Function("vkDestroyImage"); realBindImageMemory = context.Function("vkBindImageMemory"); - realCreateImageView = context.Function("vkCreateImageView"); - realDestroyImageView = context.Function("vkDestroyImageView"); + realCreateImageView = reinterpret_cast(realProc(context.device, "vkCreateImageView")); + realDestroyImageView = reinterpret_cast(realProc(context.device, "vkDestroyImageView")); realClearColorImage = context.Function("vkCmdClearColorImage"); realCopyImage = context.Function("vkCmdCopyImage"); context.deviceProc = CountingDeviceProc; @@ -488,7 +488,7 @@ class Run { { std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); const auto keptBefore = context.recorder->OpenKeptBytes(); - storageView = MultisampleTargetStorageView(context, resource); + storageView = MultisampleTargetStorageView(context, resource).view; promoted = ImageFor(storageView, &promotedImage); Require(promoted.generation != old.generation && Alive(oldImage, old), "MSAA storage promotion did not retain its source image"); Require(ImageFor(sampledView).generation == old.generation, "MSAA storage promotion destroyed a held sampled view"); @@ -496,7 +496,7 @@ class Run { totalBytes = AllocationBytesOf(old) + AllocationBytesOf(promoted); const auto kept = context.recorder->OpenKeptBytes(); Require(kept == keptBefore + totalBytes, "MSAA storage promotion did not account for exactly both allocations"); - Require(MultisampleTargetStorageView(context, resource) == storageView, "a repeated MSAA storage lookup changed its view"); + Require(MultisampleTargetStorageView(context, resource).view == storageView, "a repeated MSAA storage lookup changed its view"); Require(context.recorder->OpenKeptBytes() == kept, "a repeated MSAA storage lookup double-counts its allocations"); } Sync(); @@ -506,10 +506,10 @@ class Run { Require(held->View() == sampledView, "a held sampled MSAA alias changed after promotion completion"); held.reset(); const auto keptBefore = context.recorder->OpenKeptBytes(); - Require(MultisampleTargetStorageView(context, resource) == storageView, "a later MSAA storage lookup changed its promoted image"); + Require(MultisampleTargetStorageView(context, resource).view == storageView, "a later MSAA storage lookup changed its promoted image"); const auto kept = context.recorder->OpenKeptBytes(); Require(kept == keptBefore + totalBytes, "an already-storable MSAA target is missing allocations from the new batch budget"); - Require(MultisampleTargetStorageView(context, resource) == storageView, "a repeated promoted MSAA lookup changed its view"); + Require(MultisampleTargetStorageView(context, resource).view == storageView, "a repeated promoted MSAA lookup changed its view"); Require(context.recorder->OpenKeptBytes() == kept, "an already-storable MSAA target double-counts its allocations in one batch"); } block.Unmap(); @@ -549,7 +549,7 @@ class Run { Sync(); { std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); - promoted = ImageFor(MultisampleTargetStorageView(context, resource), &promotedImage); + promoted = ImageFor(MultisampleTargetStorageView(context, resource).view, &promotedImage); Require(bornStorable == (promoted.generation == rendered.generation), bornStorable ? "a born-storable MSAA target was promoted to a new image" : "MSAA storage promotion kept the rendered image"); const auto promotedTwin = MultisampleTargetView(context, twin); ImageFor(promotedTwin, &promotedTwinImage); @@ -573,9 +573,9 @@ class Run { { std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); MultisampleTargetView(context, target); - storageView = MultisampleTargetStorageView(context, resource); + storageView = MultisampleTargetStorageView(context, resource).view; Require(storageView != VK_NULL_HANDLE, "a UNORM storage access to a multisampled sRGB target has no view"); - Require(MultisampleTargetStorageView(context, resource) == storageView, "a repeated UNORM storage access to a multisampled sRGB target changed its view"); + Require(MultisampleTargetStorageView(context, resource).view == storageView, "a repeated UNORM storage access to a multisampled sRGB target changed its view"); resource.format = 60; bool refused = false; try { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp index 56f324d45c13..4194ba49fedd 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp @@ -129,7 +129,7 @@ int main() { device->WaitIdle(); std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); const auto captured = Capture::Install(base); - Recorder recorder(captured); + Recorder recorder(captured, device->TimelineSemaphores()); recorder.Activate(); const auto depthA = reinterpret_cast(DepthA.data()); const auto depthB = reinterpret_cast(DepthB.data()); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/OversizedDispatch.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/OversizedDispatch.cpp index b31f2c597f42..cc52c5b01c64 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/OversizedDispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/OversizedDispatch.cpp @@ -1,6 +1,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "Recompiler.hpp" @@ -160,7 +161,7 @@ alignas(256) constexpr std::array GroupYCode{ constexpr std::uint32_t GroupYSplitCap = 1u << 20u; constexpr std::uint32_t GroupYTail = 4097u; -bool CheckGroupYSplitCoverage(AgcDriver::VulkanDevice& device) { +bool CheckGroupYSplitCoverage(AgcDriver::VulkanDevice& device, bool heap) { const auto limit = device.WorkGroupCountLimit()[1]; if (limit >= GroupYSplitCap) { std::printf("oversized dispatch Y split: skipped, the device reports a %u Y workgroup limit\n", limit); @@ -174,11 +175,14 @@ bool CheckGroupYSplitCoverage(AgcDriver::VulkanDevice& device) { const std::span code(GroupYCode); const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0, {false, true, false}, false, 1}; + auto target = device.Target(); + target.gpuResolvedImages = heap; ShaderRecompiler::RecompileRequest request{ {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {64, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), {0, 0, 0, 128}, std::nullopt, false}; + target, {0, 0, 0, 128}, std::nullopt, false}; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == heap, "oversized dispatch Y split: the program did not take the requested binding mode"); device.Dispatch(result, 1, groups, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(guest.Data()), guest.Bytes); @@ -195,7 +199,8 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; CheckLdsSplitThrows(*device); - bool split = CheckGroupYSplitCoverage(*device); + bool split = CheckGroupYSplitCoverage(*device, false); + if (split && AgcDriver::Graphics::DescriptorHeapEnabled()) static_cast(CheckGroupYSplitCoverage(*device, true)); if (device->WorkGroupCountLimit()[0] < Groups) { CheckSplitCoverage(*device); split = true; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp index defa974a025c..6fb45ada82ac 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp @@ -143,7 +143,7 @@ int main() { const auto shaders = Compile(*device); device->WaitIdle(); std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); - Recorder recorder(context); + Recorder recorder(context, device->TimelineSemaphores()); recorder.Activate(); Expect(MultisampledDepthBytes_nid_no_patch({Width, Height}, sizeof(float), Samples) == DepthA.Bytes().size(), "the depth backing differs from its multisample footprint"); const auto depthA = DepthA.Address(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp index efbb0995d7bd..f0a715fa83f7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp @@ -1,6 +1,7 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" @@ -16,6 +17,7 @@ #include "Recompiler.hpp" #include "ShaderDiskCache.hpp" #include "Optimization/ResourceProgram.hpp" +#include "HeapSampleKernel.hpp" #include "VulkanTestDevice.hpp" #ifdef _WIN32 #ifndef NOMINMAX @@ -31,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -326,10 +329,50 @@ Totals Snapshot() { return {AgcDriver::Graphics::PipelineJournalTotals(), AgcDriver::Graphics::PipelineStoreTotals()}; } +alignas(256) std::array SampleTexture{}; +alignas(4096) std::array SampleOutput{}; + +void DispatchSample(AgcDriver::VulkanDevice& device, const char* what) { + SampleOutput.fill(-1.0f); + const auto result = CompileSampleKernel(device, SampleTexture.data(), SampleOutput.data()); + Require(result.gpuResolvedImages, std::string(what) + ": the sampling compute stage is not GPU mode"); + const auto before = AgcDriver::Graphics::HeapComputeStages(); + device.Dispatch(result, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); + device.WaitIdle(); + Require(AgcDriver::Graphics::HeapComputeStages() > before, std::string(what) + ": the heap did not take the sampling compute stage"); + RequireSampled(SampleOutput.data(), SampleTexel, what); +} + +void HeapJournalTests() { + FillTexels(SampleTexture, SampleTexel); + { + const auto device = OpenVulkanTestDevice(); + Require(device != nullptr, "the first device is required once the second opened"); + device->WaitForPipelineJournalReplay(); + DispatchSample(*device, "first run"); + Require(device->ComputePipelinesCreated() == 1, "the first run did not build exactly one compute pipeline"); + AgcDriver::Graphics::FlushPipelineJournal(); + Require(Snapshot().journal.recordedCompute == 1, "the first run did not record the GPU-mode compute pipeline"); + Require(AgcDriver::Graphics::PipelineJournalPath().filename() == "pipelines-heap.journal", "the GPU-mode pipelines were recorded in the journal the per-draw binding model replays"); + } + { + const auto device = OpenVulkanTestDevice(); + Require(device != nullptr, "the second device could not be opened"); + device->WaitForPipelineJournalReplay(); + const auto replayed = Snapshot(); + Require(replayed.journal.replayedCompute == 1 && replayed.journal.replayFailed == 0 && replayed.journal.replayRejected == 0, "the replay did not build the GPU-mode compute pipeline"); + Require(device->ComputePipelinesCreated() == 1, "the replay did not build the compute pipeline on the new device"); + Require(device->DescriptorHeapComputePipelines() == 1, "the replay did not build the GPU-mode compute pipeline on the descriptor heap"); + DispatchSample(*device, "second run"); + Require(device->ComputePipelinesCreated() == 1, "the second run's dispatch built a compute pipeline the replay had built"); + } +} + void JournalTests() { using namespace NarrowConstantStoreFixture; Require(AgcDriver::Graphics::PipelineJournalEnabled(), "the pipeline journal is disabled although the shader cache directory is set"); const auto journalPath = AgcDriver::Graphics::PipelineJournalPath(); + Require(journalPath.filename() == (AgcDriver::Graphics::GpuHeapEnabled() ? "pipelines-heap.journal" : "pipelines.journal"), "the pipeline journal file does not match the GPU heap mode"); Block compute(BlockBytes); Block target(ColorTargetLayout(Width, Height, ColorTileMode::Linear, 2).Bytes()); const auto computeCode = ComputeCode(0); @@ -880,6 +923,12 @@ int main(int argc, char** argv) { Benchmark(argc >= 3 ? static_cast(std::strtoul(argv[2], nullptr, 10)) : 24u); return 0; } + if (argc >= 2 && std::string(argv[1]) == "--gpu-heap") { + if (AgcDriver::Graphics::GpuHeapEnabled() && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; + HeapJournalTests(); + std::puts("pipeline journal record and replay of a GPU-mode compute stage passed"); + return 0; + } if (argc >= 2 && std::string(argv[1]) == "--undecodable-module") { UndecodableModuleIsNotExpanded(); std::puts("pipeline journal undecodable module passed"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PixelBarycentricEmulation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PixelBarycentricEmulation.cpp index e6cc79c1e00b..87c5a65c16fd 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PixelBarycentricEmulation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PixelBarycentricEmulation.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" #include "VulkanTestDevice.hpp" @@ -104,6 +105,7 @@ ShaderRecompiler::RecompileResult Draw(AgcDriver::VulkanDevice& device, Emulatio auto target = device.Target(); target.fragmentShaderBarycentricEnabled = NativePerVertex; target.hostInterpolationFirst = NativePerVertex; + target.gpuResolvedImages = AgcDriver::Graphics::DescriptorHeapEnabled(); target.fragmentBarycentricBuiltins = builtins; static const auto trianglePositions = ClipPositions(Emulation::Geometry); static const auto rectanglePositions = ClipPositions(Emulation::RectList); @@ -144,6 +146,7 @@ ShaderRecompiler::RecompileResult Draw(AgcDriver::VulkanDevice& device, Emulatio }; fragment.useCache = false; auto pixelResult = ShaderRecompiler::Recompile(fragment); + AgcDriver::Graphics::Require(vertexResult.gpuResolvedImages == target.gpuResolvedImages && pixelResult.gpuResolvedImages == target.gpuResolvedImages, "the barycentric draw's stages did not take GPU mode"); if (CompileOnly) return pixelResult; std::vector shaders{{ShaderStage::Vertex, &vertexResult, 0}}; ShaderRecompiler::RecompileResult geometry; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp index 34c005409e59..ad654dd338bd 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "VulkanTestDevice.hpp" #include "prx/libSceAgcDriver/Execution/include/ShaderPreparation.hpp" #include "SceShaders.hpp" @@ -23,6 +24,12 @@ namespace { +std::vector PreparePerDrawStages(const AgcDriver::DriverDetail::DrawDecode& decoded, const ShaderRecompiler::SpirvTarget& target) { + auto stages = AgcDriver::DriverDetail::PrepareGraphicsStages(decoded, target); + std::erase_if(stages, [](const AgcDriver::DriverDetail::PreparedGraphicsStage& stage) { return stage.heapVariant; }); + return stages; +} + void Require(bool condition, const char* message) { if (!condition) throw std::runtime_error(message); } @@ -135,7 +142,7 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path target.mesh = MeshTargetLimits{{128, 1, 1}, 128, 32768, 256, 256, 128, 32768, 1, 1}; target.spirvVersion = 0x00010400u; } - const auto stages = PrepareGraphicsStages(prepared, target); + const auto stages = PreparePerDrawStages(prepared, target); Require(stages.size() == (tessellation ? 4u : 2u), "graphics preparation compiled the wrong stages"); if (!mesh && !tessellation && target.registrationModules) { const auto prebuild = [&](const std::vector& group, std::initializer_list picked) { @@ -153,10 +160,17 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path Require(stages.front().registration == nullptr && !GetPreparedArtifact(*stages.front().entry.handle).registrationModule, "registration modules: the vertex stage was prepared in registration form"); const auto pixelOnly = prebuild(stages, {1u}); Require(pixelOnly.second == 1u, "registration modules: the pixel stage alone did not build its fragment library"); - const auto again = PrepareGraphicsStages(prepared, target); + const auto again = PreparePerDrawStages(prepared, target); Require(again.back().registration != stages.back().registration, "registration modules: the second preparation reused the first result object"); const auto repeated = prebuild(again, {1u}); Require(repeated.first == 0u && repeated.second == 0u, "registration modules: another materialization of the same stage did not find the prebuilt library"); + std::size_t heapVertexStages = 0; + for (const auto& stage : AgcDriver::DriverDetail::PrepareGraphicsStages(prepared, target)) { + if (!stage.heapVariant || stage.stage != ShaderRecompiler::ShaderStage::Vertex) continue; + Require(GetPreparedArtifact(*stage.entry.handle).registrationModule, "registration modules: the heap vertex stage was not prepared in registration form"); + ++heapVertexStages; + } + Require(!target.descriptorMemory || heapVertexStages != 0, "registration modules: the descriptor heap prepared no heap vertex stage"); } for (const auto& stage : stages) stage.snapshot->prepared->entries.push_back(stage.entry); const auto& pixelArtifact = GetPreparedArtifact(*stages.back().entry.handle); @@ -192,7 +206,7 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path auto changed = prepared; changed.state.stages.vertexWaveSize = 64; changed.pixel.interpolatorSettings[0] = 0x404u; - const auto newStages = PrepareGraphicsStages(changed, target); + const auto newStages = PreparePerDrawStages(changed, target); front.snapshot->prepared->entries.push_back(newStages.front().entry); ResolvePreparedGraphics(*front.snapshot, {}, 7, target); const auto newVertexId = GetPreparedArtifact(*newStages.front().entry.handle).variantId; @@ -214,7 +228,7 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path Require(front.snapshot->prepared->rectangleProgress.size() == 1 && !front.snapshot->prepared->rectangleProgress.front().fragment.expired(), "expired rectangle progress was not removed"); auto drawOnly = prepared; drawOnly.pixel.interpolatorSettings[0] = 0x405u; - const auto drawStages = PrepareGraphicsStages(drawOnly, target); + const auto drawStages = PreparePerDrawStages(drawOnly, target); auto unlinked = std::make_shared(); unlinked->type = 1; unlinked->prepared->entries.push_back(drawStages.back().entry); @@ -236,10 +250,10 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path } auto incomplete = prepared; incomplete.roles.pop_back(); - Reject([&] { static_cast(PrepareGraphicsStages(incomplete, target)); }, "program roles are incomplete"); + Reject([&] { static_cast(PreparePerDrawStages(incomplete, target)); }, "program roles are incomplete"); auto wrongEntry = prepared; wrongEntry.programs.front().binary.codeAddress += 4; - Reject([&] { static_cast(PrepareGraphicsStages(wrongEntry, target)); }, "entry point differs"); + Reject([&] { static_cast(PreparePerDrawStages(wrongEntry, target)); }, "entry point differs"); std::vector linked; std::vector memory; for (std::size_t index = 0; index < draw.programs.size(); ++index) { @@ -283,7 +297,7 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path resolved.pixel = prepared.pixel; DecodeGraphicsPrograms(resolved, unbound, registry, true, true); Require(resolved.programs.size() == 3u && resolved.roles.front() == ProgramRole::Hull, "an unbound local program was not left to the draw"); - Require(PrepareGraphicsStages(resolved, target).size() == 3u, "graphics preparation without the local program compiled the wrong stages"); + Require(PreparePerDrawStages(resolved, target).size() == 3u, "graphics preparation without the local program compiled the wrong stages"); auto bound = queue; late.Bind(bound, 0x148u, 0x10bu); DrawDecode lateDraw{}; @@ -346,7 +360,7 @@ void PushBudgetBoundaries(AgcDriver::VulkanDevice& device) { auto target = device.Target(); target.fixedPushSlots = fixedSlots; target.registrationModules = false; - auto stages = PrepareGraphicsStages(decoded, target); + auto stages = PreparePerDrawStages(decoded, target); Require(stages.size() == decoded.programs.size(), "push budget preparation lost a graphics stage"); for (std::size_t index = 0u; index < stages.size(); ++index) { Require(stages[index].entry.handle != nullptr, "push budget preparation lost its source handle"); @@ -399,7 +413,7 @@ void PrebuildPolicyReadback(AgcDriver::VulkanDevice& device, bool disabled) { append(ShaderStage::Vertex, vertexCode, {static_cast(address), static_cast(address >> 32u) | (16u << 16u), 3u, 0x01016facu}); append(ShaderStage::Fragment, pixelCode, {}); const auto target = device.Target(); - const auto stages = PrepareGraphicsStages(decoded, target); + const auto stages = PreparePerDrawStages(decoded, target); Require(stages.size() == 2u, "prebuild policy lost a required graphics stage"); for (const auto& stage : stages) { Require(stage.entry.handle != nullptr && stage.snapshot != nullptr, "prebuild policy lost a required source handle"); @@ -516,7 +530,7 @@ void RetainedPixelMatchesNullProgram(AgcDriver::VulkanDevice& device) { Require(AgcDriver::Graphics::DrawKeyCovers(read), "a pixel substitution dependency is absent from the draw key"); Require(read.bank != AgcDriver::Graphics::RegisterBank::Shader || read.offset < 0x00bu || read.offset > 0x02bu, "the substituted program read fragment resources or userdata"); } - const auto stages = PrepareGraphicsStages(draw, device.Target()); + const auto stages = PreparePerDrawStages(draw, device.Target()); Require(stages.size() == 2 && stages.back().entry.handle != nullptr, "a retained-format null program was not prepared"); std::vector linked; std::vector memory; @@ -625,7 +639,23 @@ void CheckMergedHull(AgcDriver::VulkanDevice& device) { DecodeGraphicsPrograms(stale, unmapped, registry, false, true); Require(stale.programs[1].userData[0] == 0x10u && stale.programs[1].userData[1] == 0u, "a merged hull draw did not pass a user-data address it does not need unchecked"); const auto stages = PrepareGraphicsStages(prepared, device.Target()); - Require(stages.size() == 4u && stages[0].entry.handle != stages[1].entry.handle, "a merged hull program was not prepared as separate local and hull stages"); + for (const bool heapVariant : {false, true}) { + std::vector set; + for (const auto& stage : stages) { + if (stage.heapVariant == heapVariant) set.push_back(&stage); + } + if (heapVariant && set.empty()) { + Require(!AgcDriver::Graphics::DescriptorHeapEnabled(), "the heap prepared no heap variants of the merged hull draw"); + continue; + } + const auto handleOf = [&](ShaderRecompiler::ShaderStage wanted) { + const auto found = std::find_if(set.begin(), set.end(), [&](const auto* stage) { return stage->stage == wanted; }); + return found == set.end() ? nullptr : (*found)->entry.handle.get(); + }; + const auto* local = handleOf(ShaderRecompiler::ShaderStage::Local); + const auto* hull = handleOf(ShaderRecompiler::ShaderStage::TessellationControl); + Require((heapVariant || set.size() == 4u) && local != nullptr && hull != nullptr && local != hull, "a merged hull program was not prepared as separate local and hull stages"); + } for (const auto& stage : stages) stage.snapshot->prepared->entries.push_back(stage.entry); std::vector linked; std::vector memory; @@ -641,8 +671,12 @@ void CheckMergedHull(AgcDriver::VulkanDevice& device) { RecompileRequest request{program.binary, {64u, program.firstUserSgpr, program.userData, {}, std::nullopt, vertex, memory}, device.Target(), {0, 0, 0, 128u}, GraphicsCompileContext{program.firstUserSgpr, linked, std::nullopt, draw.state.stages.tessellation, {0, 3, 4, 1}}}; static_cast(InvocationFor(*program.snapshot, program.codeOffset, request)); Require(merged.snapshot->prepared->entries.size() == predicted, "a merged hull stage prepared at ABI resolution was prepared again at its draw"); + const auto wanted = index == 0u ? ShaderRecompiler::ShaderStage::Local : ShaderRecompiler::ShaderStage::TessellationControl; + const auto regular = std::find_if(stages.begin(), stages.end(), [&](const auto& stage) { return !stage.heapVariant && stage.stage == wanted; }); + Require(regular != stages.end(), "a merged hull draw prepared no regular stage for its program"); + Require(MatchesPreparedShader(request, *regular->entry.handle), "an unchanged merged hull request did not match its prepared artifact"); request.graphics->tessellation->mergedHull = false; - Require(!MatchesPreparedShader(request, *stages[index].entry.handle), "a separate hull configuration matched a merged hull artifact"); + Require(!MatchesPreparedShader(request, *regular->entry.handle), "a separate hull configuration matched a merged hull artifact"); } Fixture front; front.Initialize(5u); @@ -773,7 +807,7 @@ void NullPixelMatchesRegistration(AgcDriver::VulkanDevice& device) { DecodeGraphicsPrograms(draw, queue, registry, false, true); const auto& fragment = draw.programs.back(); Require(fragment.snapshot == null && fragment.userData.empty(), "a null pixel draw took the last pixel shader's user SGPRs"); - const auto stages = PrepareGraphicsStages(draw, device.Target()); + const auto stages = PreparePerDrawStages(draw, device.Target()); const auto& handle = stages.back().entry.handle; Require(std::ranges::any_of(registered, [&](const auto& entry) { return entry.handle == handle; }), "a null pixel draw did not match the variant prepared at registration"); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp index 684a1f334be3..eb7ec7b0d6af 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp @@ -90,6 +90,8 @@ void RunUnregistered(AgcDriver::VulkanDevice& device, ShaderRecompiler::Recompil Require(snapshot.prepared->entries.size() == 1, "unregistered compute invocation did not cache exactly one artifact"); const auto handle = snapshot.prepared->entries.front().handle; const auto& artifact = ShaderRecompiler::GetPreparedArtifact(*handle); + const std::uint32_t* module = artifact.gpuResolvedImages ? nullptr : artifact.spirv.data(); + std::vector> keptResults; for (const bool useCache : {false, true}) { request.useCache = useCache; Require(AgcDriver::DriverDetail::SourceHandleFor(snapshot, 0, request) == handle, "unregistered compute source was prepared again"); @@ -98,7 +100,9 @@ void RunUnregistered(AgcDriver::VulkanDevice& device, ShaderRecompiler::Recompil runtime.userData = request.context.userData; const auto capture = repeated.Capture(runtime); const auto result = repeated.Materialize(*capture); - Require(snapshot.prepared->entries.size() == 1 && result->variantId == artifact.variantId && result->spirv.data() == artifact.spirv.data(), "unregistered compute invocation replaced its cached artifact"); + if (module == nullptr) module = result->spirv.data(); + keptResults.push_back(result); + Require(snapshot.prepared->entries.size() == 1 && result->variantId == artifact.variantId && result->spirv.data() == module, "unregistered compute invocation replaced its cached artifact"); device.Dispatch(*result, 1, 1, 1); } device.WaitIdle(); @@ -141,6 +145,8 @@ void Run(AgcDriver::VulkanDevice& device) { snapshot.prepared->entries.push_back({0, handle}); ExpectFailure([&] { static_cast(AgcDriver::DriverDetail::SourceHandleFor(snapshot, 1, request)); }, "outside the snapshot"); const auto& artifact = ShaderRecompiler::GetPreparedArtifact(*handle); + const std::uint32_t* module = artifact.gpuResolvedImages ? nullptr : artifact.spirv.data(); + std::vector> keptResults; for (std::uint32_t value = 0; value < 8; ++value) { users.fill(value); request.useCache = value % 2 == 0; @@ -149,7 +155,9 @@ void Run(AgcDriver::VulkanDevice& device) { runtime.userData = users; const auto capture = ShaderRecompiler::CaptureResources(request, runtime, *ready); const auto result = ShaderRecompiler::MaterializeShader(request, *capture, *ready); - Require(result->variantId == artifact.variantId && result->spirv.data() == artifact.spirv.data(), "invocation replaced the prepared artifact"); + if (module == nullptr) module = result->spirv.data(); + keptResults.push_back(result); + Require(result->variantId == artifact.variantId && result->spirv.data() == module, "invocation replaced the prepared artifact"); device.Dispatch(*result, 1, 1, 1); } device.WaitIdle(); @@ -185,7 +193,7 @@ void Run(AgcDriver::VulkanDevice& device) { const auto replacementInvocation = AgcDriver::DriverDetail::InvocationFor(snapshot, 0, replacementRequest); const auto replacementCapture = replacementInvocation.Capture(preparedRuntime); const auto replacementResult = replacementInvocation.Materialize(*replacementCapture); - Require(replacementResult->spirv.data() == artifact.spirv.data(), "device replacement recompiled the prepared shader"); + Require(replacementResult->spirv.data() == (artifact.gpuResolvedImages ? firstResult->spirv.data() : artifact.spirv.data()), "device replacement recompiled the prepared shader"); replacement->Dispatch(*replacementResult, 1, 1, 1); replacement->WaitIdle(); replacementRequest.target.nonConstantImageOffsets = !replacementRequest.target.nonConstantImageOffsets; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp new file mode 100644 index 000000000000..610fc266e510 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp @@ -0,0 +1,116 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::BindlessHeap; +using AgcDriver::Graphics::Buffer; +using AgcDriver::Graphics::Recorder; +using AgcDriver::Graphics::Require; + +void RunChangedCopy(const AgcDriver::VulkanDevice& device) { + const auto context = device.graphicsContext(); + const bool heapMode = AgcDriver::Graphics::DescriptorHeapEnabled() && context.descriptorHeap && BindlessHeap::For(context).DescriptorHeapMode(); + constexpr std::uint32_t words = 300; + constexpr auto usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + auto result = std::make_shared(context, words * 4u, usage); + auto snapshot = std::make_shared(context, words * 4u, usage); + auto target = std::make_shared(context, words * 4u, usage); + std::vector shader(words); + for (std::uint32_t i = 0; i < words; ++i) shader[i] = i % 3 == 0 ? 0x9e3779b9u * (i + 1u) : 0u; + std::memset(snapshot->Bytes().data(), 0, words * 4u); + std::memset(target->Bytes().data(), 0, words * 4u); + std::memcpy(result->Bytes().data(), shader.data(), words * 4u); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + auto* recorder = Recorder::Active(); + Require(recorder != nullptr, "push-only heap passes: no active recorder"); + if (heapMode) BindlessHeap::For(context).BindDescriptorHeaps(recorder->Commands()); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds(); + Require(recorder->RecordChangedCopy(recorder->Commands(), result->DeviceAddress(), snapshot->DeviceAddress(), target->DeviceAddress(), words), "push-only heap passes: the changed copy kernel is unavailable"); + if (heapMode) { + BindlessHeap::For(context).BindDescriptorHeaps(recorder->Commands()); + Require(AgcDriver::Graphics::DescriptorHeapBinds() == binds, "push-only heap passes: the changed copy put its command buffer back in classic descriptor mode, so the heaps were bound again"); + } + recorder->Keep(result); + recorder->Keep(snapshot); + recorder->Keep(target); + recorder->Submit(); + recorder->Sync(); + std::vector stored(words); + std::memcpy(stored.data(), target->Bytes().data(), words * 4u); + for (std::uint32_t i = 0; i < words; ++i) { + Require(stored[i] == shader[i], "push-only heap passes: changed copy word " + std::to_string(i) + " is " + std::to_string(stored[i]) + ", the shader wrote " + std::to_string(shader[i])); + } +} + +void RunDispatchArguments(const AgcDriver::VulkanDevice& device) { + const auto context = device.graphicsContext(); + const bool heapMode = AgcDriver::Graphics::DescriptorHeapEnabled() && context.descriptorHeap && BindlessHeap::For(context).DescriptorHeapMode(); + constexpr auto usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + auto threads = std::make_shared(context, 16, usage); + auto oversized = std::make_shared(context, 16, usage); + auto grouped = std::make_shared(context, 32, usage); + auto refused = std::make_shared(context, 32, usage); + const std::uint32_t threadCounts[4] = {3u, 5u, 7u, 0u}; + const auto* limit = context.limits.maxComputeWorkGroupCount; + const auto axis = static_cast(std::min_element(limit, limit + 3) - limit); + const bool limited = limit[axis] < std::numeric_limits::max(); + std::uint32_t tooMany[4] = {1u, 1u, 1u, 0u}; + tooMany[axis] = limited ? limit[axis] + 1u : limit[axis]; + std::memcpy(threads->Bytes().data(), threadCounts, sizeof(threadCounts)); + std::memcpy(oversized->Bytes().data(), tooMany, sizeof(tooMany)); + std::memset(grouped->Bytes().data(), 0xff, 32); + std::memset(refused->Bytes().data(), 0xff, 32); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + auto* recorder = Recorder::Active(); + Require(recorder != nullptr, "push-only heap passes: no active recorder"); + if (heapMode) BindlessHeap::For(context).BindDescriptorHeaps(recorder->Commands()); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds(); + const std::array group{2u, 2u, 2u}; + Require(recorder->RecordDispatchArguments(recorder->Commands(), threads->DeviceAddress(), grouped->DeviceAddress(), &group), "push-only heap passes: the dispatch argument kernel is unavailable"); + Require(recorder->RecordDispatchArguments(recorder->Commands(), oversized->DeviceAddress(), refused->DeviceAddress()), "push-only heap passes: the dispatch argument kernel is unavailable"); + if (heapMode) { + BindlessHeap::For(context).BindDescriptorHeaps(recorder->Commands()); + Require(AgcDriver::Graphics::DescriptorHeapBinds() == binds, "push-only heap passes: the dispatch argument check put its command buffer back in classic descriptor mode, so the heaps were bound again"); + } + for (const auto& kept : {threads, oversized, grouped, refused}) recorder->Keep(kept); + recorder->Submit(); + recorder->Sync(); + std::uint32_t words[6]{}; + std::memcpy(words, grouped->Bytes().data(), sizeof(words)); + const std::uint32_t expected[6] = {2u, 3u, 4u, 3u, 5u, 7u}; + for (std::size_t i = 0; i < 6; ++i) Require(words[i] == expected[i], "push-only heap passes: dispatch argument word " + std::to_string(i) + " is " + std::to_string(words[i]) + ", expected " + std::to_string(expected[i])); + std::memcpy(words, refused->Bytes().data(), 3 * sizeof(std::uint32_t)); + if (limited) Require(words[0] == 0u && words[1] == 0u && words[2] == 0u, "push-only heap passes: a group count past the device limit was dispatched"); +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + RunChangedCopy(*device); + RunDispatchArguments(*device); + device->WaitIdle(); + std::puts("push-only heap pass tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/RecipeTemplateAging.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/RecipeTemplateAging.cpp new file mode 100644 index 000000000000..10e32a1b72cc --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/RecipeTemplateAging.cpp @@ -0,0 +1,159 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.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; + +constexpr std::size_t Entries = 16; +constexpr std::uint32_t Dispatches = 40; +constexpr std::size_t SrtBytes = 64; +constexpr std::size_t OutputBytes = 256; +constexpr std::size_t SrtOffset = 4096; +constexpr std::size_t OutputOffset = SrtOffset + static_cast(Dispatches) * SrtBytes; +constexpr std::size_t BlockBytes = (OutputOffset + static_cast(Dispatches) * OutputBytes + 65535) & ~static_cast(65535); + +constexpr std::array StoreCode{0xf4080100u, 0xfa000000u, 0xbf8c0000u, 0x7e020281u, 0xe0700000u, 0x80010100u, 0xbf810000u}; + +class GuestBlock { +public: + GuestBlock() { +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(BlockBytes, 65536)); + if (block != nullptr) GuestArena::GuestArenaCommit_nid_postfix(block, BlockBytes, PAGE_READWRITE, BlockBytes); +#else + constexpr std::uintptr_t alignment = 65536; + void* mapped = mmap(nullptr, BlockBytes + alignment, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (mapped != MAP_FAILED) { + const auto begin = reinterpret_cast(mapped); + const auto aligned = (begin + alignment - 1) & ~(alignment - 1); + if (aligned != begin) munmap(mapped, aligned - begin); + if (aligned + BlockBytes != begin + BlockBytes + alignment) munmap(reinterpret_cast(aligned + BlockBytes), begin + alignment - aligned); + block = reinterpret_cast(aligned); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, BlockBytes); + } +#endif + Require(block != nullptr, "recipe template aging: cannot allocate the guest block"); + GuestAllocations::Mutation().Add(block, BlockBytes, true, true, true); + } + + GuestBlock(const GuestBlock&) = delete; + GuestBlock& operator=(const GuestBlock&) = delete; + + std::uint64_t At(std::size_t offset) const { return static_cast(reinterpret_cast(block + offset)); } + std::uint8_t* Bytes(std::size_t offset) const { return block + offset; } + +private: + std::uint8_t* block = nullptr; +}; + +std::vector Pm4(std::uint32_t opcode, std::initializer_list body) { + std::vector words{0xc0000000u | (static_cast(body.size() - 1) << 16u) | (opcode << 8u)}; + words.insert(words.end(), body); + return words; +} + +void Prepare(const GuestBlock& block) { + std::memcpy(block.Bytes(0), StoreCode.data(), sizeof(StoreCode)); + for (std::uint32_t dispatch = 0; dispatch < Dispatches; ++dispatch) { + const auto output = block.At(OutputOffset + static_cast(dispatch) * OutputBytes); + const std::array descriptor{static_cast(output), static_cast((output >> 32u) & 0xffffu), static_cast(OutputBytes), 0x31016facu}; + std::memcpy(block.Bytes(SrtOffset + static_cast(dispatch) * SrtBytes), descriptor.data(), sizeof(descriptor)); + } + std::memset(block.Bytes(OutputOffset), 0, static_cast(Dispatches) * OutputBytes); +} + +void Run(const GuestBlock& block, std::span order) { + const auto kernel = block.At(0); + std::vector words; + for (const auto dispatch : order) { + const auto srt = block.At(SrtOffset + static_cast(dispatch) * SrtBytes); + for (const auto& packet : {Pm4(0x76, {0x20c, static_cast(kernel >> 8u)}), Pm4(0x76, {0x20d, static_cast(kernel >> 40u) & 0xffu}), Pm4(0x76, {0x207, 64}), Pm4(0x76, {0x208, 1}), Pm4(0x76, {0x209, 1}), Pm4(0x76, {0x213, 2u << 1u}), Pm4(0x76, {0x240, static_cast(srt)}), Pm4(0x76, {0x241, static_cast(srt >> 32u)}), Pm4(0x15, {1, 1, 1, 0x41})}) { + words.insert(words.end(), packet.begin(), packet.end()); + } + } + Packet dcb{words.data(), static_cast(words.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&dcb) == 0, "recipe template aging: the dispatch submission failed"); + AgcDriverWaitIdle_nid_postfix(); +} + +void HotTemplateOutlivesChurn(const GuestBlock& block) { + std::vector warm{0, 0, 0}; + Run(block, warm); + std::vector order; + for (std::uint32_t cold = 1; cold < Dispatches; ++cold) { + order.push_back(0); + order.push_back(cold); + } + const auto hot = static_cast(std::count(order.begin(), order.end(), 0u)); + const auto restarts = AgcDriver::VulkanDevice::DispatchRecipeTemplatesGone(); + const auto touches = AgcDriver::Graphics::ResourceCache::Touches(); + for (std::size_t at = 0; at < order.size(); at += 2) Run(block, std::span(order).subspan(at, 2)); + const auto touched = AgcDriver::Graphics::ResourceCache::Touches() - touches; + const auto restarted = AgcDriver::VulkanDevice::DispatchRecipeTemplatesGone() - restarts; + if (!AgcDriver::VulkanDevice::VerifyRecipes()) Require(touched > 0 && touched < hot, "recipe template aging: " + std::to_string(hot) + " recipe hits on the hot dispatch made " + std::to_string(touched) + " cache touches; expected some, and fewer than one per hit"); + Require(restarted == 0, "recipe template aging: the hot dispatch's template aged out of a " + std::to_string(Entries) + "-entry cache under cold dispatches, so " + std::to_string(restarted) + " of its " + std::to_string(hot) + " recipe hits rebuilt"); + for (std::uint32_t dispatch = 0; dispatch < Dispatches; ++dispatch) { + std::uint32_t stored = 0; + AgcDriver::GuestMemory::Read(block.At(OutputOffset + static_cast(dispatch) * OutputBytes), std::as_writable_bytes(std::span(&stored, 1)), 4); + Require(stored == 1u, "recipe template aging: dispatch " + std::to_string(dispatch) + " stored " + std::to_string(stored) + ", expected 1"); + } +} + +} + +int main() { +#ifdef _WIN32 + _putenv_s("APS5_RESOURCE_CACHE_ENTRIES", "16"); +#else + setenv("APS5_RESOURCE_CACHE_ENTRIES", "16", 1); +#endif + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + if (!AgcDriver::VulkanDevice::DispatchRecipes()) { + std::puts("skipped, dispatch recipes are off"); + return VulkanTestSkipped; + } + auto& cache = AgcDriver::Graphics::SharedResourceCache(); + cache.Clear(); + GuestBlock block; + Prepare(block); + HotTemplateOutlivesChurn(block); + AgcDriverShutdown_nid_postfix(); + std::puts("a hot dispatch served by recipes kept its template in a churning resource cache with fewer touches than hits"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp index dccf41cc03ba..1b93ed7db6fb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp @@ -2,14 +2,17 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/GuestTextureResource.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTextureLayout.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderInputState.hpp" #include "prx/libSceAgcDriver/Graphics/include/State.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -468,7 +471,7 @@ ShaderRecompiler::RecompileResult CompileProgram(AgcDriver::VulkanDevice& device ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; @@ -600,6 +603,26 @@ void CheckFirstSampleReads(AgcDriver::VulkanDevice& device, const std::arrayCommands()); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds(); + const auto texture = AgcDriver::Graphics::MultisampleTargetFirstSample(context, resource, {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY}); + Require(texture != nullptr, "first-sample copy in heap mode: the drawn 4x target has no sample 0 texture"); + heap.BindDescriptorHeaps(recorder->Commands()); + Require(AgcDriver::Graphics::DescriptorHeapBinds() == binds, + "a first-sample copy in heap mode put its command buffer back in classic descriptor mode, so the heaps were bound again"); + recorder->Submit(); + recorder->Sync(); +} + std::array CompressedDescriptor(const Block& block, std::uint32_t tileMode, std::uint64_t htile) { auto texture = TargetDescriptor(block, SampleShift, Format16161616Float, tileMode); const auto meta = htile >> 8u; @@ -1068,7 +1091,7 @@ int NonuniformInitialLifetime(AgcDriver::VulkanDevice& device) { { auto recorded = context; recorded.bufferPool = std::make_shared(context); - Recorder recorder(recorded); + Recorder recorder(recorded, true); std::shared_ptr owner; VkImageView view = VK_NULL_HANDLE; std::size_t initialBytes = 0; @@ -2117,6 +2140,7 @@ int main(int argc, char** argv) { const auto drawn = LoadSamples(*device, block); CheckSamples(state, drawn, {}); CheckFirstSampleReads(*device, TargetDescriptor(block, SampleShift), drawn, true, "from the drawn 4x target"); + CheckFirstSampleCopyStaysInHeapMode(*device, block); CheckFirstSampleReads(*device, TargetDescriptor(block, SampleShift), drawn, true, "from the drawn 4x target", AdjustedPlaneCode, "image_sample_a"); std::puts("a DIM 2D image_sample_a read of a 4x color target returns each pixel's sample 0"); Draw(*device, state, 0, 2u, Unorm8PixelCode); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampleOrder.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampleOrder.cpp index 43cea034604f..76c6aba38878 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampleOrder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampleOrder.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" @@ -62,6 +63,21 @@ struct VulkanDeviceTestAccess { namespace { +template +void RecordStayingOnHeap(const AgcDriver::Graphics::Context& context, VkCommandBuffer commands, const std::string& what, Record&& record) { + if (!AgcDriver::Graphics::HeapPassesActive(context)) { + record(); + return; + } + auto& heap = AgcDriver::Graphics::BindlessHeap::For(context); + heap.BindDescriptorHeaps(commands); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds(); + record(); + heap.BindDescriptorHeaps(commands); + if (AgcDriver::Graphics::DescriptorHeapBinds() != binds) throw std::runtime_error(what + " put its command buffer back in classic descriptor mode, so the heaps were bound again"); +} + + using AgcDriver::Graphics::Check; using AgcDriver::Graphics::Context; using AgcDriver::Graphics::KeptSampleOrder; @@ -533,7 +549,8 @@ bool ColorSwaps(const Context& context, VkFormat format, std::uint32_t elementBy texels.Storage(1u, values.Handle()); const std::array store{SwapExtent.width, SwapExtent.height, samples, 1u}; const std::array load{SwapExtent.width, SwapExtent.height, samples, 0u}; - const SampleOrderTarget target{image.Handle(), view, alias, SwapExtent, samples, SampleOrderMethod::Storage, nullptr}; + const AgcDriver::Graphics::HeapPassSlots slots(context); + const SampleOrderTarget target{image.Handle(), view, alias, SwapExtent, samples, SampleOrderMethod::Storage, nullptr, &slots}; const SampleOrderPass pass{order, SwapRegion, {}, false}; std::vector> kept; Submit(context, [&](VkCommandBuffer commands) { @@ -545,14 +562,14 @@ bool ColorSwaps(const Context& context, VkFormat format, std::uint32_t elementBy }); Require(Masked(ReadValues(values, count), elementBytes) == before, name + ": the stored samples did not read back"); Submit(context, [&](VkCommandBuffer commands) { - RecordSampleOrderOn(context, commands, pass, std::span(&target, 1u), true, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { RecordSampleOrderOn(context, commands, pass, std::span(&target, 1u), true, kept); }); FullBarrier(context, commands); texels.Dispatch(commands, load.data(), SwapExtent); HostBarrier(context, commands); }); CheckOrdered(before, Masked(ReadValues(values, count), elementBytes), SwapExtent, SwapRegion, samples, order, true, name + " put in the host's order"); Submit(context, [&](VkCommandBuffer commands) { - RecordSampleOrderOn(context, commands, pass, std::span(&target, 1u), false, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { RecordSampleOrderOn(context, commands, pass, std::span(&target, 1u), false, kept); }); FullBarrier(context, commands); texels.Dispatch(commands, load.data(), SwapExtent); HostBarrier(context, commands); @@ -633,14 +650,14 @@ bool DepthSwaps(const Context& context, VkFormat format, std::uint32_t samples, Require(depthHeld && (!stencil || before[index][1] == filled[index][1]), name + ": the filled sample " + std::to_string(index) + " did not read back"); } Submit(context, [&](VkCommandBuffer commands) { - RecordSampleOrderOn(context, commands, pass, std::span(&target, 1u), true, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { RecordSampleOrderOn(context, commands, pass, std::span(&target, 1u), true, kept); }); FullBarrier(context, commands); read.Dispatch(commands, push.data(), SwapExtent); HostBarrier(context, commands); }); CheckOrdered(before, ReadValues(values, count), SwapExtent, SwapRegion, samples, order, true, name + " put in the host's order"); Submit(context, [&](VkCommandBuffer commands) { - RecordSampleOrderOn(context, commands, pass, std::span(&target, 1u), false, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { RecordSampleOrderOn(context, commands, pass, std::span(&target, 1u), false, kept); }); FullBarrier(context, commands); read.Dispatch(commands, push.data(), SwapExtent); HostBarrier(context, commands); @@ -1451,8 +1468,9 @@ int Bench(AgcDriver::VulkanDevice& device, VkExtent2D extent, std::uint32_t samp Image depth(context, VK_FORMAT_D32_SFLOAT, samples, extent, DepthUsage, located ? VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT : 0u); const auto storage = color.View(alias, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_USAGE_STORAGE_BIT); const auto attachment = depth.View(VK_FORMAT_D32_SFLOAT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); + const AgcDriver::Graphics::HeapPassSlots slots(context); const std::array targets{{ - {color.Handle(), storage, alias, extent, samples, SampleOrderMethod::Storage, nullptr}, + {color.Handle(), storage, alias, extent, samples, SampleOrderMethod::Storage, nullptr, &slots}, {depth.Handle(), attachment, VK_FORMAT_D32_SFLOAT, extent, samples, SampleOrderMethod::Depth, nullptr}, }}; VkQueryPoolCreateInfo queryInfo{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; @@ -1475,13 +1493,13 @@ int Bench(AgcDriver::VulkanDevice& device, VkExtent2D extent, std::uint32_t samp context.Function("vkCmdWriteTimestamp")(commands, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, queries, query); }; stamp(0u); - RecordSampleOrderOn(context, commands, pass, std::span(targets).subspan(1u), true, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { RecordSampleOrderOn(context, commands, pass, std::span(targets).subspan(1u), true, kept); }); stamp(1u); - RecordSampleOrderOn(context, commands, pass, std::span(targets).subspan(1u), false, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { RecordSampleOrderOn(context, commands, pass, std::span(targets).subspan(1u), false, kept); }); stamp(2u); - RecordSampleOrderOn(context, commands, pass, targets, true, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { RecordSampleOrderOn(context, commands, pass, targets, true, kept); }); stamp(3u); - RecordSampleOrderOn(context, commands, pass, targets, false, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { RecordSampleOrderOn(context, commands, pass, targets, false, kept); }); stamp(4u); }); std::array ticks{}; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp index 3a8d113d1607..6e7fbba1adfc 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp @@ -1,6 +1,8 @@ #include "../PortabilitySubset.hpp" #include "prx/libSceAgcDriver/Execution/include/BdaFeatures.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -602,6 +604,47 @@ void viewTests(const Context& context) { Require(heldView.expired() && heldStorage.expired(), "the evicted image outlived its last caller without a sampled lookup"); } +bool heapViewTests(const Context& context) { + if (!GpuHeapEnabled() || !context.descriptorHeap || context.hostImportAlignment == 0) return false; + Block block(context); + if (HostImportFor(context, block.Surface(0), BlockBytes) == nullptr) return false; + auto view = Sampled(context, block.Surface(0)); + Require(view->ViewsStorageImage(), "a sampled texture in host-imported memory is not a view of its storage image"); + const std::weak_ptr viewed = view; + for (std::size_t surface = 1; surface < Surfaces; ++surface) CachedStorageSurface(context, Resource(block.Surface(surface))); + Require(!view->StorageSource()->Cached(), "the heap view's storage image was not evicted"); + auto& heap = BindlessHeap::For(context); + const auto slot = heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, view.get(), view->View(), view->Layout()); + Require(slot.has_value(), "the view of an evicted storage image took no heap slot"); + view.reset(); + Require(viewed.expired(), "a heap slot kept the view of an evicted storage image, and with it the image"); + Require(heap.SlotTexture(ShaderRecompiler::RuntimeAbi::FirstImageBinding, *slot) == nullptr, "a destroyed view kept its heap slot"); + return true; +} + +void heapHeldReleaseTests(const Context& context) { + Block block(context); + auto& heap = BindlessHeap::For(context); + std::vector> held; + std::vector slots; + for (std::size_t surface = 0; surface < 2; ++surface) { + auto texture = Sampled(context, block.Surface(surface)); + const auto slot = heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, texture.get(), texture->View(), texture->Layout()); + Require(slot.has_value(), "the cached sampled texture took no heap slot"); + held.push_back(texture); + slots.push_back(*slot); + } + Require(TextureCacheUsage().sampledEntries == 2u, "the two sampled textures were not cached"); + Require(!held[0].expired() && !held[1].expired(), "the cache and the heap slots did not keep the sampled textures"); + if (auto* recorder = Recorder::Active()) recorder->Sync(); + const auto released = ReleaseTextureCaches(SurfaceBytes, true); + Require(held[0].expired() != held[1].expired(), "a memory recovery for one texture's bytes did not free exactly one of two textures that only the cache and the GPU heap held"); + Require(released >= SurfaceBytes && TextureCacheUsage().sampledEntries == 1u, "a memory recovery did not count the texture it freed from the cache and the GPU heap, or went past its target"); + const auto gone = held[0].expired() ? 0u : 1u; + Require(heap.SlotTexture(ShaderRecompiler::RuntimeAbi::FirstImageBinding, slots[gone]) == nullptr, "the texture a memory recovery freed kept its heap slot"); + Require(heap.SlotTexture(ShaderRecompiler::RuntimeAbi::FirstImageBinding, slots[1u - gone]) == held[1u - gone].lock().get(), "the texture a memory recovery kept lost its heap slot"); +} + ShaderRecompiler::RecompileResult SampledProgram(std::uint64_t address) { ShaderRecompiler::DescriptorBinding binding{}; binding.kind = ShaderRecompiler::DescriptorKind::SampledImage; @@ -1504,6 +1547,34 @@ int main(int argc, char** argv) { if (!memory && mode != "budget-report-age") setenv("APS5_TEXTURE_CACHE_MIB", recover ? "16" : "1", 1); setenv("APS5_TEMPLATE_AUDIT_MS", "250", 0); #endif + if (mode == "heap-view") { + SetTestEnvironment("APS5_GPU_HEAP", "1"); + auto heapDevice = OpenVulkanTestDevice(); + if (!heapDevice) return VulkanTestSkipped; + if (!heapDevice->graphicsContext().descriptorHeap) { + std::puts("skipped, the device has no VK_EXT_descriptor_heap"); + return VulkanTestSkipped; + } + bool tested = false; + { + const auto context = heapDevice->graphicsContext(); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + heapHeldReleaseTests(context); + ClearCachedTextures(context.device); + tested = heapViewTests(context); + ClearCachedTextures(context.device); + } + heapDevice->WaitIdle(); + } + heapDevice.reset(); + if (!tested) { + std::puts("skipped, host imports unavailable: heap views of evicted storage images not tested"); + return VulkanTestSkipped; + } + std::puts("heap view release tests passed"); + return 0; + } std::unique_ptr device; try { device = std::make_unique(!disableStorageImageMultisample); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp index 0359abebcc3a..473e719ae1c4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" @@ -244,14 +245,16 @@ struct Facts { bool functionArrayAccess = false; }; -Facts Inspect(std::span words) { +Facts Inspect(const ShaderRecompiler::RecompileResult& result) { + const std::span words(result.spirv.data(), result.spirv.size()); + const auto poolSet = result.gpuResolvedImages ? ShaderRecompiler::GpuScratchPoolDescriptorSet : ShaderRecompiler::ScratchPoolDescriptorSet; Facts facts; std::set arrays, pointers, variables; for (std::size_t cursor = 5; cursor < words.size();) { const auto count = words[cursor] >> 16u; const auto op = words[cursor] & 0xffffu; Require(count != 0u, "scratch pool: malformed SPIR-V"); - if (op == spv::OpDecorate && words[cursor + 2u] == spv::DecorationDescriptorSet && words[cursor + 3u] == ShaderRecompiler::ScratchPoolDescriptorSet) facts.poolBinding = true; + if (op == spv::OpDecorate && words[cursor + 2u] == spv::DecorationDescriptorSet && words[cursor + 3u] == poolSet) facts.poolBinding = true; if (op == spv::OpTypeArray) arrays.insert(words[cursor + 1u]); if (op == spv::OpTypePointer && words[cursor + 2u] == spv::StorageClassFunction && arrays.contains(words[cursor + 3u])) pointers.insert(words[cursor + 1u]); if (op == spv::OpVariable && pointers.contains(words[cursor + 1u])) variables.insert(words[cursor + 2u]); @@ -261,15 +264,23 @@ Facts Inspect(std::span words) { return facts; } +void RequireHeapPipeline(const AgcDriver::VulkanDevice& device, const ShaderRecompiler::RecompileResult& result, std::uint64_t before, const std::string& name) { + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) return; + Require(result.gpuResolvedImages, name + ": the scratch program is not GPU mode"); + Require(device.DescriptorHeapComputePipelines() > before, name + ": the scratch program did not take the descriptor heap"); +} + ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const Words& code, std::vector& userData, std::uint32_t waveSize, std::uint32_t threads, bool groupId, std::uint32_t scratchDwords) { const std::span codeSpan(code); const std::array memory{{{reinterpret_cast(codeSpan.data()), std::as_bytes(codeSpan)}}}; ShaderRecompiler::ShaderComputeStageInfo compute{{threads, 1, 1}, 0, {groupId, false, false}, false, 1}; compute.scratchDwords = scratchDwords; + auto target = device.Target(); + target.gpuResolvedImages = device.ComputeTarget(waveSize).gpuResolvedImages; ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(codeSpan.data()), codeSpan, 0, {}}, {waveSize, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + target, {0, 0, 0, 128} }; request.useCache = false; @@ -294,11 +305,13 @@ void RunAlias(AgcDriver::VulkanDevice& device, Form form, bool atomic, std::uint std::copy(tableDescriptor.begin(), tableDescriptor.end(), userData.begin() + 4); const auto code = AliasKernel(form, atomic); const auto result = Compile(device, code, userData, waveSize, waveSize, false, AliasScratchDwords); - const auto facts = Inspect(std::span(result.spirv.data(), result.spirv.size())); + const auto facts = Inspect(result); Require(facts.poolBinding && result.scratchPoolSlotDwords != 0u, name + ": the scratch program has no scratch pool binding"); Require(!facts.functionArrayAccess, name + ": the scratch program indexes a Function array"); + const auto heapPipelines = device.DescriptorHeapComputePipelines(); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); + RequireHeapPipeline(device, result, heapPipelines, name); for (std::uint32_t lane = 0; lane < waveSize; ++lane) { const auto first = output[lane * 8u]; const auto second = output[lane * 8u + 1u]; @@ -326,8 +339,10 @@ void RunCallee(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) { const auto code = CalleeKernel(); const auto result = Compile(device, code, userData, waveSize, waveSize, false, AliasScratchDwords); Require(result.scratchPoolSlotDwords != 0u, name + ": the scratch program has no scratch pool binding"); + const auto heapPipelines = device.DescriptorHeapComputePipelines(); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); + RequireHeapPipeline(device, result, heapPipelines, name); for (std::uint32_t lane = 0; lane < waveSize; ++lane) { Require(output[lane * 8u] == OperandA(lane), name + ": lane " + std::to_string(lane) + " read " + Hex(output[lane * 8u]) + " back, expected " + Hex(OperandA(lane))); } @@ -343,7 +358,7 @@ void RunPlain(AgcDriver::VulkanDevice& device) { std::copy(tableDescriptor.begin(), tableDescriptor.end(), userData.begin() + 4); const auto code = PlainKernel(); const auto result = Compile(device, code, userData, 32u, 32u, false, 0u); - const auto facts = Inspect(std::span(result.spirv.data(), result.spirv.size())); + const auto facts = Inspect(result); Require(!facts.poolBinding && result.scratchPoolSlotDwords == 0u, "scratch pool: a program without scratch got a scratch pool binding"); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp index 75282a2894b6..a86f4226ef8b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -11,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -74,14 +76,44 @@ void Record(AgcDriver::VulkanDevice& device, std::uint64_t address) { device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); } +bool heapSlots = false; + +struct HeapSlotted { + std::uint32_t slot = 0; + std::uint32_t generation = 0; +}; +std::map heapSlotsByAddress; + +std::shared_ptr heapSlotted(AgcDriver::VulkanDevice& device, std::uint64_t address, std::shared_ptr image) { + if (!heapSlots || image == nullptr) return image; + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + auto& heap = AgcDriver::Graphics::BindlessHeap::For(device.graphicsContext()); + const auto slot = heap.StorageSlot(ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding, image.get(), image->StorageView(0, false)); + Require(slot.has_value(), "the stored image took no GPU heap storage slot"); + heapSlotsByAddress.try_emplace(address, HeapSlotted{*slot, heap.SlotGeneration(*slot)}); + return image; +} + +bool heapSlotFreed(AgcDriver::VulkanDevice& device, std::uint64_t address) { + const auto found = heapSlotsByAddress.find(address); + Require(found != heapSlotsByAddress.end(), "no GPU heap slot was recorded for the surface"); + return AgcDriver::Graphics::BindlessHeap::For(device.graphicsContext()).SlotGeneration(found->second.slot) != found->second.generation; +} + std::shared_ptr Store(AgcDriver::VulkanDevice& device, std::uint64_t base, std::uint32_t surface, bool flush = true) { const auto address = base + surface * Stride; Record(device, address); device.WaitIdle(); - if (!flush) return StorageTexture::FindLive(address, SurfaceBytes); + if (!flush) return heapSlotted(device, address, StorageTexture::FindLive(address, SurfaceBytes)); StorageTexture::FlushPending(address, static_cast(SurfaceBytes), nullptr, "test"); device.WaitIdle(); - return StorageTexture::FindLive(address, SurfaceBytes); + return heapSlotted(device, address, StorageTexture::FindLive(address, SurfaceBytes)); +} + +bool LacksHeapSlots(AgcDriver::VulkanDevice& device) { + if (!heapSlots || device.graphicsContext().descriptorHeap) return false; + std::puts("skipped, the device has no VK_EXT_descriptor_heap"); + return true; } int RetainedBatch() { @@ -94,6 +126,7 @@ int RetainedBatch() { #endif const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; + if (LacksHeapSlots(*device)) return VulkanTestSkipped; std::vector storage((SurfaceBytes + MaxSurfaces * Stride + Stride) / 4u, 0u); auto* texels = reinterpret_cast((reinterpret_cast(storage.data()) + Stride - 1u) & ~std::uintptr_t{Stride - 1u}); const auto base = static_cast(reinterpret_cast(texels)); @@ -110,8 +143,9 @@ int RetainedBatch() { }; try { Record(*device, base); - auto retained = StorageTexture::FindLive(base, SurfaceBytes); + auto retained = heapSlotted(*device, base, StorageTexture::FindLive(base, SurfaceBytes)); Require(retained != nullptr, "surface 0 has no cached storage image"); + const std::weak_ptr weak = retained; const auto retainedBytes = retained->BudgetBytes(); auto* recorder = Recorder::Active(); Require(recorder != nullptr && recorder->Recording(), "the surface dispatch was not left in an open batch"); @@ -122,6 +156,11 @@ int RetainedBatch() { for (std::uint32_t surface = 1; surface <= capacity; ++surface) Record(*device, base + surface * Stride); Require(StorageTexture::FindLive(base, SurfaceBytes) == nullptr, "surface 0 remained cached after the storage budget was exceeded"); Require(recorder->OpenKeptBytes() >= beforeEviction + retainedBytes, "an evicted storage image held by a batch without a shared resource-cache entry was not charged to that batch"); + if (heapSlots) { + Require(!weak.expired() && !heapSlotFreed(*device, base), "an evicted storage image lost its GPU heap slot while its open batch still read it"); + device->WaitIdle(); + Require(weak.expired() && heapSlotFreed(*device, base), "an evicted storage image kept its GPU heap slot after the batch that held it finished"); + } } catch (...) { release(); throw; @@ -134,9 +173,12 @@ int RetainedBatch() { int main(int argc, char** argv) { try { - if (argc == 2 && std::string(argv[1]) == "--retained-batch") return RetainedBatch(); - const bool budgetOnly = argc == 2 && std::string(argv[1]) == "--budget-only"; - Require(argc == 1 || budgetOnly, "storage cache budget: unknown arguments"); + const std::string mode = argc == 2 ? argv[1] : ""; + heapSlots = mode == "--heap-slots" || mode == "--retained-batch-heap-slots"; + if (heapSlots) Require(SetTestEnvironment("APS5_GPU_HEAP", "1") == 0, "cannot enable the GPU heap"); + if (mode == "--retained-batch" || mode == "--retained-batch-heap-slots") return RetainedBatch(); + const bool budgetOnly = mode == "--budget-only"; + Require(argc == 1 || budgetOnly || heapSlots, "storage cache budget: unknown arguments"); #ifdef _WIN32 Require(_putenv_s("APS5_TEXTURE_CACHE_MIB", "32") == 0, "cannot set the test cache budget"); #else @@ -144,6 +186,7 @@ int main(int argc, char** argv) { #endif const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; + if (LacksHeapSlots(*device)) return VulkanTestSkipped; const auto budget = TestBudget; std::vector storage((SurfaceBytes + MaxSurfaces * Stride + Stride) / 4u, 0u); auto* texels = reinterpret_cast((reinterpret_cast(storage.data()) + Stride - 1u) & ~std::uintptr_t{Stride - 1u}); @@ -181,6 +224,10 @@ int main(int argc, char** argv) { const auto capacity = static_cast(budget / held); Require(capacity + 2u <= MaxSurfaces, "the eviction set exceeds the test storage"); for (std::uint32_t surface = reused; surface < capacity + 2u; ++surface) images[surface] = Store(*device, base, surface); + for (std::uint32_t surface = 0; heapSlots && surface < capacity + 2u; ++surface) { + const bool evicted = surface < 2u; + Require(heapSlotFreed(*device, base + surface * Stride) == evicted, "surface " + std::to_string(surface) + (evicted ? " was evicted but kept its GPU heap slot" : " is cached but lost its GPU heap slot")); + } for (std::uint32_t surface = 0; surface < capacity + 2u; ++surface) { const bool cached = StorageTexture::FindLive(base + surface * Stride, SurfaceBytes) != nullptr; Require(cached == (surface >= 2u), "surface " + std::to_string(surface) + (cached ? " is still cached" : " was evicted") + " after " + std::to_string(capacity + 2u) + " surfaces under a budget of " + std::to_string(capacity) + " of them"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StorageFlushOrdering.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StorageFlushOrdering.cpp index ace7e80efc44..1716004f77db 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StorageFlushOrdering.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StorageFlushOrdering.cpp @@ -216,7 +216,7 @@ void RunShadowedUnitUnderWriter(AgcDriver::VulkanDevice& device, const GuestBloc void Run(AgcDriver::VulkanDevice& device, const GuestBlock& guest, std::size_t offset, bool submit, const char* name) { const auto* words = guest.Words() + offset / 4u; const auto image = guest.Address() + offset; - const auto target = device.Target(); + const auto target = device.ComputeTarget(64); const auto storeImage = Compile(StoreImageCode, ImageUserData(image), target); const auto storeGlobal = Compile(StoreGlobalCode, GlobalUserData(image), target); device.Dispatch(storeImage, 1u, 1u, 1u, {}, reinterpret_cast(StoreImageCode.data())); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StorageOneSliceAlias.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StorageOneSliceAlias.cpp index 78437ac99d4f..cbb2b9b485e3 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StorageOneSliceAlias.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StorageOneSliceAlias.cpp @@ -129,7 +129,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::span co ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp index 31ae127eab47..31e495d555df 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -669,6 +670,8 @@ void Draw(AgcDriver::VulkanDevice& device, const Stages& stages, VkCullModeFlags for (std::size_t i = 0; i < Pixels.size(); i += 4) { for (std::size_t c = 0; c < 4; ++c) Pixels[i + c] = std::byte{Background[c]}; } + const bool heap = AgcDriver::Graphics::DescriptorHeapEnabled(); + Require(stages.local.gpuResolvedImages == heap && stages.hull.gpuResolvedImages == heap && stages.domain.gpuResolvedImages == heap && stages.fragment.gpuResolvedImages == heap, "the tessellation draw's stages did not take GPU mode"); std::uint32_t cursor = 0; const auto offset = [&](const ShaderRecompiler::RecompileResult& result) { const auto at = result.pushConstants.empty() ? 0u : cursor; @@ -718,6 +721,7 @@ void Draw(AgcDriver::VulkanDevice& device, const Stages& stages, VkCullModeFlags void RequireDepthRangeRemap(AgcDriver::VulkanDevice& device) { auto target = device.Target(); + target.gpuResolvedImages = AgcDriver::Graphics::DescriptorHeapEnabled(); Require(device.graphicsContext().depthClamp, "tessellation depth remap needs depth clamping"); target.depthRangeRemap = true; const auto compile = [&](float z, std::uint32_t mode) { @@ -1215,7 +1219,8 @@ int main(int argc, char** argv) { try { auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - const auto target = device->Target(); + auto target = device->Target(); + target.gpuResolvedImages = AgcDriver::Graphics::DescriptorHeapEnabled(); if (!target.tessellation.has_value()) { std::puts("tessellation: skipped, the device has no tessellation shaders"); return VulkanTestSkipped; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp new file mode 100644 index 000000000000..a58c70692612 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp @@ -0,0 +1,291 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::uint32_t Width = 256; +constexpr std::uint32_t Height = 80; +constexpr std::array Background{16, 24, 40, 255}; +alignas(256) std::array Pixels{}; +alignas(256) std::array HullUserMemory{}; + +alignas(256) constexpr std::array LocalCode{ + 0xd5480004, 0x02090502, 0xd5480005, 0x02090102, 0xd5480006, 0x02110902, 0xd5480007, 0x02111102, 0x7e080d04, 0x7e0a0d05, + 0x7e0c0d06, 0x7e0e0d07, 0x10100cff, 0x3f19999a, 0x061010ff, 0xbf666666, 0x3e1008ff, 0x3e800000, 0xd54b0009, 0x03c5e105, + 0x161406a0, 0xd9340000, 0x0000080a, 0xd8340008, 0x0000070a, 0xd8340010, 0x0000070a, 0xbf8cc07f, 0xbefd2106, +}; + +alignas(256) constexpr std::array HullCode{ + 0xd7650000, 0x000100c1, 0xd7660000, 0x000200c1, 0xbf8a0000, 0x7da206f9, 0x81060000, 0xd5480014, 0x02151101, 0x362402ff, + 0x000000ff, 0x160028a0, 0xd5430015, 0x040224ff, 0x00000060, 0xdbfc0000, 0x02000015, 0x162c2890, 0xd5430016, 0x045a24ff, + 0x00000030, 0xbf8cc07f, 0xe0781000, 0x02020216, 0x7da82881, 0xbe94047e, 0xb06a0060, 0x162602f9, 0x0086066a, 0xd8d80008, + 0x06000013, 0xd8dc1008, 0x07000013, 0xbf8cc07f, 0x7e300306, 0x7e320306, 0x7e340306, 0x7e360306, 0x34142484, 0xbefe0414, + 0xe0781000, 0x0403180a, 0x4a162481, 0x16161690, 0x4c1616ff, 0x00008000, 0xe0741000, 0x0202070b, 0xbf810000, +}; + +alignas(256) constexpr std::array DomainCode{ + 0xf8000941, 0x00000000, 0x34020e84, 0x16020283, 0xe0341000, 0x04030a01, 0xe0341010, 0x04030c01, 0xe0341020, 0x04030e01, + 0xbf8c3f70, 0x08040af2, 0x08040d02, 0x10201505, 0x3e201906, 0x3e201d02, 0x10221705, 0x3e221b06, 0x3e221f02, 0xd5510012, + 0x040a0d05, 0x102424ff, 0x40400000, 0x7e260280, 0x7e2802f2, 0xf80008cf, 0x14131110, 0xf800020f, 0x14131214, 0xbf810000, +}; + +alignas(256) constexpr std::array DomainGeometryCode{ + 0x8f6a9003, 0x94fe6ac1, 0xbf880028, 0x342a0e84, 0x162a2a83, 0xe0341000, 0x04030a15, 0xe0341010, + 0x04030c15, 0xe0341020, 0x04030e15, 0xbf8c3f70, 0x082c0af2, 0x082c0d16, 0x10201505, 0x3e201906, + 0x3e201d16, 0x10221705, 0x3e221b06, 0x3e221f16, 0xd5510012, 0x045a0d05, 0x102424ff, 0x40400000, + 0x7e260280, 0x7e2802f2, 0xd7650009, 0x000100c1, 0xd7660009, 0x000212c1, 0x93ebff03, 0x00040018, + 0xd7460009, 0x04250c6b, 0x34121285, 0xd8380100, 0x00111009, 0xd8380302, 0x00141309, 0xd8380504, + 0x00121409, 0xd8380706, 0x00141309, 0xbf8cc07f, 0xbefe04c1, 0xbf8a0000, 0x938dff02, 0x00090016, + 0x9382ff03, 0x00040018, 0x938cff03, 0x00080008, 0xd7650009, 0x000100c1, 0xd7660009, 0x000212c1, + 0xd746000a, 0x04250c02, 0x7da8120c, 0xbf88002e, 0x361600ff, 0x0000ffff, 0x34161682, 0x2c180090, + 0x34181882, 0x361a02ff, 0x0000ffff, 0x341a1a82, 0xdbfc0000, 0x1000000b, 0xdbfc0010, 0x1400000b, + 0xdbfc0000, 0x1800000c, 0xdbfc0010, 0x1c00000c, 0xdbfc0000, 0x2000000d, 0xdbfc0010, 0x2400000d, + 0xbf8cc07f, 0xbf800000, 0xbf800000, 0xbf800000, 0x161c1483, 0x161e14ff, 0x00000060, 0xbf8c3f70, + 0xdb7c0400, 0x0000100f, 0xdb7c0410, 0x0000140f, 0xdb7c0420, 0x0000180f, 0xdb7c0430, 0x00001c0f, + 0xdb7c0440, 0x0000200f, 0xdb7c0450, 0x0000240f, 0x4a501c81, 0x4a521c82, 0x3450508a, 0x34525294, + 0xd772002a, 0x04a6510e, 0xbf8cc07f, 0xbefe04c1, 0xbf8a0000, 0x930e830d, 0xbf078002, 0xbf850003, + 0x8f0f8c0d, 0x887c0f0e, 0xbf900009, 0x7da8140d, 0xbf880002, 0xf8000941, 0x0000002a, 0xbefe04c1, + 0x7da8140e, 0xbf88000a, 0x34561485, 0xdbfc0400, 0x2c00002b, 0xdbfc0410, 0x3000002b, 0xbf8cc07f, + 0xf80008cf, 0x2f2e2d2c, 0xf800020f, 0x33323130, 0xbf810000, +}; + +alignas(256) constexpr std::array PixelCode{ + 0xc8020002, 0xc8060102, 0xc80a0202, 0xc80e0302, 0xf800180f, 0x03020100, 0xbf810000, +}; + +constexpr std::array PatchLevels{1u, 0u, 5u}; + +constexpr std::uint16_t Corner(std::uint32_t patch, std::uint32_t x, std::uint32_t y) { + return static_cast((PatchLevels[patch] << 8u) | (patch << 4u) | (x << 2u) | y); +} + +alignas(256) constexpr std::array Indices{ + Corner(0, 0, 0), Corner(0, 2, 0), Corner(0, 1, 2), Corner(1, 0, 0), Corner(1, 2, 0), + Corner(1, 1, 2), Corner(2, 0, 0), Corner(2, 2, 0), Corner(2, 1, 2), +}; + +struct Header { + Shader shader{}; + ShaderUserData users{}; +}; + +Header LocalHeader{}; +Header HullHeader{}; +Header DomainHeader{}; +Header DomainGeometryHeader{}; +Header PixelHeader{}; + +void Register(Header& header, const std::uint32_t* code, std::size_t size, 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(size); + header.shader.code = code; + header.shader.type = type; + header.shader.user_data = &header.users; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +void Write(std::vector& commands, std::uint32_t opcode, std::uint32_t offset, std::uint32_t value) { + commands.insert(commands.end(), {0xc0010000u | (opcode << 8u), offset, value}); +} + +std::uint32_t Lo(const void* address) { + return static_cast(reinterpret_cast(address) >> 8u); +} + +std::uint32_t Hi(const void* address) { + return static_cast(reinterpret_cast(address) >> 40u); +} + +std::vector Commands(bool geometry) { + const auto color = reinterpret_cast(Pixels.data()); + const auto users = reinterpret_cast(HullUserMemory.data()); + const std::vector> context{{0x2d5, geometry ? 0x0000212du : 0x0200210du}, + {0x2d6, 128u | (3u << 8u) | (3u << 14u)}, + {0x2db, 1u | (2u << 2u) | (2u << 5u)}, + {0x286, std::bit_cast(64.0f)}, + {0x287, std::bit_cast(1.0f)}, + {0x1b6, 1}, + {0x191, 0x400}, + {0x1b3, 0}, + {0x1b4, 0}, + {0x260, 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, ((Width - 1u) << 14u) | (Height - 1u)}, + {0x3b8, 0x9000000}, + {0x1e0, 0}, + {0xc, 0}, + {0xd, (Height << 16u) | Width}, + {0x81, 0x80000000}, + {0x82, (Height << 16u) | Width}, + {0x90, 0x80000000}, + {0x91, (Height << 16u) | Width}, + {0x94, 0x80000000}, + {0x95, (Height << 16u) | Width}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x10f, std::bit_cast(Width / 2.0f)}, + {0x110, std::bit_cast(Width / 2.0f)}, + {0x111, std::bit_cast(-(Height / 2.0f))}, + {0x112, std::bit_cast(Height / 2.0f)}, + {0x113, std::bit_cast(1.0f)}, + {0x114, 0}, + {0xb4, 0}, + {0xb5, std::bit_cast(1.0f)}}; + const std::vector> shaders{{0x148, Lo(LocalCode.data())}, + {0x149, Hi(LocalCode.data())}, + {0x108, Lo(HullCode.data())}, + {0x109, Hi(HullCode.data())}, + {0x102, static_cast(users)}, + {0x103, static_cast(users >> 32u)}, + {0x10b, 0}, + {0xc8, geometry ? Lo(DomainGeometryCode.data()) : Lo(DomainCode.data())}, + {0xc9, geometry ? Hi(DomainGeometryCode.data()) : Hi(DomainCode.data())}, + {0x8a, 0}, + {0x8b, geometry ? 0x400010u : 0u}, + {0x8, Lo(PixelCode.data())}, + {0x9, Hi(PixelCode.data())}, + {0xb, 0}}; + std::vector commands; + Write(commands, 0x79, 0x242, 9); + for (const auto& [offset, value] : context) Write(commands, 0x69, offset, value); + if (geometry) { + for (const auto& [offset, value] : std::initializer_list>{{0x1ff, 12u}, {0x2ce, 3u}, {0x2ab, 8u}, {0x29b, 2u}}) Write(commands, 0x69, offset, value); + Write(commands, 0x79, 0x25b, 0x1804u); + } + for (const auto& [offset, value] : shaders) Write(commands, 0x76, offset, value); + commands.insert(commands.end(), {0xc0002a00u, 0u}); + const auto address = reinterpret_cast(Indices.data()); + commands.insert(commands.end(), {0xc0042700u, static_cast(Indices.size()), static_cast(address), + static_cast(address >> 32u), static_cast(Indices.size()), 0u}); + return commands; +} + +std::array PixelAt(std::uint32_t x, std::uint32_t y) { + const auto offset = (static_cast(y) * Width + x) * 4u; + return {std::to_integer(Pixels[offset]), std::to_integer(Pixels[offset + 1]), + std::to_integer(Pixels[offset + 2]), std::to_integer(Pixels[offset + 3])}; +} + +std::string PixelText(const std::array& pixel) { + return "(" + std::to_string(pixel[0]) + ", " + std::to_string(pixel[1]) + ", " + std::to_string(pixel[2]) + ", " + + std::to_string(pixel[3]) + ")"; +} + +std::uint32_t Column(std::uint32_t patch, float offset) { + return static_cast((-0.9f + 0.6f * static_cast(patch) + offset + 1.0f) * 0.5f * Width); +} + +std::uint32_t Row(float y) { + return static_cast((1.0f - y) * 0.5f * Height); +} + +std::uint32_t CoveredPixels(std::uint32_t patch, bool interior) { + std::uint32_t count = 0; + for (std::uint32_t y = Row(0.5f); y <= Row(-0.5f) && y < Height; ++y) { + for (std::uint32_t x = Column(patch, 0.0f); x <= Column(patch, 0.5f) && x < Width; ++x) { + const auto pixel = PixelAt(x, y); + if (pixel == Background) continue; + Require(pixel[0] == 255 && pixel[2] == 0 && pixel[3] == 255, "patch " + std::to_string(patch) + " pixel (" + std::to_string(x) + + ", " + std::to_string(y) + ") is " + PixelText(pixel)); + if (!interior || pixel[1] > 32) ++count; + } + } + return count; +} + +void SubmittedPatches(bool geometry) { + for (std::size_t i = 0; i < Pixels.size(); i += 4) { + for (std::size_t c = 0; c < 4; ++c) Pixels[i + c] = std::byte{Background[c]}; + } + const auto pushes = AgcDriver::Graphics::DataAddressPushes(); + auto commands = Commands(geometry); + const std::string path = geometry ? "tessellation and geometry" : "tessellation"; + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, path + " submission failed"); + AgcDriverWaitIdle_nid_postfix(); + const auto center = Row(-0.5f + 1.0f / 3.0f); + Require(CoveredPixels(0, false) > 100 && CoveredPixels(0, true) == 0, + path + ": the level-1 patch was not drawn as one flat triangle, centre " + PixelText(PixelAt(Column(0, 0.25f), center))); + Require(CoveredPixels(1, false) == 0, path + ": the patch with level 0 was not culled"); + Require(CoveredPixels(2, false) > 100 && PixelAt(Column(2, 0.25f), center)[1] > 32, + path + ": the level-5 patch has no interior domain points at its centre, " + PixelText(PixelAt(Column(2, 0.25f), center))); + Require(PixelAt(0, 0) == Background && PixelAt(Width - 1, Height - 1) == Background, path + ": the corners changed"); + Require(!AgcDriver::Graphics::DescriptorHeapEnabled() || AgcDriver::Graphics::DataAddressPushes() > pushes, + "the submitted " + path + " draw did not take the descriptor heap"); +} + +} + +int main(int argc, char** argv) { + try { + const bool geometry = argc > 1 && std::string_view(argv[1]) == "--geometry"; + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!device->Target().tessellation.has_value()) { + std::cout << "skipped, the device has no tessellation shaders\n"; + return VulkanTestSkipped; + } + if (geometry && (!device->GeometryLimits().has_value() || (device->SubgroupStages() & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) == 0)) { + std::cout << "skipped, the device has no geometry shaders or no subgroup operations in tessellation-evaluation shaders\n"; + return VulkanTestSkipped; + } + } + Register(LocalHeader, LocalCode.data(), sizeof(LocalCode), 5); + Register(HullHeader, HullCode.data(), sizeof(HullCode), 7); + Register(DomainHeader, DomainCode.data(), sizeof(DomainCode), 2); + Register(DomainGeometryHeader, DomainGeometryCode.data(), sizeof(DomainGeometryCode), 2); + Register(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); + SubmittedPatches(geometry); + AgcDriverShutdown_nid_postfix(); + std::cout << (geometry ? "A submitted tessellation and geometry draw drew its patches\n" : "A submitted tessellation draw drew its patches\n"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ViewPastLastMip.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ViewPastLastMip.cpp index ec229885ef14..98c56fec3415 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ViewPastLastMip.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ViewPastLastMip.cpp @@ -64,7 +64,7 @@ void Store(AgcDriver::VulkanDevice& device, const std::uint32_t* texels, std::ui ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/VulkanTestDevice.hpp b/core/libs/prx/libSceAgcDriver/tests/execution/VulkanTestDevice.hpp index 9d1ed597d07f..5ed36d39017b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/VulkanTestDevice.hpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/VulkanTestDevice.hpp @@ -21,9 +21,25 @@ inline bool TargetHasCapability(const ShaderRecompiler::SpirvTarget& target, spv return std::find(capabilities.begin(), capabilities.end(), static_cast(capability)) != capabilities.end(); } +inline int SetTestEnvironment(const char* name, const char* value) { +#ifdef _WIN32 + return _putenv_s(name, value); +#else + return setenv(name, value, 1); +#endif +} + +inline bool SkipWithoutDescriptorHeap() { + if (AgcDriver::Graphics::DescriptorHeapEnabled()) return false; + std::puts("skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it, so the GPU heap has nothing to run through"); + return true; +} + inline std::unique_ptr OpenVulkanTestDevice() { try { - return std::make_unique(); + auto device = std::make_unique(); + if (std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr && SkipWithoutDescriptorHeap()) return nullptr; + return device; } catch (const AgcDriver::VulkanUnavailable& error) { if (std::getenv("ANYPS5_REQUIRE_VULKAN") != nullptr) throw; std::printf("skipped, no usable Vulkan device: %s\n", error.what()); diff --git a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp index 0dc269bc7286..fc96f7439eb6 100644 --- a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp @@ -15,8 +15,9 @@ #include "spirv-tools/libspirv.hpp" #endif -#include #include +#include +#include #include #include #include @@ -56,12 +57,76 @@ bool g_waveLdsMemoryBarriers = false; bool g_deviceScopeLdsMemoryBarriers = false; bool g_ldsLockFences = false; bool g_shaderFma = false; +bool g_gpuHeap = false; +bool g_noGpuHeap = false; +bool g_hasHeapDataUniformDwords = false; +std::uint32_t g_heapDataUniformDwords = 0; + +constexpr std::uint32_t DefaultHeapDataUniformDwords = 16384u; + +struct HeapProfileSelection { + const char* source; + bool heap; +}; + +HeapProfileSelection SelectHeapProfile(ShaderRecompiler::SpirvTarget& target) { + HeapProfileSelection selection{"captured", target.gpuResolvedImages || target.descriptorMemory}; + if (g_noGpuHeap) { + target.gpuResolvedImages = false; + target.descriptorMemory = false; + target.heapDataUniformDwords = 0u; + selection = {"override", false}; + } + if (g_gpuHeap) { + target.gpuResolvedImages = true; + target.descriptorMemory = true; + if (!g_hasHeapDataUniformDwords) target.heapDataUniformDwords = DefaultHeapDataUniformDwords; + selection = {"override", true}; + } + if (g_hasHeapDataUniformDwords) { + target.heapDataUniformDwords = g_heapDataUniformDwords; + selection.source = "override"; + } + return selection; +} bool g_f16HostNans = false; bool g_shaderInt16 = false; bool g_code = false; bool g_float16WidenNans = false; bool g_float16NarrowNans = false; +bool ParseHeapDataUniformDwords(int index, int argc, char** argv, std::uint32_t& result) { + char* end = nullptr; + const auto value = index + 1 < argc ? std::strtoull(argv[index + 1], &end, 10) : 0ull; + if (index + 1 >= argc || end == argv[index + 1] || *end != '\0' || value > UINT32_MAX) return false; + result = static_cast(value); + return true; +} + +bool HeapFlagsConflict(int argc, char** argv) { + bool gpuHeap = false; + bool noGpuHeap = false; + std::uint32_t dwords = 0; + for (int i = 1; i < argc; ++i) { + const std::string argument = argv[i]; + if (argument == "--gpu-heap") gpuHeap = true; + else if (argument == "--no-gpu-heap") noGpuHeap = true; + else if (argument == "--heap-data-uniform-dwords") { + std::uint32_t value = 0; + if (ParseHeapDataUniformDwords(i, argc, argv, value) && value != 0u && dwords == 0u) dwords = value; + } + } + if (gpuHeap && noGpuHeap) { + std::fprintf(stderr, "--gpu-heap and --no-gpu-heap conflict\n"); + return true; + } + if (noGpuHeap && dwords != 0u) { + std::fprintf(stderr, "--no-gpu-heap conflicts with --heap-data-uniform-dwords %u: the limit needs a heap profile\n", dwords); + return true; + } + return false; +} + bool OutputSpirv(const char* path, std::span spirv) { if (g_spirv) { std::string name(path); @@ -92,12 +157,20 @@ bool OutputSpirv(const char* path, std::span spirv) { bool Replay(const char* path) { auto request = ShaderRecompiler::RequestSerializer{}.Deserialize(ReadText(path)); - if (g_maintenance8) request.request.target.nonConstantImageOffsets = true; - if (g_robust2) request.request.target.robustBufferAccess2 = true; - if (g_waveLdsMemoryBarriers) request.request.target.waveLdsMemoryBarriers = true; - if (g_deviceScopeLdsMemoryBarriers) request.request.target.deviceScopeLdsMemoryBarriers = true; - if (g_ldsLockFences) request.request.target.ldsLockFences = true; - if (g_f16HostNans) request.request.target.float16HostNans = true; + std::string forced; + const auto force = [&](bool enabled, bool& field, const char* name) { + if (!enabled) return; + if (!forced.empty()) forced += ", "; + forced += field ? std::string(name) + " (already captured)" : name; + field = true; + }; + auto& target = request.request.target; + force(g_maintenance8, target.nonConstantImageOffsets, "maintenance8"); + force(g_robust2, target.robustBufferAccess2, "robust2"); + force(g_waveLdsMemoryBarriers, target.waveLdsMemoryBarriers, "wave-lds-memory-barriers"); + force(g_deviceScopeLdsMemoryBarriers, target.deviceScopeLdsMemoryBarriers, "device-scope-lds-memory-barriers"); + force(g_ldsLockFences, target.ldsLockFences, "lds-lock-fences"); + force(g_f16HostNans, target.float16HostNans, "f16-host-nans"); if (g_shaderFma) { request.supportedCapabilities.push_back(spv::CapabilityFMAKHR); request.supportedExtensions.push_back("SPV_KHR_fma"); @@ -108,9 +181,12 @@ bool Replay(const char* path) { request.supportedCapabilities.push_back(spv::CapabilityInt16); request.request.target.supportedCapabilities = request.supportedCapabilities; } + const auto heapProfile = SelectHeapProfile(request.request.target); if (g_float16WidenNans) request.request.target.float16WidenNans = true; if (g_float16NarrowNans) request.request.target.float16NarrowNans = true; std::printf("%s: %zu code words, %zu user data, %zu memory regions, wave%u\n", path, request.request.shader.code.size(), request.request.context.userData.size(), request.request.context.memory.size(), request.request.context.waveSize); + std::printf(" heap profile (%s): %s, gpuResolvedImages %d, descriptorMemory %d, data uniform dwords %u\n", heapProfile.source, heapProfile.heap ? "heap" : "no heap", request.request.target.gpuResolvedImages, request.request.target.descriptorMemory, request.request.target.heapDataUniformDwords); + if (!forced.empty()) std::printf(" target flags forced on: %s\n", forced.c_str()); if (request.request.context.compute.has_value()) { const auto& compute = *request.request.context.compute; std::printf(" compute: threads %ux%ux%u, lds %u dwords, group ids %d%d%d, tg size %d, thread id components %u\n", compute.numThreads[0], compute.numThreads[1], compute.numThreads[2], compute.ldsSizeDwords, compute.groupIdEnable[0], compute.groupIdEnable[1], compute.groupIdEnable[2], compute.tgSizeEnable, compute.threadIdComponentCount); @@ -247,9 +323,10 @@ bool Replay(const char* path) { int main(int argc, char** argv) { if (argc < 2) { - std::fprintf(stderr, "usage: agc_shader_replay [--dis] [--asm] [--cfg] [--mem] [--spv] [--prepare] [--materialize] [--code] [--maintenance8] [--robust2] [--wave-lds-memory-barriers] [--device-scope-lds-memory-barriers] [--lds-lock-fences] [--shader-fma] [--shader-int16] [--f16-widen-nans] [--f16-narrow-nans] [--f16-host-nans] ...\n the driver writes shader_
.req files when APS5_DUMP_SHADERS is set; shader_
.prepare.req holds a request whose preparation failed before any resource capture, so replay it with --prepare\n"); + std::fprintf(stderr, "usage: agc_shader_replay [--dis] [--asm] [--cfg] [--mem] [--spv] [--prepare] [--materialize] [--code] [--maintenance8] [--robust2] [--wave-lds-memory-barriers] [--device-scope-lds-memory-barriers] [--lds-lock-fences] [--shader-fma] [--shader-int16] [--f16-widen-nans] [--f16-narrow-nans] [--f16-host-nans] [--gpu-heap] [--no-gpu-heap] [--heap-data-uniform-dwords N] ...\n the driver writes shader_
.req files when APS5_DUMP_SHADERS is set; shader_
.prepare.req holds a request whose preparation failed before any resource capture, so replay it with --prepare\n a request replays with the heap profile it was captured with; --gpu-heap forces the heap profile (gpuResolvedImages, descriptorMemory, and 16384 data uniform dwords unless --heap-data-uniform-dwords is given, replacing a captured limit), --no-gpu-heap forces it off, --heap-data-uniform-dwords N forces the limit (0 selects ring-address reads); --gpu-heap with --no-gpu-heap, and --no-gpu-heap with a nonzero limit, exit 2\n --maintenance8, --robust2, --wave-lds-memory-barriers, --device-scope-lds-memory-barriers, --lds-lock-fences and --f16-host-nans force their target flag on over the captured value and are listed on a 'target flags forced on' line\n"); return 2; } + if (HeapFlagsConflict(argc, argv)) return 2; int failures = 0; for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "--gcn") { @@ -272,6 +349,23 @@ int main(int argc, char** argv) { g_maintenance8 = true; continue; } + if (std::string(argv[i]) == "--gpu-heap") { + g_gpuHeap = true; + continue; + } + if (std::string(argv[i]) == "--no-gpu-heap") { + g_noGpuHeap = true; + continue; + } + if (std::string(argv[i]) == "--heap-data-uniform-dwords") { + if (!ParseHeapDataUniformDwords(i, argc, argv, g_heapDataUniformDwords)) { + std::fprintf(stderr, "--heap-data-uniform-dwords needs an unsigned 32-bit number\n"); + return 2; + } + g_hasHeapDataUniformDwords = true; + ++i; + continue; + } if (std::string(argv[i]) == "--robust2") { g_robust2 = true; continue; diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index 1bee82bc00bb..9ccf3b942294 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -120,7 +120,6 @@ function(add_shader_recompiler target runtimeTarget) ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/NanPayloadEliminator.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/VectorWindowStoreEliminator.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/RedundantValueEliminator.cpp - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/SrtWalker/SrtAddressArithmetic.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/SrtWalker/SrtDescriptorEvaluation.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/SrtWalker/SrtDiagnostics.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/SrtWalker/SrtEvaluator.cpp @@ -255,10 +254,28 @@ function(add_shader_recompiler target runtimeTarget) string(APPEND shaderCacheExtra " system-deps=${ANYPS5_SYSTEM_DEPS_STAMP}") endif() set(shaderCacheReviewedNames + HeapCache + HeapCacheEnabled + HeapCacheLegacyBypassed + HeapCacheBypassMask + HeapCacheNames + HeapVerifyEnabled + HeapVerifyEvery + HeapOnlyCacheCount + ParseHeapCacheBypass BdaAbi::OtherFaults BdaAbi::RangesOrdered + RuntimeAbi::GpuHeapStorageKind + RuntimeAbi::StageGroup + StagePushFeatures + RuntimeAbi::UintStorageImageKind + StorageElementPointer + FirstAtomicStorageImageBinding BuildBarycentricGeometryShader BuildBarycentricTessellationShaders + CompleteHeapDataWords + OverlayUserWords + HeapTemplateCounts BuildPreparedShaderKey BuildRectListShaders BuildTessellationCaptureGeometryShader @@ -282,6 +299,9 @@ function(add_shader_recompiler target runtimeTarget) PipelineSpecialization::WorkgroupOffsetWords PixelInput PixelInputBit + PlacePushData + PushBytesMask + PushPartOf RayTracingStrict RayTracingMiss ReadWholeFile diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index 8afae6cd5369..c75253e19731 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -6,6 +6,9 @@ #include "prx/libc/include/HostThreadLocal.hpp" #include #include +#include +#include +#include #include #include #include @@ -383,6 +386,10 @@ class RecompileCacheKey { append(key, value.largePixelFunctionLdsBuffer); append(key, value.pixelFunctionStorageDwords); append(key, value.deviceScopeLdsMemoryBarriers); + append(key, value.gpuResolvedImages); + append(key, value.descriptorMemory); + append(key, value.heapDataUniformDwords); + append(key, value.uniformConstantBuffers); append(key, value.ldsLockFences); append(key, value.meshWindowBuffer); append(key, value.hostInterpolationFirst); diff --git a/core/shader/recompiler/CompiledVariant.hpp b/core/shader/recompiler/CompiledVariant.hpp index adc493521b7f..5d84bcf29ef9 100644 --- a/core/shader/recompiler/CompiledVariant.hpp +++ b/core/shader/recompiler/CompiledVariant.hpp @@ -22,6 +22,11 @@ class BufferSubstituteTable { return slots; } + void CopySlots(std::vector& out) const { + std::lock_guard lock(mutex); + out.assign(slots.begin(), slots.end()); + } + void Learn(std::size_t slot, const BufferSubstitute& value) { std::lock_guard lock(mutex); if (slot >= slots.size() || slots[slot].known) return; diff --git a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp index 63ac303e6691..902f3b9e1d28 100644 --- a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp +++ b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp @@ -916,7 +916,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const std::string buffer; Writer writer(buffer); writer.WriteU32(0x41505335u); - writer.WriteU32(62u); + writer.WriteU32(63u); writeShaderBinary(writer, request.shader); writeGuestContext(writer, request.context); writeSpirvTarget(writer, request.target); @@ -963,6 +963,16 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const writer.WriteBool(request.target.shaderImageMinLod); writer.WriteBool(request.target.float16WidenNans); writer.WriteBool(request.target.float16NarrowNans); + writer.WriteBool(request.target.gpuResolvedImages); + writer.WriteBool(request.target.descriptorMemory); + writer.WriteU32(request.target.heapDataUniformDwords); + writer.WriteBool(request.target.ldsLockFences); + writer.WriteBool(request.target.meshWindowBuffer); + writer.WriteBool(request.target.waveLdsMemoryBarriers); + writer.WriteBool(request.target.deviceScopeLdsMemoryBarriers); + writer.WriteBool(request.target.exactRobustLoads); + writer.WriteBool(request.target.robustBufferAccess2); + writer.WriteBool(request.target.uniformConstantBuffers); if (request.context.compute.has_value()) { writer.WriteU32(request.context.compute->granulatedVgprCount); writer.WriteU32(request.context.compute->sharedVgprBlocks); @@ -978,7 +988,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const Reader reader(decoded); if (reader.ReadU32() != 0x41505335u) throw std::runtime_error("invalid recompile request signature"); const auto version = reader.ReadU32(); - if (version < 1u || version > 62u || version == 50u || (version >= 58u && version <= 61u)) throw std::runtime_error("unsupported recompile request serialization version"); + if (version < 1u || version > 63u || version == 50u || (version >= 58u && version <= 61u)) throw std::runtime_error("unsupported recompile request serialization version"); DeserializedRequest result{}; result.request.shader = readShaderBinary(reader, result.shaderCode, result.shaderHeader); result.request.context = readGuestContext(reader, result, version); @@ -1045,6 +1055,18 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const result.request.target.float16WidenNans = reader.ReadBool(); result.request.target.float16NarrowNans = reader.ReadBool(); } + if (version >= 63u) { + result.request.target.gpuResolvedImages = reader.ReadBool(); + result.request.target.descriptorMemory = reader.ReadBool(); + result.request.target.heapDataUniformDwords = reader.ReadU32(); + result.request.target.ldsLockFences = reader.ReadBool(); + result.request.target.meshWindowBuffer = reader.ReadBool(); + result.request.target.waveLdsMemoryBarriers = reader.ReadBool(); + result.request.target.deviceScopeLdsMemoryBarriers = reader.ReadBool(); + result.request.target.exactRobustLoads = reader.ReadBool(); + result.request.target.robustBufferAccess2 = reader.ReadBool(); + result.request.target.uniformConstantBuffers = reader.ReadBool(); + } if (version >= 56u && result.request.context.compute.has_value()) { result.request.context.compute->granulatedVgprCount = reader.ReadU32(); result.request.context.compute->sharedVgprBlocks = reader.ReadU32(); diff --git a/core/shader/recompiler/Deserialize.cpp b/core/shader/recompiler/Deserialize.cpp index d35dff0ccb70..a2734e622685 100644 --- a/core/shader/recompiler/Deserialize.cpp +++ b/core/shader/recompiler/Deserialize.cpp @@ -230,7 +230,7 @@ int main(int argc, char** argv) { std::cout << "ShaderInfoCollector::Collect OK\n"; BindingAllocator bindingAllocator; - const auto bindings = bindingAllocator.Allocate(program, request.layout, request.target.registrationModules); + const auto bindings = bindingAllocator.Allocate(program, request.layout, {.registrationModules = request.target.registrationModules}); std::cout << "BindingAllocator::Allocate OK, bindings=" << bindings.bindings.size() << "\n"; std::cout << "ALL STAGES OK\n"; diff --git a/core/shader/recompiler/HeapCacheSwitch.hpp b/core/shader/recompiler/HeapCacheSwitch.hpp new file mode 100644 index 000000000000..ebb191092d75 --- /dev/null +++ b/core/shader/recompiler/HeapCacheSwitch.hpp @@ -0,0 +1,122 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ShaderRecompiler { + +enum class HeapCache : std::uint32_t { + TemplateFront, + Templates, + Slots, + StageData, + TableMap, + PushImage, + DrawKey, + DrawDataHits, + DrawStageDataHits, + DrawSrtEntries, + DrawRecipe, + DrawResourceCache, + ResourceCache, + ValidateCache, + ShapeMemo, + MovedBufferTemplates, + ResultMemo, + Count, +}; + +inline constexpr std::uint32_t HeapOnlyCacheCount = static_cast(HeapCache::DrawKey); + +inline constexpr std::array(HeapCache::Count)> HeapCacheNames{ + "template-front", "templates", "slots", "stage-data", "table-map", "push-image", "draw-key", "draw-data-hits", "draw-stage-data-hits", "draw-srt-entries", + "draw-recipe", "draw-resource-cache", "resource-cache", "validate-cache", "shape-memo", "moved-buffer-templates", "result-memo", +}; + +[[nodiscard]] inline std::uint64_t ParseHeapCacheBypass(std::string_view text) { + std::uint64_t mask = 0; + constexpr auto count = static_cast(HeapCache::Count); + while (!text.empty()) { + const auto comma = text.find(','); + const auto name = text.substr(0, comma); + text = comma == std::string_view::npos ? std::string_view{} : text.substr(comma + 1); + if (name.empty()) continue; + if (name == "all" || name == "1") { + mask |= (std::uint64_t{1} << count) - 1u; + continue; + } + if (name == "heap") { + mask |= (std::uint64_t{1} << HeapOnlyCacheCount) - 1u; + continue; + } + bool known = false; + for (std::uint32_t index = 0; index < count; ++index) { + if (HeapCacheNames[index] != name) continue; + mask |= std::uint64_t{1} << index; + known = true; + } + if (!known) throw std::runtime_error("APS5_HEAP_NO_CACHE names an unknown cache: " + std::string(name)); + } + return mask; +} + +[[nodiscard]] inline bool HeapCacheLegacyBypassed(HeapCache cache) { + switch (cache) { + case HeapCache::DrawKey: return std::getenv("APS5_NO_DRAW_KEY") != nullptr; + case HeapCache::DrawDataHits: return std::getenv("APS5_NO_DRAW_DATA_HITS") != nullptr; + case HeapCache::DrawStageDataHits: return std::getenv("APS5_NO_DRAW_STAGE_DATA_HITS") != nullptr; + case HeapCache::DrawSrtEntries: return std::getenv("APS5_NO_DRAW_SRT_ENTRIES") != nullptr; + case HeapCache::DrawRecipe: return std::getenv("APS5_NO_DRAW_RECIPE") != nullptr; + case HeapCache::DrawResourceCache: return std::getenv("APS5_NO_DRAW_RESOURCE_CACHE") != nullptr; + case HeapCache::ResourceCache: return std::getenv("APS5_NO_RESOURCE_CACHE") != nullptr; + case HeapCache::ValidateCache: return std::getenv("APS5_NO_VALIDATE_CACHE") != nullptr; + case HeapCache::ShapeMemo: return std::getenv("APS5_NO_SHAPE_MEMO") != nullptr; + case HeapCache::MovedBufferTemplates: return std::getenv("APS5_NO_MOVED_BUFFER_TEMPLATES") != nullptr; + case HeapCache::ResultMemo: return std::getenv("APS5_NO_RESULT_MEMO") != nullptr; + default: return false; + } +} + +[[nodiscard]] inline std::uint64_t HeapCacheBypassMask() { + static const std::uint64_t mask = [] { + const char* text = std::getenv("APS5_HEAP_NO_CACHE"); + std::uint64_t bypassed = text == nullptr ? std::uint64_t{0} : ParseHeapCacheBypass(text); + for (std::uint32_t index = 0; index < static_cast(HeapCache::Count); ++index) { + if (HeapCacheLegacyBypassed(static_cast(index))) bypassed |= std::uint64_t{1} << index; + } + return bypassed; + }(); + return mask; +} + +[[nodiscard]] inline bool HeapCacheEnabled(HeapCache cache) { + return (HeapCacheBypassMask() >> static_cast(cache) & 1u) == 0u; +} + +[[nodiscard]] inline bool HeapVerifyEnabled() { + static const bool enabled = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + return enabled; +} + +[[nodiscard]] inline std::uint64_t HeapVerifyEvery() { + static const std::uint64_t every = [] { + const char* text = std::getenv("APS5_VERIFY_GPU_HEAP"); + if (text == nullptr) return std::uint64_t{0}; + std::uint64_t value = 0; + const auto* end = text + std::strlen(text); + if (text != end) { + const auto parsed = std::from_chars(text, end, value); + if (parsed.ec != std::errc{} || parsed.ptr != end) throw std::runtime_error("APS5_VERIFY_GPU_HEAP must be empty or a non-negative integer"); + } + return value == 0 ? std::uint64_t{1} : value; + }(); + return every; +} + +} diff --git a/core/shader/recompiler/HeapTemplateBudget.hpp b/core/shader/recompiler/HeapTemplateBudget.hpp new file mode 100644 index 000000000000..658ac5fa30f3 --- /dev/null +++ b/core/shader/recompiler/HeapTemplateBudget.hpp @@ -0,0 +1,110 @@ +#pragma once + +#include "Recompiler.hpp" + +#include +#include +#include +#include +#include +#include + +namespace ShaderRecompiler { + +template +[[nodiscard]] std::uint64_t OwnedBytes(const std::vector& values) { + return static_cast(values.capacity()) * sizeof(TValue); +} + +[[nodiscard]] inline std::uint64_t OwnedBytes(const std::vector& values) { + return (static_cast(values.capacity()) + 7u) / 8u; +} + +[[nodiscard]] inline std::uint64_t OwnedBytes(const ElementFlags& flags) { + return flags.size() > 64u ? (static_cast(flags.size()) + 7u) / 8u : 0u; +} + +[[nodiscard]] inline std::uint64_t OwnedBytes(const DescriptorBinding& binding) { + return OwnedBytes(binding.guestDescriptor) + OwnedBytes(binding.samplerDepthCompare) + OwnedBytes(binding.imageWritten) + OwnedBytes(binding.imageDepthCompare) + OwnedBytes(binding.imageAtomic) + OwnedBytes(binding.imageAtomic64) + + OwnedBytes(binding.imageShapes) + OwnedBytes(binding.bufferAtomic) + OwnedBytes(binding.bufferWritten) + OwnedBytes(binding.samplerUnnormalized) + OwnedBytes(binding.samplerIntegerBorder) + + OwnedBytes(binding.samplerCoordinatesIgnored) + OwnedBytes(binding.imageUnnormalized) + OwnedBytes(binding.imageUnnormalizedBaseLevel) + OwnedBytes(binding.imageSamplers) + OwnedBytes(binding.bufferRead) + + OwnedBytes(binding.bufferExtent) + OwnedBytes(binding.samplerEmbedded) + OwnedBytes(binding.samplerEmbeddedWords); +} + +[[nodiscard]] inline std::uint64_t OwnedBytes(const RecompileResult& result) { + std::uint64_t bytes = sizeof(RecompileResult) + OwnedBytes(result.vertexInputPatches) + OwnedBytes(result.runtimeImageResources) + OwnedBytes(result.vertexInputs) + OwnedBytes(result.parameterExports) + + OwnedBytes(result.fragmentParameters) + OwnedBytes(result.stencilReferences) + OwnedBytes(result.specialization) + OwnedBytes(result.heapSlotWords) + OwnedBytes(result.bindings) + + OwnedBytes(result.pushConstants) + OwnedBytes(result.vertexAttributes) + OwnedBytes(result.imageTablePoison) + OwnedBytes(result.imageTableRanges) + OwnedBytes(result.imageTableReadRanges) + + OwnedBytes(result.heapUserWords) + OwnedBytes(result.shaderDataUserWords) + OwnedBytes(result.pushedData); + if (result.meshBarycentrics.has_value()) bytes += OwnedBytes(result.meshBarycentrics->parameters); + for (const auto& binding : result.bindings) bytes += OwnedBytes(binding); + for (const auto& ranges : result.imageTableReadRanges) bytes += OwnedBytes(ranges); + return bytes; +} + +class HeapTemplateLru { +public: + struct Name { + std::uint64_t owner = 0; + std::uint64_t key = 0; + std::uint64_t id = 0; + }; + + struct Evicted { + Name name; + std::weak_ptr owner; + }; + + explicit HeapTemplateLru(std::uint64_t budget) : budget(budget) {} + + [[nodiscard]] std::vector Insert(const Name& name, std::uint64_t bytes, std::weak_ptr owner = {}) { + std::vector evicted; + if (const auto found = index.find(Slot{name.owner, name.key}); found != index.end()) { + total -= found->second->bytes; + order.erase(found->second); + index.erase(found); + } + order.push_back({name, bytes, std::move(owner)}); + index.emplace(Slot{name.owner, name.key}, std::prev(order.end())); + total += bytes; + while (total > budget && !order.empty()) { + auto oldest = std::move(order.front()); + index.erase(Slot{oldest.name.owner, oldest.name.key}); + order.pop_front(); + total -= oldest.bytes; + evicted.push_back({oldest.name, std::move(oldest.owner)}); + } + return evicted; + } + + void Touch(const Name& name) { + const auto found = index.find(Slot{name.owner, name.key}); + if (found == index.end() || found->second->name.id != name.id) return; + order.splice(order.end(), order, found->second); + } + + [[nodiscard]] std::uint64_t Entries() const { return order.size(); } + [[nodiscard]] std::uint64_t Bytes() const { return total; } + +private: + struct Entry { + Name name; + std::uint64_t bytes = 0; + std::weak_ptr owner; + }; + struct Slot { + std::uint64_t owner = 0; + std::uint64_t key = 0; + bool operator==(const Slot&) const = default; + }; + struct SlotHash { + std::size_t operator()(const Slot& slot) const { return std::hash{}(slot.owner * 0x9e3779b97f4a7c15ull ^ slot.key); } + }; + + std::uint64_t budget = 0; + std::uint64_t total = 0; + std::list order; + std::unordered_map::iterator, SlotHash> index; +}; + +} diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp index 809c3e0932e3..abfc6051b710 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp @@ -39,12 +39,19 @@ struct IrDescriptorBinding { struct IrBindingLayout { std::uint32_t pushDataStartDword = PushData::NoStart; + bool dataAddress = false; std::uint32_t stencilReferenceDword = PushData::NoStart; std::uint32_t memoryOffsetDword = 0; std::uint32_t memoryOffsetCount = 0; bool dispatchThreadLimit = false; std::uint32_t runtimeImageCount = 0; std::uint32_t runtimeStateDwords = 0; + std::uint32_t samplerSlotDwords = 0; + std::uint32_t imageSlotDwords = 0; + std::uint32_t bufferAddressDwords = 0; + std::vector pushedData; + bool gpuResolvedImages = false; + bool heapStorageImages = false; std::vector userDataRegisters; std::vector descriptors; @@ -54,22 +61,42 @@ struct IrBindingLayout { [[nodiscard]] std::uint32_t ImageMetadataDword() const { return DispatchThreadLimitDword() + (dispatchThreadLimit ? 3u : 0u); } + [[nodiscard]] std::uint32_t ImageFirstElementDword(std::uint32_t image) const { + return ImageMetadataDword() + image * (sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)) + offsetof(RuntimeAbi::ResourceMetadata, firstElement) / sizeof(std::uint32_t); + } [[nodiscard]] std::uint32_t RuntimeStateDword() const { return ImageMetadataDword() + runtimeImageCount * (sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)); } - [[nodiscard]] std::uint32_t ShaderDataDwords() const { + [[nodiscard]] std::uint32_t SamplerSlotDword() const { return RuntimeStateDword() + runtimeStateDwords; } + [[nodiscard]] std::uint32_t ImageSlotDword() const { + return SamplerSlotDword() + samplerSlotDwords; + } + [[nodiscard]] std::uint32_t BufferAddressDword() const { + return ImageSlotDword() + imageSlotDwords; + } + [[nodiscard]] std::uint32_t ShaderDataDwords() const { + return BufferAddressDword() + bufferAddressDwords; + } + [[nodiscard]] bool HeapSlotWordKind(DescriptorBindingKind kind) const { + return HeapImageKind(kind) && (runtimeImageCount == 0u || RuntimeAbi::GpuHeapStorageKind(static_cast(kind))); + } + [[nodiscard]] bool HeapImageKind(DescriptorBindingKind kind) const { + const auto value = static_cast(kind); + return (value >= RuntimeAbi::FirstImageBinding && value < RuntimeAbi::FirstStorageImageBinding) || (heapStorageImages && RuntimeAbi::GpuHeapStorageKind(value)); + } [[nodiscard]] bool UsesPushData() const { return pushDataStartDword != PushData::NoStart; } + [[nodiscard]] bool UsesDataAddress() const { + return dataAddress; + } [[nodiscard]] std::uint32_t PushSlotDword() const { return UsesPushData() ? pushDataStartDword / PushData::DwordCount * PushData::DwordCount : 0u; } void AdvancePushData(std::uint32_t& cursor) const { - if (UsesPushData()) { - cursor = pushDataStartDword + ShaderDataDwords(); - } + if (UsesPushData()) cursor = pushDataStartDword + ShaderDataDwords(); } bool operator==(const IrBindingLayout& other) const = default; diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp index c5d72b4770c5..7abb9c9e4eb8 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp @@ -5,6 +5,7 @@ #include "IntermediateRepresentation/IrMetadata/ShaderStage.hpp" #include "IntermediateRepresentation/IrOpcode.hpp" #include "RdnaDecoder/RdnaInstruction.hpp" +#include #include #include #include @@ -156,6 +157,8 @@ struct SamplerResource { std::uint16_t uses = 0; bool foldTexelOffsetsOnly = false; std::uint32_t table = NoTable; + bool constant = false; + std::array constantWords{}; bool operator==(const SamplerResource& other) const = default; }; diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrProgram.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrProgram.hpp index 69abc3bb2b47..9a50f8f4cfd4 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrProgram.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrProgram.hpp @@ -145,6 +145,9 @@ IrValue* ResolveInvariantPhi(const IrResourcePlan& program, IrValue* value); bool IsAddressResourceKind(ResourceKind kind); PositionExportComponent DecodePositionExportComponent(std::uint32_t control, std::uint32_t positionIndex, std::uint32_t component); std::uint32_t NativeBinding(IrShaderStage stage, DescriptorBindingKind kind); +bool SharedHeapArray(const IrBindingLayout& layout, DescriptorBindingKind kind, bool gpuResolved); +std::uint32_t DescriptorBindingNumber(const IrBindingLayout& layout, DescriptorBindingKind kind, IrShaderStage stage, bool gpuResolved); +std::uint32_t DescriptorSetNumber(const IrBindingLayout& layout, DescriptorBindingKind kind, IrShaderStage stage, bool gpuResolved, bool fragmentDescriptorSet, bool plan); ImageResourceClass ImageBindingResourceClass(DescriptorBindingKind kind); std::uint32_t ImageBindingIndex(DescriptorBindingKind kind); DescriptorBindingKind DescriptorBindingForImage(const ImageResource& image); diff --git a/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp b/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp index 7046b20a4bd4..9ffd4a0d98ee 100644 --- a/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp +++ b/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp @@ -992,6 +992,24 @@ std::uint32_t NativeBinding(IrShaderStage stage, DescriptorBindingKind kind) { return RuntimeAbi::BindingNumber(static_cast(group), kind); } +bool SharedHeapArray(const IrBindingLayout& layout, DescriptorBindingKind kind, bool gpuResolved) { + return gpuResolved && (kind == DescriptorBindingKind::Samplers || layout.HeapImageKind(kind)); +} + +std::uint32_t DescriptorBindingNumber(const IrBindingLayout& layout, DescriptorBindingKind kind, IrShaderStage stage, bool gpuResolved) { + return NativeBinding(SharedHeapArray(layout, kind, gpuResolved) ? IrShaderStage::Pixel : stage, kind); +} + +std::uint32_t DescriptorSetNumber(const IrBindingLayout& layout, DescriptorBindingKind kind, IrShaderStage stage, bool gpuResolved, bool fragmentDescriptorSet, bool plan) { + if (kind == DescriptorBindingKind::Gds && layout.UsesDataAddress()) return RuntimeAbi::GpuGdsSet; + if (gpuResolved) { + if (SharedHeapArray(layout, kind, true)) return RuntimeAbi::FragmentDescriptorSet; + if (kind == DescriptorBindingKind::ShaderData || kind == DescriptorBindingKind::FlattenedSrt) return plan ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::GpuDataSet; + return RuntimeAbi::DescriptorSet; + } + return fragmentDescriptorSet && stage == IrShaderStage::Pixel ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet; +} + ImageResourceClass ImageBindingResourceClass(DescriptorBindingKind kind) { const auto value = static_cast(kind); if (value >= FirstImageBinding && value < FirstStorageImageBinding) { diff --git a/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp b/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp index 7396e8e96d78..0710b88619b9 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp @@ -22,9 +22,16 @@ struct BindingAllocationResult : CompiledBindingLayout { std::vector shaderDataUserWords; }; +struct AllocationOptions { + bool registrationModules = false; + bool stencilReplay = false; + bool gpuResolvedImages = false; + bool descriptorMemory = false; +}; + class BindingAllocator { public: - [[nodiscard]] BindingAllocationResult Allocate(IrProgram& program, const BindingLayout& layout, bool registrationModules = false, bool stencilReplay = false) const; + [[nodiscard]] BindingAllocationResult Allocate(IrProgram& program, const BindingLayout& layout, const AllocationOptions& options = {}) const; [[nodiscard]] const IrDescriptorBinding& FindBinding(const IrBindingLayout& layout, DescriptorBindingKind kind) const; }; diff --git a/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp b/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp index 7163cd216712..8cc8eccd9e76 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp @@ -45,7 +45,10 @@ struct DescriptorBindingPlan { std::vector imageMetadata; std::vector specialization; std::vector runtimeState; + std::vector heapSlotWords; bool storageData = false; + bool addressedBuffers = false; + bool addressedData = false; }; class DescriptorBindingBuilder { @@ -53,6 +56,7 @@ class DescriptorBindingBuilder { DescriptorBindingPlan Prepare(const IrBindingLayout& layout, const ShaderInfo& info, IrShaderStage stage, const ResourceSnapshot& snapshot, std::span exportMappings = {}, bool registrationModules = false, bool fragmentDescriptorSet = false, std::span substitutes = {}, bool shaderImageMinLod = false) const; DescriptorBindingPlan Select(const DescriptorBindingPlan& plan, std::span bindings) const; void Populate(BindingAllocationResult& allocation, const CompiledBindingLayout& compiled, const DescriptorBindingPlan& plan, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads, const ResolvedImageTables* tables = nullptr) const; + void PopulateGuestWords(std::vector>& words, const CompiledBindingLayout& compiled, const DescriptorBindingPlan& plan, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads, const ResolvedImageTables* tables = nullptr) const; void Populate(BindingAllocationResult& allocation, const IrProgram& program, const ResourceSnapshot& snapshot, const std::array& partialThreads, std::span exportMappings = {}) const; void Populate(BindingAllocationResult& allocation, const ShaderInfo& info, IrShaderStage stage, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads, std::span exportMappings = {}) const; }; diff --git a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp index 3e4930b2a838..b1e8ff15b016 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp @@ -4,8 +4,11 @@ #include "Recompiler.hpp" #include "IntermediateRepresentation/IrProgram.hpp" #include "Optimization/SrtWalker.hpp" +#include #include #include +#include +#include namespace ShaderRecompiler { @@ -57,24 +60,39 @@ struct SourceHandle { std::shared_ptr source; std::shared_ptr artifact; std::vector staticKey; + bool imageTableBindings = false; +}; +struct HeapTemplateMiss { + bool missing = false; + std::uint64_t key = 0; }; class PreparedShaderInvocation { public: static std::optional TryCreate(const RecompileRequest& request, const std::shared_ptr& handle); static std::optional TryCreate(const RecompileRequest& request, const std::shared_ptr& handle, std::span key); + static std::optional TryCreate(RecompileRequest&& request, const std::shared_ptr& handle, std::span key); const RecompileRequest& Request() const { return request; } std::shared_ptr Capture(const SrtRuntime& runtime) const; std::shared_ptr Materialize(const ResourceCapture& capture) const; + std::shared_ptr MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words, HeapTemplateMiss* miss = nullptr) const; + std::shared_ptr Plan() const; + std::shared_ptr LoadPlan() const; + std::shared_ptr PlanOrLoad() const; + std::uint64_t VariantId() const; [[nodiscard]] std::shared_ptr MaterializeIfMemoized(const ResourceCapture& capture, bool* contended = nullptr) const; [[nodiscard]] PreparedShaderInvocation Rebound(const RecompileRequest& request) const; [[nodiscard]] std::uint64_t SnapshotKey(const ResourceCapture& capture) const; private: - PreparedShaderInvocation(const RecompileRequest& request, const std::shared_ptr& handle); + PreparedShaderInvocation(RecompileRequest request, const std::shared_ptr& handle); RecompileRequest request; std::shared_ptr handle; }; [[nodiscard]] std::span GetPreparedCode(const SourceHandle& handle); +void CompleteHeapDataWords(const RecompileResult& shared, HeapStageWords& words); +inline void OverlayUserWords(std::vector& descriptor, std::span userData) { + std::copy_n(userData.begin(), std::min(userData.size(), descriptor.size()), descriptor.begin()); +} [[nodiscard]] std::shared_ptr PrepareShader(const RecompileRequest& request); [[nodiscard]] std::shared_ptr PrepareShader(const RecompileRequest& request, ShaderPreparationContext* preparation); [[nodiscard]] bool MatchesPreparedShader(const RecompileRequest& request, const SourceHandle& handle); diff --git a/core/shader/recompiler/Optimization/include/Optimization/SrtWalker/SrtAddressArithmetic.hpp b/core/shader/recompiler/Optimization/include/Optimization/SrtWalker/SrtAddressArithmetic.hpp index ae6e279ac180..69af7761e421 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/SrtWalker/SrtAddressArithmetic.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/SrtWalker/SrtAddressArithmetic.hpp @@ -7,7 +7,25 @@ namespace ShaderRecompiler::Detail { inline constexpr std::uint64_t AddressMask = 0x0000ffffffffffffull; -bool AddSignedAddress(std::uint64_t base, std::int64_t offset, std::uint64_t& result); +inline bool AddSignedAddress(std::uint64_t base, std::int64_t offset, std::uint64_t& result) { + if (base > AddressMask) { + return false; + } + if (offset < 0) { + const auto magnitude = std::uint64_t {0} - static_cast(offset); + if (magnitude > base) { + return false; + } + result = base - magnitude; + return true; + } + const auto magnitude = static_cast(offset); + if (magnitude > AddressMask - base) { + return false; + } + result = base + magnitude; + return true; +} } diff --git a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp index 6e55b49757e6..de5e63860fb0 100644 --- a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp +++ b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp @@ -13,6 +13,18 @@ namespace { throw std::runtime_error(message); } +void placePushedData(IrBindingLayout& layout) { + const auto capacity = RuntimeAbi::PushedDataWantedLimit; + const auto take = [&](std::uint32_t dword) { + if (layout.pushedData.size() < capacity && std::ranges::find(layout.pushedData, dword) == layout.pushedData.end()) layout.pushedData.push_back(dword); + }; + for (auto dword = layout.SamplerSlotDword(); dword < layout.BufferAddressDword(); ++dword) take(dword); + for (std::uint32_t image = 0; image < layout.runtimeImageCount; ++image) take(layout.ImageFirstElementDword(image)); + for (std::uint32_t dword = 0; dword < layout.userDataRegisters.size(); ++dword) take(dword); + for (auto dword = layout.memoryOffsetDword; dword < layout.memoryOffsetDword + (layout.memoryOffsetCount + 3u) / 4u; ++dword) take(dword); + for (auto dword = layout.ImageMetadataDword(); dword < layout.SamplerSlotDword(); ++dword) take(dword); +} + std::vector collectUserData(const IrProgram& program) { std::array registers {}; for (const auto& block : program.Blocks()) { @@ -68,7 +80,8 @@ bool usesGds(const IrProgram& program) { } -BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const BindingLayout& layout, bool registrationModules, bool stencilReplay) const { +BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const BindingLayout& layout, const AllocationOptions& options) const { + const auto [registrationModules, stencilReplay, gpuResolvedImages, descriptorMemory] = options; IrProgramMetadata& metadata = program.Metadata(); if (!metadata.shaderInfoComplete || metadata.bindingLayoutComplete) { fail(metadata.shaderInfoComplete ? "shader binding layout failed: binding layout already allocated" @@ -113,10 +126,15 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } next.runtimeStateDwords = (attributes + RuntimeAbi::VertexSelectorsPerDword - 1u) / RuntimeAbi::VertexSelectorsPerDword; } + if (gpuResolvedImages) { + next.samplerSlotDwords = static_cast(info.samplers.size()) * RuntimeAbi::SamplerSlotWords; + next.gpuResolvedImages = true; + } const auto pushSize = layout.pushConstantSizeBytes / 4u; const auto dataSize = stencilReplay && pushSize != 0u ? pushSize - 1u : pushSize; - next.pushDataStartDword = next.runtimeImageCount == 0u && next.ShaderDataDwords() != 0u && next.ShaderDataDwords() <= dataSize ? layout.pushConstantOffsetBytes / 4u : PushData::NoStart; - if (stencilReplay) { + next.pushDataStartDword = !gpuResolvedImages && next.runtimeImageCount == 0u && next.ShaderDataDwords() != 0u && next.ShaderDataDwords() <= dataSize ? layout.pushConstantOffsetBytes / 4u : PushData::NoStart; + next.dataAddress = descriptorMemory && gpuResolvedImages; + if (stencilReplay && !next.UsesDataAddress()) { const auto offset = next.UsesPushData() ? next.ShaderDataDwords() : 0u; if (offset >= pushSize) fail("stencil replay requires an unused push constant dword"); next.stencilReferenceDword = offset; @@ -154,6 +172,15 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } } + next.heapStorageImages = gpuResolvedImages && descriptorMemory; + if (gpuResolvedImages) { + for (const auto& descriptor : next.descriptors) { + if (next.HeapSlotWordKind(descriptor.kind)) next.imageSlotDwords += static_cast(descriptor.resources.size()); + } + } + if (descriptorMemory && gpuResolvedImages) next.bufferAddressDwords = static_cast(info.buffers.size()) * RuntimeAbi::BufferAddressWords; + if (next.UsesDataAddress()) placePushedData(next); + std::vector samplers; for (std::uint32_t i = 0; i < info.samplers.size(); i++) { if (info.samplers[i].table == NoTable) { @@ -205,7 +232,7 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin result.pushConstantOffsetBytes = result.layout.pushDataStartDword * static_cast(sizeof(std::uint32_t)); result.pushConstantSizeBytes = result.layout.ShaderDataDwords() * static_cast(sizeof(std::uint32_t)); } - if (stencilReplay) { + if (stencilReplay && !result.layout.UsesDataAddress()) { result.pushConstantOffsetBytes = layout.pushConstantOffsetBytes; result.pushConstantSizeBytes += sizeof(std::uint32_t); } diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index e9c3f40c7d4d..f599e212333c 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -20,14 +21,15 @@ namespace ShaderRecompiler { static_assert(PipelineSpecialization::ImageBase + ShaderInfo::MaxImages * PipelineSpecialization::ImageWords <= PipelineSpecialization::VertexBase); -static_assert(PipelineSpecialization::MipCountBase + ShaderInfo::MaxImages <= PipelineSpecialization::StoreQuantizeBase); +static_assert(PipelineSpecialization::MipCountBase + ShaderInfo::MaxImages <= PipelineSpecialization::RootItemPositionBase); static_assert(PipelineSpecialization::StoreQuantizeBase + ShaderInfo::MaxImages * PipelineSpecialization::StoreQuantizeWords <= PipelineSpecialization::DescriptorIndexBase); static_assert(PipelineSpecialization::CompareBase + ShaderInfo::MaxImages * PipelineSpecialization::CompareWords <= PipelineSpecialization::FoldOffsetBase); static_assert(PipelineSpecialization::FoldOffsetBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::UnnormalizedBaseLevelBase); static_assert(PipelineSpecialization::UnnormalizedBaseLevelBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::MirrorUnnormalizedBase); static_assert(PipelineSpecialization::MirrorUnnormalizedBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::MinLodBase); static_assert(PipelineSpecialization::MinLodBase + ShaderInfo::MaxImages <= PipelineSpecialization::SamplerLodBiasBase); -static_assert(PipelineSpecialization::SamplerLodBiasBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::FmaskFormatBase); +static_assert(PipelineSpecialization::SamplerLodBiasBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::BufferRootPosition); +static_assert(PipelineSpecialization::BufferOverflowPosition < PipelineSpecialization::FmaskFormatBase); static_assert(PipelineSpecialization::FmaskFormatBase + ShaderInfo::MaxImages <= PipelineSpecialization::VolumeGatherBase); static_assert(PipelineSpecialization::VolumeGatherBase + ShaderInfo::MaxImages <= PipelineSpecialization::ImageComponentBase); static_assert(PipelineSpecialization::ImageComponentBase + ShaderInfo::MaxImages <= PipelineSpecialization::NormalizedImageBase); @@ -194,24 +196,6 @@ DescriptorImageShape ImageShapeForResource(const ImageResource& image) { fail("DescriptorBindingBuilder::Populate image resource dimension has no descriptor image shape"); } -std::vector GuestBuffersDescriptor(const std::vector& resources, const ResourceSnapshot& snapshot) { - std::vector result; - result.reserve(resources.size() * 4u); - for (const std::uint32_t r : resources) { - if (r >= snapshot.buffers.size()) { - fail("DescriptorBindingBuilder::Populate guest buffer index is out of range"); - } - const DescriptorValue& value = snapshot.buffers[r]; - if (value.dwordCount != 4u) { - fail("DescriptorBindingBuilder::Populate guest buffer descriptor has an invalid width"); - } - for (std::uint32_t dword = 0; dword < 4u; dword++) { - result.push_back(value.dwords[dword]); - } - } - return result; -} - std::vector GuestSamplersDescriptor(const std::vector& resources, const ResourceSnapshot& snapshot) { std::vector result; result.reserve(resources.size() * 4u); @@ -442,6 +426,8 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l if (stage == IrShaderStage::Pixel && exportMappings.size() != 8u) fail("fragment runtime export mappings are missing"); if (info.images.size() > ShaderInfo::MaxImages) fail("runtime image count exceeds the static capacity (" + std::to_string(info.images.size()) + " of " + std::to_string(ShaderInfo::MaxImages) + ")"); DescriptorBindingPlan plan; + plan.addressedBuffers = layout.bufferAddressDwords != 0u; + plan.addressedData = layout.UsesDataAddress(); const auto unnormalized = ProveUnnormalized(info, snapshot); for (std::uint32_t index = 0; index < info.samplers.size(); ++index) { if (FoldsTexelOffsets(info.samplers[index])) plan.specialization.push_back({PipelineSpecialization::FoldOffsetBase + index, unnormalized.samplers[index] ? 1u : 0u}); @@ -574,10 +560,14 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l if (last < first || last - first >= RuntimeAbi::StorageMipSlots) fail("invalid dynamic storage mip range"); if (!registrationModules) plan.specialization.push_back({PipelineSpecialization::MipCountBase + index, last - first + 1u}); } + std::vector> activeElements(info.images.size(), {UINT32_MAX, 0u}); plan.bindings.reserve(layout.descriptors.size()); + const bool slotWords = layout.gpuResolvedImages && !registrationModules; + std::uint32_t imageSlotBase = layout.ImageSlotDword(); for (const auto& logical : layout.descriptors) { const bool imageHeap = ImageBindingResourceClass(logical.kind) != ImageResourceClass::None; const bool samplerHeap = logical.kind == DescriptorBindingKind::Samplers; + const bool sampledSlots = layout.gpuResolvedImages && layout.HeapSlotWordKind(logical.kind); IrDescriptorBinding compact{logical.kind, {}}; std::vector originals; std::vector inactive; @@ -600,18 +590,22 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l active = (samplerModes.at(resource) & (1u << (element & 1u))) != 0u; } if ((imageHeap || samplerHeap) && !registrationModules) plan.specialization.push_back({PipelineSpecialization::DescriptorIndex(static_cast(logical.kind), element), active ? static_cast(compact.resources.size()) : 0u}); + if (active && sampledSlots) plan.heapSlotWords.push_back({imageSlotBase + element, static_cast(logical.kind), static_cast(compact.resources.size())}); + const bool embeddedSampler = samplerHeap && layout.gpuResolvedImages && info.samplers.at(resource).constant; + if (active && slotWords && samplerHeap && !embeddedSampler) plan.heapSlotWords.push_back({layout.SamplerSlotDword() + element, static_cast(logical.kind), static_cast(compact.resources.size())}); if (active || ((imageHeap || samplerHeap) && registrationModules)) { compact.resources.push_back(resource); originals.push_back(element); inactive.push_back(!active); } } + if (sampledSlots) imageSlotBase += static_cast(logical.resources.size()); if ((imageHeap || samplerHeap) && !registrationModules) plan.specialization.push_back({PipelineSpecialization::HeapCountBase + static_cast(logical.kind), std::max(1u, static_cast(compact.resources.size()))}); if ((imageHeap || samplerHeap) && compact.resources.empty()) continue; PreparedDescriptorBinding entry{}; auto& physical = entry.descriptor; - physical.descriptorSet = fragmentDescriptorSet && stage == IrShaderStage::Pixel ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet; - physical.binding = NativeBinding(stage, compact.kind); + physical.descriptorSet = DescriptorSetNumber(layout, compact.kind, stage, layout.gpuResolvedImages, fragmentDescriptorSet, true); + physical.binding = DescriptorBindingNumber(layout, compact.kind, stage, layout.gpuResolvedImages); physical.count = compact.resources.empty() ? 1u : static_cast(compact.resources.size()); physical.kind = PhysicalKindFor(compact.kind); physical.role = RoleFor(compact.kind); @@ -642,6 +636,7 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l physical.imageUnnormalizedBaseLevel.push_back(unnormalized.imagesAtBaseLevel.at(resource)); physical.imageSamplers.push_back(0u); physical.imageAtomic64.push_back(image.atomic64); + if (layout.gpuResolvedImages && !inactive[element] && activeElements[resource].first == UINT32_MAX && DescriptorBindingForImage(mode) == compact.kind) activeElements[resource] = {static_cast(compact.kind), static_cast(element)}; } } else if (physical.role == DescriptorRole::GuestSamplers) { for (std::uint32_t element = 0; element < compact.resources.size(); ++element) { @@ -656,6 +651,13 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l const auto& words = snapshot.samplers.at(resource).dwords; const bool tablePointOnly = (directSamplerModes.at(resource) & 2u) == 0u; if ((originals[element] & 1u) != 0u && !inactive[element] && !(tablePointOnly && ReducesBetweenTexels(words[0], words[2]))) entry.samplerFilterElements.push_back(element); + const auto& sampler = info.samplers.at(resource); + const bool embedded = layout.gpuResolvedImages && sampler.constant && !inactive[element]; + physical.samplerEmbedded.push_back(embedded ? originals[element] : RuntimeAbi::NoEmbeddedSampler); + auto embeddedWords = sampler.constantWords; + if (embedded && (originals[element] & 1u) != 0u && !(tablePointOnly && ReducesBetweenTexels(embeddedWords[0], embeddedWords[2]))) + embeddedWords[2] = PointFilteredSamplerWord(embeddedWords[0], embeddedWords[2]); + physical.samplerEmbeddedWords.insert(physical.samplerEmbeddedWords.end(), embeddedWords.begin(), embeddedWords.end()); } } else if (physical.role == DescriptorRole::ShaderData && layout.UsesPushData()) { fail("DescriptorBindingBuilder::Populate shader-data binding must not exist when push data is used"); @@ -672,6 +674,10 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l RuntimeAbi::ResourceMetadata metadata{}; if (descriptor.dwordCount != metadata.descriptor.size()) fail("invalid runtime image descriptor width"); metadata.elementCount = 1u; + if (layout.gpuResolvedImages && activeElements[resource].first != UINT32_MAX) { + metadata.binding = activeElements[resource].first; + metadata.firstElement = activeElements[resource].second; + } if (imageModes[resource] > RuntimeAbi::ImageModeMask) fail("runtime image mode exceeds its metadata field"); metadata.flags = imageModes[resource] << 1u | (registrationModules ? (compareStates[resource] & RuntimeAbi::CompareStateMask) << RuntimeAbi::CompareStateShift : 0u); if (descriptor.dwords[0] == 0u && (descriptor.dwords[1] & 0xffu) == 0u) metadata.flags |= 1u; @@ -704,15 +710,41 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l return plan; } +namespace { + +bool IsAddressedRole(const DescriptorBindingPlan& plan, DescriptorRole role) { + switch (role) { + case DescriptorRole::GuestBuffers: return plan.addressedBuffers; + case DescriptorRole::ShaderData: + case DescriptorRole::FlattenedSrt: + case DescriptorRole::BdaPagetable: + case DescriptorRole::FaultBuffer: + case DescriptorRole::ImageTable: + case DescriptorRole::ImageStorageTable: + case DescriptorRole::SamplerTable: + case DescriptorRole::ImageTableMap: return plan.addressedData; + default: return false; + } +} + +} + DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPlan& plan, std::span bindings) const { DescriptorBindingPlan selected; std::set remaining(bindings.begin(), bindings.end()); selected.bindings.reserve(remaining.size()); for (const auto& binding : plan.bindings) { - if (remaining.erase(binding.descriptor.binding) == 0u) continue; + const bool addressed = IsAddressedRole(plan, binding.descriptor.role); + const bool embedded = std::ranges::any_of(binding.descriptor.samplerEmbedded, [](std::uint32_t element) { return element != RuntimeAbi::NoEmbeddedSampler; }); + if (remaining.erase(binding.descriptor.binding) == 0u && !addressed && !embedded) continue; selected.storageData |= binding.descriptor.role == DescriptorRole::ShaderData; selected.bindings.push_back(binding); } + if (plan.addressedData) { + for (const auto kind : {RuntimeAbi::FirstImageBinding, RuntimeAbi::FirstStorageImageBinding, RuntimeAbi::FirstAtomicImageBinding, RuntimeAbi::FirstAtomic64ImageBinding, static_cast(DescriptorBindingKind::Samplers)}) { + remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(kind))); + } + } if (!remaining.empty()) fail("specialized module bindings disagree with the prepared plan"); const bool hasSamplers = std::any_of(selected.bindings.begin(), selected.bindings.end(), [](const auto& binding) { return binding.descriptor.role == DescriptorRole::GuestSamplers; }); if (!hasSamplers) { @@ -723,9 +755,98 @@ DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPl } selected.imageMetadata = plan.imageMetadata; selected.runtimeState = plan.runtimeState; + constexpr auto bindingCount = static_cast(RuntimeAbi::Binding::Count); + std::set droppedKinds; + const auto bindingKind = [](std::uint32_t binding) { return binding < RuntimeAbi::ImageStorageTableBinding ? std::optional(binding % bindingCount) : std::nullopt; }; + for (const auto& binding : plan.bindings) { + if (const auto kind = bindingKind(binding.descriptor.binding)) droppedKinds.insert(*kind); + } + for (const auto& binding : selected.bindings) { + if (const auto kind = bindingKind(binding.descriptor.binding)) droppedKinds.erase(*kind); + } + selected.heapSlotWords.reserve(plan.heapSlotWords.size()); + for (const auto& word : plan.heapSlotWords) { + if (!droppedKinds.contains(word.kind)) selected.heapSlotWords.push_back(word); + } + selected.addressedBuffers = plan.addressedBuffers; + selected.addressedData = plan.addressedData; return selected; } +namespace { + +void guestBindingWords(const PreparedDescriptorBinding& entry, std::vector& words, const ResourceSnapshot& snapshot, const ResolvedImageTables* tables) { + words.clear(); + switch (entry.descriptor.role) { + case DescriptorRole::GuestBuffers: + words.reserve(entry.resources.size() * 4u); + for (const std::uint32_t resource : entry.resources) { + if (resource >= snapshot.buffers.size()) fail("DescriptorBindingBuilder::Populate guest buffer index is out of range"); + const DescriptorValue& value = snapshot.buffers[resource]; + if (value.dwordCount != 4u) fail("DescriptorBindingBuilder::Populate guest buffer descriptor has an invalid width"); + words.insert(words.end(), value.dwords.begin(), value.dwords.begin() + 4); + } + break; + case DescriptorRole::GuestImages: + words.reserve(words.size() + entry.resources.size() * 8u); + for (std::size_t element = 0; element < entry.resources.size(); ++element) { + const auto& descriptor = snapshot.images.at(entry.resources[element]); + if (descriptor.dwordCount != 8u) fail("invalid runtime image descriptor width"); + if (!entry.inactive.empty() && entry.inactive[element]) { + words.insert(words.end(), 8u, 0u); + continue; + } + const auto offset = words.size(); + words.insert(words.end(), descriptor.dwords.begin(), descriptor.dwords.begin() + 8); + if (entry.identityImageSwizzle[element]) words[offset + 3u] = (words[offset + 3u] & ~0xfffu) | ShaderImageIdentitySwizzle; + } + break; + case DescriptorRole::GuestSamplers: + words = GuestSamplersDescriptor(entry.resources, snapshot); + for (const auto element : entry.samplerFilterElements) { + auto& filter = words.at(element * 4u + 2u); + filter = PointFilteredSamplerWord(words.at(element * 4u), filter); + } + break; + case DescriptorRole::ImageTable: + case DescriptorRole::ImageStorageTable: + if (tables == nullptr) fail("DescriptorBindingBuilder::Populate image table elements were not resolved"); + words.reserve(words.size() + tables->elements.size() * 8u); + for (const auto& element : tables->elements) words.insert(words.end(), element.words.begin(), element.words.end()); + break; + case DescriptorRole::SamplerTable: + if (tables == nullptr) fail("DescriptorBindingBuilder::Populate sampler table elements were not resolved"); + words.reserve(words.size() + tables->samplers.size() * 4u); + for (const auto& element : tables->samplers) { + const auto first = words.size(); + words.insert(words.end(), element.words.begin(), element.words.end()); + if (element.point) words[first + 2u] = PointFilteredSamplerWord(words[first], words[first + 2u]); + } + break; + case DescriptorRole::ImageTableMap: + if (tables == nullptr || tables->map.empty()) fail("DescriptorBindingBuilder::Populate image table map was not resolved"); + words = tables->map; + break; + case DescriptorRole::FlattenedSrt: + if (snapshot.flattenedSrt.empty()) fail("DescriptorBindingBuilder::Populate flattened SRT snapshot is empty"); + words = snapshot.flattenedSrt; + break; + case DescriptorRole::ShaderData: + case DescriptorRole::Gds: + case DescriptorRole::BdaPagetable: + case DescriptorRole::FaultBuffer: + break; + } + const auto role = entry.descriptor.role; + if (role == DescriptorRole::GuestBuffers || role == DescriptorRole::GuestImages || role == DescriptorRole::GuestSamplers) { + if (entry.descriptor.count == 0u || words.size() % entry.descriptor.count != 0u) { + fail("DescriptorBindingBuilder::Populate guest descriptor size is not a multiple of the binding count"); + } + } +} + +} + void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, const CompiledBindingLayout& compiled, const DescriptorBindingPlan& plan, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads, const ResolvedImageTables* tables) const { const auto& layout = compiled.layout; const bool needsShaderData = layout.UsesPushData() || plan.storageData; @@ -741,37 +862,15 @@ void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, con std::size_t readOnlyHere = 0; for (const auto& entry : plan.bindings) { auto physical = entry.descriptor; + if (physical.role == DescriptorRole::ShaderData) physical.guestDescriptor = std::move(shaderData); + else guestBindingWords(entry, physical.guestDescriptor, snapshot, tables); switch (physical.role) { case DescriptorRole::GuestBuffers: - physical.guestDescriptor = GuestBuffersDescriptor(entry.resources, snapshot); writtenHere += entry.writtenBuffers; readOnlyHere += entry.readOnlyBuffers; break; - case DescriptorRole::GuestImages: - physical.guestDescriptor.reserve(entry.resources.size() * 8u); - for (std::size_t element = 0; element < entry.resources.size(); ++element) { - const auto& descriptor = snapshot.images.at(entry.resources[element]); - if (descriptor.dwordCount != 8u) fail("invalid runtime image descriptor width"); - if (!entry.inactive.empty() && entry.inactive[element]) { - physical.guestDescriptor.insert(physical.guestDescriptor.end(), 8u, 0u); - continue; - } - const auto offset = physical.guestDescriptor.size(); - physical.guestDescriptor.insert(physical.guestDescriptor.end(), descriptor.dwords.begin(), descriptor.dwords.begin() + 8); - if (entry.identityImageSwizzle[element]) physical.guestDescriptor[offset + 3u] = (physical.guestDescriptor[offset + 3u] & ~0xfffu) | ShaderImageIdentitySwizzle; - } - break; - case DescriptorRole::GuestSamplers: - physical.guestDescriptor = GuestSamplersDescriptor(entry.resources, snapshot); - for (const auto element : entry.samplerFilterElements) { - auto& filter = physical.guestDescriptor.at(element * 4u + 2u); - filter = PointFilteredSamplerWord(physical.guestDescriptor.at(element * 4u), filter); - } - break; case DescriptorRole::ImageTable: case DescriptorRole::ImageStorageTable: - if (tables == nullptr) fail("DescriptorBindingBuilder::Populate image table elements were not resolved"); - physical.guestDescriptor.reserve(tables->elements.size() * 8u); physical.imageShapes.reserve(physical.imageShapes.size() + tables->elements.size()); physical.imageDepthCompare.reserve(physical.imageDepthCompare.size() + tables->elements.size()); physical.imageWritten.reserve(physical.imageWritten.size() + tables->elements.size()); @@ -780,14 +879,13 @@ void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, con physical.imageUintStorage.reserve(physical.imageUintStorage.size() + tables->elements.size()); physical.imageSamplers.reserve(physical.imageSamplers.size() + tables->elements.size()); for (const auto& element : tables->elements) { - physical.guestDescriptor.insert(physical.guestDescriptor.end(), element.words.begin(), element.words.end()); ImageResource shape; shape.dimension = element.dimension; physical.imageShapes.push_back(ImageShapeForResource(shape)); physical.imageDepthCompare.push_back(element.depthCompare); physical.imageWritten.push_back(ImageBindingResourceClass(element.kind) == ImageResourceClass::Storage); - physical.imageAtomic.push_back(element.atomic); - physical.imageAtomic64.push_back(element.atomic64); + physical.imageAtomic.push_back(element.atomic || RuntimeAbi::AtomicImageKind(static_cast(element.kind))); + physical.imageAtomic64.push_back(element.atomic64 || RuntimeAbi::Atomic64ImageKind(static_cast(element.kind))); physical.imageUintStorage.push_back(ImageBindingResourceClass(element.kind) == ImageResourceClass::Storage && RuntimeAbi::UintStorageImageBinding(static_cast(element.kind))); std::uint64_t samplers = 0; for (std::uint32_t sampler = 0; sampler < entry.tableSamplerMasks.size(); ++sampler) { @@ -798,45 +896,15 @@ void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, con physical.count = static_cast(tables->elements.size()); break; case DescriptorRole::SamplerTable: - if (tables == nullptr) fail("DescriptorBindingBuilder::Populate sampler table elements were not resolved"); - physical.guestDescriptor.reserve(tables->samplers.size() * 4u); physical.samplerDepthCompare.reserve(physical.samplerDepthCompare.size() + tables->samplers.size()); - for (const auto& element : tables->samplers) { - const auto first = physical.guestDescriptor.size(); - physical.guestDescriptor.insert(physical.guestDescriptor.end(), element.words.begin(), element.words.end()); - if (element.point) physical.guestDescriptor[first + 2u] = PointFilteredSamplerWord(physical.guestDescriptor[first], physical.guestDescriptor[first + 2u]); - physical.samplerDepthCompare.push_back(element.compare); - } + for (const auto& element : tables->samplers) physical.samplerDepthCompare.push_back(element.compare); physical.count = static_cast(tables->samplers.size()); break; - case DescriptorRole::ImageTableMap: - if (tables == nullptr || tables->map.empty()) fail("DescriptorBindingBuilder::Populate image table map was not resolved"); - physical.guestDescriptor = tables->map; - break; - case DescriptorRole::FlattenedSrt: - if (snapshot.flattenedSrt.empty()) { - fail("DescriptorBindingBuilder::Populate flattened SRT snapshot is empty"); - } - physical.guestDescriptor = snapshot.flattenedSrt; - break; - case DescriptorRole::ShaderData: - physical.guestDescriptor = std::move(shaderData); - break; - case DescriptorRole::Gds: - case DescriptorRole::BdaPagetable: - case DescriptorRole::FaultBuffer: + default: break; } - - if (physical.role == DescriptorRole::GuestBuffers || physical.role == DescriptorRole::GuestImages || physical.role == DescriptorRole::GuestSamplers) { - if (physical.count == 0u || physical.guestDescriptor.size() % physical.count != 0u) { - fail("DescriptorBindingBuilder::Populate guest descriptor size is not a multiple of the binding count"); - } - } - bindings.push_back(std::move(physical)); } - if (bufferWrittenTraceEnabled()) { // Cumulative counts include every Populate of the process (the replay tool populates // each program twice), so the per-call counts are the ones to sum per program. @@ -852,4 +920,19 @@ void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, con } } +void DescriptorBindingBuilder::PopulateGuestWords(std::vector>& words, const CompiledBindingLayout& compiled, const DescriptorBindingPlan& plan, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads, const ResolvedImageTables* tables) const { + const auto& layout = compiled.layout; + words.resize(plan.bindings.size()); + for (std::size_t index = 0; index < plan.bindings.size(); ++index) { + const auto& entry = plan.bindings[index]; + if (entry.descriptor.role != DescriptorRole::ShaderData) { + guestBindingWords(entry, words[index], snapshot, tables); + } else if (layout.UsesPushData() || plan.storageData) { + words[index] = ShaderDataDwordsFor(layout, userDataBase, snapshot, partialThreads, plan.imageMetadata, plan.runtimeState); + } else { + words[index].clear(); + } + } +} + } diff --git a/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp b/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp index 4c475098ba05..89c3cc115da9 100644 --- a/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp +++ b/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp @@ -582,9 +582,25 @@ void AddTargetMerge(const ShaderPixelInputInfo& pixel, ShaderInfo& info) { if (std::ranges::any_of(pixel.merges, &TargetMerge::layered)) AddInput(info, StageInputKind::Layer, 0, 1, "gl_Layer"); } +void collectConstantSampler(const IrProgram& program, SamplerResource& sampler) { + sampler.constant = false; + sampler.constantWords = {}; + const auto& sources = program.Resources().descriptorSources; + if (sampler.table != NoTable || sampler.source >= sources.size()) return; + const auto& source = sources[sampler.source]; + if (source.dwordCount != 4u) return; + for (std::uint32_t index = 0; index < 4u; ++index) { + const IrValue* word = source.dwords[index] != nullptr ? source.dwords[index]->Resolve() : nullptr; + if (word == nullptr || !word->HasImmediate() || word->Type() != IrType::U32) return; + sampler.constantWords[index] = word->ImmediateU32(); + } + sampler.constant = true; +} + void CollectSamplerUses(const IrProgram& program, ShaderInfo& info) { for (auto& sampler : info.samplers) { sampler.uses = 0; + collectConstantSampler(program, sampler); } const auto& memoryInfo = program.Resources().memoryInfo; for (const auto& block : program.Blocks()) { diff --git a/core/shader/recompiler/Optimization/src/SrtWalker/SrtAddressArithmetic.cpp b/core/shader/recompiler/Optimization/src/SrtWalker/SrtAddressArithmetic.cpp deleted file mode 100644 index 9040192bc658..000000000000 --- a/core/shader/recompiler/Optimization/src/SrtWalker/SrtAddressArithmetic.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "Optimization/SrtWalker/SrtAddressArithmetic.hpp" - -namespace ShaderRecompiler::Detail { - -bool AddSignedAddress(std::uint64_t base, std::int64_t offset, std::uint64_t& result) { - if (base > AddressMask) { - return false; - } - if (offset < 0) { - const auto magnitude = std::uint64_t {0} - static_cast(offset); - if (magnitude > base) { - return false; - } - result = base - magnitude; - return true; - } - const auto magnitude = static_cast(offset); - if (magnitude > AddressMask - base) { - return false; - } - result = base + magnitude; - return true; -} - -} diff --git a/core/shader/recompiler/PipelineSpecialization.hpp b/core/shader/recompiler/PipelineSpecialization.hpp index f7b0e1044151..9275c43705f3 100644 --- a/core/shader/recompiler/PipelineSpecialization.hpp +++ b/core/shader/recompiler/PipelineSpecialization.hpp @@ -37,16 +37,24 @@ inline constexpr std::uint32_t StencilReferenceOffset = 8235u; inline constexpr std::uint32_t ReversedBlend = 8236u; inline constexpr std::uint32_t MeshLayerBase = 8237u; inline constexpr std::uint32_t MeshLayerCount = 8238u; +inline constexpr std::uint32_t HeapImageSlots = 8239u; inline constexpr std::uint32_t DepthRemapBase = 8240u; inline constexpr std::uint32_t DepthRemapWords = 1u; inline constexpr std::uint32_t WorkgroupOffsetBase = 8241u; inline constexpr std::uint32_t WorkgroupOffsetWords = 3u; inline constexpr std::uint32_t AtomicLockTableBase = 8244u; inline constexpr std::uint32_t AtomicLockTableWords = 2u; +inline constexpr std::uint32_t PushedDataBase = 8246u; +inline constexpr std::uint32_t PushedDataCount = 8247u; +inline constexpr std::uint32_t RootItemPositionBase = 8448u; +inline constexpr std::uint32_t RootItemPositions = 16u; inline constexpr std::uint32_t HeapCountBase = 8256u; inline constexpr std::uint32_t MipCountBase = 8320u; inline constexpr std::uint32_t StoreQuantizeBase = 12288u; inline constexpr std::uint32_t StoreQuantizeWords = 4u; +inline constexpr std::uint32_t BufferRootPosition = 57856u; +inline constexpr std::uint32_t BufferRootCount = 16u; +inline constexpr std::uint32_t BufferOverflowPosition = BufferRootPosition + BufferRootCount; inline constexpr std::uint32_t DescriptorIndexBase = 16384u; inline constexpr std::uint32_t DescriptorIndexStride = 128u; inline constexpr std::uint32_t FoldOffsetBase = 57344u; @@ -62,6 +70,12 @@ inline constexpr std::uint32_t DescriptorIndex(std::uint32_t binding, std::uint3 return DescriptorIndexBase + binding * DescriptorIndexStride + element; } +static_assert(MipCountBase < RootItemPositionBase && RootItemPositionBase + RootItemPositions <= StoreQuantizeBase); + +inline constexpr bool IsPushPlacement(std::uint32_t id) { + return id == PushedDataBase || id == PushedDataCount || (id >= BufferRootPosition && id <= BufferOverflowPosition) || (id >= RootItemPositionBase && id < RootItemPositionBase + RootItemPositions); +} + inline constexpr bool IsWorkgroupOffset(std::uint32_t id) { return id >= WorkgroupOffsetBase && id < WorkgroupOffsetBase + WorkgroupOffsetWords; } diff --git a/core/shader/recompiler/PushDataLayout.hpp b/core/shader/recompiler/PushDataLayout.hpp new file mode 100644 index 000000000000..96271938331a --- /dev/null +++ b/core/shader/recompiler/PushDataLayout.hpp @@ -0,0 +1,327 @@ +#ifndef CORE_SHADER_RECOMPILER_PUSHDATALAYOUT_HPP +#define CORE_SHADER_RECOMPILER_PUSHDATALAYOUT_HPP + +#include "PipelineSpecialization.hpp" +#include "Recompiler.hpp" +#include "RuntimeAbi.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace ShaderRecompiler { + +enum class PushPart : std::uint32_t { PreRasterization, Fragment, Compute }; + +inline PushPart PushPartOf(ShaderStage stage) { + if (stage == ShaderStage::Fragment) return PushPart::Fragment; + return stage == ShaderStage::Compute ? PushPart::Compute : PushPart::PreRasterization; +} + +struct PushStage { + PushPart part = PushPart::PreRasterization; + std::uint32_t items = 0; + std::uint32_t pushedWanted = 0; + std::uint32_t pushedBuffers = 0; +}; + +static_assert(RuntimeAbi::PushedBufferLimit == PipelineSpecialization::BufferRootCount); + +constexpr std::array MakeBufferRoots() { + std::array roots{}; + roots.fill(RuntimeAbi::NoPushPosition); + return roots; +} + +struct StagePushPlacement { + std::array items{}; + RuntimeAbi::PushedPlacement pushed; + std::array bufferRoots = MakeBufferRoots(); + std::uint32_t bufferOverflow = RuntimeAbi::NoPushPosition; + std::uint32_t pushedBuffers = 0; + + [[nodiscard]] std::uint32_t Item(RuntimeAbi::RootItem item) const { return items[static_cast(item)]; } + bool operator==(const StagePushPlacement&) const = default; +}; + +constexpr std::uint64_t PushBytesMask(std::uint32_t offset, std::uint32_t bytes) { + std::uint64_t mask = 0; + for (auto dword = offset / 4u; dword < (offset + bytes + 3u) / 4u && dword < RuntimeAbi::PushDataDwords; ++dword) mask |= 1ull << dword; + return mask; +} + +constexpr std::uint64_t PushFeatureDwords(bool meshDraw, bool tessellationLevels, bool depthRemap) { + std::uint64_t mask = 0; + if (meshDraw) mask |= PushBytesMask(MeshDrawPushOffsetBytes, MeshDrawPushBytes); + if (tessellationLevels) mask |= PushBytesMask(TessellationLevelPushOffsetBytes, TessellationLevelPushBytes); + if (depthRemap) mask |= PushBytesMask(DepthRemapPushOffsetBytes, DepthRemapPushBytes); + return mask; +} + +inline constexpr std::uint32_t RootItemMask = (1u << RuntimeAbi::RootItemCount) - 1u; + +constexpr std::uint64_t StagePushFeatures(ShaderStage stage, std::uint32_t pushItems) { + const bool depthRemap = (pushItems & RuntimeAbi::DepthRemapPushBit) != 0u; + std::uint64_t mask = PushFeatureDwords(stage == ShaderStage::Mesh || stage == ShaderStage::Geometry, stage == ShaderStage::TessellationControl || stage == ShaderStage::TessellationEvaluation, depthRemap); + if (stage == ShaderStage::Compute) mask |= PushBytesMask(GpuScratchPoolAddressPushByte - 8u, GpuScratchPoolDwordsPushByte + 4u - (GpuScratchPoolAddressPushByte - 8u)); + return mask; +} + +class PushDataPlacer { +public: + PushDataPlacer(std::span stages, std::uint64_t occupied, std::uint32_t pushedRecords) + : stages(stages), used(occupied), pushedRecords(pushedRecords), placements(stages.size()), overflows(stages.size(), RuntimeAbi::NoPushPosition) { + for (auto& placement : placements) placement.items.fill(RuntimeAbi::NoPushPosition); + } + + std::vector Place() { + PlaceRoots(); + PlaceBufferRoots(); + PlaceUserData(); + ClaimPushedData(); + return std::move(placements); + } + +private: + static constexpr std::uint32_t total = RuntimeAbi::PushDataDwords; + static constexpr std::uint32_t globalItems = RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData) - 1u; + static constexpr std::uint32_t optionalItems = RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::UserData); + static constexpr std::array parts{PushPart::Fragment, PushPart::Compute, PushPart::PreRasterization}; + + static constexpr std::uint32_t fragmentRecordFloor = 2u * RuntimeAbi::RootItemCount; + + static bool Top(PushPart part) { return part != PushPart::PreRasterization; } + + bool IsFree(std::uint32_t first, std::uint32_t width) const { + for (auto dword = first; dword < first + width; ++dword) { + if (dword >= total || (used >> dword & 1ull) != 0u) return false; + } + return true; + } + + std::uint32_t TryTake(std::uint32_t width, bool aligned, bool top, std::uint32_t floor = 0u) { + for (std::uint32_t step = 0; step + width <= total; ++step) { + const auto first = top ? total - width - step : step; + if (first < floor) break; + if ((aligned && first % 2u != 0u) || !IsFree(first, width)) continue; + for (auto dword = first; dword < first + width; ++dword) used |= 1ull << dword; + return first; + } + return RuntimeAbi::NoPushPosition; + } + + std::uint32_t Take(std::uint32_t width, bool aligned, bool top) { + const auto first = TryTake(width, aligned, top); + if (first == RuntimeAbi::NoPushPosition) throw std::runtime_error("the push data has no room for a pipeline's root"); + return first; + } + + void PlaceRootItems(std::uint32_t items, bool top, std::array& positions) { + for (const bool addresses : {true, false}) { + for (std::uint32_t index = 0; index < RuntimeAbi::RootItemCount; ++index) { + const auto item = static_cast(index); + if ((items & RuntimeAbi::RootItemBit(item)) == 0u || RuntimeAbi::RootAddressItem(item) != addresses) continue; + positions[index] = Take(addresses ? 2u : 1u, addresses, top); + } + } + } + + template + void ForEachStageOfPartReserving(PushPart part, Visit&& visit) { + const auto reserved = part == PushPart::Fragment ? PushFeatureDwords(true, true, true) & ~used : 0u; + used |= reserved; + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part == part) visit(index, Top(part)); + } + used &= ~reserved; + } + + void PlaceSharedRoots() { + std::uint32_t globals = 0; + std::uint32_t fragmentGlobals = 0; + for (const auto& stage : stages) { + globals |= stage.items & globalItems; + if (stage.part == PushPart::Fragment) fragmentGlobals |= stage.items & globalItems; + } + std::array shared{}; + shared.fill(RuntimeAbi::NoPushPosition); + PlaceRootItems(fragmentGlobals, false, shared); + PlaceRootItems(globals & ~fragmentGlobals, false, shared); + for (std::size_t index = 0; index < stages.size(); ++index) { + for (std::uint32_t item = 0; item < RuntimeAbi::RootItemCount; ++item) { + if ((stages[index].items & globalItems & (1u << item)) != 0u) placements[index].items[item] = shared[item]; + } + } + } + + void PlaceRoots() { + PlaceSharedRoots(); + for (const auto part : parts) { + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part != part) continue; + PlaceRootItems(stages[index].items & ~globalItems & ~optionalItems, Top(part), placements[index].items); + placements[index].pushedBuffers = stages[index].pushedBuffers; + } + } + } + + std::uint32_t RecordsOf(std::size_t index) const { return std::min({stages[index].pushedBuffers, pushedRecords, RuntimeAbi::PushedBufferLimit}); } + + void ReserveOverflowRecords() { + for (const auto part : parts) { + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part == part && stages[index].pushedBuffers != 0u) overflows[index] = TryTake(2u, true, Top(part)); + } + } + } + + void PlaceStageBufferRoots(std::size_t index, bool top) { + const auto buffers = stages[index].pushedBuffers; + if (buffers == 0u) return; + const auto records = RecordsOf(index); + const auto floor = stages[index].part == PushPart::Fragment ? fragmentRecordFloor : 0u; + bool overflowed = buffers > records; + for (std::uint32_t buffer = 0; buffer < records; ++buffer) { + placements[index].bufferRoots[buffer] = TryTake(RuntimeAbi::PushedBufferWords, true, top, floor); + overflowed = overflowed || placements[index].bufferRoots[buffer] == RuntimeAbi::NoPushPosition; + } + if (overflowed && overflows[index] == RuntimeAbi::NoPushPosition) throw std::runtime_error("the push data has no room for a stage's buffer addresses"); + if (overflowed) placements[index].bufferOverflow = overflows[index]; + else if (overflows[index] != RuntimeAbi::NoPushPosition) used &= ~(3ull << overflows[index]); + } + + void PlaceBufferRoots() { + ReserveOverflowRecords(); + for (const auto part : parts) ForEachStageOfPartReserving(part, [&](std::size_t index, bool top) { PlaceStageBufferRoots(index, top); }); + } + + void PlaceUserData() { + for (const auto part : parts) { + ForEachStageOfPartReserving(part, [&](std::size_t index, bool top) { + if ((stages[index].items & RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::UserData)) == 0u) return; + placements[index].items[static_cast(RuntimeAbi::RootItem::UserData)] = TryTake(2u, true, top); + }); + } + } + + std::vector> FreeRuns() const { + std::vector> runs; + for (std::uint32_t dword = 0; dword < total;) { + if ((used >> dword & 1ull) != 0u) { + ++dword; + continue; + } + auto end = dword; + while (end < total && (used >> end & 1ull) == 0u) ++end; + runs.emplace_back(dword, end); + dword = end; + } + return runs; + } + + std::vector PushedDataCounts(const std::vector>& runs) const { + std::uint32_t room = 0; + std::uint32_t largest = 0; + for (const auto& [first, end] : runs) { + room += end - first; + largest = std::max(largest, end - first); + } + std::vector wanted(stages.size(), 0u); + std::uint32_t sum = 0; + for (std::size_t index = 0; index < stages.size(); ++index) { + wanted[index] = std::min({stages[index].pushedWanted, RuntimeAbi::PushedDataWantedLimit, largest}); + sum += wanted[index]; + } + auto counts = wanted; + if (sum <= room) return counts; + const auto sharedAt = [&](std::uint32_t level) { + std::uint32_t shared = 0; + for (const auto want : wanted) shared += std::min(want, level); + return shared; + }; + std::uint32_t level = 0; + while (sharedAt(level + 1u) <= room) ++level; + auto left = room - sharedAt(level); + for (std::size_t index = 0; index < counts.size(); ++index) { + counts[index] = std::min(wanted[index], level); + if (left != 0u && wanted[index] > level) { + ++counts[index]; + --left; + } + } + return counts; + } + + void ClaimRun(std::vector>& runs, std::size_t index, std::uint32_t count, bool top) { + if (count == 0u) return; + auto chosen = runs.end(); + if (top) { + for (auto run = runs.rbegin(); run != runs.rend(); ++run) { + if (run->second - run->first >= count) { + chosen = std::prev(run.base()); + break; + } + } + } else { + chosen = std::find_if(runs.begin(), runs.end(), [&](const auto& run) { return run.second - run.first >= count; }); + } + if (chosen == runs.end()) { + chosen = std::max_element(runs.begin(), runs.end(), [](const auto& left, const auto& right) { return left.second - left.first < right.second - right.first; }); + if (chosen == runs.end()) return; + count = chosen->second - chosen->first; + } + if (top) { + placements[index].pushed = {chosen->second - count, count}; + chosen->second -= count; + } else { + placements[index].pushed = {chosen->first, count}; + chosen->first += count; + } + } + + void ClaimPushedData() { + auto runs = FreeRuns(); + const auto counts = PushedDataCounts(runs); + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part == PushPart::Fragment) ClaimRun(runs, index, counts[index], true); + } + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part != PushPart::Fragment) ClaimRun(runs, index, counts[index], false); + } + } + + std::span stages; + std::uint64_t used; + std::uint32_t pushedRecords; + std::vector placements; + std::vector overflows; +}; + +inline std::vector PlacePushData(std::span stages, std::uint64_t occupied, std::uint32_t pushedRecords = RuntimeAbi::PushedBufferLimit) { + return PushDataPlacer(stages, occupied, pushedRecords).Place(); +} + +static_assert(RuntimeAbi::RootItemCount <= PipelineSpecialization::RootItemPositions); + +inline StagePushPlacement StandalonePushPlacement(ShaderStage stage, std::uint32_t pushItems, std::size_t pushedWanted, std::uint32_t pushedBuffers = 0u) { + const PushStage pushStage{PushPartOf(stage), pushItems & RootItemMask, static_cast(pushedWanted), pushedBuffers}; + return PlacePushData(std::span(&pushStage, 1), StagePushFeatures(stage, pushItems)).front(); +} + +inline void AppendPushSpecialization(std::vector& constants, const StagePushPlacement& placement) { + for (std::uint32_t item = 0; item < RuntimeAbi::RootItemCount; ++item) { + const bool optional = item == static_cast(RuntimeAbi::RootItem::UserData); + if (optional || placement.items[item] != RuntimeAbi::NoPushPosition) constants.push_back({PipelineSpecialization::RootItemPositionBase + item, placement.items[item]}); + } + for (std::uint32_t buffer = 0; buffer < std::min(placement.pushedBuffers, RuntimeAbi::PushedBufferLimit); ++buffer) constants.push_back({PipelineSpecialization::BufferRootPosition + buffer, placement.bufferRoots[buffer]}); + if (placement.pushedBuffers != 0u) constants.push_back({PipelineSpecialization::BufferOverflowPosition, placement.bufferOverflow}); + constants.push_back({PipelineSpecialization::PushedDataBase, placement.pushed.base}); + constants.push_back({PipelineSpecialization::PushedDataCount, placement.pushed.count}); +} + +} + +#endif diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 06722f171510..84a3a58297aa 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -1,9 +1,13 @@ #include "prx/libc/include/HostThreadLocal.hpp" +#include "HeapCacheSwitch.hpp" #include "Recompiler.hpp" +#include "PushDataLayout.hpp" +#include "HeapTemplateBudget.hpp" #include "RdnaDecoder/DiagnosticSink.hpp" #include "StencilReplay.hpp" #include #include +#include #include #include #include @@ -22,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -65,6 +70,16 @@ namespace ShaderRecompiler { +static std::shared_ptr Sealed(std::shared_ptr result) { + if (result != nullptr) result->SealIdentity(); + return result; +} + +bool VerifyIdentityMemo() { + static const bool verify = std::getenv("APS5_VERIFY_IDENTITY") != nullptr; + return verify; +} + namespace { ShaderStageKind toShaderStageKind(ShaderStage stage) { @@ -442,8 +457,49 @@ constexpr std::size_t ResultMemoSets = 64; constexpr std::size_t ResultMemoWays = 4; using ResultMemoTable = std::array; +std::uint64_t NextId(std::atomic& counter) { + return counter.fetch_add(1, std::memory_order_relaxed) + 1u; +} + +std::uint64_t NextSourceId() { + static std::atomic ids{0}; + return NextId(ids); +} + +std::uint64_t NextTemplateId() { + static std::atomic ids{0}; + return NextId(ids); +} + +struct UsedBindingPlan { + std::shared_ptr owner; + const DescriptorBindingPlan* plan = nullptr; +}; + +struct HeapTemplate { + std::shared_ptr result; + UsedBindingPlan plan; + std::vector buffers; + std::vector images; + std::vector samplers; + std::uint64_t bytes = 0; + bool tableRoles = false; +}; + +bool HasTableRoles(const UsedBindingPlan& used) { + return used.plan != nullptr && std::ranges::any_of(used.plan->bindings, [](const PreparedDescriptorBinding& entry) { + const auto role = entry.descriptor.role; + return role == DescriptorRole::ImageTable || role == DescriptorRole::ImageStorageTable || role == DescriptorRole::SamplerTable || role == DescriptorRole::ImageTableMap; + }); +} + +bool HasImageTableBindings(const CompiledBindingLayout& bindings) { + return std::ranges::any_of(bindings.layout.descriptors, [](const IrDescriptorBinding& descriptor) { return descriptor.kind == DescriptorBindingKind::ImageTable || descriptor.kind == DescriptorBindingKind::SamplerTable || descriptor.kind == DescriptorBindingKind::ImageTableMap; }); +} + struct SourceEntry : std::enable_shared_from_this { std::mutex mutex; + const std::uint64_t id = NextSourceId(); // The code the entry was built for: the key carries only a hash of it, so a candidate entry is // accepted only when its code matches word for word. Owned here because the request's span // points into a registration the driver may replace while the entry lives on. @@ -464,8 +520,116 @@ struct SourceEntry : std::enable_shared_from_this { std::vector emissionFailures; std::unique_ptr memo; std::unique_ptr maskedMemo; + std::unordered_map> heapTemplates; +}; + +namespace { + +std::uint64_t HeapTemplateBudget() { + static const std::uint64_t budget = [] { + const char* value = std::getenv("APS5_HEAP_TEMPLATE_MIB"); + std::uint64_t mib = 256u; + if (value != nullptr && *value != '\0') { + const auto* end = value + std::strlen(value); + const auto parsed = std::from_chars(value, end, mib); + if (parsed.ec != std::errc{} || parsed.ptr != end || mib > (1u << 20u)) throw std::runtime_error("APS5_HEAP_TEMPLATE_MIB must be an integer from 0 through 1048576"); + } + return std::max(mib, 1u) << 20u; + }(); + return budget; +} + +struct HeapTemplateStore { + std::mutex mutex; + HeapTemplateLru order{HeapTemplateBudget()}; + std::uint64_t evicted = 0; +}; + +HeapTemplateStore& HeapTemplates() { + static auto* store = new HeapTemplateStore(); + return *store; +} + +std::uint64_t HeapTemplateBytes(const HeapTemplate& entry) { + return sizeof(HeapTemplate) + OwnedBytes(*entry.result) + OwnedBytes(entry.buffers) + OwnedBytes(entry.images) + OwnedBytes(entry.samplers); +} + +HeapTemplateLru::Name HeapTemplateName(const SourceEntry& source, std::uint64_t key, const HeapTemplate& entry) { + return {source.id, key, entry.result->heapTemplateId}; +} + +std::atomic& HeapTemplateErasures() { + static std::atomic erasures{0}; + return erasures; +} + +constexpr std::size_t HeapTemplateFrontEntries = 1024; +constexpr std::uint64_t HeapTemplateTouchInterval = 256; + +struct HeapTemplateFront { + struct Entry { + std::uint64_t source = 0; + std::uint64_t key = 0; + std::uint64_t touched = 0; + std::shared_ptr found; + }; + std::array entries{}; + std::uint64_t lookups = 0; + std::uint64_t erasures = 0; + + void Follow(std::uint64_t current) { + if (current == erasures) return; + for (auto& entry : entries) entry.found.reset(); + erasures = current; + } + + Entry& At(std::uint64_t source, std::uint64_t key) { + return entries[((key ^ (source * 0x9e3779b97f4a7c15ull)) >> 17u) & (HeapTemplateFrontEntries - 1u)]; + } }; +HeapTemplateFront& HeapTemplateFrontTable() { + struct FrontStorage {}; + return HostThreadLocal(); +} + +void KeepHeapTemplate(const std::shared_ptr& source, std::uint64_t key, const HeapTemplate& entry) { + auto& store = HeapTemplates(); + std::vector evicted; + { + std::lock_guard lock(store.mutex); + evicted = store.order.Insert(HeapTemplateName(*source, key, entry), entry.bytes, source); + } + std::uint64_t erased = 0; + for (const auto& gone : evicted) { + const auto owner = std::static_pointer_cast(gone.owner.lock()); + if (owner == nullptr) continue; + std::lock_guard lock(owner->mutex); + const auto found = owner->heapTemplates.find(gone.name.key); + if (found == owner->heapTemplates.end() || found->second->result->heapTemplateId != gone.name.id) continue; + owner->heapTemplates.erase(found); + ++erased; + } + if (erased == 0) return; + HeapTemplateErasures().fetch_add(1, std::memory_order_release); + std::lock_guard lock(store.mutex); + store.evicted += erased; +} + +void TouchHeapTemplate(const HeapTemplateLru::Name& name) { + auto& store = HeapTemplates(); + std::lock_guard lock(store.mutex); + store.order.Touch(name); +} + +} + +HeapTemplateCacheCounts HeapTemplateCounts() { + auto& store = HeapTemplates(); + std::lock_guard lock(store.mutex); + return {store.order.Entries(), store.order.Bytes(), std::exchange(store.evicted, 0)}; +} + namespace { class PrimedSharedMutex : public std::shared_mutex { @@ -774,7 +938,7 @@ std::array partialThreads(const RecompileRequest& request) { std::uint64_t nextVariantId() { static std::atomic variants{0}; - return variants.fetch_add(1, std::memory_order_relaxed) + 1; + return NextId(variants); } template @@ -814,10 +978,12 @@ void prepareInterface(const RecompileRequest& request, IrProgram& program) { CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) { const auto inputInfo = RequestInputInfo(request); constexpr BindingAllocator bindingAllocator; - bool registration = request.target.registrationModules && request.shader.stage == ShaderStage::Fragment; + const bool heapVertex = request.shader.stage == ShaderStage::Vertex && request.target.gpuResolvedImages && request.target.descriptorMemory; + bool registration = request.target.registrationModules && (request.shader.stage == ShaderStage::Fragment || heapVertex); program.Metadata().bindingLayoutComplete = false; const bool stencilReplay = request.shader.stage == ShaderStage::Fragment && std::ranges::any_of(program.Info().outputs, [](const StageOutput& output) { return output.kind == StageOutputKind::StencilRef; }) && std::ranges::find(request.target.supportedCapabilities, static_cast(spv::CapabilityStencilExportEXT)) == request.target.supportedCapabilities.end(); - auto bindings = bindingAllocator.Allocate(program, request.layout, registration, stencilReplay); + AllocationOptions allocation {.registrationModules = registration, .stencilReplay = stencilReplay, .gpuResolvedImages = request.target.gpuResolvedImages, .descriptorMemory = request.target.descriptorMemory}; + auto bindings = bindingAllocator.Allocate(program, request.layout, allocation); SpirvTargetOptions targetOptions {}; targetOptions.vulkanVersion = request.target.vulkanVersion; @@ -878,6 +1044,9 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) } targetOptions.waveLdsMemoryBarriers = request.target.waveLdsMemoryBarriers; targetOptions.deviceScopeLdsMemoryBarriers = request.target.deviceScopeLdsMemoryBarriers; + targetOptions.gpuResolvedImages = allocation.gpuResolvedImages; + targetOptions.heapDataUniformDwords = request.target.heapDataUniformDwords; + targetOptions.uniformConstantBuffers = request.target.uniformConstantBuffers; targetOptions.ldsLockFences = request.target.ldsLockFences; targetOptions.meshWindowBuffer = request.target.meshWindowBuffer; targetOptions.float16WidenNans = request.target.float16WidenNans; @@ -898,7 +1067,8 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) if (registration && result.spirv.size() > request.target.registrationWordLimit) { registration = false; program.Metadata().bindingLayoutComplete = false; - bindings = bindingAllocator.Allocate(program, request.layout, false, stencilReplay); + allocation.registrationModules = false; + bindings = bindingAllocator.Allocate(program, request.layout, allocation); targetOptions.registrationModules = false; result.spirv = spirvEmitter.Emit(program, inputInfo, bindings, targetOptions, &emitted); } @@ -911,6 +1081,15 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) result.stencilReferences = StencilReferenceValues(program, request.context.pixel.has_value() && request.context.pixel->stencilOperationValueExport ? 8u : 0u); result.stencilReferenceDword = bindings.layout.stencilReferenceDword; } + result.gpuResolvedImages = targetOptions.gpuResolvedImages; + result.samplerSlotDword = result.gpuResolvedImages ? bindings.layout.SamplerSlotDword() : 0u; + result.bufferAddressDword = bindings.layout.bufferAddressDwords != 0u ? bindings.layout.BufferAddressDword() : 0u; + result.bufferAddressCount = bindings.layout.bufferAddressDwords / RuntimeAbi::BufferAddressWords; + result.pushedBufferCount = result.bufferAddressCount; + result.dataAddressPush = bindings.layout.UsesDataAddress(); + result.pushedData = bindings.layout.pushedData; + result.bdaStores = emitted.bdaStores; + result.pushItems = emitted.pushItems; result.bdaAbiVersion = program.Info().usesDma || program.Info().usesFaultBuffer ? request.target.bdaAbiVersion : 0u; result.windowLaneGuards = 0; @@ -990,6 +1169,7 @@ struct SpecializedModule { SpirvContentHash hash; mutable std::mutex mutex; mutable SharedSpirv::Weak spirv; + mutable SharedSpirv kept; }; struct SpecializedSpirv { @@ -997,6 +1177,14 @@ struct SpecializedSpirv { SharedSpirv spirv; }; +bool StencilInPush(const CompiledShaderArtifact& artifact, const IrBindingLayout& layout) { + return !artifact.stencilReferences.empty() && !layout.UsesDataAddress(); +} + +bool UsesRootOrPush(const IrBindingLayout& layout) { + return layout.UsesPushData() || layout.UsesDataAddress(); +} + std::vector specializeWords(const CompiledShaderArtifact& artifact, std::span classes, std::span constants, const SpirvTarget& target) { auto source = SpecializeVertexInputTypes(artifact, classes); std::map supplied; @@ -1014,7 +1202,7 @@ std::vector specializeWords(const CompiledShaderArtifact& artifac const auto count = words[cursor] >> 16u; const auto op = static_cast(words[cursor] & 0xffffu); if (count == 0u || count > words.size() - cursor) throw std::runtime_error("truncated prepared specialization instruction"); - if (!artifact.stencilReferences.empty() && op == spv::OpTypePointer && count == 4u && words[cursor + 2u] == spv::StorageClassPushConstant) pushTypes.insert(words[cursor + 3u]); + if (!artifact.stencilReferences.empty() && !artifact.dataAddressPush && op == spv::OpTypePointer && count == 4u && words[cursor + 2u] == spv::StorageClassPushConstant) pushTypes.insert(words[cursor + 3u]); if (op == spv::OpDecorate && count == 4u && words[cursor + 2u] == spv::DecorationSpecId) { if (PipelineSpecialization::IsWorkgroupOffset(words[cursor + 3u])) { if (supplied.contains(words[cursor + 3u])) throw std::runtime_error("a workgroup offset is supplied at dispatch, not prepared"); @@ -1030,7 +1218,7 @@ std::vector specializeWords(const CompiledShaderArtifact& artifac } const auto found = supplied.find(words[cursor + 3u]); if (found == supplied.end()) throw std::runtime_error("missing prepared specialization value"); - if (found->first == PipelineSpecialization::MeshLayerBase || found->first == PipelineSpecialization::MeshLayerCount) { + if (found->first == PipelineSpecialization::MeshLayerBase || found->first == PipelineSpecialization::MeshLayerCount || found->first == PipelineSpecialization::HeapImageSlots || PipelineSpecialization::IsPushPlacement(found->first)) { retained.insert(words[cursor + 1u]); cursor += count; continue; @@ -1117,7 +1305,7 @@ SpecializedSpirv buildSpecializedModule(const CompiledShaderArtifact& artifact, const auto op = static_cast(materialized[cursor] & 0xffffu); if (op == spv::OpEntryPoint && count >= 2u) compute = materialized[cursor + 1u] == spv::ExecutionModelGLCompute; if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationBinding) bindingNumbers.emplace(materialized[cursor + 1u], materialized[cursor + 3u]); - if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationDescriptorSet && (materialized[cursor + 3u] == PixelFunctionLdsDescriptorSet || materialized[cursor + 3u] == MeshWindowDescriptorSet || (compute && materialized[cursor + 3u] == WorkgroupMemoryDescriptorSet))) ldsBuffers.insert(materialized[cursor + 1u]); + if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationDescriptorSet && (materialized[cursor + 3u] == PixelFunctionLdsDescriptorSet || materialized[cursor + 3u] == MeshWindowDescriptorSet || materialized[cursor + 3u] == RuntimeAbi::EmbeddedSamplerSet || materialized[cursor + 3u] == RuntimeAbi::PushedBufferSet || (compute && !target.gpuResolvedImages && materialized[cursor + 3u] == WorkgroupMemoryDescriptorSet))) ldsBuffers.insert(materialized[cursor + 1u]); if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationSpecId) { const auto id = materialized[cursor + 3u]; if (!PipelineSpecialization::IsWorkgroupOffset(id) && !PipelineSpecialization::IsAtomicLockTable(id)) module->specialization.push_back({id, supplied.at(id)}); @@ -1141,6 +1329,7 @@ SharedSpirv specializedWords(const SpecializedModule& module, const CompiledShad auto spirv = InternSpirv(specializeWords(artifact, classes, constants, target)); if (spirv.ContentHash() != module.hash) throw std::runtime_error("ShaderRecompiler: a specialized module built again from its key differs from its first build"); module.spirv = spirv.Weaken(); + module.kept = spirv; return spirv; } @@ -1186,6 +1375,7 @@ struct RegistrationModuleEntry { SharedSpirv lockedWords(const SpecializedModule& module) { std::lock_guard lock(module.mutex); + if (!module.kept.empty()) return module.kept; return module.spirv.Lock(); } @@ -1225,33 +1415,42 @@ bool bufferSubstitutesEnabled() { return enabled; } -std::shared_ptr preparedBindingPlan(const CompiledVariant& variant, const ResourceSnapshot& snapshot, std::span exports, bool fragmentDescriptorSet, std::span substitutes, bool shaderImageMinLod) { - struct BindingPlanKeyStorage {}; - auto& key = HostThreadLocal, BindingPlanKeyStorage>(); - key.clear(); - key.push_back(variant.artifact.variantId); +template +void visitBindingPlanKey(const CompiledVariant& variant, const ResourceSnapshot& snapshot, std::span exports, std::span substitutes, TVisit&& visit) { + visit(variant.artifact.variantId); for (std::size_t index = 0; index < variant.info.info.buffers.size(); ++index) { const auto& descriptor = snapshot.buffers.at(index); - key.push_back(descriptor.dwordCount); + visit(descriptor.dwordCount); const auto fields = BufferSpecializationFields(descriptor, substitutes, index); - key.push_back(fields.word1); - key.push_back(fields.word3); - key.push_back(fields.known ? 4u | fields.misalignment | fields.tail << 3u : 0u); + visit(fields.word1); + visit(fields.word3); + visit(fields.known ? 4u | fields.misalignment | fields.tail << 3u : 0u); } for (std::size_t index = 0; index < variant.info.info.images.size(); ++index) { const auto& descriptor = snapshot.images.at(index); - key.push_back(descriptor.dwordCount); - key.push_back(descriptor.dwords[0] != 0u || (descriptor.dwords[1] & 0xffu) != 0u); - key.push_back(descriptor.dwords[1] & ~0xffu); - for (std::size_t word = 2; word < 8; ++word) key.push_back(descriptor.dwords[word]); + visit(descriptor.dwordCount); + visit(descriptor.dwords[0] != 0u || (descriptor.dwords[1] & 0xffu) != 0u); + visit(descriptor.dwords[1] & ~0xffu); + for (std::size_t word = 2; word < 8; ++word) visit(descriptor.dwords[word]); } for (std::size_t index = 0; index < variant.info.info.samplers.size(); ++index) { const auto& descriptor = snapshot.samplers.at(index); - key.push_back(descriptor.dwordCount); - for (std::size_t word = 0; word < 4; ++word) key.push_back(descriptor.dwords[word]); + visit(descriptor.dwordCount); + for (std::size_t word = 0; word < 4; ++word) visit(descriptor.dwords[word]); } - key.push_back(exports.size()); - for (const auto mapping : exports) key.push_back(mapping); + visit(exports.size()); + for (const auto mapping : exports) visit(mapping); +} + +void bindingPlanKey(std::vector& key, const CompiledVariant& variant, const ResourceSnapshot& snapshot, std::span exports, std::span substitutes) { + key.clear(); + visitBindingPlanKey(variant, snapshot, exports, substitutes, [&](std::uint64_t word) { key.push_back(word); }); +} + +std::shared_ptr preparedBindingPlan(const CompiledVariant& variant, const ResourceSnapshot& snapshot, std::span exports, bool fragmentDescriptorSet, std::span substitutes, bool shaderImageMinLod) { + struct BindingPlanKeyStorage {}; + auto& key = HostThreadLocal, BindingPlanKeyStorage>(); + bindingPlanKey(key, variant, snapshot, exports, substitutes); static PrimedSharedMutex mutex; static std::map, std::shared_ptr> plans; std::shared_ptr plan; @@ -1346,6 +1545,7 @@ void recordMemoPatch(MemoPatch& patch, const DescriptorBindingPlan& plan, const } } patch.pushData = layout.UsesPushData(); + if (layout.UsesDataAddress()) return; if (patch.pushData || plan.storageData) { for (const auto reg : layout.userDataRegisters) patch.userWords.push_back(reg - variant.info.userDataBase); } @@ -1363,7 +1563,7 @@ bool declaresAtomicLockTable(std::span words) { return false; } -RecompileResult materializeResult(const CompiledVariant& variant, const RecompileRequest& request, const ResourceSnapshot& captured, bool registrationDefaults = false, MemoPatch* patch = nullptr, const std::vector* substituteSnapshot = nullptr) { +RecompileResult materializeResult(const CompiledVariant& variant, const RecompileRequest& request, const ResourceSnapshot& captured, bool registrationDefaults = false, UsedBindingPlan* usedPlan = nullptr, MemoPatch* patch = nullptr, const std::vector* substituteSnapshot = nullptr) { const auto localSubstitutes = substituteSnapshot == nullptr && bufferSubstitutesEnabled() && variant.substitutes != nullptr ? variant.substitutes->Slots() : std::vector{}; const auto substitutes = substituteSnapshot != nullptr ? std::span(*substituteSnapshot) : std::span(localSubstitutes); ResourceSnapshot merged; @@ -1377,6 +1577,15 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil .runtimeImageCount = artifact.runtimeImageCount, .runtimeImageResources = artifact.runtimeImageResources, .registrationModule = artifact.registrationModule, + .gpuResolvedImages = artifact.gpuResolvedImages, + .samplerSlotDword = artifact.samplerSlotDword, + .bufferAddressDword = artifact.bufferAddressDword, + .bufferAddressCount = artifact.bufferAddressCount, + .pushedBufferCount = artifact.pushedBufferCount, + .pushedData = artifact.pushedData, + .pushItems = artifact.pushItems, + .dataAddressPush = artifact.dataAddressPush, + .bdaStores = artifact.bdaStores, .bdaAbiVersion = artifact.bdaAbiVersion, .windowLaneGuards = artifact.windowLaneGuards, .descriptorFaults = artifact.descriptorFaults, @@ -1415,7 +1624,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil auto& moduleKey = HostThreadLocal, LocalModuleKeyStorage>(); moduleKey.clear(); if (variant.bindings.layout.UsesPushData()) moduleKey.push_back(request.layout.pushConstantOffsetBytes / 4u); - if (!artifact.stencilReferences.empty()) moduleKey.push_back(request.layout.pushConstantOffsetBytes / 4u + artifact.stencilReferenceDword); + if (StencilInPush(artifact, variant.bindings.layout)) moduleKey.push_back(request.layout.pushConstantOffsetBytes / 4u + artifact.stencilReferenceDword); if (request.context.pixel) { for (const auto packing : request.context.pixel->targetExportPacking) moduleKey.push_back(static_cast(packing)); moduleKey.push_back(request.context.pixel->dualSourceBlend ? 1u : 0u); @@ -1464,7 +1673,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil if (artifact.registrationModule) runtimeSelectors.at(input.location / RuntimeAbi::VertexSelectorsPerDword) |= (selectors & 0xfffu) << (input.location % RuntimeAbi::VertexSelectorsPerDword * 16u); } } - if (!plan->bindings.specialization.empty() || variant.bindings.layout.UsesPushData() || !artifact.vertexInputPatches.empty() || request.context.pixel || depthRemap || request.shader.stage == ShaderStage::Mesh) { + if (!plan->bindings.specialization.empty() || UsesRootOrPush(variant.bindings.layout) || !artifact.vertexInputPatches.empty() || request.context.pixel || depthRemap || request.shader.stage == ShaderStage::Mesh) { { std::shared_lock lock(plan->mutex); if (const auto found = plan->modules.find(moduleKey); found != plan->modules.end()) entry = found->second; @@ -1478,9 +1687,11 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil auto constants = plan->bindings.specialization; constants.push_back({PipelineSpecialization::MeshLayerBase, 0u}); constants.push_back({PipelineSpecialization::MeshLayerCount, 0xffffffffu}); + constants.push_back({PipelineSpecialization::HeapImageSlots, RuntimeAbi::GpuImageHeapSlots}); + if (artifact.dataAddressPush) AppendPushSpecialization(constants, StandalonePushPlacement(request.shader.stage, artifact.pushItems, artifact.pushedData.size(), artifact.pushedBufferCount)); std::size_t index = 0; if (variant.bindings.layout.UsesPushData()) constants.push_back({PipelineSpecialization::PushDataOffset, moduleKey[index++]}); - if (!artifact.stencilReferences.empty()) constants.push_back({PipelineSpecialization::StencilReferenceOffset, moduleKey[index++]}); + if (StencilInPush(artifact, variant.bindings.layout)) constants.push_back({PipelineSpecialization::StencilReferenceOffset, moduleKey[index++]}); if (request.context.pixel) { for (std::uint32_t target = 0; target < request.context.pixel->targetExportPacking.size(); ++target) constants.push_back({PipelineSpecialization::ExportPackingBase + target, moduleKey[index++]}); constants.push_back({PipelineSpecialization::DualSourceBlend, moduleKey[index++]}); @@ -1507,7 +1718,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil const auto prepare = [&] { auto specialized = specialize(); const auto& module = specialized.module; - if (variant.bindings.layout.UsesPushData() && !module->pushData) throw std::runtime_error("specialization removed the prepared push constant interface"); + if (UsesRootOrPush(variant.bindings.layout) && !module->pushData) throw std::runtime_error("specialization removed the prepared push constant interface"); auto selected = DescriptorBindingBuilder{}.Select(plan->bindings, module->bindings); entry->bindings = std::move(selected); entry->module = module; @@ -1533,6 +1744,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil } const auto resolved = ResourceMaterializer::ResolveImageTablesShared(variant.info.info, snapshot, artifact.variantId); const auto& tables = *resolved; + if (usedPlan != nullptr) *usedPlan = {entry != nullptr ? std::shared_ptr(entry) : std::shared_ptr(plan), bindingPlan}; BindingAllocationResult bindings; DescriptorBindingBuilder{}.Populate(bindings, variant.bindings, *bindingPlan, variant.info.userDataBase, snapshot, partialThreads(request), &tables); if (patch != nullptr) recordMemoPatch(*patch, *bindingPlan, variant); @@ -1553,13 +1765,15 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil if (std::ranges::none_of(result.bindings, [](const DescriptorBinding& binding) { return binding.role == DescriptorRole::BdaPagetable || binding.role == DescriptorRole::FaultBuffer; })) result.bdaAbiVersion = 0u; result.pushConstants = std::move(bindings.pushConstants); result.readsDepthRemapPush = depthRemap; + if ((result.pushItems & RuntimeAbi::DepthRemapPushBit) != 0u && !depthRemap) throw std::runtime_error("a stage reads the depth remap push words its request does not remap"); if (request.shader.stage == ShaderStage::Compute) { for (std::uint32_t component = 0; component < PipelineSpecialization::WorkgroupOffsetWords; ++component) result.specialization.push_back({PipelineSpecialization::WorkgroupOffsetBase + component, 0u}); } + result.heapSlotWords = bindingPlan->heapSlotWords; if (declaresAtomicLockTable(artifact.spirv.Words())) { for (std::uint32_t word = 0; word < PipelineSpecialization::AtomicLockTableWords; ++word) result.specialization.push_back({PipelineSpecialization::AtomicLockTableBase + word, 0u}); } - if (!artifact.stencilReferences.empty()) { + if (StencilInPush(artifact, variant.bindings.layout)) { if (artifact.stencilReferenceDword * sizeof(std::uint32_t) != result.pushConstants.size() || result.pushConstants.size() + sizeof(std::uint32_t) > request.layout.pushConstantSizeBytes) throw std::runtime_error("stencil replay push constant lies outside the stage range"); result.pushConstants.resize(result.pushConstants.size() + sizeof(std::uint32_t)); } @@ -1818,7 +2032,7 @@ RecompileResult RecompileImpl(const RecompileRequest& request) { // APS5_NO_RESULT_MEMO=1: every Recompile(request, capture) materializes its own result as before. bool ResultMemo() { - static const bool resultMemo = std::getenv("APS5_NO_RESULT_MEMO") == nullptr; + static const bool resultMemo = HeapCacheEnabled(HeapCache::ResultMemo); return resultMemo; } @@ -1837,6 +2051,8 @@ ResultMemoEntry* memoSet(const std::unique_ptr& table, std::uin return table->data() + static_cast((index ^ (index >> 32u)) % ResultMemoSets) * ResultMemoWays; } + + struct ResultMemoCounters { std::atomic hits{0}, patched{0}, misses{0}, evictions{0}, trimmed{0}, populateNanoseconds{0}, patchNanoseconds{0}, mismatches{0}; std::atomic lastReport{0}; @@ -1905,7 +2121,7 @@ std::uint64_t vectorBytes(const ElementFlags& values) { } std::uint64_t descriptorBindingBytes(const DescriptorBinding& binding) { - return vectorBytes(binding.guestDescriptor) + vectorBytes(binding.imageShapes) + vectorBytes(binding.imageSamplers) + vectorBytes(binding.bufferExtent) + vectorBytes(binding.samplerDepthCompare) + vectorBytes(binding.imageWritten) + vectorBytes(binding.imageDepthCompare) + vectorBytes(binding.imageAtomic) + vectorBytes(binding.imageAtomic64) + vectorBytes(binding.imageUintStorage) + vectorBytes(binding.bufferAtomic) + vectorBytes(binding.bufferWritten) + vectorBytes(binding.samplerUnnormalized) + vectorBytes(binding.samplerIntegerBorder) + vectorBytes(binding.samplerCoordinatesIgnored) + vectorBytes(binding.imageUnnormalized) + vectorBytes(binding.imageUnnormalizedBaseLevel) + vectorBytes(binding.bufferRead); + return vectorBytes(binding.guestDescriptor) + vectorBytes(binding.samplerEmbedded) + vectorBytes(binding.samplerEmbeddedWords) + vectorBytes(binding.imageShapes) + vectorBytes(binding.imageSamplers) + vectorBytes(binding.bufferExtent) + vectorBytes(binding.samplerDepthCompare) + vectorBytes(binding.imageWritten) + vectorBytes(binding.imageDepthCompare) + vectorBytes(binding.imageAtomic) + vectorBytes(binding.imageAtomic64) + vectorBytes(binding.imageUintStorage) + vectorBytes(binding.bufferAtomic) + vectorBytes(binding.bufferWritten) + vectorBytes(binding.samplerUnnormalized) + vectorBytes(binding.samplerIntegerBorder) + vectorBytes(binding.samplerCoordinatesIgnored) + vectorBytes(binding.imageUnnormalized) + vectorBytes(binding.imageUnnormalizedBaseLevel) + vectorBytes(binding.bufferRead); } std::uint64_t resultBytes(const RecompileResult& result) { @@ -2045,7 +2261,13 @@ void reportResultMemo() { // Everything materializeResult reads besides the variant: the snapshot (the descriptor words, the // flattened SRT, the user data, the uniform fill) and, for the vertex family, the V# table the // attributes are resolved from. -std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapshot& snapshot, bool masked, std::span substitutes = {}) { +struct SnapshotHashScope { + bool masked = false; + bool perDrawData = true; + bool descriptors = true; +}; + +std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapshot& snapshot, SnapshotHashScope scope = {}, std::span substitutes = {}) { std::uint64_t hash = 0xcbf29ce484222325ull; const auto mix = [&](std::uint64_t value) { hash ^= value; @@ -2063,29 +2285,31 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh for (std::uint32_t i = 0; i < value.dwordCount && i < value.dwords.size(); ++i) mix(value.dwords[i]); } }; - if (masked) { - mix(snapshot.buffers.size()); - for (std::size_t index = 0; index < snapshot.buffers.size(); ++index) { - const auto& value = snapshot.buffers[index]; - mix(value.dwordCount); - mix(value.availableDwordMask); - const auto fields = BufferSpecializationFields(value, substitutes, index); - mix(fields.known ? 4u | fields.misalignment | fields.tail << 3u : 0u); - mix(fields.word1); - if (value.dwordCount > 3u) mix(fields.word3); - for (std::uint32_t i = 4; i < value.dwordCount && i < value.dwords.size(); ++i) mix(value.dwords[i]); - } - } else { - mixDescriptors(snapshot.buffers); - for (std::size_t index = 0; index < substitutes.size() && index < snapshot.buffers.size(); ++index) { - const auto fields = BufferSpecializationFields(snapshot.buffers[index], substitutes, index); - mix(fields.word1); - mix(fields.word3); - mix(fields.known ? 4u | fields.misalignment | fields.tail << 3u : 0u); + if (scope.descriptors) { + if (scope.masked) { + mix(snapshot.buffers.size()); + for (std::size_t index = 0; index < snapshot.buffers.size(); ++index) { + const auto& value = snapshot.buffers[index]; + mix(value.dwordCount); + mix(value.availableDwordMask); + const auto fields = BufferSpecializationFields(value, substitutes, index); + mix(fields.known ? 4u | fields.misalignment | fields.tail << 3u : 0u); + mix(fields.word1); + if (value.dwordCount > 3u) mix(fields.word3); + for (std::uint32_t i = 4; i < value.dwordCount && i < value.dwords.size(); ++i) mix(value.dwords[i]); + } + } else { + mixDescriptors(snapshot.buffers); + for (std::size_t index = 0; index < substitutes.size() && index < snapshot.buffers.size(); ++index) { + const auto fields = BufferSpecializationFields(snapshot.buffers[index], substitutes, index); + mix(fields.word1); + mix(fields.word3); + mix(fields.known ? 4u | fields.misalignment | fields.tail << 3u : 0u); + } } + mixDescriptors(snapshot.images); + mixDescriptors(snapshot.samplers); } - mixDescriptors(snapshot.images); - mixDescriptors(snapshot.samplers); mix(snapshot.registeredImages.size()); for (const auto& view : snapshot.registeredImages) { mix(view.resource); @@ -2103,10 +2327,10 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh for (const auto word : view.provenance.dwords) mix(word); for (const auto word : view.effective.dwords) mix(word); } - if (masked) { + if (scope.masked) { mix(snapshot.flattenedSrt.size()); mix(snapshot.userData.size()); - } else { + } else if (scope.perDrawData) { mixWords(snapshot.flattenedSrt); mixWords(snapshot.userData); } @@ -2158,7 +2382,8 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh mix(merge.layered); mix(merge.firstSlice); mix(merge.lastSlice); - for (const auto word : merge.descriptor) mix(word); + if (scope.descriptors) + for (const auto word : merge.descriptor) mix(word); if (!merge.blend.enabled) continue; mix(merge.blend.snorm); mix(merge.blend.colorSource); @@ -2176,7 +2401,11 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh const auto count = std::min(vertex.resourcesNum, ShaderVertexStageInfo::MaxResources); mix(count); for (std::uint32_t i = 0; i < count; ++i) { - for (const auto field : vertex.resources[i].fields) mix(field); + if (scope.perDrawData) { + for (const auto field : vertex.resources[i].fields) mix(field); + } else { + mix(vertex.resources[i].fields[3]); + } mix(vertex.resourcesDst[i].fetchIndex); } } else { @@ -2192,7 +2421,7 @@ std::shared_ptr materializePreparedMemoized(SourceEntry& static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; const auto variantId = variant->artifact.variantId; const auto substitutes = bufferSubstitutesEnabled() && variant->substitutes != nullptr ? variant->substitutes->Slots() : std::vector{}; - const auto hash = snapshotHash(request, snapshot, false, substitutes); + const auto hash = snapshotHash(request, snapshot, {}, substitutes); const auto index = (variantId * 0x9e3779b97f4a7c15ull) ^ hash; auto& counters = resultMemoCounters(); const auto acquire = [&](std::unique_lock& lock) { @@ -2220,7 +2449,7 @@ std::shared_ptr materializePreparedMemoized(SourceEntry& } } const bool masking = MaskedResultMemo(); - const auto maskedHash = masking ? snapshotHash(request, snapshot, true, substitutes) : 0u; + const auto maskedHash = masking ? snapshotHash(request, snapshot, {.masked = true}, substitutes) : 0u; const auto maskedIndex = (variantId * 0x9e3779b97f4a7c15ull) ^ maskedHash; std::shared_ptr donor; std::shared_ptr donorPatch; @@ -2245,12 +2474,12 @@ std::shared_ptr materializePreparedMemoized(SourceEntry& if (donor != nullptr) { result = std::make_shared(*donor); applyMemoPatch(*result, *donorPatch, snapshot); - if (VerifyMaskedResultMemo()) verifyPatchedResult(*result, materializeResult(*variant, request, snapshot, false, nullptr, &substitutes), variantId); + if (VerifyMaskedResultMemo()) verifyPatchedResult(*result, materializeResult(*variant, request, snapshot, false, nullptr, nullptr, &substitutes), variantId); if (profile) counters.patchNanoseconds.fetch_add(static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - started).count()), std::memory_order_relaxed); counters.patched.fetch_add(1, std::memory_order_relaxed); } else { if (masking) patch = std::make_shared(); - result = std::make_shared(materializeResult(*variant, request, snapshot, false, patch.get(), &substitutes)); + result = std::make_shared(materializeResult(*variant, request, snapshot, false, nullptr, patch.get(), &substitutes)); if (profile) counters.populateNanoseconds.fetch_add(static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - started).count()), std::memory_order_relaxed); counters.misses.fetch_add(1, std::memory_order_relaxed); } @@ -2317,10 +2546,10 @@ std::shared_ptr RecompileImpl(const RecompileRequest& req if (!request.useCache || capture.source == nullptr) { auto program = PrepareResourceProgram(request); const auto variant = CountedCompile([&] { return compileVariant(request, std::move(program)); }); - return std::make_shared(materializeResult(variant, request, capture.snapshot)); + return Sealed(std::make_shared(materializeResult(variant, request, capture.snapshot))); } - if (!ResultMemo()) return std::make_shared(materializeVariant(*capture.source, request, capture.snapshot)); - return materializeMemoized(*capture.source, request, capture.snapshot, memoHit); + if (!ResultMemo()) return Sealed(std::make_shared(materializeVariant(*capture.source, request, capture.snapshot))); + return Sealed(materializeMemoized(*capture.source, request, capture.snapshot, memoHit)); } template @@ -2417,6 +2646,7 @@ std::shared_ptr PrepareShader(const RecompileRequest& reques bool cacheHit = false; std::lock_guard lock(handle->source->mutex); handle->artifact = findOrCompileVariant(*handle->source, request, cacheHit, preparation); + handle->imageTableBindings = HasImageTableBindings(handle->artifact->bindings); return handle; }); trimResourcePlansOverBudget(); @@ -2444,9 +2674,12 @@ bool MatchesPreparedShader(const RecompileRequest& request, const SourceHandle& const auto words = prepared.ShaderDataDwords(); const auto pushSize = layout.pushConstantSizeBytes / 4u; const auto dataSize = !handle.artifact->artifact.stencilReferences.empty() && pushSize != 0u ? pushSize - 1u : pushSize; - const bool usesPush = prepared.runtimeImageCount == 0u && words != 0u && words <= dataSize; + const bool usesPush = !prepared.gpuResolvedImages && prepared.runtimeImageCount == 0u && words != 0u && words <= dataSize; if (prepared.UsesPushData() != usesPush) return false; - if (!handle.artifact->artifact.stencilReferences.empty() && (prepared.stencilReferenceDword >= layout.pushConstantSizeBytes / 4u || prepared.stencilReferenceDword != (usesPush ? words : 0u))) return false; + if (!handle.artifact->artifact.stencilReferences.empty()) { + const bool misplaced = prepared.UsesDataAddress() ? prepared.stencilReferenceDword != PushData::NoStart : prepared.stencilReferenceDword >= layout.pushConstantSizeBytes / 4u || prepared.stencilReferenceDword != (usesPush ? words : 0u); + if (misplaced) return false; + } if (!std::ranges::equal(key, handle.staticKey) || handle.source->code.size() != request.shader.code.size()) return false; return handle.source->code.data() == request.shader.code.data() || std::ranges::equal(handle.source->code, request.shader.code); } @@ -2456,7 +2689,7 @@ std::span GetPreparedCode(const SourceHandle& handle) { return handle.source->code; } -PreparedShaderInvocation::PreparedShaderInvocation(const RecompileRequest& request, const std::shared_ptr& handle) : request(request), handle(handle) { +PreparedShaderInvocation::PreparedShaderInvocation(RecompileRequest request, const std::shared_ptr& handle) : request(std::move(request)), handle(handle) { this->request.context.linkedCallFallbacks = handle->source->linkedCallFallbacks; } @@ -2473,6 +2706,12 @@ std::optional PreparedShaderInvocation::TryCreate(cons return PreparedShaderInvocation(request, handle); } +std::optional PreparedShaderInvocation::TryCreate(RecompileRequest&& request, const std::shared_ptr& handle, std::span key) { + if (handle == nullptr || !MatchesPreparedShader(request, *handle, key)) return std::nullopt; + if (request.shader.stage != ShaderStage::Compute && request.shader.stage != ShaderStage::Fragment) ValidateRequestInputs(request); + return PreparedShaderInvocation(std::move(request), handle); +} + std::shared_ptr PreparedShaderInvocation::Capture(const SrtRuntime& runtime) const { auto capture = std::make_shared(); capture->source = handle->source; @@ -2482,12 +2721,210 @@ std::shared_ptr PreparedShaderInvocation::Capture(const S return capture; } +namespace { + +bool AllEmpty(const std::vector>& words) { + return std::all_of(words.begin(), words.end(), [](const std::vector& descriptor) { return descriptor.empty(); }); +} + +std::uint64_t HeapTemplateKey(const RecompileRequest& request, const CompiledVariant& variant, const ResourceSnapshot& snapshot, bool perDrawBindings, std::span substitutes) { + std::uint64_t key = snapshotHash(request, snapshot, {.perDrawData = false, .descriptors = !perDrawBindings}, substitutes) ^ variant.artifact.variantId * 0x9e3779b97f4a7c15ull; + if (perDrawBindings) { + visitBindingPlanKey(variant, snapshot, request.context.pixel ? std::span(request.context.pixel->targetExportMapping) : std::span{}, substitutes, [&](std::uint64_t word) { key = (key ^ word) * 0x100000001b3ull; }); + } + return key; +} + +void HeapVertexAttributes(const RecompileRequest& request, const RecompileResult& result, HeapStageWords& words) { + words.vertexAttributes.clear(); + if (!request.context.vertex) return; + const auto& vertex = *request.context.vertex; + words.vertexAttributes = result.vertexAttributes; + for (auto& attribute : words.vertexAttributes) { + if (attribute.location >= vertex.resourcesNum || attribute.location >= vertex.resources.size()) throw std::runtime_error("ShaderRecompiler: vertex attribute outside the draw's vertex resources"); + attribute.resource = vertex.resources[attribute.location]; + if (vertex.fetchEmbedded) attribute.fetchIndex = vertex.resourcesDst[attribute.location].fetchIndex; + } +} + +void HeapBindingWords(const RecompileRequest& request, const CompiledVariant& variant, const ResourceSnapshot& snapshot, const HeapTemplate& shared, HeapStageWords& words) { + const auto& layout = variant.bindings.layout; + if (shared.plan.plan == nullptr) throw std::runtime_error("ShaderRecompiler: a heap template has no binding plan"); + const bool sameBuffers = snapshot.buffers == shared.buffers; + const bool sameImages = snapshot.images == shared.images && snapshot.samplers == shared.samplers; + if (sameBuffers && sameImages) return; + const auto count = shared.result->bindings.size(); + if (shared.plan.plan->bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap template's binding plan differs from its bindings"); + if (sameImages) { + words.bindings.assign(count, {}); + for (std::size_t index = 0; index < count; ++index) { + const auto& entry = shared.plan.plan->bindings[index]; + if (entry.descriptor.role != DescriptorRole::GuestBuffers) continue; + auto& descriptor = words.bindings[index]; + descriptor.reserve(entry.resources.size() * 4u); + for (const auto resource : entry.resources) { + if (resource >= snapshot.buffers.size() || snapshot.buffers[resource].dwordCount != 4u) throw std::runtime_error("ShaderRecompiler: a heap stage's guest buffer descriptor is out of range"); + descriptor.insert(descriptor.end(), snapshot.buffers[resource].dwords.begin(), snapshot.buffers[resource].dwords.begin() + 4); + } + if (descriptor == shared.result->bindings[index].guestDescriptor) descriptor.clear(); + } + if (AllEmpty(words.bindings)) words.bindings.clear(); + return; + } + const auto tables = shared.tableRoles ? std::optional(ResourceMaterializer::ResolveImageTables(variant.info.info, snapshot, variant.artifact.variantId)) : std::nullopt; + DescriptorBindingBuilder{}.PopulateGuestWords(words.bindings, variant.bindings, *shared.plan.plan, variant.info.userDataBase, snapshot, partialThreads(request), tables ? &*tables : nullptr); + if (words.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ from its template"); + if (HeapVerifyEnabled()) { + const auto resolved = ResourceMaterializer::ResolveImageTables(variant.info.info, snapshot, variant.artifact.variantId); + BindingAllocationResult bindings; + DescriptorBindingBuilder{}.Populate(bindings, variant.bindings, *shared.plan.plan, variant.info.userDataBase, snapshot, partialThreads(request), &resolved); + for (std::size_t index = 0; index < count; ++index) { + if (bindings.bindings[index].guestDescriptor != words.bindings[index]) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw binding " + std::to_string(index) + " words differ from a full populate"); + } + } + if (variant.artifact.registrationModule && request.shader.stage != ShaderStage::Fragment && layout.runtimeStateDwords != 0u) { + const auto first = layout.RuntimeStateDword() + RuntimeAbi::StateVertexSelectors; + for (std::size_t index = 0; index < words.bindings.size(); ++index) { + if (shared.result->bindings[index].role != DescriptorRole::ShaderData) continue; + const auto& kept = shared.result->bindings[index].guestDescriptor; + if (first + layout.runtimeStateDwords > kept.size() || first + layout.runtimeStateDwords > words.bindings[index].size()) throw std::runtime_error("ShaderRecompiler: vertex selector state lies outside a heap stage's shader data"); + std::copy_n(kept.begin() + first, layout.runtimeStateDwords, words.bindings[index].begin() + first); + } + } + for (std::size_t index = 0; index < count; ++index) { + if (words.bindings[index] == shared.result->bindings[index].guestDescriptor) words.bindings[index].clear(); + } + if (AllEmpty(words.bindings)) words.bindings.clear(); +} + +} + +std::shared_ptr PreparedShaderInvocation::MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words, HeapTemplateMiss* miss) const { + if (capture.source != handle->source || capture.plan != Plan()) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); + const auto& variant = handle->artifact; + if (!variant->artifact.gpuResolvedImages || !variant->artifact.registrationModule || variant->bindings.layout.UsesPushData()) return nullptr; + const auto& snapshot = capture.snapshot; + const auto& layout = variant->bindings.layout; + const auto userDataBase = request.context.userDataBaseRegister; + words.userData.resize(layout.userDataRegisters.size()); + for (std::size_t i = 0; i < layout.userDataRegisters.size(); ++i) { + const auto reg = layout.userDataRegisters[i]; + if (reg < userDataBase || reg - userDataBase >= snapshot.userData.size()) throw std::runtime_error("ShaderRecompiler: shader user-data register is out of range"); + words.userData[i] = snapshot.userData[reg - userDataBase]; + } + words.flattenedSrt.assign(snapshot.flattenedSrt.begin(), snapshot.flattenedSrt.end()); + words.bindings.clear(); + const bool perDrawBindings = (request.shader.stage == ShaderStage::Fragment || request.shader.stage == ShaderStage::Vertex) && !handle->imageTableBindings; + auto& source = *handle->source; + static thread_local std::vector substitutes; + substitutes.clear(); + if (bufferSubstitutesEnabled() && variant->substitutes != nullptr) variant->substitutes->CopySlots(substitutes); + ResourceSnapshot mergedStorage; + const auto& merged = mergeTargetImage(*variant, request, snapshot, false, mergedStorage); + const std::uint64_t key = HeapTemplateKey(request, *variant, merged, perDrawBindings, substitutes); + const auto complete = [&](const std::shared_ptr& shared) { + HeapVertexAttributes(request, *shared->result, words); + if (perDrawBindings) HeapBindingWords(request, *variant, merged, *shared, words); + CompleteHeapDataWords(*shared->result, words); + }; + auto& front = HeapTemplateFrontTable(); + front.Follow(HeapTemplateErasures().load(std::memory_order_acquire)); + auto& entry = front.At(source.id, key); + ++front.lookups; + std::shared_ptr hit; + const bool templates = HeapCacheEnabled(HeapCache::Templates); + if (templates && HeapCacheEnabled(HeapCache::TemplateFront) && entry.found != nullptr && entry.source == source.id && entry.key == key) { + hit = entry.found; + } else if (templates) { + { + std::lock_guard lock(source.mutex); + const auto found = source.heapTemplates.find(key); + if (found != source.heapTemplates.end()) hit = found->second; + } + if (hit != nullptr) entry = {source.id, key, 0, hit}; + } + if (hit != nullptr) { + complete(hit); + if (front.lookups - entry.touched >= HeapTemplateTouchInterval || entry.touched == 0) { + entry.touched = front.lookups; + TouchHeapTemplate({source.id, key, hit->result->heapTemplateId}); + } + return Sealed(hit->result); + } + if (miss != nullptr && templates) { + miss->missing = true; + miss->key = key ^ source.id * 0x9e3779b97f4a7c15ull; + return nullptr; + } + UsedBindingPlan usedPlan; + auto built = std::make_shared(materializeResult(*variant, request, snapshot, false, &usedPlan, nullptr, &substitutes)); + built->cacheHit = true; + for (const auto reg : layout.userDataRegisters) built->heapUserWords.push_back(reg - userDataBase); + built->heapTemplateId = NextTemplateId(); + auto created = std::make_shared(HeapTemplate{std::move(built), std::move(usedPlan), perDrawBindings ? merged.buffers : std::vector{}, perDrawBindings ? merged.images : std::vector{}, perDrawBindings ? merged.samplers : std::vector{}}); + created->bytes = HeapTemplateBytes(*created); + created->tableRoles = HasTableRoles(created->plan); + std::shared_ptr shared = std::move(created); + if (!templates) { + complete(shared); + return Sealed(shared->result); + } + bool inserted = false; + { + std::lock_guard lock(source.mutex); + auto [at, added] = source.heapTemplates.emplace(key, shared); + inserted = added; + shared = at->second; + } + if (inserted) KeepHeapTemplate(source.shared_from_this(), key, *shared); + else TouchHeapTemplate(HeapTemplateName(source, key, *shared)); + entry = {source.id, key, front.lookups, shared}; + complete(shared); + return Sealed(shared->result); +} + std::shared_ptr PreparedShaderInvocation::Materialize(const ResourceCapture& capture) const { if (capture.source != handle->source) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); - if (request.useCache && ResultMemo()) return materializePreparedMemoized(*handle->source, handle->artifact, request, capture.snapshot, true, nullptr); + if (request.useCache && ResultMemo()) return Sealed(materializePreparedMemoized(*handle->source, handle->artifact, request, capture.snapshot, true, nullptr)); auto result = std::make_shared(materializeResult(*handle->artifact, request, capture.snapshot)); result->cacheHit = true; - return result; + return Sealed(std::move(result)); +} + +std::shared_ptr PreparedShaderInvocation::Plan() const { + if (handle == nullptr || handle->source == nullptr) return nullptr; + std::lock_guard lock(handle->source->mutex); + return handle->source->plan; +} + +std::shared_ptr PreparedShaderInvocation::LoadPlan() const { + if (handle == nullptr || handle->source == nullptr) return nullptr; + return acquirePlan(request, handle->source, false, handle.get()); +} + +std::shared_ptr PreparedShaderInvocation::PlanOrLoad() const { + auto plan = Plan(); + return plan != nullptr ? std::move(plan) : LoadPlan(); +} + +std::uint64_t PreparedShaderInvocation::VariantId() const { + return handle != nullptr && handle->artifact != nullptr ? handle->artifact->artifact.variantId : 0u; +} + +void CompleteHeapDataWords(const RecompileResult& shared, HeapStageWords& words) { + const auto count = shared.bindings.size(); + if (!words.bindings.empty() && words.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ in number from its template"); + for (std::size_t index = 0; index < count; ++index) { + const auto& binding = shared.bindings[index]; + if (binding.role != DescriptorRole::ShaderData) continue; + if (!words.bindings.empty() && !words.bindings[index].empty()) continue; + const auto patched = std::min(words.userData.size(), binding.guestDescriptor.size()); + if (std::equal(words.userData.begin(), words.userData.begin() + static_cast(patched), binding.guestDescriptor.begin())) continue; + if (words.bindings.empty()) words.bindings.resize(count); + auto& descriptor = words.bindings[index]; + descriptor.assign(binding.guestDescriptor.begin(), binding.guestDescriptor.end()); + OverlayUserWords(descriptor, words.userData); + } } std::shared_ptr PreparedShaderInvocation::MaterializeIfMemoized(const ResourceCapture& capture, bool* contended) const { @@ -2503,7 +2940,7 @@ PreparedShaderInvocation PreparedShaderInvocation::Rebound(const RecompileReques std::uint64_t PreparedShaderInvocation::SnapshotKey(const ResourceCapture& capture) const { if (capture.source != handle->source) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); const auto substitutes = bufferSubstitutesEnabled() && handle->artifact->substitutes != nullptr ? handle->artifact->substitutes->Slots() : std::vector{}; - std::uint64_t key = snapshotHash(request, capture.snapshot, false, substitutes); + std::uint64_t key = snapshotHash(request, capture.snapshot, {}, substitutes); for (const std::uint64_t value : {static_cast(reinterpret_cast(handle.get())), static_cast(handle->artifact->artifact.variantId), static_cast(request.layout.descriptorSet), static_cast(request.layout.pushConstantSizeBytes)}) { key ^= value; key *= 0x100000001b3ull; @@ -2527,16 +2964,16 @@ std::shared_ptr RegistrationResult(const RecompileRequest snapshot.samplers.assign(info.samplers.size(), {{}, 4u}); snapshot.userData.assign(RuntimeAbi::UserDataCapacity, 0u); snapshot.flattenedSrt.assign(1u, 0u); - return std::make_shared(materializeResult(*handle.artifact, request, snapshot, true)); + return Sealed(std::make_shared(materializeResult(*handle.artifact, request, snapshot, true))); } std::shared_ptr MaterializeShader(const RecompileRequest& request, const ResourceCapture& capture, const SourceHandle& handle) { if (!MatchesPreparedShader(request, handle)) throw std::runtime_error("ShaderRecompiler: prepared artifact does not match the static ABI"); if (capture.source != handle.source) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); - if (request.useCache && ResultMemo()) return materializePreparedMemoized(*handle.source, handle.artifact, request, capture.snapshot, true, nullptr); + if (request.useCache && ResultMemo()) return Sealed(materializePreparedMemoized(*handle.source, handle.artifact, request, capture.snapshot, true, nullptr)); auto result = std::make_shared(materializeResult(*handle.artifact, request, capture.snapshot)); result->cacheHit = true; - return result; + return Sealed(std::move(result)); } std::shared_ptr CaptureResources(const RecompileRequest& request, const SrtRuntime& runtime, const SourceHandle& handle) { diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index a784d163d924..5498c2c72c7f 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -377,6 +377,10 @@ struct SpirvTarget { bool largePixelFunctionLdsBuffer = false; std::uint32_t pixelFunctionStorageDwords = 4096u; bool deviceScopeLdsMemoryBarriers = false; + bool gpuResolvedImages = false; + bool descriptorMemory = false; + std::uint32_t heapDataUniformDwords = 0; + bool uniformConstantBuffers = false; bool ldsLockFences = false; bool fragmentBarycentricBuiltins = false; bool meshWindowBuffer = false; @@ -462,7 +466,10 @@ inline constexpr std::uint32_t TessellationCaptureArgumentAddressDword = 2; inline constexpr std::uint32_t MeshIndexBufferUserWord = 4; inline constexpr std::uint32_t WorkgroupMemoryDescriptorSet = 1; inline constexpr std::uint32_t ScratchPoolDescriptorSet = 2; - +inline constexpr std::uint32_t GpuWorkgroupMemoryDescriptorSet = 3; +inline constexpr std::uint32_t GpuScratchPoolDescriptorSet = 5; +inline constexpr std::uint32_t GpuScratchPoolAddressPushByte = 136; +inline constexpr std::uint32_t GpuScratchPoolDwordsPushByte = 144; struct GraphicsDrawParameters { std::uint64_t indexAddress; std::uint32_t indexCount; @@ -505,6 +512,57 @@ struct GraphicsCompileContext { std::optional meshBarycentrics; }; +struct VertexAttribute; + +struct HeapTemplateCacheCounts { + std::uint64_t entries = 0; + std::uint64_t bytes = 0; + std::uint64_t evicted = 0; +}; +HeapTemplateCacheCounts HeapTemplateCounts(); + +struct ResultKeyMemo { + mutable AtomicSharedPtr> words; + ResultKeyMemo() = default; + ResultKeyMemo(const ResultKeyMemo&) {} + ResultKeyMemo& operator=(const ResultKeyMemo&) { + words.store(nullptr, std::memory_order_relaxed); + return *this; + } +}; + +struct IdentityMemo { + mutable std::atomic taken{false}; + mutable std::atomic sealed{false}; + mutable std::atomic low{0}; + mutable std::atomic high{0}; + mutable std::atomic moduleLow{0}; + mutable std::atomic moduleHigh{0}; + IdentityMemo() = default; + IdentityMemo(const IdentityMemo&) {} + IdentityMemo& operator=(const IdentityMemo&) { + Reset(); + return *this; + } + void Reset() const { + taken.store(false, std::memory_order_relaxed); + sealed.store(false, std::memory_order_relaxed); + } +}; + +[[nodiscard]] bool VerifyIdentityMemo(); + +struct HeapStageWords { + std::vector userData; + std::vector flattenedSrt; + std::vector vertexAttributes; + std::vector> bindings; + std::shared_ptr base; + std::uint64_t dataOrigin = 0; + ResultKeyMemo drawKeyMemo; + bool memoizeKey = true; +}; + struct RecompileRequest { ShaderBinary shader; GuestContext context; @@ -716,6 +774,8 @@ struct DescriptorBinding { ElementFlags samplerUnnormalized; ElementFlags samplerIntegerBorder; ElementFlags samplerCoordinatesIgnored; + std::vector samplerEmbedded; + std::vector samplerEmbeddedWords; ElementFlags imageUnnormalized; ElementFlags imageUnnormalizedBaseLevel; std::vector imageSamplers; @@ -912,6 +972,15 @@ struct CompiledShaderArtifact { std::uint32_t runtimeImageCount = 0; std::vector runtimeImageResources; bool registrationModule = false; + bool gpuResolvedImages = false; + std::uint32_t samplerSlotDword = 0; + std::uint32_t bufferAddressDword = 0; + std::uint32_t bufferAddressCount = 0; + std::uint32_t pushedBufferCount = 0; + std::vector pushedData; + std::uint32_t pushItems = 0; + bool dataAddressPush = false; + bool bdaStores = false; std::uint32_t bdaAbiVersion = 0; std::uint32_t windowLaneGuards = 0; std::uint32_t descriptorFaults = 0; @@ -942,6 +1011,7 @@ struct CompiledShaderArtifact { struct ShaderInvocation { std::vector specialization; + std::vector heapSlotWords; std::uint64_t specializationId = 0; std::vector bindings; std::vector pushConstants; @@ -970,23 +1040,38 @@ struct PipelineIdentity { auto operator<=>(const PipelineIdentity&) const = default; }; -struct ResultKeyMemo { - mutable AtomicSharedPtr> words; - ResultKeyMemo() = default; - ResultKeyMemo(const ResultKeyMemo&) {} - ResultKeyMemo& operator=(const ResultKeyMemo&) { - words.store(nullptr, std::memory_order_relaxed); - return *this; - } -}; - struct RecompileResult : CompiledShaderArtifact, ShaderInvocation { + std::uint64_t heapTemplateId = 0; + std::vector heapUserWords; ResultKeyMemo drawKeyMemo; bool cacheHit = false; std::uint32_t workgroupMemoryDwords = 0; std::vector shaderDataUserWords; [[nodiscard]] std::uint64_t PipelineVariantId() const { return specializationId != 0 ? specializationId : variantId; } + IdentityMemo identityMemo; [[nodiscard]] PipelineIdentity Identity() const { + if (!identityMemo.sealed.load(std::memory_order_acquire)) return ComputeIdentity(); + const auto module = spirv.ContentHash(); + if (identityMemo.taken.load(std::memory_order_acquire) && identityMemo.moduleLow.load(std::memory_order_relaxed) == module.low && + identityMemo.moduleHigh.load(std::memory_order_relaxed) == module.high) { + const PipelineIdentity kept{identityMemo.low.load(std::memory_order_relaxed), identityMemo.high.load(std::memory_order_relaxed)}; + if (VerifyIdentityMemo() && !(kept == ComputeIdentity())) throw std::runtime_error("a shader's kept pipeline identity differs from its hash: a hashed field changed after the identity was taken"); + return kept; + } + const auto identity = ComputeIdentity(); + if (identity.Empty()) return identity; + identityMemo.taken.store(false, std::memory_order_relaxed); + identityMemo.low.store(identity.low, std::memory_order_relaxed); + identityMemo.high.store(identity.high, std::memory_order_relaxed); + identityMemo.moduleLow.store(module.low, std::memory_order_relaxed); + identityMemo.moduleHigh.store(module.high, std::memory_order_relaxed); + identityMemo.taken.store(true, std::memory_order_release); + return identity; + } + void SealIdentity() const { + if (!identityMemo.sealed.load(std::memory_order_relaxed)) identityMemo.sealed.store(true, std::memory_order_release); + } + [[nodiscard]] PipelineIdentity ComputeIdentity() const { const auto hash = spirv.ContentHash(); if (hash == SpirvContentHash{}) return {}; PipelineIdentity identity{hash.low, hash.high}; @@ -1000,7 +1085,17 @@ struct RecompileResult : CompiledShaderArtifact, ShaderInvocation { for (const auto& constant : specialization) mix(constant.id | (static_cast(constant.value) << 32u)); mix(hostSubgroupSize | (fullSubgroups ? 0x10000u : 0u) | (functionLdsBuffer ? 0x20000u : 0u) | (meshWindowBuffer ? 0x40000u : 0u) | (static_cast(workgroupMemoryDwords) << 32u)); mix(bindings.size()); - for (const auto& binding : bindings) mix(binding.descriptorSet | (static_cast(binding.binding) << 16u) | (static_cast(binding.kind) << 40u) | (static_cast(binding.count) << 48u)); + for (const auto& binding : bindings) { + mix(binding.descriptorSet | (static_cast(binding.binding) << 16u) | (static_cast(binding.kind) << 40u) | (static_cast(binding.count) << 48u)); + mix(binding.samplerEmbedded.size()); + for (const auto value : binding.samplerEmbedded) mix(value); + mix(binding.samplerEmbeddedWords.size()); + for (const auto value : binding.samplerEmbeddedWords) mix(value); + for (const auto* flags : {&binding.samplerDepthCompare, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored}) { + mix(flags->size()); + for (std::size_t element = 0; element < flags->size(); ++element) mix((*flags)[element] ? 1u : 0u); + } + } if (identity.Empty()) identity.low = 1; return identity; } diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 8091a03d013a..3231511e434e 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -9,7 +9,7 @@ namespace ShaderRecompiler::RuntimeAbi { -inline constexpr std::uint32_t Version = 14u; +inline constexpr std::uint32_t Version = 18u; inline constexpr std::uint32_t DescriptorSet = 0u; inline constexpr std::uint32_t FragmentDescriptorSet = 1u; inline constexpr std::uint32_t StageCount = 4u; @@ -18,6 +18,41 @@ inline constexpr std::uint32_t FirstImageBinding = 1u; inline constexpr std::uint32_t FirstComparisonImageBinding = 22u; inline constexpr std::uint32_t FirstStorageImageBinding = 29u; inline constexpr std::uint32_t ImageBindingCount = 56u; +inline constexpr bool GpuHeapStorageKind(std::uint32_t kind) { return kind >= FirstStorageImageBinding && kind < FirstImageBinding + ImageBindingCount; } +inline constexpr std::uint32_t StorageKindStride = 7u; +inline constexpr std::uint32_t FirstUintStorageImageBinding = FirstStorageImageBinding + StorageKindStride; +inline constexpr std::uint32_t FirstAtomicImageBinding = FirstStorageImageBinding + 2u * StorageKindStride; +inline constexpr std::uint32_t FirstAtomic64ImageBinding = FirstStorageImageBinding + 3u * StorageKindStride; +inline constexpr std::uint32_t SamplerSlotWords = 2u; +inline constexpr std::uint32_t BufferAddressWords = 4u; +inline constexpr std::uint32_t PushedBufferWords = 3u; +inline constexpr std::uint32_t PushedBufferLimit = 16u; +inline constexpr std::uint32_t OverflowRecordWords = 4u; +inline constexpr std::uint32_t PushedBufferOverflowBinding = 1023u; +inline constexpr bool AtomicImageKind(std::uint32_t kind) { return kind >= FirstAtomicImageBinding && kind < FirstAtomic64ImageBinding; } +inline constexpr bool Atomic64ImageKind(std::uint32_t kind) { return kind >= FirstAtomic64ImageBinding && kind < FirstImageBinding + ImageBindingCount; } +inline constexpr bool UintStorageImageKind(std::uint32_t kind) { return kind >= FirstUintStorageImageBinding && kind < FirstAtomicImageBinding; } + +enum class HeapPart : std::uint32_t { Sampled, Storage, Sampler, Atomic, Atomic64, UintStorage }; + +inline constexpr HeapPart StorageHeapPart(std::uint32_t kind) { + if (AtomicImageKind(kind)) return HeapPart::Atomic; + if (Atomic64ImageKind(kind)) return HeapPart::Atomic64; + if (UintStorageImageKind(kind)) return HeapPart::UintStorage; + return HeapPart::Storage; +} + +inline constexpr std::uint32_t HeapPartFirstBinding(HeapPart part) { + switch (part) { + case HeapPart::Sampled: return FirstImageBinding; + case HeapPart::Storage: return FirstStorageImageBinding; + case HeapPart::Atomic: return FirstAtomicImageBinding; + case HeapPart::Atomic64: return FirstAtomic64ImageBinding; + case HeapPart::UintStorage: return FirstUintStorageImageBinding; + case HeapPart::Sampler: break; + } + return 0u; +} enum class Binding : std::uint32_t { Buffers = 0u, @@ -29,13 +64,21 @@ enum class Binding : std::uint32_t { ShaderData = 62u, SamplerTable = 63u, ImageTableMap = 64u, - Count = 65u, + UserData = 65u, + Count = 66u, ImageTable = 256u, ImageStorageTable = 257u }; enum class Stage : std::uint32_t { Main, Fragment, TessellationControl, TessellationEvaluation }; +inline constexpr Stage StageGroup(bool fragment, bool tessellationControl, bool tessellationEvaluation) { + if (fragment) return Stage::Fragment; + if (tessellationControl) return Stage::TessellationControl; + if (tessellationEvaluation) return Stage::TessellationEvaluation; + return Stage::Main; +} + inline constexpr std::uint32_t UserDataCapacity = 128u; inline constexpr std::uint32_t BufferCapacity = 128u; inline constexpr std::uint32_t ImageCapacity = 256u; @@ -44,6 +87,40 @@ inline constexpr std::uint32_t BindlessTableSlots = 16u; inline constexpr std::uint32_t StorageMipSlots = 16u; inline constexpr std::uint32_t StorageHeapCapacity = 64u; inline constexpr std::uint32_t SamplerHeapCapacity = 64u; +inline constexpr std::uint32_t GpuImageHeapSlots = static_cast(Binding::Samplers) * 4096u; +inline constexpr std::uint32_t GpuSamplerHeapSlots = 2048u; +inline constexpr std::uint32_t GpuDataSet = 2u; +inline constexpr std::uint32_t GpuGdsSet = 4u; +inline constexpr std::uint32_t EmbeddedSamplerSet = 6u; +inline constexpr std::uint32_t PushedBufferSet = 7u; +inline constexpr std::uint32_t UniformConstantBufferBytes = 65536u; +inline constexpr std::uint32_t UniformViewAdjustmentLimit = 255u; +inline constexpr std::uint32_t NoEmbeddedSampler = ~0u; +inline constexpr std::uint32_t GdsBytes = 0x10000u; +inline constexpr std::uint32_t PushDataDwords = 64u; +inline constexpr std::uint32_t PushedDataWantedLimit = 48u; +enum class RootItem : std::uint32_t { PagetableAddress, FaultAddress, GdsAddress, StencilReference, ShaderData, TableMap, SrtAddress, UserData, Count }; +inline constexpr std::uint32_t RootItemCount = static_cast(RootItem::Count); +inline constexpr std::uint32_t RootItemBit(RootItem item) { return 1u << static_cast(item); } +inline constexpr bool RootAddressItem(RootItem item) { + return item == RootItem::PagetableAddress || item == RootItem::FaultAddress || item == RootItem::GdsAddress || item == RootItem::ShaderData || item == RootItem::TableMap || + item == RootItem::SrtAddress || item == RootItem::UserData; +} +inline constexpr std::uint32_t DepthRemapPushBit = 1u << 16u; +inline constexpr std::uint32_t NoPushPosition = 0xffffffffu; +struct PushedPlacement { + std::uint32_t base = 0; + std::uint32_t count = 0; + + bool operator==(const PushedPlacement&) const = default; +}; +struct HeapSlotWord { + std::uint32_t dword = 0; + std::uint32_t kind = 0; + std::uint32_t element = 0; + + bool operator==(const HeapSlotWord& other) const = default; +}; inline constexpr std::uint32_t AtomicLockCount = 1u << 20u; inline constexpr std::uint32_t StateExportMappings = 0u; inline constexpr std::uint32_t StateDwords = 2u; @@ -119,7 +196,7 @@ inline bool UintStorageImageBinding(std::uint32_t number) { } static_assert(FirstImageBinding + ImageBindingCount == static_cast(Binding::Samplers)); -static_assert(static_cast(Binding::ImageTable) > static_cast(Binding::Count) && ImageStorageTableBinding == 260u && ImageTableBinding == 261u); +static_assert(static_cast(Binding::ImageTable) > static_cast(Binding::Count) && ImageStorageTableBinding == 264u && ImageTableBinding == 265u); } diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index 6280a2b45153..c32d34f892cb 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -87,27 +87,27 @@ std::filesystem::path ShaderCacheDirectory() { namespace ShaderRecompiler::ShaderDiskCache { #if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__) -static_assert(sizeof(CompiledShaderArtifact) == 288, "CompiledShaderArtifact changed: update the artifact encoder"); -static_assert(sizeof(ShaderInvocation) == 216, "ShaderInvocation changed: update the invocation encoder"); +static_assert(sizeof(CompiledShaderArtifact) == 336, "CompiledShaderArtifact changed: update the artifact encoder"); +static_assert(sizeof(ShaderInvocation) == 240, "ShaderInvocation changed: update the invocation encoder"); #if defined(__cpp_lib_atomic_shared_ptr) -static_assert(sizeof(RecompileResult) == 552, "RecompileResult changed: update EncodeResult and DecodeResult"); +static_assert(sizeof(RecompileResult) == 696, "RecompileResult changed: update EncodeResult and DecodeResult"); #endif -static_assert(sizeof(DescriptorBinding) == 920, "DescriptorBinding changed: update the binding encoder"); +static_assert(sizeof(DescriptorBinding) == 968, "DescriptorBinding changed: update the binding encoder"); static_assert(sizeof(VertexAttribute) == 32, "VertexAttribute changed: update the attribute encoder"); static_assert(sizeof(VertexInput) == 16, "VertexInput changed: update the vertex input encoder"); static_assert(sizeof(FragmentParameter) == 16, "FragmentParameter changed: update the parameter encoder"); -static_assert(sizeof(CompiledShaderInfo) == 352, "CompiledShaderInfo changed: update the info encoder"); +static_assert(sizeof(CompiledShaderInfo) == 400, "CompiledShaderInfo changed: update the info encoder"); static_assert(sizeof(ShaderInfo) == 232, "ShaderInfo changed: update the info encoder"); static_assert(sizeof(BufferResource) == 32, "BufferResource changed: update the info encoder"); static_assert(sizeof(ImageResource) == 108, "ImageResource changed: update the info encoder"); -static_assert(sizeof(SamplerResource) == 24, "SamplerResource changed: update the info encoder"); +static_assert(sizeof(SamplerResource) == 44, "SamplerResource changed: update the info encoder"); static_assert(sizeof(SampledResourcePair) == 16, "SampledResourcePair changed: update the info encoder"); static_assert(sizeof(StageInput) == 56, "StageInput changed: update the info encoder"); static_assert(sizeof(StageOutput) == 48, "StageOutput changed: update the info encoder"); -static_assert(sizeof(IrBindingLayout) == 80, "IrBindingLayout changed: update the layout encoder"); +static_assert(sizeof(IrBindingLayout) == 128, "IrBindingLayout changed: update the layout encoder"); static_assert(sizeof(IrDescriptorBinding) == 32, "IrDescriptorBinding changed: update the layout encoder"); -static_assert(sizeof(BindingAllocationResult) == 184, "BindingAllocationResult changed: update the allocation encoder"); -static_assert(sizeof(CompiledBindingLayout) == 88, "CompiledBindingLayout changed: update the allocation encoder"); +static_assert(sizeof(BindingAllocationResult) == 232, "BindingAllocationResult changed: update the allocation encoder"); +static_assert(sizeof(CompiledBindingLayout) == 136, "CompiledBindingLayout changed: update the allocation encoder"); static_assert(sizeof(BindingLayout) == 16, "BindingLayout changed: update BuildKey"); static_assert(sizeof(IrResourcePlan) == 728, "IrResourcePlan changed: update EncodePlan and DecodePlan"); static_assert(sizeof(IrValue) == 144, "IrValue changed: update the plan value encoder"); @@ -146,7 +146,7 @@ constexpr std::size_t fieldCount() { static_assert(fieldCount() == 24, "ShaderInfo changed: update the info encoder"); static_assert(fieldCount() == 12, "BufferResource changed: update the info encoder"); static_assert(fieldCount() == 51, "ImageResource changed: update the info encoder"); -static_assert(fieldCount() == 8, "SamplerResource changed: update the info encoder"); +static_assert(fieldCount() == 10, "SamplerResource changed: update the info encoder"); static_assert(fieldCount() == 4, "SampledResourcePair changed: update the info encoder"); static_assert(fieldCount() == 5, "StageInput changed: update the info encoder"); static_assert(fieldCount() == 4, "StageOutput changed: update the info encoder"); @@ -481,6 +481,8 @@ void encodeBinding(Writer& writer, const DescriptorBinding& binding) { writer.Flags(binding.imageUnnormalizedBaseLevel); writer.Flags(binding.samplerIntegerBorder); writer.Flags(binding.samplerCoordinatesIgnored); + writer.Values(std::span(binding.samplerEmbedded)); + writer.Values(std::span(binding.samplerEmbeddedWords)); writer.Values(std::span(binding.imageSamplers)); writer.Flags(binding.bufferRead); writer.Values(std::span(binding.bufferExtent)); @@ -511,6 +513,8 @@ void decodeBinding(Reader& reader, DescriptorBinding& binding) { reader.Flags(binding.imageUnnormalizedBaseLevel); reader.Flags(binding.samplerIntegerBorder); reader.Flags(binding.samplerCoordinatesIgnored); + reader.Values(binding.samplerEmbedded); + reader.Values(binding.samplerEmbeddedWords); reader.Values(binding.imageSamplers); reader.Flags(binding.bufferRead); reader.Values(binding.bufferExtent); @@ -528,6 +532,15 @@ void encodeArtifact(Writer& writer, const CompiledShaderArtifact& result) { writer.Value(result.runtimeImageCount); writer.Values(std::span(result.runtimeImageResources)); writer.Value(result.registrationModule); + writer.Value(result.gpuResolvedImages); + writer.Value(result.samplerSlotDword); + writer.Value(result.bufferAddressDword); + writer.Value(result.bufferAddressCount); + writer.Value(result.pushedBufferCount); + writer.Values(std::span(result.pushedData)); + writer.Value(result.pushItems); + writer.Value(result.dataAddressPush); + writer.Value(result.bdaStores); writer.List(result.vertexInputPatches, [](Writer& out, const VertexInputPatch& patch) { out.Value(patch.location); out.Value(patch.word); @@ -595,6 +608,15 @@ void decodeArtifact(Reader& reader, CompiledShaderArtifact& result) { reader.Value(result.runtimeImageCount); reader.Values(result.runtimeImageResources); reader.Value(result.registrationModule); + reader.Value(result.gpuResolvedImages); + reader.Value(result.samplerSlotDword); + reader.Value(result.bufferAddressDword); + reader.Value(result.bufferAddressCount); + reader.Value(result.pushedBufferCount); + reader.Values(result.pushedData); + reader.Value(result.pushItems); + reader.Value(result.dataAddressPush); + reader.Value(result.bdaStores); reader.List(result.vertexInputPatches, 20, [](Reader& in, VertexInputPatch& patch) { in.Value(patch.location); in.Value(patch.word); @@ -661,6 +683,11 @@ void encodeInvocation(Writer& writer, const ShaderInvocation& invocation) { out.Value(constant.value); }); writer.List(invocation.bindings, encodeBinding); + writer.List(invocation.heapSlotWords, [](Writer& out, const RuntimeAbi::HeapSlotWord& word) { + out.Value(word.dword); + out.Value(word.kind); + out.Value(word.element); + }); writer.Value(invocation.pushConstants.size()); for (const auto byte : invocation.pushConstants) writer.Value(static_cast(byte)); writer.Value(invocation.readsDepthRemapPush); @@ -700,6 +727,11 @@ void decodeInvocation(Reader& reader, ShaderInvocation& invocation) { in.Value(constant.value); }); reader.List(invocation.bindings, 8, decodeBinding); + reader.List(invocation.heapSlotWords, 12, [](Reader& in, RuntimeAbi::HeapSlotWord& word) { + in.Value(word.dword); + in.Value(word.kind); + in.Value(word.element); + }); std::vector pushConstants; reader.Values(pushConstants); invocation.pushConstants.resize(pushConstants.size()); @@ -736,12 +768,19 @@ void decodeInvocation(Reader& reader, ShaderInvocation& invocation) { void encodeLayout(Writer& writer, const IrBindingLayout& layout) { writer.Value(layout.pushDataStartDword); + writer.Value(layout.dataAddress); writer.Value(layout.stencilReferenceDword); writer.Value(layout.memoryOffsetDword); writer.Value(layout.memoryOffsetCount); writer.Value(layout.dispatchThreadLimit); writer.Value(layout.runtimeImageCount); writer.Value(layout.runtimeStateDwords); + writer.Value(layout.samplerSlotDwords); + writer.Value(layout.imageSlotDwords); + writer.Value(layout.bufferAddressDwords); + writer.Values(std::span(layout.pushedData)); + writer.Value(layout.heapStorageImages); + writer.Value(layout.gpuResolvedImages); writer.Values(std::span(layout.userDataRegisters)); writer.List(layout.descriptors, [](Writer& out, const IrDescriptorBinding& descriptor) { out.Value(descriptor.kind); @@ -751,12 +790,19 @@ void encodeLayout(Writer& writer, const IrBindingLayout& layout) { void decodeLayout(Reader& reader, IrBindingLayout& layout) { reader.Value(layout.pushDataStartDword); + reader.Value(layout.dataAddress); reader.Value(layout.stencilReferenceDword); reader.Value(layout.memoryOffsetDword); reader.Value(layout.memoryOffsetCount); reader.Value(layout.dispatchThreadLimit); reader.Value(layout.runtimeImageCount); reader.Value(layout.runtimeStateDwords); + reader.Value(layout.samplerSlotDwords); + reader.Value(layout.imageSlotDwords); + reader.Value(layout.bufferAddressDwords); + reader.Values(layout.pushedData); + reader.Value(layout.heapStorageImages); + reader.Value(layout.gpuResolvedImages); reader.Values(layout.userDataRegisters); reader.List(layout.descriptors, 12, [](Reader& in, IrDescriptorBinding& descriptor) { in.Value(descriptor.kind); @@ -844,6 +890,8 @@ void encodeShaderInfo(Writer& writer, const ShaderInfo& info) { out.Value(sampler.uses); out.Value(sampler.foldTexelOffsetsOnly); out.Value(sampler.table); + out.Value(sampler.constant); + for (const auto word : sampler.constantWords) out.Value(word); }); writer.List(info.sampledPairs, [](Writer& out, const SampledResourcePair& pair) { out.Value(pair.image); @@ -954,7 +1002,7 @@ void decodeShaderInfo(Reader& reader, ShaderInfo& info) { bool preparedImageModes = false; reader.Value(preparedImageModes); if (preparedImageModes) ResourceMaterializer::PrepareImageModes(info); - reader.List(info.samplers, 21, [](Reader& in, SamplerResource& sampler) { + reader.List(info.samplers, 38, [](Reader& in, SamplerResource& sampler) { in.Value(sampler.source); in.Value(sampler.firstUsePc); in.Value(sampler.copyOf); @@ -963,6 +1011,8 @@ void decodeShaderInfo(Reader& reader, ShaderInfo& info) { in.Value(sampler.uses); in.Value(sampler.foldTexelOffsetsOnly); in.Value(sampler.table); + in.Value(sampler.constant); + for (auto& word : sampler.constantWords) in.Value(word); }); reader.List(info.sampledPairs, 13, [](Reader& in, SampledResourcePair& pair) { in.Value(pair.image); @@ -1429,6 +1479,7 @@ constexpr std::string_view NeutralSwitches[] = { "APS5_NO_PERF_LAYOUT_PAIR", "APS5_NO_BUFFER_SUBSTITUTES", "APS5_NO_RESULT_MEMO", + "APS5_HEAP_NO_CACHE", "APS5_NO_TABLE_RESOLUTION_REUSE", "APS5_NO_TABLE_SNAPSHOT_REUSE", "APS5_RESOURCE_PLAN_MB", diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index 098cdac6d4d4..7944cb71f522 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 = 88; +inline constexpr std::uint32_t FormatVersion = 89; enum class LoadStatus { Loaded, diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp index 3793eb2c4ea7..eed8eb0212dd 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp @@ -45,6 +45,9 @@ struct SpirvTargetOptions { bool largePixelFunctionLdsBuffer = false; std::uint32_t pixelFunctionStorageDwords = 4096u; bool deviceScopeLdsMemoryBarriers = false; + bool gpuResolvedImages = false; + std::uint32_t heapDataUniformDwords = 0; + bool uniformConstantBuffers = false; bool ldsLockFences = false; bool meshWindowBuffer = false; bool float16WidenNans = false; @@ -55,7 +58,9 @@ struct SpirvTargetOptions { struct SpirvEmitInfo { bool fullSubgroups = false; bool functionLdsBuffer = false; + bool bdaStores = false; bool meshWindowBuffer = false; + std::uint32_t pushItems = 0; std::uint32_t scratchPoolSlotDwords = 0; bool anySubgroupSize = false; }; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp index c7617942e11d..9a1ac04e0f7c 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp @@ -42,6 +42,9 @@ std::uint32_t TypeStorageBufferU8Block(SpirvEmitterState& state); std::uint32_t TypeStorageBufferU8Pointer(SpirvEmitterState& state); std::uint32_t TypeStorageBufferU8ElementPointer(SpirvEmitterState& state); std::uint32_t TypePhysicalU32Pointer(SpirvEmitterState& state); +std::uint32_t TypePhysicalBufferPointer(SpirvEmitterState& state, bool wide); +std::uint32_t ReadOnlyStorageBufferType(SpirvEmitterState& state, std::uint32_t element, std::uint32_t stride); +std::uint32_t TypePhysicalReadOnlyBufferPointer(SpirvEmitterState& state, bool wide); std::uint32_t TypePushConstantElementPointer(SpirvEmitterState& state); std::uint32_t TypeU32ArrayPointer(SpirvEmitterState& state, std::uint32_t storageClass, std::uint32_t dwords); std::uint32_t TypeU32ElementPointer(SpirvEmitterState& state, std::uint32_t storageClass); @@ -112,13 +115,17 @@ std::uint32_t EmitBallotLaneActiveBool(SpirvEmitterState& state, std::uint32_t b std::uint32_t EmitSubgroupLaneActiveBool(SpirvEmitterState& state, std::uint32_t lane); std::uint32_t EmitBinaryU32(SpirvEmitterState& state, std::uint32_t opcode, std::uint32_t lhs, std::uint32_t rhs); std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex); +bool WritesGuestBuffers(const IrProgram& program); +bool WritesGuestMemory(const IrProgram& program); void EmitMemoryOffsets(SpirvEmitterState& state); +void EmitHeapSlotPreload(SpirvEmitterState& state); std::uint32_t LdsDwordCount(const SpirvEmitterState& state); bool LdsInDeviceMemory(const SpirvEmitterState& state); std::uint32_t LdsMemorySemantics(const SpirvEmitterState& state); std::uint32_t LdsMemoryBarrierScope(const SpirvEmitterState& state); void EmitLdsBufferBase(SpirvEmitterState& state); bool ScratchPoolActive(const SpirvEmitterState& state); +bool GpuScratchPool(const SpirvEmitterState& state); std::uint32_t ScratchPoolSlotDwords(const SpirvEmitterState& state); void DefineScratchPool(SpirvEmitterState& state); void EmitScratchPoolAcquire(SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index a56618dd4f94..5f8ce9215a35 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -72,6 +72,16 @@ struct MemoryResourceAccess { bool addIndexOffset = false; std::uint32_t memoryAccess = 0; std::uint32_t misalignment = 0; + bool physical = false; + bool softwareBounds = false; + bool uniform = false; +}; + +struct PushedBufferVariables { + std::uint32_t plain = 0; + std::uint32_t coherent = 0; + std::uint32_t u64 = 0; + std::uint32_t uniform = 0; }; struct SpirvTableImageVariable { @@ -85,12 +95,16 @@ struct SpirvTableAccess { std::uint32_t samplerElement = 0; bool active = false; bool uniform = false; + bool heap = false; }; struct SpirvEmitterState { const ImageResource* runtimeImage = nullptr; SpirvTableAccess tableAccess; SpirvEmitterState(const IrProgram& program, const ShaderStageInputInfo& inputInfo); + [[nodiscard]] bool BdaAddressed() const; + [[nodiscard]] bool TableMapAddressed() const; + [[nodiscard]] bool TableHeap() const; SpirvModule module; const IrProgram& program; @@ -113,6 +127,12 @@ struct SpirvEmitterState { bool depthRangeRemap = false; std::uint32_t depthRemapClipIndex = 0; bool registrationModules = false; + bool gpuResolvedImages = false; + std::uint32_t heapDataUniformDwords = 0; + bool uniformConstantBuffers = false; + bool addressedBuffers = false; + std::vector pushedBuffers; + std::optional guestBuffersWritten; bool fragmentDescriptorSet = false; bool float16DenormPreserve = false; bool robustBufferAccess2 = false; @@ -229,7 +249,14 @@ struct SpirvEmitterState { std::uint32_t gdsLength = 0; std::uint32_t pushConstantVariable = 0; std::uint32_t shaderDataStorageVariable = 0; + std::uint32_t shaderDataUniformVariable = 0; + std::uint32_t userDataUniformVariable = 0; + std::uint32_t flattenedSrtUniformVariable = 0; + std::uint32_t bufferOverflowUniformVariable = 0; + std::uint32_t pushItems = 0; + std::unordered_map heapSlotVariables; std::uint32_t flattenedSrtVariable = 0; + bool flattenedSrtAddressed = false; std::uint32_t ldsVariable = 0; std::uint32_t ldsBufferVariable = 0; std::uint32_t ldsBufferU64Variable = 0; @@ -256,6 +283,7 @@ struct SpirvEmitterState { std::unordered_set meshWindowBufferLoads; std::array imageVariables {}; std::uint32_t samplerVariable = 0; + std::map embeddedSamplerVariables; std::vector tableImageVariables; std::uint32_t tableSamplerVariable = 0; std::uint32_t tableMapVariable = 0; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index 537aac33eb7d..f9170ede0195 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -4,18 +4,33 @@ #include "SpirvBackend/SpirvEmitterState.hpp" #include "IntermediateRepresentation/IrProgram.hpp" #include +#include namespace ShaderRecompiler { std::uint32_t EmitBinaryU32(SpirvEmitterState& state, std::uint32_t opcode, std::uint32_t lhs, std::uint32_t rhs); std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex); +std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t index); +std::uint32_t ComposeAddress64(SpirvEmitterState& state, const std::function& loadLow, const std::function& loadHigh); +std::uint32_t EmitAlignedLoadU32(SpirvEmitterState& state, std::uint32_t pointer); +std::uint32_t EmitRootItemDword(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t word); +std::uint32_t EmitBufferRootDword(SpirvEmitterState& state, std::uint32_t buffer, std::uint32_t word); +std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); +std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); +std::uint32_t EmitRootAddress(SpirvEmitterState& state, RuntimeAbi::RootItem item); +std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index); +bool HasFlattenedSrt(const SpirvEmitterState& state); +bool SplitUserData(const SpirvEmitterState& state); void EmitMemoryOffsets(SpirvEmitterState& state); +std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index); +std::uint32_t LoadHeapSlotWord(SpirvEmitterState& state, std::uint32_t dword); std::uint32_t LdsDwordCount(const SpirvEmitterState& state); bool LdsInDeviceMemory(const SpirvEmitterState& state); std::uint32_t LdsMemorySemantics(const SpirvEmitterState& state); std::uint32_t LdsMemoryBarrierScope(const SpirvEmitterState& state); void EmitLdsBufferBase(SpirvEmitterState& state); bool ScratchPoolActive(const SpirvEmitterState& state); +bool GpuScratchPool(const SpirvEmitterState& state); std::uint32_t ScratchPoolSlotDwords(const SpirvEmitterState& state); void DefineScratchPool(SpirvEmitterState& state); void EmitScratchPoolAcquire(SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvConstants.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvConstants.hpp index fb59644f8bed..aece716687b0 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvConstants.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvConstants.hpp @@ -14,6 +14,7 @@ std::uint32_t ConstantF32Value(SpirvEmitterState& state, float value); std::uint32_t ConstantBool(SpirvEmitterState& state, bool value); std::uint32_t ConstantU64(SpirvEmitterState& state, std::uint64_t value); std::uint32_t ConstantU32CompositeZero(SpirvEmitterState& state, std::uint32_t components); +std::uint32_t HeapImageSlotCount(SpirvEmitterState& state); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp index 31cd6007d85d..f13509e1364a 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp @@ -1,6 +1,7 @@ #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include #include #include @@ -12,6 +13,8 @@ std::uint32_t BdaConstant(SpirvEmitterState& state, std::uint64_t value) { } std::uint32_t BdaWord(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index) { + if (state.BdaAddressed() && variable == state.bdaPagetableVariable) return EmitRootAddressReadOnlyWordPointer(state, RuntimeAbi::RootItem::PagetableAddress, index); + if (state.BdaAddressed() && variable == state.faultBufferVariable) return EmitRootAddressWordPointer(state, RuntimeAbi::RootItem::FaultAddress, index); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, variable, ConstantU32(state, 0u), index); return pointer; @@ -19,7 +22,8 @@ std::uint32_t BdaWord(SpirvEmitterState& state, std::uint32_t variable, std::uin std::uint32_t BdaLoadWord(SpirvEmitterState& state, std::uint32_t index) { const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, BdaWord(state, state.bdaPagetableVariable, index)); + if (state.BdaAddressed()) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, BdaWord(state, state.bdaPagetableVariable, index), spv::MemoryAccessAlignedMask, 4u); + else state.module.AddFunction(spv::OpLoad, TypeU32(state), value, BdaWord(state, state.bdaPagetableVariable, index)); return value; } @@ -61,7 +65,8 @@ void DefineBdaFaultFunction(SpirvEmitterState& state) { const auto store = [&](std::uint32_t index, std::uint32_t value) { const auto target = state.module.AllocateId(); state.module.AddFunction(spv::OpSelect, u32, target, won, ConstantU32(state, index), discard); - state.module.AddFunction(spv::OpStore, BdaWord(state, state.faultBufferVariable, target), value); + if (state.BdaAddressed()) state.module.AddFunction(spv::OpStore, BdaWord(state, state.faultBufferVariable, target), value, spv::MemoryAccessAlignedMask, 4u); + else state.module.AddFunction(spv::OpStore, BdaWord(state, state.faultBufferVariable, target), value); }; store(1, reason); store(2, words ? address : Unary(state, spv::OpUConvert, TypeU32(state), address)); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp index d1889a85fe02..433d72e39796 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp @@ -1,6 +1,7 @@ #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include #include #include @@ -64,21 +65,42 @@ std::uint32_t DefineBdaLookup(SpirvEmitterState& state, const char* name, bool r } leaveIf(binary(spv::OpINotEqual, boolean, reason, constant(0u)), reason); }; - const auto length = state.module.AllocateId(); - state.module.AddFunction(spv::OpArrayLength, u32, length, state.bdaPagetableVariable, 0u); - fail(binary(spv::OpULessThan, boolean, length, constant(4)), BdaAbi::FaultReason::InvalidTable); + std::uint32_t length = 0; + if (state.BdaAddressed()) { + const auto table = EmitRootAddress(state, RuntimeAbi::RootItem::PagetableAddress); + fail(binary(spv::OpIEqual, boolean, table, BdaConstant(state, 0u)), BdaAbi::FaultReason::InvalidTable); + } else { + length = state.module.AllocateId(); + state.module.AddFunction(spv::OpArrayLength, u32, length, state.bdaPagetableVariable, 0u); + fail(binary(spv::OpULessThan, boolean, length, constant(4)), BdaAbi::FaultReason::InvalidTable); + } const auto count = BdaLoadWord(state, constant(1)); - const auto available = binary(spv::OpISub, u32, length, constant(4)); const auto end = binary(spv::OpIAdd, u64, address, Unary(state, spv::OpUConvert, u64, bytes)); - failFirst({ - {binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(0)), constant(BdaAbi::Version)), BdaAbi::FaultReason::InvalidTable}, - {binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(2)), constant(sizeof(BdaAbi::Range))), BdaAbi::FaultReason::InvalidTable}, - {binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(3)), constant(0)), BdaAbi::FaultReason::InvalidTable}, - {binary(spv::OpINotEqual, boolean, binary(spv::OpBitwiseAnd, u32, available, constant(7)), constant(0)), BdaAbi::FaultReason::InvalidTable}, - {binary(spv::OpINotEqual, boolean, count, binary(spv::OpShiftRightLogical, u32, available, constant(3))), BdaAbi::FaultReason::InvalidTable}, - {binary(spv::OpIEqual, boolean, bytes, constant(0)), BdaAbi::FaultReason::Overflow}, - {binary(spv::OpULessThanEqual, boolean, end, address), BdaAbi::FaultReason::Overflow}, - }); + const auto version = binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(0)), constant(BdaAbi::Version)); + const auto entryBytes = binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(2)), constant(sizeof(BdaAbi::Range))); + const auto reserved = binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(3)), constant(0)); + const auto empty = binary(spv::OpIEqual, boolean, bytes, constant(0)); + const auto wrapped = binary(spv::OpULessThanEqual, boolean, end, address); + if (state.BdaAddressed()) { + failFirst({ + {version, BdaAbi::FaultReason::InvalidTable}, + {entryBytes, BdaAbi::FaultReason::InvalidTable}, + {reserved, BdaAbi::FaultReason::InvalidTable}, + {empty, BdaAbi::FaultReason::Overflow}, + {wrapped, BdaAbi::FaultReason::Overflow}, + }); + } else { + const auto available = binary(spv::OpISub, u32, length, constant(4)); + failFirst({ + {version, BdaAbi::FaultReason::InvalidTable}, + {entryBytes, BdaAbi::FaultReason::InvalidTable}, + {reserved, BdaAbi::FaultReason::InvalidTable}, + {binary(spv::OpINotEqual, boolean, binary(spv::OpBitwiseAnd, u32, available, constant(7)), constant(0)), BdaAbi::FaultReason::InvalidTable}, + {binary(spv::OpINotEqual, boolean, count, binary(spv::OpShiftRightLogical, u32, available, constant(3))), BdaAbi::FaultReason::InvalidTable}, + {empty, BdaAbi::FaultReason::Overflow}, + {wrapped, BdaAbi::FaultReason::Overflow}, + }); + } const auto header = state.module.AllocateId(); const auto body = state.module.AllocateId(); const auto continuation = state.module.AllocateId(); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp index c9cce7727290..39373f5fbdaa 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp @@ -80,6 +80,18 @@ std::uint32_t WaveLdsScope(const IrProgram& program, const ShaderWorkgroupInputI SpirvEmitterState::SpirvEmitterState(const IrProgram& program, const ShaderStageInputInfo& inputInfo) : module(program.Resources().stage == IrShaderStage::Mesh ? 0x00010400u : 0x00010300u), program(program), inputInfo(inputInfo), requirements(AnalyzeProgramRequirements(program)) { } +bool SpirvEmitterState::BdaAddressed() const { + return (bdaPagetableVariable != 0 || faultBufferVariable != 0) && program.Metadata().bindings.UsesDataAddress(); +} + +bool SpirvEmitterState::TableMapAddressed() const { + return tableMapVariable != 0 && program.Metadata().bindings.UsesDataAddress(); +} + +bool SpirvEmitterState::TableHeap() const { + return gpuResolvedImages && program.Metadata().bindings.UsesDataAddress(); +} + SpirvValueEmitContext::SpirvValueEmitContext(SpirvEmitterState& state) : state(state) { } @@ -268,6 +280,9 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Sh state.float64DenormPreserve = target.float64DenormPreserve; state.depthRangeRemap = target.depthRangeRemap; state.registrationModules = target.registrationModules; + state.gpuResolvedImages = target.gpuResolvedImages; + state.heapDataUniformDwords = target.heapDataUniformDwords; + state.uniformConstantBuffers = target.uniformConstantBuffers; state.fragmentDescriptorSet = target.fragmentDescriptorSet; state.meshBarycentricPixel = target.meshBarycentricPixel; state.meshBarycentricVertex = target.meshBarycentricVertex; @@ -348,6 +363,8 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Sh if (info != nullptr) { info->fullSubgroups = state.spannedWave; info->functionLdsBuffer = state.pixelFunctionLdsBuffer; + info->bdaStores = state.bdaWritePointerFunction != 0; + info->pushItems = state.pushItems; info->meshWindowBuffer = state.meshWindowBuffer; info->scratchPoolSlotDwords = ScratchPoolActive(state) ? ScratchPoolSlotDwords(state) : 0u; info->anySubgroupSize = state.spannedAnySubgroup; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp index f7883c172133..fd10ae533f4a 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp @@ -3,6 +3,7 @@ #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvEmitterInstructions.hpp" #include "SpirvBackend/SpirvRuntimeBuffer.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include "SpirvBackend/SpirvMemory/SpirvSubgroup.hpp" #include #include @@ -103,11 +104,17 @@ void EmitReturnTerminator(SpirvValueEmitContext& ctx) { state.module.AddFunction(spv::OpLoad, TypeI32(state), value, state.stencilRefVariable); const auto reference = Unary(state, spv::OpBitcast, TypeU32(state), value); const auto masked = Binary(state, spv::OpBitwiseAnd, TypeU32(state), reference, ConstantU32(state, 0xffu)); - const auto offset = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::StencilReferenceOffset, state.program.Metadata().bindings.stencilReferenceDword); - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0u), offset); - const auto expected = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), expected, pointer); + const auto& layout = state.program.Metadata().bindings; + auto expected = 0u; + if (layout.UsesDataAddress()) { + expected = EmitRootItemDword(state, RuntimeAbi::RootItem::StencilReference, 0u); + } else { + const auto offset = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::StencilReferenceOffset, layout.stencilReferenceDword); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0u), offset); + expected = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), expected, pointer); + } EmitKillIfBoolFalse(state, Binary(state, spv::OpIEqual, TypeBool(state), masked, expected)); } EmitReturnReleasingScratch(state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp index 74565eb291cb..2fa0264415de 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp @@ -9,6 +9,7 @@ #include "RdnaDecoder/RdnaImageOpDecoder.hpp" #include "RdnaDecoder/RdnaInstructionDecoder.hpp" #include "ImageTableAbi.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include #include #include @@ -2150,7 +2151,14 @@ ScalarBufferDword EmitScalarBufferDword(SpirvEmitterState& state, std::uint32_t return dword; } +} + std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index) { + if (state.TableMapAddressed()) { + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, EmitRootAddressReadOnlyWordPointer(state, RuntimeAbi::RootItem::TableMap, index), spv::MemoryAccessAlignedMask, 4u); + return value; + } const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.tableMapVariable, ConstantU32(state, 0u), index); const auto value = state.module.AllocateId(); @@ -2158,6 +2166,8 @@ std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index) { return value; } +namespace { + std::uint32_t TableMapAt(SpirvEmitterState& state, std::uint32_t base, std::uint32_t offset) { return LoadTableMap(state, offset == 0u ? base : Binary(state, spv::OpIAdd, TypeU32(state), base, ConstantU32(state, offset))); } @@ -2362,7 +2372,8 @@ TableAccessResult EmitTableAccess(SpirvValueEmitContext& ctx, const IrValue& ins result.valid = both(checked, negate(driverRejected)); result.flags = flags; live = selected; - state.tableAccess.element = Binary(state, spv::OpIAdd, u32, LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)), element); + state.tableAccess.element = state.TableHeap() ? Select(state, u32, checked, element, ConstantU32(state, 0u)) : Binary(state, spv::OpIAdd, u32, LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)), element); + state.tableAccess.heap = state.TableHeap(); const auto& sources = state.program.Resources().descriptorSources; state.tableAccess.uniform = base.source < sources.size() && sources[base.source].tableColumn.has_value() && sources[base.source].tableColumn->selected; if (!state.tableAccess.uniform) DecorateTableNonUniform(state, state.tableAccess.element); @@ -2853,8 +2864,7 @@ void EmitImageBvhIntersectRay(SpirvValueEmitContext& ctx, const IrValue& inst) { for (std::uint32_t i = 0; i < 4u; ++i) { const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, op(spv::OpIAdd, u64, physical, BdaConstant(state, (first + i) * 4u))); - values[i] = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, u32, values[i], pointer, spv::MemoryAccessAlignedMask, 4u); + values[i] = EmitAlignedLoadU32(state, pointer); } return compose(values); }); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 99a53e4d1b05..39ac17a228c4 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -4,7 +4,9 @@ #include "SpirvBackend/SpirvEmitterHelpers.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvDescriptors.hpp" +#include "SpirvBackend/SpirvBda.hpp" #include +#include #include #include #include @@ -33,21 +35,215 @@ std::uint32_t EmitBinaryU32(SpirvEmitterState& state, std::uint32_t opcode, std: return result; } -std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex) { - const IrBindingLayout& layout = state.program.Metadata().bindings; +std::uint32_t EmitAlignedLoadU32(SpirvEmitterState& state, std::uint32_t pointer) { + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, spv::MemoryAccessAlignedMask, 4u); + return value; +} + +namespace { + +std::uint32_t loadPushDword(SpirvEmitterState& state, std::uint32_t index) { + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), index); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); + return value; +} + +std::uint32_t loadStorageDword(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index) { const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, variable, ConstantU32(state, 0u), index); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); + return value; +} + +std::uint32_t placedPushDword(SpirvEmitterState& state, std::uint32_t specialization, std::uint32_t word) { + const auto u32 = TypeU32(state); + const auto position = state.module.SpecializationConstant(u32, specialization, RuntimeAbi::NoPushPosition); + const auto placed = Binary(state, spv::OpINotEqual, TypeBool(state), position, ConstantU32(state, RuntimeAbi::NoPushPosition)); + const auto index = Select(state, u32, placed, Binary(state, spv::OpIAdd, u32, position, ConstantU32(state, word)), ConstantU32(state, 0u)); + return loadPushDword(state, index); +} + +std::uint32_t overflowDword(SpirvEmitterState& state, std::uint32_t buffer, std::uint32_t word) { + if (state.bufferOverflowUniformVariable == 0u) FailEmit("a stage reads buffer overflow records without the records block"); + const auto u32x4 = TypeU32Vector(state, 4); + const auto element = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassUniform, u32x4), element, state.bufferOverflowUniformVariable, ConstantU32(state, 0u), ConstantU32(state, buffer)); + const auto record = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, u32x4, record, element); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), value, record, word); + return value; +} + +} + +std::uint32_t EmitBufferRootDword(SpirvEmitterState& state, std::uint32_t buffer, std::uint32_t word) { + if (state.program.Metadata().bindings.bufferAddressDwords == 0u) FailEmit("only a stage with pushed buffer addresses reads the buffer root"); + if (word >= RuntimeAbi::PushedBufferWords) FailEmit("a pushed buffer record has no such word"); + if (buffer >= RuntimeAbi::PushedBufferLimit) return overflowDword(state, buffer, word); + const auto u32 = TypeU32(state); + const auto position = state.module.SpecializationConstant(u32, PipelineSpecialization::BufferRootPosition + buffer, RuntimeAbi::NoPushPosition); + const auto placed = Binary(state, spv::OpINotEqual, TypeBool(state), position, ConstantU32(state, RuntimeAbi::NoPushPosition)); + return EmitValueIfElse(state, placed, u32, [&] { return placedPushDword(state, PipelineSpecialization::BufferRootPosition + buffer, word); }, [&] { return overflowDword(state, buffer, word); }); +} + +std::uint32_t EmitRootItemDword(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t word) { + if (!state.program.Metadata().bindings.UsesDataAddress()) FailEmit("the root is read only by stages that take their data through it"); + state.pushItems |= RuntimeAbi::RootItemBit(item); + const auto u32 = TypeU32(state); + std::uint32_t position = 0; + if (item == RuntimeAbi::RootItem::UserData) { + state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData); + const auto user = state.module.SpecializationConstant(u32, PipelineSpecialization::RootItemPositionBase + static_cast(item), RuntimeAbi::NoPushPosition); + const auto data = state.module.SpecializationConstant(u32, PipelineSpecialization::RootItemPositionBase + static_cast(RuntimeAbi::RootItem::ShaderData), 0u); + const auto placed = Binary(state, spv::OpINotEqual, TypeBool(state), user, ConstantU32(state, RuntimeAbi::NoPushPosition)); + position = Select(state, u32, placed, user, data); + } else { + position = state.module.SpecializationConstant(u32, PipelineSpecialization::RootItemPositionBase + static_cast(item), 0u); + } + return loadPushDword(state, word == 0u ? position : Binary(state, spv::OpIAdd, u32, position, ConstantU32(state, word))); +} + +namespace { + +std::uint32_t EmitPushedDataSelect(SpirvEmitterState& state, std::uint32_t position, std::uint32_t ring) { + const auto u32 = TypeU32(state); + const auto base = state.module.SpecializationConstant(u32, PipelineSpecialization::PushedDataBase, 0u); + const auto count = state.module.SpecializationConstant(u32, PipelineSpecialization::PushedDataCount, 0u); + const auto inside = state.module.AllocateId(); + state.module.AddFunction(spv::OpULessThan, TypeBool(state), inside, ConstantU32(state, position), count); + const auto index = state.module.AllocateId(); + state.module.AddFunction(spv::OpSelect, u32, index, inside, Binary(state, spv::OpIAdd, u32, base, ConstantU32(state, position)), ConstantU32(state, 0u)); + const auto pushedValue = loadPushDword(state, index); const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpSelect, u32, value, inside, pushedValue, ring); + return value; +} + +} + +std::uint32_t ComposeAddress64(SpirvEmitterState& state, const std::function& loadLow, const std::function& loadHigh) { + const auto u64 = TypeScalarU64(state); + const auto low = Unary(state, spv::OpUConvert, u64, loadLow()); + const auto high = Binary(state, spv::OpShiftLeftLogical, u64, Unary(state, spv::OpUConvert, u64, loadHigh()), BdaConstant(state, 32u)); + return Binary(state, spv::OpBitwiseOr, u64, low, high); +} + +std::uint32_t EmitRootAddress(SpirvEmitterState& state, RuntimeAbi::RootItem item) { + return ComposeAddress64(state, [&] { return EmitRootItemDword(state, item, 0u); }, [&] { return EmitRootItemDword(state, item, 1u); }); +} + +namespace { + +std::uint32_t wordPointer(SpirvEmitterState& state, std::uint32_t base, std::uint32_t index) { + const auto u64 = TypeScalarU64(state); + const auto offset = Binary(state, spv::OpShiftLeftLogical, u64, Unary(state, spv::OpUConvert, u64, index), BdaConstant(state, 2u)); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, Binary(state, spv::OpIAdd, u64, base, offset)); + return pointer; +} + +std::uint32_t readOnlyWordPointer(SpirvEmitterState& state, std::uint32_t base, std::uint32_t index) { + const auto words = ReadOnlyStorageBufferType(state, TypeU32(state), 4u); + const auto block = state.module.AllocateId(); + state.module.AddFunction(spv::OpConvertUToPtr, TypePointer(state, spv::StorageClassPhysicalStorageBuffer, words), block, base); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePhysicalU32Pointer(state), pointer, block, ConstantU32(state, 0u), index); + return pointer; +} + +} + +std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index) { + return wordPointer(state, EmitRootAddress(state, item), index); +} + +std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index) { + return readOnlyWordPointer(state, EmitRootAddress(state, item), index); +} + +namespace { + +std::uint32_t dataAddressLoad(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index) { + const auto uniform = item == RuntimeAbi::RootItem::ShaderData ? state.shaderDataUniformVariable + : item == RuntimeAbi::RootItem::UserData ? state.userDataUniformVariable + : item == RuntimeAbi::RootItem::SrtAddress ? state.flattenedSrtUniformVariable + : 0u; + if (uniform != 0u) { + const auto u32 = TypeU32(state); + const auto vector = Binary(state, spv::OpShiftRightLogical, u32, index, ConstantU32(state, 2u)); + const auto component = Binary(state, spv::OpBitwiseAnd, u32, index, ConstantU32(state, 3u)); + const auto u32x4 = TypeU32Vector(state, 4); + const auto element = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassUniform, u32x4), element, uniform, ConstantU32(state, 0u), vector); + const auto words = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, u32x4, words, element); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpVectorExtractDynamic, u32, value, words, component); + return value; + } + const auto pointer = EmitRootAddressReadOnlyWordPointer(state, item, index); + return EmitAlignedLoadU32(state, pointer); +} + +} + +bool HasFlattenedSrt(const SpirvEmitterState& state) { + return state.flattenedSrtVariable != 0 || state.flattenedSrtAddressed; +} + +bool SplitUserData(const SpirvEmitterState& state) { + const auto& layout = state.program.Metadata().bindings; + return layout.UsesDataAddress() && !layout.userDataRegisters.empty(); +} + +std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t index) { + if (SplitUserData(state)) { + const auto u32 = TypeU32(state); + const auto userWords = static_cast(state.program.Metadata().bindings.userDataRegisters.size()); + const auto user = Binary(state, spv::OpULessThan, TypeBool(state), index, ConstantU32(state, userWords)); + const auto userValue = dataAddressLoad(state, RuntimeAbi::RootItem::UserData, Select(state, u32, user, index, ConstantU32(state, 0u))); + return Select(state, u32, user, userValue, dataAddressLoad(state, RuntimeAbi::RootItem::ShaderData, index)); + } + if (state.program.Metadata().bindings.UsesDataAddress()) return dataAddressLoad(state, RuntimeAbi::RootItem::ShaderData, index); + if (state.shaderDataStorageVariable == 0) FailEmit("shader data is neither in push constants nor in a storage buffer"); + return loadStorageDword(state, state.shaderDataStorageVariable, index); +} + +std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index) { + if (state.flattenedSrtAddressed) { + const auto u32 = TypeU32(state); + const auto& resources = state.program.Resources(); + const auto dwords = ConstantU32(state, resources.srtGuardOffset + static_cast(resources.guardedSrtSlots.size())); + const auto inBounds = Binary(state, spv::OpULessThan, TypeBool(state), index, dwords); + const auto last = Select(state, u32, Binary(state, spv::OpIEqual, TypeBool(state), dwords, ConstantU32(state, 0u)), ConstantU32(state, 0u), Binary(state, spv::OpISub, u32, dwords, ConstantU32(state, 1u))); + const auto clamped = Select(state, u32, inBounds, index, last); + return Select(state, u32, inBounds, dataAddressLoad(state, RuntimeAbi::RootItem::SrtAddress, clamped), ConstantU32(state, 0u)); + } + if (state.flattenedSrtVariable == 0) FailEmit("the flattened SRT descriptor is missing"); + return loadStorageDword(state, state.flattenedSrtVariable, index); +} + +std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex) { + const IrBindingLayout& layout = state.program.Metadata().bindings; + if (layout.UsesDataAddress()) { + const auto pushed = std::ranges::find(layout.pushedData, dwordIndex); + const bool user = SplitUserData(state) && dwordIndex < layout.userDataRegisters.size(); + const auto ring = dataAddressLoad(state, user ? RuntimeAbi::RootItem::UserData : RuntimeAbi::RootItem::ShaderData, ConstantU32(state, dwordIndex)); + if (pushed == layout.pushedData.end()) return ring; + return EmitPushedDataSelect(state, static_cast(pushed - layout.pushedData.begin()), ring); + } if (layout.UsesPushData()) { const auto base = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::PushDataOffset, state.stencilReplay ? layout.pushDataStartDword % PushData::DwordCount : layout.pushDataStartDword); const auto index = Binary(state, spv::OpIAdd, TypeU32(state), Binary(state, spv::OpISub, TypeU32(state), base, ConstantU32(state, state.stencilReplay ? 0u : layout.PushSlotDword())), ConstantU32(state, dwordIndex)); - state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), index); - } else if (state.shaderDataStorageVariable != 0) { - state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.shaderDataStorageVariable, ConstantU32(state, 0), ConstantU32(state, dwordIndex)); - } else { - FailEmit("shader data is neither in push constants nor in a storage buffer"); + return loadPushDword(state, index); } - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); - return value; + if (state.shaderDataStorageVariable == 0) FailEmit("shader data is neither in push constants nor in a storage buffer"); + return loadStorageDword(state, state.shaderDataStorageVariable, ConstantU32(state, dwordIndex)); } void EmitMemoryOffsets(SpirvEmitterState& state) { @@ -60,6 +256,29 @@ void EmitMemoryOffsets(SpirvEmitterState& state) { } } +void EmitHeapSlotPreload(SpirvEmitterState& state) { + if (!state.gpuResolvedImages || (state.shaderDataStorageVariable == 0 && !state.program.Metadata().bindings.UsesDataAddress())) return; + const IrBindingLayout& layout = state.program.Metadata().bindings; + std::vector dwords; + for (auto dword = layout.SamplerSlotDword(); dword < layout.ShaderDataDwords(); ++dword) dwords.push_back(dword); + for (std::uint32_t image = 0; image < layout.runtimeImageCount; ++image) dwords.push_back(layout.ImageFirstElementDword(image)); + const auto pointerType = TypePointer(state, spv::StorageClassPrivate, TypeU32(state)); + for (const auto dword : dwords) { + if (dword >= layout.ShaderDataDwords() || state.heapSlotVariables.contains(dword)) continue; + const auto variable = state.module.DefineGlobalVariable(pointerType, spv::StorageClassPrivate); + state.module.AddFunction(spv::OpStore, variable, EmitShaderDataDwordLoad(state, dword)); + state.heapSlotVariables.emplace(dword, variable); + } +} + +std::uint32_t LoadHeapSlotWord(SpirvEmitterState& state, std::uint32_t dword) { + const auto found = state.heapSlotVariables.find(dword); + if (found == state.heapSlotVariables.end()) return EmitShaderDataDwordLoad(state, dword); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, found->second); + return value; +} + std::uint32_t LdsDwordCount(const SpirvEmitterState& state) { const auto* workgroup = ShaderWorkgroupInput(state); if (workgroup != nullptr) return workgroup->ldsSizeDwords; @@ -263,13 +482,15 @@ std::uint32_t LdsStorageDwords(const SpirvEmitterState& state) { bool LoadsSelectable(const SpirvEmitterState& state, const MemoryResourceAccess& access) { if (access.kind == ResourceKind::Scratch) return true; + if (access.physical) return false; + if (access.softwareBounds) return true; if (access.kind == ResourceKind::Lds) return false; return state.robustBufferAccess2; } std::uint32_t GuardedElementIndex(SpirvEmitterState& state, const MemoryResourceAccess& access, std::uint32_t condition, std::uint32_t index) { if (access.kind == ResourceKind::Lds) FailEmit("LDS loads keep their branch and have no guarded element"); - const auto fallback = access.kind == ResourceKind::Scratch ? 0u : 0xfffffffeu; + const auto fallback = access.kind == ResourceKind::Scratch || access.physical || access.softwareBounds ? 0u : 0xfffffffeu; return Select(state, TypeU32(state), condition, index, ConstantU32(state, fallback)); } @@ -293,6 +514,17 @@ std::uint32_t EmitMemoryElementPointer(SpirvEmitterState& state, const MemoryRes } std::uint32_t EmitStorageBufferElementPointer(SpirvEmitterState& state, const MemoryResourceAccess& access, std::uint32_t index, std::uint32_t pointerType) { + if (access.uniform) { + if (pointerType != TypeStorageBufferElementPointer(state)) FailEmit("a pushed constant buffer is read wider than a dword"); + const auto u32 = TypeU32(state); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassUniform, u32), pointer, access.objectPointer, ConstantU32(state, 0), index); + return pointer; + } + if (access.physical) { + if (pointerType == TypeStorageBufferU64ElementPointer(state)) pointerType = TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeScalarU64(state)); + else pointerType = TypePhysicalU32Pointer(state); + } const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, access.objectPointer, ConstantU32(state, 0), index); return pointer; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvConstants.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvConstants.cpp index c4a0e26277db..5862b43cb8a7 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvConstants.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvConstants.cpp @@ -1,6 +1,8 @@ #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" #include "SpirvBackend/SpirvEmitterHelpers.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" +#include "PipelineSpecialization.hpp" +#include "RuntimeAbi.hpp" #include #include #include @@ -36,6 +38,10 @@ std::uint32_t ConstantU64(SpirvEmitterState& state, std::uint64_t value) { return state.module.Constant(spv::OpConstantComposite, TypeU64(state), ConstantU32(state, static_cast(value)), ConstantU32(state, static_cast(value >> 32u))); } +std::uint32_t HeapImageSlotCount(SpirvEmitterState& state) { + return state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::HeapImageSlots, RuntimeAbi::GpuImageHeapSlots); +} + std::uint32_t ConstantU32CompositeZero(SpirvEmitterState& state, std::uint32_t components) { if (components < 2u || components > 4u) { FailEmit("u32 composite component count is out of range"); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index 79924f87ec4a..bed4899f2225 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -2,9 +2,12 @@ #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" #include "SpirvBackend/SpirvEmitterHelpers.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include "PipelineSpecialization.hpp" +#include "ImageTableAbi.hpp" #include #include +#include #include #include @@ -57,11 +60,7 @@ std::uint32_t DescriptorElementPointer(SpirvEmitterState& state, std::uint32_t r std::uint32_t RuntimeImageDword(SpirvEmitterState& state, std::uint32_t resource, std::uint32_t member) { const auto index = ConstantU32(state, resource); const auto dword = Binary(state, spv::OpIAdd, TypeU32(state), ConstantU32(state, state.program.Metadata().bindings.ImageMetadataDword() + member), Binary(state, spv::OpIMul, TypeU32(state), index, ConstantU32(state, sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)))); - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.shaderDataStorageVariable, ConstantU32(state, 0u), dword); - const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); - return value; + return EmitShaderDataWordLoad(state, dword); } std::uint32_t RuntimeMipCount(SpirvEmitterState& state, std::uint32_t resource) { @@ -79,11 +78,39 @@ void DecorateTableNonUniform(SpirvEmitterState& state, std::uint32_t id) { state.module.AddAnnotation(spv::OpDecorate, id, spv::DecorationNonUniform); } +namespace { + +std::uint32_t tableHeapSlot(SpirvEmitterState& state, RuntimeAbi::HeapPart part, std::uint32_t element, std::uint32_t slots) { + using RuntimeAbi::HeapPart; + const auto partIndex = static_cast(part); + const auto u32 = TypeU32(state); + const auto base = LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)); + const auto count = LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementCount)); + std::uint32_t partBase = base; + if (part == HeapPart::Storage || part == HeapPart::Sampler) { + partBase = Binary(state, spv::OpIAdd, u32, base, Binary(state, spv::OpIMul, u32, count, ConstantU32(state, partIndex))); + } else if (part >= HeapPart::Atomic) { + const auto samplers = LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderSamplerCount)); + const auto samplerSpan = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), count, samplers), samplers, count); + const auto extra = Binary(state, spv::OpIMul, u32, count, ConstantU32(state, partIndex - 1u)); + partBase = Binary(state, spv::OpIAdd, u32, Binary(state, spv::OpIAdd, u32, base, samplerSpan), extra); + } + const auto slot = LoadTableMap(state, Binary(state, spv::OpIAdd, u32, partBase, element)); + const auto fallback = RuntimeAbi::HeapPartFirstBinding(part); + const auto clamped = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), slot, slots), slot, ConstantU32(state, fallback)); + DecorateTableNonUniform(state, clamped); + return clamped; +} + +} + std::uint32_t TableStorageImagePointer(SpirvEmitterState& state, DescriptorBindingKind kind, std::uint32_t resource, std::uint32_t pointerType) { const auto found = std::find_if(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; }); if (found == state.tableImageVariables.end() || !state.tableAccess.active) ExitDescriptorBindingFailure(state, kind, resource, "image storage table array was not emitted for the mode"); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.element); + const auto value = static_cast(kind); + const auto part = RuntimeAbi::StorageHeapPart(value); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, part, state.tableAccess.element, HeapImageSlotCount(state)) : state.tableAccess.element); DecorateTableNonUniform(state, pointer); return pointer; } @@ -154,6 +181,43 @@ std::uint32_t ImageViewSizeType(SpirvEmitterState& state, RdnaImageDimension dim } } +namespace { + +void RequireDynamicIndexing(SpirvEmitterState& state, std::uint32_t capability, DescriptorBindingKind kind, std::uint32_t resource, const char* reason) { + const auto supported = std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), capability) != state.supportedCapabilities.end(); + if (!supported) ExitDescriptorBindingFailure(state, kind, resource, reason); + state.module.EmitCapability(capability); +} + +} + +std::uint32_t HeapImageSlot(SpirvEmitterState& state, DescriptorBindingKind kind, std::uint32_t resource) { + RequireDynamicIndexing(state, spv::CapabilitySampledImageArrayDynamicIndexing, kind, resource, "the image heap needs image array dynamic indexing, which the device lacks"); + return LoadHeapSlotWord(state, state.program.Metadata().bindings.ImageFirstElementDword(resource)); +} + +std::uint32_t HeapImageSlotWord(SpirvEmitterState& state, DescriptorBindingKind kind, std::uint32_t resource, std::uint32_t arrayIndex) { + RequireDynamicIndexing(state, spv::CapabilitySampledImageArrayDynamicIndexing, kind, resource, "the image heap needs image array dynamic indexing, which the device lacks"); + const auto& layout = state.program.Metadata().bindings; + auto dword = layout.ImageSlotDword(); + for (const auto& descriptor : layout.descriptors) { + if (descriptor.kind == kind) break; + if (state.program.Metadata().bindings.HeapSlotWordKind(descriptor.kind)) dword += static_cast(descriptor.resources.size()); + } + dword += arrayIndex; + if (dword >= layout.ShaderDataDwords()) ExitDescriptorBindingFailure(state, kind, resource, "image heap slot word lies outside the shader data"); + return LoadHeapSlotWord(state, dword); +} + +std::uint32_t StorageElementPointer(SpirvEmitterState& state, std::uint32_t pointerType, std::uint32_t variable, std::uint32_t arrayIndex, DescriptorBindingKind kind, std::uint32_t resource) { + if (!state.gpuResolvedImages || !state.program.Metadata().bindings.HeapImageKind(kind)) return DescriptorElementPointer(state, pointerType, variable, arrayIndex, kind, resource, "storage image descriptor array was not emitted"); + if (variable == 0) ExitDescriptorBindingFailure(state, kind, resource, "storage image heap array was not emitted"); + RequireDynamicIndexing(state, spv::CapabilityStorageImageArrayDynamicIndexing, kind, resource, "the storage image heap needs storage image array dynamic indexing, which the device lacks"); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, variable, state.registrationModules && arrayIndex == ResourceForDescriptor(state, kind, resource) ? HeapImageSlot(state, kind, resource) : HeapImageSlotWord(state, kind, resource, arrayIndex)); + return pointer; +} + std::uint32_t LoadSampledImageDescriptor(SpirvEmitterState& state, std::uint32_t resource) { const auto& imageResource = state.runtimeImage != nullptr ? *state.runtimeImage : state.program.Info().images.at(resource); if (imageResource.resourceClass != ImageResourceClass::Sampled) { @@ -166,7 +230,7 @@ std::uint32_t LoadSampledImageDescriptor(SpirvEmitterState& state, std::uint32_t const auto found = std::find_if(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; }); if (found == state.tableImageVariables.end() || !state.tableAccess.active) ExitDescriptorBindingFailure(state, kind, resource, "image table array was not emitted for the mode"); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, RuntimeAbi::HeapPart::Sampled, state.tableAccess.element, HeapImageSlotCount(state)) : state.tableAccess.element); if (!state.tableAccess.uniform) DecorateTableNonUniform(state, pointer); const auto image = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, imageType, image, pointer); @@ -178,7 +242,13 @@ std::uint32_t LoadSampledImageDescriptor(SpirvEmitterState& state, std::uint32_t if (variable == 0) { ExitDescriptorBindingFailure(state, kind, resource, "sampled image descriptor array was not emitted"); } - const auto pointer = DescriptorElementPointer(state, pointerType, variable, arrayIndex, kind, resource, "sampled image descriptor array was not emitted"); + std::uint32_t pointer = 0; + if (state.gpuResolvedImages) { + pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, variable, state.registrationModules ? HeapImageSlot(state, kind, resource) : HeapImageSlotWord(state, kind, resource, arrayIndex)); + } else { + pointer = DescriptorElementPointer(state, pointerType, variable, arrayIndex, kind, resource, "sampled image descriptor array was not emitted"); + } const auto image = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, imageType, image, pointer); return image; @@ -196,7 +266,7 @@ std::uint32_t LoadSamplerDescriptor(SpirvEmitterState& state, std::uint32_t samp const auto variant = image != nullptr && image->depthCompare ? 2u : 0u; const auto element = Binary(state, spv::OpIAdd, TypeU32(state), state.tableAccess.samplerElement, ConstantU32(state, variant + (point ? 1u : 0u))); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.tableSamplerVariable, element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.tableSamplerVariable, state.TableHeap() ? tableHeapSlot(state, RuntimeAbi::HeapPart::Sampler, element, ConstantU32(state, RuntimeAbi::GpuSamplerHeapSlots)) : element); DecorateTableNonUniform(state, pointer); const auto loaded = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, samplerType, loaded, pointer); @@ -204,7 +274,25 @@ std::uint32_t LoadSamplerDescriptor(SpirvEmitterState& state, std::uint32_t samp return loaded; } const auto arrayIndex = ResourceForDescriptor(state, DescriptorBindingKind::Samplers, sampler) + (point ? 1u : 0u); - const auto pointer = DescriptorElementPointer(state, pointerType, state.samplerVariable, arrayIndex, DescriptorBindingKind::Samplers, sampler, "sampler descriptor array was not emitted"); + std::uint32_t pointer = 0; + if (state.gpuResolvedImages && samplerResource.constant) { + auto& variable = state.embeddedSamplerVariables[arrayIndex]; + if (variable == 0u) { + variable = state.module.DefineGlobalVariable(pointerType, spv::StorageClassUniformConstant); + state.module.AddName(variable, "embedded_sampler"); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::EmbeddedSamplerSet); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, arrayIndex); + } + pointer = variable; + } else if (state.gpuResolvedImages) { + if (state.samplerVariable == 0) ExitDescriptorBindingFailure(state, DescriptorBindingKind::Samplers, sampler, "sampler descriptor array was not emitted"); + RequireDynamicIndexing(state, spv::CapabilitySampledImageArrayDynamicIndexing, DescriptorBindingKind::Samplers, sampler, "the sampler heap needs sampler array dynamic indexing, which the device lacks"); + const auto slot = LoadHeapSlotWord(state, state.program.Metadata().bindings.SamplerSlotDword() + arrayIndex); + pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.samplerVariable, slot); + } else { + pointer = DescriptorElementPointer(state, pointerType, state.samplerVariable, arrayIndex, DescriptorBindingKind::Samplers, sampler, "sampler descriptor array was not emitted"); + } const auto samplerId = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, samplerType, samplerId, pointer); return samplerId; @@ -231,7 +319,7 @@ std::uint32_t StorageImageDescriptorPointer(SpirvEmitterState& state, std::uint3 if (image.table != NoTable) return TableStorageImagePointer(state, kind, resource, pointerType); const auto arrayIndex = ResourceForDescriptor(state, kind, resource); const auto variable = state.imageVariables.at(ImageBindingIndex(kind)); - return DescriptorElementPointer(state, pointerType, variable, arrayIndex, kind, resource, "storage image descriptor array was not emitted"); + return StorageElementPointer(state, pointerType, variable, arrayIndex, kind, resource); } std::uint32_t EmitStorageImageRead(SpirvEmitterState& state, std::uint32_t resource, std::uint32_t coord, std::uint32_t sample) { @@ -277,7 +365,7 @@ void EmitStorageImageWrite(SpirvEmitterState& state, std::uint32_t resource, std const auto arrayIndex = ResourceForDescriptor(state, kind, resource); const auto variable = state.imageVariables.at(ImageBindingIndex(kind)); const auto loadAt = [&](std::uint32_t index) { - const auto pointer = DescriptorElementPointer(state, pointerType, variable, index, kind, resource, "storage image descriptor array was not emitted"); + const auto pointer = StorageElementPointer(state, pointerType, variable, index, kind, resource); const auto descriptor = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, imageType, descriptor, pointer); return descriptor; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index 63e75e3a2951..c136cfe68064 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -7,6 +7,7 @@ #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" #include "SpirvBackend/SpirvMemory/SpirvDescriptors.hpp" #include "SpirvBackend/SpirvMemory/SpirvInputOutput.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include #include #include @@ -141,7 +142,7 @@ std::uint32_t StorageBufferU64BlockType(SpirvEmitterState& state) { } std::uint32_t PushConstantArrayType(SpirvEmitterState& state) { - const auto count = ConstantU32(state, PushData::DwordCount); + const auto count = ConstantU32(state, state.program.Metadata().bindings.UsesDataAddress() || GpuScratchPool(state) ? RuntimeAbi::PushDataDwords : PushData::DwordCount); return state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, static_cast(sizeof(std::uint32_t))}}}, TypeU32(state), count); @@ -168,7 +169,7 @@ void CheckBindings(const IrProgram& program, const CompiledBindingLayout& bindin void EmitBaseHeader(SpirvModule& module, const IrProgram& program, bool atomicLockTable) { module.EmitCapability(spv::CapabilityShader); - const bool physical = program.Info().usesDma || program.Resources().stage == IrShaderStage::Mesh || atomicLockTable; + const bool physical = program.Info().usesDma || program.Resources().stage == IrShaderStage::Mesh || program.Metadata().bindings.bufferAddressDwords != 0u || program.Metadata().bindings.UsesDataAddress() || atomicLockTable; if (physical) { module.EmitCapability(spv::CapabilityInt64); module.EmitCapability(spv::CapabilityPhysicalStorageBufferAddresses); @@ -495,31 +496,133 @@ void DefineOutputs(SpirvEmitterState& state) { } } +namespace { + +std::uint32_t UniformWordsBlockType(SpirvEmitterState& state, std::uint32_t elementType, std::uint32_t stride, std::uint32_t count) { + const auto array = state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, stride}}}, elementType, ConstantU32(state, count)); + return state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); +} + +std::vector UniformConstantBufferWords(SpirvEmitterState& state, std::uint32_t count) { + std::vector uniformWords(count, 0u); + if (!state.uniformConstantBuffers) return uniformWords; + std::vector eligible(count, true); + std::vector end(count, 0u); + const auto& memory = state.program.Resources().memoryInfo; + for (const auto& block : state.program.Blocks()) { + for (const IrValue* inst : block->Instructions()) { + const auto op = inst->Opcode(); + if (op != IrOpcode::ReadConstBuffer && BufferAccessOf(op) == BufferAccess::None) continue; + const auto index = inst->Flags().index; + if (index >= memory.size()) continue; + const auto& info = memory[index]; + if (info.gpuDescriptor || info.planningOnly || (info.kind != ResourceKind::Buffer && info.kind != ResourceKind::ScalarBuffer)) continue; + const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, info.resource); + if (element >= count) continue; + const auto* offset = inst->ArgumentCount() > 1u ? inst->Argument(1u) : nullptr; + if (op != IrOpcode::ReadConstBuffer || info.coherent || offset == nullptr || !offset->HasImmediate()) { + eligible[element] = false; + continue; + } + const auto byte = static_cast(offset->ImmediateU32()) + info.offset; + end[element] = std::max(end[element], static_cast(std::min((byte & ~std::uint64_t{3u}) + 8u, 0xffffffffu))); + } + } + for (std::uint32_t element = 0; element < count; ++element) { + const auto bytes = static_cast(end[element]) + RuntimeAbi::UniformViewAdjustmentLimit; + if (eligible[element] && end[element] != 0u && bytes <= RuntimeAbi::UniformConstantBufferBytes) uniformWords[element] = static_cast((bytes + 3u) / 4u); + } + return uniformWords; +} + +std::uint32_t DefinePushedBufferVariable(SpirvEmitterState& state, std::uint32_t pointee, std::uint32_t storage, std::uint32_t element, const std::string& name) { + const auto variable = state.module.DefineGlobalVariable(TypePointer(state, storage, pointee), storage); + state.module.AddName(variable, name.c_str()); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::PushedBufferSet); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, element); + return variable; +} + +PushedBufferVariables DefinePushedStorageBuffer(SpirvEmitterState& state, std::uint32_t element) { + const auto storage = [&](std::uint32_t type, const char* name) { return DefinePushedBufferVariable(state, type, spv::StorageClassStorageBuffer, element, std::string(name) + "_" + std::to_string(element)); }; + const bool aliased = state.requirements.coherentBufferAlias || state.requirements.bufferU64View; + PushedBufferVariables variables; + variables.plain = storage(StorageBufferBlockType(state), "pushed_buffer"); + variables.coherent = state.requirements.coherentBufferAlias ? storage(StorageBufferBlockType(state), "pushed_buffer_coherent") : 0u; + variables.u64 = state.requirements.bufferU64View ? storage(StorageBufferU64BlockType(state), "pushed_buffer_u64") : 0u; + for (const auto variable : {variables.plain, variables.coherent, variables.u64}) { + if (variable != 0u && aliased) state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationAliased); + } + if (state.requirements.coherentBuffers) { + state.module.AddAnnotation(spv::OpDecorate, variables.coherent != 0u ? variables.coherent : variables.plain, spv::DecorationCoherent); + if (variables.u64 != 0u) state.module.AddAnnotation(spv::OpDecorate, variables.u64, spv::DecorationCoherent); + } + return variables; +} + +void DefinePushedBuffers(SpirvEmitterState& state, const IrBindingLayout& layout) { + state.addressedBuffers = true; + const auto count = layout.bufferAddressDwords / RuntimeAbi::BufferAddressWords; + const auto uniformWords = UniformConstantBufferWords(state, count); + for (std::uint32_t element = 0; element < count; ++element) { + PushedBufferVariables variables; + if (uniformWords[element] != 0u) { + const auto block = UniformWordsBlockType(state, TypeU32(state), 4u, uniformWords[element]); + variables.uniform = DefinePushedBufferVariable(state, block, spv::StorageClassUniform, element, "pushed_constant_buffer_" + std::to_string(element)); + } else { + variables = DefinePushedStorageBuffer(state, element); + } + state.pushedBuffers.push_back(variables); + } + if (count != 0u) { + const auto block = UniformWordsBlockType(state, TypeU32Vector(state, 4), RuntimeAbi::OverflowRecordWords * 4u, count); + state.bufferOverflowUniformVariable = DefinePushedBufferVariable(state, block, spv::StorageClassUniform, RuntimeAbi::PushedBufferOverflowBinding, "buffer_overflow"); + state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData); + } +} + +std::uint32_t defineHeapArray(SpirvEmitterState& state, std::uint32_t slotCount, std::uint32_t elementType, const char* name, std::uint32_t heapKind) { + const auto type = state.module.Type(spv::OpTypeArray, elementType, slotCount); + const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniformConstant, type), spv::StorageClassUniformConstant); + state.module.AddName(variable, name); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::FragmentDescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, NativeBinding(IrShaderStage::Pixel, static_cast(heapKind))); + return variable; +} + +} + void DefineDescriptors(SpirvEmitterState& state) { const IrBindingLayout& layout = state.program.Metadata().bindings; const IrShaderStage stage = state.program.Resources().stage; - if (layout.UsesPushData() || state.stencilReplay || stage == IrShaderStage::Mesh || stage == IrShaderStage::TessellationControl || (state.depthRangeRemap && (stage == IrShaderStage::Vertex || stage == IrShaderStage::TessellationEvaluation))) { + if (layout.UsesPushData() || layout.UsesDataAddress() || GpuScratchPool(state) || state.stencilReplay || stage == IrShaderStage::Mesh || stage == IrShaderStage::TessellationControl || (state.depthRangeRemap && (stage == IrShaderStage::Vertex || stage == IrShaderStage::TessellationEvaluation))) { const auto type = PushConstantBlockType(state); state.pushConstantVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassPushConstant, type), spv::StorageClassPushConstant); state.module.AddName(type, "BufferResource"); state.module.AddName(state.pushConstantVariable, "vsharp"); } for (const IrDescriptorBinding& binding : layout.descriptors) { + const bool gpuHeap = SharedHeapArray(layout, binding.kind, state.gpuResolvedImages); const auto Define = [&](std::uint32_t type, const char* name, std::uint32_t storage = spv::StorageClassStorageBuffer) { const auto variable = state.module.DefineGlobalVariable(TypePointer(state, storage, type), storage); state.module.AddName(variable, name); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, state.fragmentDescriptorSet && stage == IrShaderStage::Pixel ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, NativeBinding(stage, binding.kind)); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, DescriptorSetNumber(layout, binding.kind, stage, state.gpuResolvedImages, state.fragmentDescriptorSet, false)); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, DescriptorBindingNumber(layout, binding.kind, stage, state.gpuResolvedImages)); return variable; }; const auto ArrayType = [&](std::uint32_t type) { const bool heap = binding.kind == DescriptorBindingKind::Samplers || ImageBindingResourceClass(binding.kind) != ImageResourceClass::None; - const auto count = static_cast(binding.resources.size()); - const auto length = heap && !state.registrationModules ? state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::HeapCountBase + static_cast(binding.kind), count) : ConstantU32(state, count); + const bool samplers = binding.kind == DescriptorBindingKind::Samplers; + const auto count = gpuHeap ? (samplers ? RuntimeAbi::GpuSamplerHeapSlots : RuntimeAbi::GpuImageHeapSlots) : static_cast(binding.resources.size()); + const auto length = gpuHeap && !samplers ? HeapImageSlotCount(state) : heap && !gpuHeap && !state.registrationModules ? state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::HeapCountBase + static_cast(binding.kind), count) : ConstantU32(state, count); return state.module.Type(spv::OpTypeArray, type, length); }; switch (binding.kind) { - case DescriptorBindingKind::Buffers: + case DescriptorBindingKind::Buffers: { + if (layout.bufferAddressDwords != 0u) { + DefinePushedBuffers(state, layout); + break; + } state.storageBufferVariable = Define(ArrayType(StorageBufferBlockType(state)), "buffers"); if (state.requirements.coherentBufferAlias) state.storageBufferCoherentVariable = Define(ArrayType(StorageBufferBlockType(state)), "buffers_coherent"); if (state.requirements.bufferU64View) state.storageBufferU64Variable = Define(ArrayType(StorageBufferU64BlockType(state)), "buffers_u64"); @@ -533,25 +636,61 @@ void DefineDescriptors(SpirvEmitterState& state) { if (state.storageBufferU64Variable != 0u) state.module.AddAnnotation(spv::OpDecorate, state.storageBufferU64Variable, spv::DecorationCoherent); } break; + } case DescriptorBindingKind::BdaPagetable: - state.bdaPagetableVariable = Define(StorageBufferBlockType(state), "bda_pagetable"); - state.module.AddAnnotation(spv::OpDecorate, state.bdaPagetableVariable, spv::DecorationNonWritable); + if (layout.UsesDataAddress()) { + state.bdaPagetableVariable = state.module.AllocateId(); + } else { + state.bdaPagetableVariable = Define(StorageBufferBlockType(state), "bda_pagetable"); + state.module.AddAnnotation(spv::OpDecorate, state.bdaPagetableVariable, spv::DecorationNonWritable); + } break; case DescriptorBindingKind::FaultBuffer: - state.faultBufferVariable = Define(StorageBufferBlockType(state), "fault_buffer"); + if (layout.UsesDataAddress()) { + state.faultBufferVariable = state.module.AllocateId(); + } else { + state.faultBufferVariable = Define(StorageBufferBlockType(state), "fault_buffer"); + } break; case DescriptorBindingKind::ShaderData: - state.shaderDataStorageVariable = Define(StorageBufferBlockType(state), "shader_data"); + if (!layout.UsesDataAddress()) { + state.shaderDataStorageVariable = Define(StorageBufferBlockType(state), "shader_data"); + state.module.AddAnnotation(spv::OpDecorate, state.shaderDataStorageVariable, spv::DecorationNonWritable); + } else if (layout.ShaderDataDwords() != 0u && layout.ShaderDataDwords() <= state.heapDataUniformDwords) { + const auto block = UniformWordsBlockType(state, TypeU32Vector(state, 4), 16u, (layout.ShaderDataDwords() + 3u) / 4u); + state.shaderDataUniformVariable = Define(block, "shader_data", spv::StorageClassUniform); + state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData); + } + if (layout.UsesDataAddress() && SplitUserData(state) && layout.userDataRegisters.size() <= state.heapDataUniformDwords) { + const auto block = UniformWordsBlockType(state, TypeU32Vector(state, 4), 16u, static_cast((layout.userDataRegisters.size() + 3u) / 4u)); + state.userDataUniformVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniform, block), spv::StorageClassUniform); + state.module.AddName(state.userDataUniformVariable, "user_data"); + state.module.AddAnnotation(spv::OpDecorate, state.userDataUniformVariable, spv::DecorationDescriptorSet, RuntimeAbi::GpuDataSet); + state.module.AddAnnotation(spv::OpDecorate, state.userDataUniformVariable, spv::DecorationBinding, NativeBinding(stage, DescriptorBindingKind::UserData)); + state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::UserData) | RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData); + } break; case DescriptorBindingKind::FlattenedSrt: - state.flattenedSrtVariable = Define(StorageBufferBlockType(state), "flattened_srt"); - state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); + if (layout.UsesDataAddress()) { + state.flattenedSrtAddressed = true; + const auto& resources = state.program.Resources(); + const auto dwords = resources.srtGuardOffset + static_cast(resources.guardedSrtSlots.size()); + if (dwords != 0u && dwords <= state.heapDataUniformDwords) { + const auto block = UniformWordsBlockType(state, TypeU32Vector(state, 4), 16u, (dwords + 3u) / 4u); + state.flattenedSrtUniformVariable = Define(block, "flattened_srt", spv::StorageClassUniform); + state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::SrtAddress); + } + } else { + state.flattenedSrtVariable = Define(StorageBufferBlockType(state), "flattened_srt"); + state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); + } break; case DescriptorBindingKind::Samplers: state.samplerVariable = Define(ArrayType(state.module.Type(spv::OpTypeSampler)), "samplers", spv::StorageClassUniformConstant); break; case DescriptorBindingKind::Gds: state.gdsVariable = Define(StorageBufferBlockType(state), "gds"); + if (layout.UsesDataAddress()) state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::GdsAddress); state.module.AddAnnotation(spv::OpDecorate, state.gdsVariable, spv::DecorationCoherent); if (state.requirements.gdsInt64Atomics) { state.gdsU64Variable = Define(StorageBufferU64BlockType(state), "gds_u64"); @@ -573,7 +712,15 @@ void DefineDescriptors(SpirvEmitterState& state) { if ((ImageBindingResourceClass(kind) == ImageResourceClass::Storage) != (binding.kind == DescriptorBindingKind::ImageStorageTable)) continue; if (std::any_of(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; })) continue; const auto name = "table_images_" + std::to_string(static_cast(kind)); - state.tableImageVariables.push_back({kind, Define(state.module.Type(spv::OpTypeRuntimeArray, ImageType(state, mode)), name.c_str(), spv::StorageClassUniformConstant)}); + if (state.TableHeap()) { + const auto value = static_cast(kind); + const auto part = RuntimeAbi::StorageHeapPart(value); + const auto heapKind = binding.kind != DescriptorBindingKind::ImageStorageTable ? RuntimeAbi::FirstImageBinding : part == RuntimeAbi::HeapPart::Atomic || part == RuntimeAbi::HeapPart::Atomic64 ? RuntimeAbi::HeapPartFirstBinding(part) : RuntimeAbi::FirstStorageImageBinding; + const auto slotCount = HeapImageSlotCount(state); + state.tableImageVariables.push_back({kind, defineHeapArray(state, slotCount, ImageType(state, mode), name.c_str(), heapKind)}); + } else { + state.tableImageVariables.push_back({kind, Define(state.module.Type(spv::OpTypeRuntimeArray, ImageType(state, mode)), name.c_str(), spv::StorageClassUniformConstant)}); + } if (mode.atomic64 && state.requirements.imageAtomicLocks) state.module.AddAnnotation(spv::OpDecorate, state.tableImageVariables.back().variable, spv::DecorationCoherent); if (mode.dimension == RdnaImageDimension::Dim1D || mode.dimension == RdnaImageDimension::Dim1DArray) state.module.EmitCapability(binding.kind == DescriptorBindingKind::ImageStorageTable ? spv::CapabilityImage1D : spv::CapabilitySampled1D); } @@ -581,11 +728,20 @@ void DefineDescriptors(SpirvEmitterState& state) { break; case DescriptorBindingKind::SamplerTable: RequireTableIndexing(state); - state.tableSamplerVariable = Define(state.module.Type(spv::OpTypeRuntimeArray, state.module.Type(spv::OpTypeSampler)), "table_samplers", spv::StorageClassUniformConstant); + if (state.gpuResolvedImages && layout.UsesDataAddress()) { + const auto slotCount = ConstantU32(state, RuntimeAbi::GpuSamplerHeapSlots); + state.tableSamplerVariable = defineHeapArray(state, slotCount, state.module.Type(spv::OpTypeSampler), "table_samplers", static_cast(DescriptorBindingKind::Samplers)); + } else { + state.tableSamplerVariable = Define(state.module.Type(spv::OpTypeRuntimeArray, state.module.Type(spv::OpTypeSampler)), "table_samplers", spv::StorageClassUniformConstant); + } break; case DescriptorBindingKind::ImageTableMap: - state.tableMapVariable = Define(StorageBufferBlockType(state), "table_map"); - state.module.AddAnnotation(spv::OpDecorate, state.tableMapVariable, spv::DecorationNonWritable); + if (layout.UsesDataAddress()) { + state.tableMapVariable = state.module.AllocateId(); + } else { + state.tableMapVariable = Define(StorageBufferBlockType(state), "table_map"); + state.module.AddAnnotation(spv::OpDecorate, state.tableMapVariable, spv::DecorationNonWritable); + } break; default: { if (ImageBindingResourceClass(binding.kind) == ImageResourceClass::None) { @@ -608,13 +764,13 @@ void DefineDescriptors(SpirvEmitterState& state) { if (LdsInDeviceMemory(state)) { state.ldsBufferVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassStorageBuffer, StorageBufferBlockType(state)), spv::StorageClassStorageBuffer); state.module.AddName(state.ldsBufferVariable, "workgroup_memory"); - state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferVariable, spv::DecorationDescriptorSet, WorkgroupMemoryDescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferVariable, spv::DecorationDescriptorSet, state.gpuResolvedImages ? GpuWorkgroupMemoryDescriptorSet : WorkgroupMemoryDescriptorSet); state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferVariable, spv::DecorationBinding, 0u); state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferVariable, spv::DecorationCoherent); if (state.requirements.ldsBufferInt64Atomics) { state.ldsBufferU64Variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassStorageBuffer, StorageBufferU64BlockType(state)), spv::StorageClassStorageBuffer); state.module.AddName(state.ldsBufferU64Variable, "workgroup_memory_u64"); - state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferU64Variable, spv::DecorationDescriptorSet, WorkgroupMemoryDescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferU64Variable, spv::DecorationDescriptorSet, state.gpuResolvedImages ? GpuWorkgroupMemoryDescriptorSet : WorkgroupMemoryDescriptorSet); state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferU64Variable, spv::DecorationBinding, 0u); state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferU64Variable, spv::DecorationCoherent); for (const auto variable : {state.ldsBufferVariable, state.ldsBufferU64Variable}) state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationAliased); @@ -650,7 +806,7 @@ void DefineScratchPool(SpirvEmitterState& state) { if (!ScratchPoolActive(state)) return; state.scratchPoolVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassStorageBuffer, StorageBufferBlockType(state)), spv::StorageClassStorageBuffer); state.module.AddName(state.scratchPoolVariable, "scratch_pool"); - state.module.AddAnnotation(spv::OpDecorate, state.scratchPoolVariable, spv::DecorationDescriptorSet, ScratchPoolDescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, state.scratchPoolVariable, spv::DecorationDescriptorSet, GpuScratchPool(state) ? GpuScratchPoolDescriptorSet : ScratchPoolDescriptorSet); state.module.AddAnnotation(spv::OpDecorate, state.scratchPoolVariable, spv::DecorationBinding, 0u); state.module.AddAnnotation(spv::OpDecorate, state.scratchPoolVariable, spv::DecorationCoherent); state.scratchPoolSlotVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassWorkgroup, TypeU32(state)), spv::StorageClassWorkgroup); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp index 40bedebdd7ce..d13c3a5bc08f 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp @@ -3,6 +3,7 @@ #include "SpirvBackend/SpirvEmitterInstructions.hpp" #include "SpirvBackend/SpirvMemory/SpirvSubgroup.hpp" #include "SpirvBackend/SpirvBufferFormat.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include "RdnaDecoder/RdnaInstructionDecoder.hpp" #include #include @@ -1672,7 +1673,7 @@ std::uint32_t AtomicFloatCompareSwap(SpirvEmitterState& state, std::uint32_t old std::uint32_t EmitReadConst(SpirvValueEmitContext& ctx, const IrValue& inst) { auto& state = ctx.state; - if (state.flattenedSrtVariable == 0) { + if (!HasFlattenedSrt(state)) { ctx.Fail(inst, "requires the flattened SRT descriptor"); } const auto& resources = state.program.Resources(); @@ -1688,13 +1689,7 @@ std::uint32_t EmitReadConst(SpirvValueEmitContext& ctx, const IrValue& inst) { ctx.Fail(inst, "reads a guarded SRT slot without a fault buffer"); } const auto u32 = TypeU32(state); - const auto load = [&](std::uint32_t index) { - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.flattenedSrtVariable, ConstantU32(state, 0u), index); - const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, u32, value, pointer); - return value; - }; + const auto load = [&](std::uint32_t index) { return EmitFlattenedSrtLoad(state, index); }; const auto guard = static_cast(found - guarded.begin()); const auto flag = load(ConstantU32(state, resources.srtGuardOffset + guard)); const auto poisoned = Binary(state, spv::OpINotEqual, TypeBool(state), flag, ConstantU32(state, 0u)); @@ -1718,11 +1713,7 @@ std::uint32_t EmitReadConst(SpirvValueEmitContext& ctx, const IrValue& inst) { StopBdaInvocationIf(state, poisoned); } } - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.flattenedSrtVariable, ConstantU32(state, 0u), ctx.Arg(inst, 1)); - const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); - return value; + return EmitFlattenedSrtLoad(state, ctx.Arg(inst, 1)); } void EmitReadConstBuffer(SpirvValueEmitContext& ctx, const IrValue& inst) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp index 3ff4f6fec117..d1bcfa7dc30c 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp @@ -307,12 +307,12 @@ void PlanMeshWindowBuffer(SpirvEmitterState& state) { } } -bool WritesGuestMemory(const IrProgram& program) { +} + +bool WritesGuestBuffers(const IrProgram& program) { const auto& info = program.Info(); - const auto writtenImage = [](const ImageResource& image) { return !image.targetMerge && (image.written || image.atomic || image.atomic64); }; - const auto writtenModes = [&](const std::vector& modes) { return std::ranges::any_of(modes, writtenImage); }; const auto writtenBuffer = [](const BufferResource& buffer) { return buffer.written || buffer.atomic; }; - if (info.bdaWrites || std::ranges::any_of(info.buffers, writtenBuffer) || std::ranges::any_of(info.images, writtenImage) || std::ranges::any_of(info.runtimeImageModes, writtenModes)) return true; + if (info.bdaWrites || std::ranges::any_of(info.buffers, writtenBuffer)) return true; const auto& memory = program.Resources().memoryInfo; for (const auto& block : program.Blocks()) { for (const IrValue* inst : block->Instructions()) { @@ -326,6 +326,11 @@ bool WritesGuestMemory(const IrProgram& program) { return false; } +bool WritesGuestMemory(const IrProgram& program) { + const auto& info = program.Info(); + const auto writtenImage = [](const ImageResource& image) { return !image.targetMerge && (image.written || image.atomic || image.atomic64); }; + const auto writtenModes = [&](const std::vector& modes) { return std::ranges::any_of(modes, writtenImage); }; + return std::ranges::any_of(info.images, writtenImage) || std::ranges::any_of(info.runtimeImageModes, writtenModes) || WritesGuestBuffers(program); } void DefineModule(SpirvEmitterState& state) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp index ccbbf7d35016..2bb4adc42b10 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp @@ -52,6 +52,10 @@ bool ScratchPoolActive(const SpirvEmitterState& state) { return state.requirements.functionScratch && state.program.Resources().stage == IrShaderStage::Compute; } +bool GpuScratchPool(const SpirvEmitterState& state) { + return state.gpuResolvedImages && ScratchPoolActive(state); +} + std::uint32_t ScratchPoolSlotDwords(const SpirvEmitterState& state) { const auto* workgroup = ShaderWorkgroupInput(state); if (workgroup == nullptr) FailEmit("scratch pool needs a compute workgroup size"); @@ -69,7 +73,14 @@ void EmitScratchPoolAcquire(SpirvEmitterState& state) { const auto device = ConstantU32(state, spv::ScopeDevice); const auto relaxed = ConstantU32(state, spv::MemorySemanticsMaskNone); const auto length = state.module.AllocateId(); - state.module.AddFunction(spv::OpArrayLength, TypeU32(state), length, state.scratchPoolVariable, 0u); + if (GpuScratchPool(state)) { + if (state.pushConstantVariable == 0u) FailEmit("a GPU-mode scratch pool has no push data for its length"); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0u), ConstantU32(state, GpuScratchPoolDwordsPushByte / 4u)); + state.module.AddFunction(spv::OpLoad, TypeU32(state), length, pointer); + } else { + state.module.AddFunction(spv::OpArrayLength, TypeU32(state), length, state.scratchPoolVariable, 0u); + } const auto slotDwords = ScratchPoolSlotDwords(state); const auto slots = EmitBinaryU32(state, spv::OpUDiv, length, ConstantU32(state, slotDwords + HeaderWordsPerSlot)); state.scratchPoolSlotCount = slots; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp index 1265fd1b0280..dbc57f23ae0e 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp @@ -7,6 +7,15 @@ namespace ShaderRecompiler { +std::uint32_t ReadOnlyStorageBufferType(SpirvEmitterState& state, std::uint32_t element, std::uint32_t stride) { + const auto array = state.module.DecoratedType(spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, stride}}}, element); + return state.module.DecoratedType(spv::OpTypeStruct, + {{spv::OpDecorate, {spv::DecorationBlock}}, + {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpMemberDecorate, {0, spv::DecorationNonWritable}}}, + array); +} + namespace { std::uint32_t StorageBufferType(SpirvEmitterState& state) { @@ -137,6 +146,14 @@ std::uint32_t TypeStorageBufferU8ElementPointer(SpirvEmitterState& state) { return TypePointer(state, spv::StorageClassStorageBuffer, TypeU8(state)); } +std::uint32_t TypePhysicalReadOnlyBufferPointer(SpirvEmitterState& state, bool wide) { + return TypePointer(state, spv::StorageClassPhysicalStorageBuffer, wide ? ReadOnlyStorageBufferType(state, TypeScalarU64(state), 8u) : ReadOnlyStorageBufferType(state, TypeU32(state), 4u)); +} + +std::uint32_t TypePhysicalBufferPointer(SpirvEmitterState& state, bool wide) { + return TypePointer(state, spv::StorageClassPhysicalStorageBuffer, wide ? StorageBufferU64Type(state) : StorageBufferType(state)); +} + std::uint32_t TypePhysicalU32Pointer(SpirvEmitterState& state) { return TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeU32(state)); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp index 5e4822cbf3a4..5f400b56cba7 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp @@ -1,6 +1,7 @@ #include "SpirvBackend/SpirvModuleEmitter.hpp" #include "SpirvBackend/SpirvBufferFormat.hpp" #include "SpirvBackend/SpirvEmitterHelpers.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include "SpirvBackend/SpirvEmitterInstructions.hpp" #include "SpirvBackend/SpirvFlowEmitter.hpp" #include "SpirvBackend/SpirvBda.hpp" @@ -973,6 +974,7 @@ std::uint32_t RemapPositionDepth(SpirvEmitterState& state, std::uint32_t positio state.module.AddFunction(spv::OpCompositeExtract, f32, components.at(i), position, i); } const auto mode = state.module.SpecializationConstant(u32, PipelineSpecialization::DepthRemapBase, remap.mode); + state.pushItems |= RuntimeAbi::DepthRemapPushBit; if (state.pushConstantVariable == 0u) throw std::runtime_error("depth remap push constants were not declared"); const auto pushFloat = [&](std::uint32_t dword) { const auto pointer = state.module.AllocateId(); @@ -1987,7 +1989,9 @@ void EmitProgram(SpirvEmitterState& state) { }); state.module.AddFunction(spv::OpControlBarrier, ConstantU32(state, spv::ScopeWorkgroup), ConstantU32(state, spv::ScopeWorkgroup), ConstantU32(state, spv::MemorySemanticsAcquireReleaseMask | LdsMemorySemantics(state))); } - if (state.gdsVariable != 0u) { + if (state.gdsVariable != 0u && state.program.Metadata().bindings.UsesDataAddress()) { + state.gdsLength = ConstantU32(state, RuntimeAbi::GdsBytes / 4u); + } else if (state.gdsVariable != 0u) { state.gdsLength = state.module.AllocateId(); state.module.AddFunction(spv::OpArrayLength, TypeU32(state), state.gdsLength, state.gdsVariable, 0u); } @@ -2025,6 +2029,7 @@ void EmitProgram(SpirvEmitterState& state) { state.module.AddFunction(spv::OpBeginInvocationInterlockEXT); } EmitMemoryOffsets(state); + EmitHeapSlotPreload(state); if (state.program.Resources().stage == IrShaderStage::Pixel && state.inputInfo.pixel != nullptr && state.inputInfo.pixel->QuadMasked()) { const auto& pixel = *state.inputInfo.pixel; const auto quad = EmitQuadPixel(state); @@ -2170,9 +2175,7 @@ std::uint32_t LoadMeshArgumentWord(SpirvEmitterState& state, std::uint32_t addre const auto element = Binary(state, spv::OpIAdd, TypeScalarU64(state), address, Binary(state, spv::OpShiftLeftLogical, TypeScalarU64(state), Unary(state, spv::OpUConvert, TypeScalarU64(state), dword), ConstantU32(state, 2u))); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpConvertUToPtr, TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeU32(state)), pointer, element); - const auto loaded = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), loaded, pointer, spv::MemoryAccessAlignedMask, 4u); - return loaded; + return EmitAlignedLoadU32(state, pointer); } } @@ -2219,8 +2222,7 @@ std::uint32_t EmitMeshArgument(SpirvValueEmitContext& ctx, const IrValue& inst) const auto element = Binary(state, spv::OpIAdd, TypeScalarU64(state), address, BdaConstant(state, 4ull * index)); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpConvertUToPtr, TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeU32(state)), pointer, element); - const auto loaded = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), loaded, pointer, spv::MemoryAccessAlignedMask, 4u); + const auto loaded = EmitAlignedLoadU32(state, pointer); state.module.AddFunction(spv::OpBranch, merge); EmitLabel(state, merge); const auto value = state.module.AllocateId(); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvOptimizer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvOptimizer.cpp index 2b089a3e8f41..521f54e8424e 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvOptimizer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvOptimizer.cpp @@ -175,6 +175,7 @@ std::vector ValidateAndOptimizeSpirvInline(std::span= state.pushedBuffers.size()) context.Fail(instruction, "a pushed buffer has no storage buffer variable"); + if (state.pushedBuffers[element].uniform != 0u) { + if (instruction.Opcode() != IrOpcode::ReadConstBuffer || wide) context.Fail(instruction, "a pushed constant buffer is read by an access other than a scalar load"); + MemoryResourceAccess access; + access.kind = memory.kind; + access.objectPointer = state.pushedBuffers[element].uniform; + access.softwareBounds = true; + access.uniform = true; + access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), word(2u), ConstantU32(state, 2u)); + access.byteOffset = state.memoryByteOffsets.at(element); + return access; + } + const auto& pushed = state.pushedBuffers[element]; + const auto variable = wide ? pushed.u64 : plainLoad || pushed.coherent == 0u ? pushed.plain : pushed.coherent; + if (variable == 0u) context.Fail(instruction, "a pushed buffer lacks the view this access needs"); + MemoryResourceAccess access; + access.kind = memory.kind; + access.objectPointer = variable; + access.softwareBounds = true; + access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), word(2u), ConstantU32(state, wide ? 3u : 2u)); + access.byteOffset = state.memoryByteOffsets.at(element); + access.memoryAccess = memory.coherent ? spv::MemoryAccessVolatileMask : 0u; + return access; + } const auto variable = wide ? state.storageBufferU64Variable : plainLoad || state.storageBufferCoherentVariable == 0u ? state.storageBufferVariable : state.storageBufferCoherentVariable; if (variable == 0u) context.Fail(instruction, "direct buffer descriptor array is missing"); const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, memory.resource); @@ -276,16 +311,21 @@ std::uint32_t directWordIndex(SpirvEmitterState& state, const MemoryResourceAcce return EmitAddU32(state, relative, base); } +bool addressedCoherent(SpirvValueEmitContext& context, const IrValue& instruction) { + const auto& state = context.state; + return context.Memory(instruction).coherent || (state.requirements.coherentBuffers && state.program.Metadata().invalidatesCaches); +} + std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruction, std::uint32_t address, std::uint32_t bits, std::uint32_t enable = 0u, std::uint32_t boundedEnable = 0u) { if (context.Memory(instruction).gpuDescriptor) return EmitBdaRead(context, instruction, address, bits); auto& state = context.state; - const auto access = directAccess(context, instruction, false, !context.Memory(instruction).coherent); + const auto access = directAccess(context, instruction, false, !context.Memory(instruction).coherent, readOnlyLoad(context, instruction)); const auto index = directWordIndex(state, access, address); const auto misalignment = baseMisalignment(context, instruction); const auto unaligned = nonzero(state, misalignment); const auto next = EmitAddU32(state, index, ConstantU32(state, 1u)); const auto last = Select(state, TypeU32(state), unaligned, next, index); - const bool exact = state.exactRobustLoads && LoadsSelectable(state, access); + const bool exact = state.exactRobustLoads && !access.physical && !access.softwareBounds && LoadsSelectable(state, access); if (!exact && boundedEnable != 0u) enable = boundedEnable; const auto bounds = exact ? 0u : EmitMemoryElementInBounds(state, access, last); const auto inBounds = exact ? 0u : (enable != 0u ? both(state, enable, bounds) : bounds); @@ -293,7 +333,9 @@ std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruct const auto value = state.module.AllocateId(); const auto pointer = EmitMemoryElementPointer(state, access, word); static const bool atomicLoads = std::getenv("APS5_COHERENT_ATOMIC_LOADS") != nullptr; - if (access.memoryAccess != 0u && atomicLoads) state.module.AddFunction(spv::OpAtomicLoad, TypeU32(state), value, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, 0u)); + if (access.physical && addressedCoherent(context, instruction)) state.module.AddFunction(spv::OpAtomicLoad, TypeU32(state), value, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone)); + else if (access.physical) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access.memoryAccess | spv::MemoryAccessAlignedMask, 4u); + else if (access.memoryAccess != 0u && atomicLoads) state.module.AddFunction(spv::OpAtomicLoad, TypeU32(state), value, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, 0u)); else if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access.memoryAccess); else state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); return value; @@ -332,10 +374,12 @@ std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruct const auto low = Binary(state, spv::OpShiftRightLogical, TypeU32(state), load(lowIndex), shift); const auto high = EmitValueOrZero(state, unaligned, Binary(state, spv::OpShiftLeftLogical, TypeU32(state), load(highIndex), highShift)); const auto value = combine(low, high); - return (access.memoryAccess & spv::MemoryAccessVolatileMask) != 0u || (state.requirements.readOnlyStorage && access.memoryAccess == 0u) ? value : EmitValueOrZero(state, inBounds, value); + const bool robustZero = !access.physical && !access.softwareBounds && ((access.memoryAccess & spv::MemoryAccessVolatileMask) != 0u || (state.requirements.readOnlyStorage && access.memoryAccess == 0u)); + return robustZero ? value : EmitValueOrZero(state, inBounds, value); } std::uint32_t byteBuffers(SpirvEmitterState& state) { + if (state.addressedBuffers) return 0u; if (state.storageBufferU8Variable != 0u) return state.storageBufferU8Variable; if (state.program.Resources().stage != IrShaderStage::Compute) return 0u; if (std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), static_cast(spv::CapabilityStorageBuffer8BitAccess)) == state.supportedCapabilities.end()) return 0u; @@ -404,7 +448,9 @@ void writeBuffer(SpirvValueEmitContext& context, const IrValue& instruction, std if (bits == 32u) { EmitIfCondition(state, Unary(state, spv::OpLogicalNot, TypeBool(state), unaligned), [&] { const auto pointer = EmitMemoryElementPointer(state, access, index); - if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess); + if (access.physical && addressedCoherent(context, instruction)) state.module.AddFunction(spv::OpAtomicStore, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone), value); + else if (access.physical) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess | spv::MemoryAccessAlignedMask, 4u); + else if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess); else state.module.AddFunction(spv::OpStore, pointer, value); }); } @@ -979,7 +1025,8 @@ struct CoherentPair { std::optional coherentPair(SpirvValueEmitContext& context, const IrValue& instruction, const RuntimeDescriptor& resource, std::uint32_t components) { auto& state = context.state; const auto& memory = context.Memory(instruction); - if (components != 2u || !memory.coherent || memory.gpuDescriptor || memory.dataBits != 32u || state.storageBufferU64Variable == 0u) return std::nullopt; + const bool wideView = state.addressedBuffers ? state.requirements.bufferU64View : state.storageBufferU64Variable != 0u; + if (components != 2u || !memory.coherent || memory.gpuDescriptor || memory.dataBits != 32u || !wideView) return std::nullopt; const auto low = address(context, instruction, resource, 0u, 4u); const auto high = address(context, instruction, resource, 4u, 4u); const auto wide = directAccess(context, instruction, true); diff --git a/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp b/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp new file mode 100644 index 000000000000..55116ded878e --- /dev/null +++ b/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp @@ -0,0 +1,86 @@ +#include "HeapTemplateBudget.hpp" + +#include +#include +#include +#include +#include + +namespace { + +using ShaderRecompiler::HeapTemplateLru; + +void Require(bool condition, const std::string& what) { + if (!condition) throw std::runtime_error(what); +} + +std::string Names(const std::vector& evicted) { + std::string names; + for (const auto& gone : evicted) names += " " + std::to_string(gone.name.owner) + ":" + std::to_string(gone.name.key); + return names.empty() ? " none" : names; +} + +void LeastRecentlyUsedAcrossShaders() { + HeapTemplateLru order(200); + const HeapTemplateLru::Name a{1, 7, 1}, b{2, 7, 2}, c{3, 7, 3}; + Require(order.Insert(a, 100).empty() && order.Insert(b, 100).empty(), "two templates that fit the budget evicted one"); + order.Touch(a); + order.Touch(b); + const auto evicted = order.Insert(c, 100); + Require(evicted.size() == 1 && evicted[0].name.owner == a.owner && evicted[0].name.id == a.id, "insert A, insert B, touch A, touch B, insert C evicted" + Names(evicted) + " instead of A, the least recently used"); + Require(order.Entries() == 2 && order.Bytes() == 200, "the budget does not hold B and C after A was evicted"); + order.Touch(b); + const auto next = order.Insert({4, 7, 4}, 100); + Require(next.size() == 1 && next[0].name.owner == c.owner, "after touching B, the next insert evicted" + Names(next) + " instead of C"); +} + +void StaleTouchAndReplacedTemplate() { + HeapTemplateLru order(200); + Require(order.Insert({1, 5, 1}, 100).empty() && order.Insert({2, 5, 2}, 100).empty(), "two templates that fit the budget evicted one"); + order.Touch({1, 5, 9}); + const auto evicted = order.Insert({3, 5, 3}, 100); + Require(evicted.size() == 1 && evicted[0].name.owner == 1, "a touch naming a template id that is not kept moved the kept template, evicted" + Names(evicted)); + Require(order.Insert({2, 5, 4}, 150).size() == 1 && order.Bytes() == 150 && order.Entries() == 1, "a template replacing the one kept under the same shader and key was charged on top of it"); +} + +void ChargesOwnedArrays() { + ShaderRecompiler::RecompileResult result; + const auto empty = ShaderRecompiler::OwnedBytes(result); + result.imageTableReadRanges.resize(64); + for (auto& ranges : result.imageTableReadRanges) ranges.resize(1024); + const auto readRanges = std::uint64_t{64} * 1024u * sizeof(std::pair); + Require(ShaderRecompiler::OwnedBytes(result) >= empty + readRanges, "a template whose image table read ranges hold " + std::to_string(readRanges) + " bytes was charged " + std::to_string(ShaderRecompiler::OwnedBytes(result) - empty)); + const auto withRanges = ShaderRecompiler::OwnedBytes(result); + result.heapSlotWords.resize(4096); + result.imageTableRanges.resize(4096); + result.imageTablePoison.resize(1024); + const auto arrays = ShaderRecompiler::OwnedBytes(result.heapSlotWords) + ShaderRecompiler::OwnedBytes(result.imageTableRanges) + ShaderRecompiler::OwnedBytes(result.imageTablePoison); + Require(ShaderRecompiler::OwnedBytes(result) >= withRanges + arrays, "a template's heap slot words, image table ranges and poison were not charged"); + result.bindings.resize(8); + for (auto& binding : result.bindings) binding.guestDescriptor.resize(4096); + Require(ShaderRecompiler::OwnedBytes(result) >= withRanges + arrays + 8u * 4096u * sizeof(std::uint32_t), "the guest descriptor words of a template's bindings were not charged"); + const auto bound = ShaderRecompiler::OwnedBytes(result); + for (auto& binding : result.bindings) { + binding.samplerEmbedded.resize(2048); + binding.samplerEmbeddedWords.resize(8192); + } + Require(ShaderRecompiler::OwnedBytes(result) >= bound + 8u * (2048u + 8192u) * sizeof(std::uint32_t), "the embedded sampler vectors of a template's bindings were not charged"); + const auto embedded = ShaderRecompiler::OwnedBytes(result); + result.pushedData.resize(4096); + Require(ShaderRecompiler::OwnedBytes(result) >= embedded + 4096u * sizeof(std::uint32_t), "a template's pushed data was not charged"); +} + +} + +int main() { + try { + LeastRecentlyUsedAcrossShaders(); + StaleTouchAndReplacedTemplate(); + ChargesOwnedArrays(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } + std::cout << "heap template budget tests passed\n"; + return 0; +} diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index a4460e375b3a..cf4330a681e7 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -180,6 +180,123 @@ std::string EncodeBase64(const std::vector& bytes) { } return text; } +std::vector AtVersion55(std::vector bytes) { + Require(bytes.size() > 8u && bytes[4] == 56u); + bytes[4] = 55u; + return bytes; +} + +void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { + struct Profile { + bool gpuResolvedImages; + bool descriptorMemory; + std::uint32_t heapDataUniformDwords; + }; + constexpr std::array profiles{{{false, false, 0u}, {true, true, 0u}, {true, true, 4096u}, {true, true, 16384u}, {true, false, 16384u}, {false, true, 16384u}}}; + for (const auto& profile : profiles) { + ShaderRecompiler::RecompileRequest request{}; + request.target.gpuResolvedImages = profile.gpuResolvedImages; + request.target.descriptorMemory = profile.descriptorMemory; + request.target.heapDataUniformDwords = profile.heapDataUniformDwords; + const auto encoded = serializer.Serialize(request); + const auto replay = serializer.Deserialize(encoded); + Require(replay.request.target.gpuResolvedImages == profile.gpuResolvedImages); + Require(replay.request.target.descriptorMemory == profile.descriptorMemory); + Require(replay.request.target.heapDataUniformDwords == profile.heapDataUniformDwords); + Require(serializer.Serialize(replay.request) == encoded); + auto bytes = DecodeBase64(encoded); + Require(bytes[4] == 63u && bytes.size() > 19u); + bytes.resize(bytes.size() - 19u); + for (const std::uint8_t version : {55u, 54u, 53u, 52u}) { + if (version == 53u) bytes.resize(bytes.size() - 2u); + if (version == 52u) bytes.pop_back(); + bytes[4] = version; + const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; + Require(!older.gpuResolvedImages && !older.descriptorMemory && older.heapDataUniformDwords == 0u); + } + bytes.push_back(0u); + bytes[4] = 63u; + bool truncated = false; + try { + static_cast(serializer.Deserialize(EncodeBase64(bytes))); + } catch (const std::runtime_error& error) { + truncated = std::string_view(error.what()) == "RequestSerializer: truncated data"; + } + Require(truncated); + bytes = DecodeBase64(encoded); + bytes.push_back(0u); + bool trailing = false; + try { + static_cast(serializer.Deserialize(EncodeBase64(bytes))); + } catch (const std::runtime_error& error) { + trailing = std::string_view(error.what()) == "RequestSerializer: unexpected trailing data"; + } + Require(trailing); + } + ShaderRecompiler::RecompileRequest limits{}; + limits.target.gpuResolvedImages = true; + limits.target.descriptorMemory = true; + limits.target.heapDataUniformDwords = 16384u; + ShaderRecompiler::RecompileRequest addressed = limits; + addressed.target.heapDataUniformDwords = 0u; + Require(serializer.Serialize(limits) != serializer.Serialize(addressed)); +} + +void VerifyComputeAcrossVersions(const ShaderRecompiler::RequestSerializer& serializer) { + ShaderRecompiler::RecompileRequest request{}; + request.context.compute = ShaderRecompiler::ShaderComputeStageInfo{}; + request.context.compute->granulatedVgprCount = 13u; + request.context.compute->sharedVgprBlocks = 2u; + request.target.maxImageArrayLayers = 2048u; + request.target.fixedPushSlots = true; + request.target.gpuResolvedImages = true; + request.target.descriptorMemory = true; + request.target.heapDataUniformDwords = 16384u; + const auto encoded = serializer.Serialize(request); + const auto bytes = DecodeBase64(encoded); + Require(bytes.size() > 26u && bytes[4] == 63u); + const auto replay63 = serializer.Deserialize(encoded).request; + Require(replay63.context.compute->granulatedVgprCount == 13u && replay63.context.compute->sharedVgprBlocks == 2u && replay63.target.maxImageArrayLayers == 2048u && replay63.target.fixedPushSlots && replay63.target.gpuResolvedImages && replay63.target.heapDataUniformDwords == 16384u); + auto version57 = bytes; + version57.erase(version57.end() - 6 - 8 - 13, version57.end() - 6 - 8); + version57.pop_back(); + version57[4] = 57u; + const auto replay57 = serializer.Deserialize(EncodeBase64(version57)).request; + Require(replay57.context.compute->granulatedVgprCount == 13u && replay57.context.compute->sharedVgprBlocks == 2u && replay57.target.maxImageArrayLayers == 2048u && replay57.target.fixedPushSlots); + Require(!replay57.target.gpuResolvedImages && !replay57.target.descriptorMemory && replay57.target.heapDataUniformDwords == 0u); +} + +void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializer) { + using Field = bool ShaderRecompiler::SpirvTarget::*; + constexpr std::array fields{&ShaderRecompiler::SpirvTarget::ldsLockFences, &ShaderRecompiler::SpirvTarget::meshWindowBuffer, &ShaderRecompiler::SpirvTarget::waveLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::deviceScopeLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::exactRobustLoads, &ShaderRecompiler::SpirvTarget::robustBufferAccess2, &ShaderRecompiler::SpirvTarget::uniformConstantBuffers}; + const ShaderRecompiler::RecompileRequest defaults{}; + const auto defaultEncoded = serializer.Serialize(defaults); + for (std::size_t chosen = 0; chosen <= fields.size(); ++chosen) { + ShaderRecompiler::RecompileRequest request{}; + for (std::size_t index = 0; index < fields.size(); ++index) request.target.*fields[index] = chosen == fields.size() || index == chosen; + const auto encoded = serializer.Serialize(request); + Require(chosen == fields.size() ? encoded != defaultEncoded : encoded != defaultEncoded && encoded.size() == defaultEncoded.size()); + const auto replay = serializer.Deserialize(encoded); + for (std::size_t index = 0; index < fields.size(); ++index) Require(replay.request.target.*fields[index] == (chosen == fields.size() || index == chosen)); + Require(serializer.Serialize(replay.request) == encoded); + auto bytes = DecodeBase64(encoded); + Require(bytes[4] == 63u && bytes.size() > 19u); + bytes.resize(bytes.size() - 19u); + for (const std::uint8_t version : {55u, 54u, 53u, 52u}) { + if (version == 53u) bytes.resize(bytes.size() - 2u); + if (version == 52u) bytes.pop_back(); + bytes[4] = version; + const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; + for (const auto field : fields) Require(!(older.*field)); + } + for (std::size_t index = 0; index < fields.size(); ++index) { + auto other = request; + other.target.*fields[index] = !(other.target.*fields[index]); + Require(serializer.Serialize(other) != encoded); + } + } +} + } @@ -202,8 +319,10 @@ void VerifyTessellationInstancePatches() { std::string SerializeVersion56(const ShaderRecompiler::RecompileRequest& request) { auto bytes = DecodeBase64(ShaderRecompiler::RequestSerializer{}.Serialize(request)); - Require(bytes.size() > 14u && bytes[4] == 62u); + Require(bytes.size() > 26u && bytes[4] == 63u); bytes.resize(bytes.size() - 6u); + const std::ptrdiff_t compute = request.context.compute.has_value() ? 8 : 0; + bytes.erase(bytes.end() - compute - 13, bytes.end() - compute); bytes[4] = 56u; return EncodeBase64(bytes); } @@ -226,7 +345,7 @@ void VerifyTargetOptions() { Require(replay.request.target.float16WidenNans == widen && replay.request.target.float16NarrowNans == narrow); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 62u && bytes.back() == 0u); + Require(bytes[4] == 63u && bytes.back() == 0u); for (std::size_t missing = 1u; missing <= 6u; ++missing) { auto truncated = bytes; truncated.resize(truncated.size() - missing); @@ -238,6 +357,11 @@ void VerifyTargetOptions() { } Require(rejected); } + const std::ptrdiff_t compute = request.context.compute.has_value() ? 8 : 0; + bytes.erase(bytes.end() - compute - 6 - 13, bytes.end() - compute - 6); + bytes[4] = 62u; + const auto legacy62 = serializer.Deserialize(EncodeBase64(bytes)); + Require(legacy62.request.target.fixedPushSlots == fixed && legacy62.request.target.maxImageArrayLayers == layers && !legacy62.request.target.gpuResolvedImages && !legacy62.request.target.uniformConstantBuffers); bytes.pop_back(); bytes[4] = 57u; const auto legacy57 = serializer.Deserialize(EncodeBase64(bytes)); @@ -760,8 +884,8 @@ int VerifyVersion56Compatibility() { const auto encoded = SerializeVersion56(request); const auto replay = serializer.Deserialize(encoded); Require(replay.request.target.float16DenormPreserve == preserve && replay.request.target.float32FlushToZero == !preserve && replay.request.target.float32DenormPreserve == preserve && replay.request.target.largePixelFunctionLdsBuffer == !preserve && replay.request.target.pixelFunctionStorageDwords == request.target.pixelFunctionStorageDwords); - auto bytes = DecodeBase64(encoded); - Require(bytes.size() >= 8u && bytes[4] == 56u && bytes[5] == 0u && bytes[6] == 0u && bytes[7] == 0u); + auto bytes = AtVersion55(DecodeBase64(encoded)); + Require(bytes.size() >= 8u && bytes[4] == 55u && bytes[5] == 0u && bytes[6] == 0u && bytes[7] == 0u); auto version40 = bytes; version40.pop_back(); version40.pop_back(); @@ -776,7 +900,7 @@ int VerifyVersion56Compatibility() { version40[4] = 40u; const auto replay40 = serializer.Deserialize(EncodeBase64(version40)); Require(!replay40.request.target.float32DenormPreserve && replay40.request.target.float32FlushToZero == !preserve); - for (const std::uint8_t unwritten : {58u, 59u, 60u, 61u, 63u}) { + for (const std::uint8_t unwritten : {58u, 59u, 60u, 61u, 64u}) { auto future = bytes; future[4] = unwritten; bool futureRejected = false; @@ -825,7 +949,7 @@ int VerifyVersion56Compatibility() { const auto pixelEncoded = SerializeVersion56(request); const auto pixelReplay = serializer.Deserialize(pixelEncoded); Require(pixelReplay.request.context.pixel.has_value() && pixelReplay.request.context.pixel->iteratesSamples && pixelReplay.request.context.pixel->positionLocation == ShaderRecompiler::PixelPositionLocation::UpperLeft && pixelReplay.request.context.pixel->sampleLocations == pixel.sampleLocations); - auto pixelBytes = DecodeBase64(pixelEncoded); + auto pixelBytes = AtVersion55(DecodeBase64(pixelEncoded)); const auto marker = std::search(pixelBytes.begin(), pixelBytes.end(), pixel.sampleLocations.begin(), pixel.sampleLocations.begin() + 4); Require(marker != pixelBytes.end() && marker - pixelBytes.begin() >= 2 && *(marker - 1) == 3u && *(marker - 2) == 1u); *(marker - 1) = 4u; @@ -840,7 +964,7 @@ int VerifyVersion56Compatibility() { request.context.pixel = pixel; const auto orderEncoded = SerializeVersion56(request); Require(serializer.Deserialize(orderEncoded).request.context.pixel->sampleOrder == pixel.sampleOrder); - auto version42 = DecodeBase64(orderEncoded); + auto version42 = AtVersion55(DecodeBase64(orderEncoded)); const auto orderOffset = std::search(version42.begin(), version42.end(), pixel.sampleLocations.begin(), pixel.sampleLocations.end()) - version42.begin() + static_cast(pixel.sampleLocations.size() + 1u); Require(version42.end() - version42.begin() > orderOffset + static_cast(sizeof(pixel.sampleOrder)) && version42[static_cast(orderOffset)] == 0x10u); EraseDefaultTargetMerge(version42, orderOffset + static_cast(sizeof(pixel.sampleOrder))); @@ -891,8 +1015,12 @@ int VerifyVersion56Compatibility() { const auto replay35 = serializer.Deserialize(EncodeBase64(version35)); Require(replay35.request.target.spannedWaves == spanned && !replay35.request.target.float32FlushToZero); request.target.spannedAnySubgroup = spanned; - const auto version62 = DecodeBase64(serializer.Serialize(request)); - Require(version62[4] == 62u && version62.back() == (spanned ? 1u : 0u)); + const auto version63 = DecodeBase64(serializer.Serialize(request)); + Require(version63[4] == 63u && version63.back() == (spanned ? 1u : 0u)); + Require(serializer.Deserialize(EncodeBase64(version63)).request.target.spannedAnySubgroup == spanned); + auto version62 = version63; + version62.erase(version62.end() - 6 - 13, version62.end() - 6); + version62[4] = 62u; Require(serializer.Deserialize(EncodeBase64(version62)).request.target.spannedAnySubgroup == spanned); auto version57 = version62; version57[4] = 57u; @@ -1166,6 +1294,11 @@ int VerifyVersion56Compatibility() { request.target.float16WidenNans = false; request.target.float16NarrowNans = false; + VerifyHeapProfile(serializer); + + VerifyKeyedTargetFields(serializer); + VerifyComputeAcrossVersions(serializer); + return 0; } diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 75dcc4b3255b..32c46adf4c1a 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -141,17 +141,18 @@ flowchart LR - [`Recompiler.cpp`](../../core/shader/recompiler/Recompiler.cpp) runs the stages in this order. With `ANYPS5_ENABLE_SPIRV_TOOLS`, the SPIR-V is also validated and optimized with SPIRV-Tools. - `ShaderRecompiler::Recompile` keeps compiled variants in memory, and `ShaderDiskCache` stores them on disk so later runs reuse them. Before the writable cache, a miss is also looked up in read-only prebuilt packs and loose entry folders under `shader_cache/prebuilt`; pack entries are ordinary encoded cache entries behind a sorted key-hash index, validated by magic, compiler source version and index checksum when mapped, and a miss or rejected entry falls through to the writable cache and the compiler. The cache format (`ShaderDiskCache::FormatVersion`) stores, among other things, the finite stencil-reference set, its replay-safety proof and reserved push-data word in the artifact and binding layouts. An entry of any other format, or written by another compiler source version, is rejected. -- The Vulkan pipelines are journaled as well ([`PipelineJournal.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp)): a graphics pipeline the store builds (`CachedPipeline`) or a compute pipeline a dispatch builds is appended to `pipelines.journal` next to the shader cache entries, as the materialized result of each stage (the specialized SPIR-V, bindings and push constants, through `ShaderDiskCache::EncodeResult`) plus the recipe the pipeline was built from (`GraphicsPipelineRecipe`: the stages' identities, vertex input layout, descriptor set layout keys and the state fields the `Pipeline` constructor reads, `CanonicalPipelineState`). When a `VulkanDevice` is created, the journal is loaded and its pipelines are built on a pool of `hardware_concurrency() / 2` threads (`APS5_PIPELINE_JOURNAL_THREADS`) while the title loads. The load parses the file a record at a time and keeps it open, and a replay thread reads an entry's modules from it when it builds that entry (a record that no longer reads back as loaded rejects the entry), so the replay holds the modules of the entries being built rather than the file, so the first draw or dispatch of a configuration seen on an earlier run finds its pipeline resident. The pipeline stores key on `RecompileResult::Identity`, a hash of the module words, specialization constants, subgroup width and bindings that is the same on every run (`SharedSpirv::ContentHash`, computed once per shared module), rather than on the process-lifetime variant ids; compute pipelines and their journal modules key on `DescribedPipelineIdentity` instead, the same hash with the element count of image, storage image and sampler table bindings left out, since `DescribeSetLayouts` gives those tables a fixed capacity and two results that differ only in a table's size build the same pipeline. A graphics pipeline is built outside the store's mutex, so the replay threads and the queue workers build in parallel. A draw that arrives before its replayed entry builds the pipeline itself; the first inserted wins. A replayed entry enters the store at its least recently used end and a full store takes none, so the title's own pipelines are never evicted for a replayed one, and the optimized relink of a replayed pipeline (`OptimizedPipeline::Schedule`) waits for the first draw that binds it, so the relink thread serves the title's pipelines first. A device created without a window starts its replay at its first draw or dispatch rather than at creation, since `Driver::AttachWindow` usually replaces it before the title draws. The journal records a pipeline once (modules and recipes are deduplicated by content), keeps at most `APS5_PIPELINE_JOURNAL_MAX_MIB` (1024), replays the last `APS5_PIPELINE_JOURNAL_ENTRIES` recorded (4096, the pipeline store's largest bound: a replayed pipeline that finds the store full grows its bound from 1024 instead of being dropped), and is disabled with `APS5_NO_PIPELINE_JOURNAL=1` or without a shader cache directory. The file header names the device (`PipelineJournalDeviceFingerprint`, the properties the driver's pipeline cache file is named by), so a journal written for another GPU or driver is started over rather than replayed; appends and reads hold `pipelines.journal.lock` against another process sharing the directory, and a device cancels its replay before it is replaced (`PrepareForReplacement`) or destroyed, so a replaced headless device never inserts entries the window's device then sweeps. `APS5_PROFILE_DRAW=1` prints a `[pipeline-journal]` summary when the replay finishes and at teardown. +- The Vulkan pipelines are journaled as well ([`PipelineJournal.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp)): a graphics pipeline the store builds (`CachedPipeline`) or a compute pipeline a dispatch builds is appended to `pipelines.journal` (`pipelines-heap.journal` under `GpuHeapEnabled`, so the two binding models never replay each other's pipelines) next to the shader cache entries, as the materialized result of each stage (the specialized SPIR-V, bindings and push constants, through `ShaderDiskCache::EncodeResult`) plus the recipe the pipeline was built from (`GraphicsPipelineRecipe`: the stages' identities, vertex input layout, descriptor set layout keys and the state fields the `Pipeline` constructor reads, `CanonicalPipelineState`). When a `VulkanDevice` is created, the journal is loaded and its pipelines are built on a pool of `hardware_concurrency() / 2` threads (`APS5_PIPELINE_JOURNAL_THREADS`) while the title loads. The load parses the file a record at a time and keeps it open, and a replay thread reads an entry's modules from it when it builds that entry (a record that no longer reads back as loaded rejects the entry), so the replay holds the modules of the entries being built rather than the file, so the first draw or dispatch of a configuration seen on an earlier run finds its pipeline resident. The pipeline stores key on `RecompileResult::Identity`, a hash of the module words, specialization constants, subgroup width and bindings that is the same on every run (`SharedSpirv::ContentHash`, computed once per shared module), rather than on the process-lifetime variant ids; compute pipelines and their journal modules key on `DescribedPipelineIdentity` instead, the same hash with the element count of image, storage image and sampler table bindings left out, since `DescribeSetLayouts` gives those tables a fixed capacity and two results that differ only in a table's size build the same pipeline. A graphics pipeline is built outside the store's mutex, so the replay threads and the queue workers build in parallel. A draw that arrives before its replayed entry builds the pipeline itself; the first inserted wins. A replayed entry enters the store at its least recently used end and a full store takes none, so the title's own pipelines are never evicted for a replayed one, and the optimized relink of a replayed pipeline (`OptimizedPipeline::Schedule`) waits for the first draw that binds it, so the relink thread serves the title's pipelines first. A device created without a window starts its replay at its first draw or dispatch rather than at creation, since `Driver::AttachWindow` usually replaces it before the title draws. The journal records a pipeline once (modules and recipes are deduplicated by content), keeps at most `APS5_PIPELINE_JOURNAL_MAX_MIB` (1024), replays the last `APS5_PIPELINE_JOURNAL_ENTRIES` recorded (4096, the pipeline store's largest bound: a replayed pipeline that finds the store full grows its bound from 1024 instead of being dropped), and is disabled with `APS5_NO_PIPELINE_JOURNAL=1` or without a shader cache directory. The file header names the device (`PipelineJournalDeviceFingerprint`, the properties the driver's pipeline cache file is named by), so a journal written for another GPU or driver is started over rather than replayed; appends and reads hold `pipelines.journal.lock` against another process sharing the directory, and a device cancels its replay before it is replaced (`PrepareForReplacement`) or destroyed, so a replaced headless device never inserts entries the window's device then sweeps. `APS5_PROFILE_DRAW=1` prints a `[pipeline-journal]` summary when the replay finishes and at teardown. - A compute shader whose LDS plus its lock dword exceeds the host's `maxComputeSharedMemorySize` is not given a `Workgroup` array. `Recompile` sets `ShaderInfo::sharedMemoryBytes` for it and the SPIR-V backend addresses the LDS in a coherent storage buffer at descriptor set 1 (`WorkgroupMemoryDescriptorSet`), with a slice of `RecompileResult::workgroupMemoryDwords` per workgroup, indexed by `WorkgroupID` and `NumWorkGroups`. `VulkanDevice` keeps one such buffer, sized from the dispatch dimensions, and binds it after the resource set; programs that fit keep using shared memory. - `Driver::RegisterShader` splits shader preparation in two. `PlanRegistered` runs on the registering guest thread: it validates the registers and entry point, decodes the code and builds the recompile request, so invalid registrations still fail there. The RDNA to IR translation and resource plan (`PrepareShader`) run on a background pool of `hardware_concurrency() / 2` threads (at least 2, 64 MiB stacks), which `Driver::stop` joins when it closes the pool. - A thread that needs the GPU mutex, the committer's next item or the end of the committer's queue spins before it blocks (`HandoffSpin.hpp`): `GpuMutexType::lock` retries `try_lock` for the window, the committer polls its item count, and `DrawPipeline::Drain` polls it for twice the window, so a hand-off that completes within the window costs no kernel wake-up. The window is 150 us when the process may run on more than 8 logical processors (its affinity mask, via `CpuTopology`) and 0 otherwise, where the spinning threads would compete with the holder; `APS5_HANDOFF_SPIN_US=` sets it (0 turns it off, at most 10000). Ordering and the lock's semantics are unchanged. - Queue 0's packet worker decodes, captures and prepares a draw and hands its recording (`Graphics::Draw` under the GPU lock) to a committer thread in [`DrawPipeline.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp), so the next packet is decoded while the previous draw is recorded. Each queued item carries the guest ranges it will write (`DrawWriteRanges`: written buffers and storage images, color targets with their DCC and CMASK, depth and stencil). A later packet that reads or writes one of those ranges, or that the pipeline can't order, drains it first; labels, submission ends, buffer fills and DMA packets are queued as items instead. With `APS5_PIPELINE_DISPATCH=1` (off by default), a `DISPATCH_DIRECT` whose dispatch-cache entry hits with a recipe is queued as an item too, carrying the dispatch's written buffers and storage images (`DispatchWriteRanges`); the capture and the cache lookup stay on the worker and the recipe is recorded on the committer. A dispatch still drains when its lookup misses, when what it reads overlaps a write still pending, when the hit is verified against data or when its writes cannot be ranged (bindless access, GDS, fault buffer). An indirect draw resolved on the CPU (its records read by the worker) drains only when its records or its count overlap a queued write; the records it draws inline drain first, and its last drawn record is queued like a direct draw (`APS5_NO_PIPELINED_INDIRECT=1` drains at every indirect draw). An exception thrown by a commit is rethrown on the worker at its next enqueue or drain, as an inline draw error would be. On by default; `APS5_PIPELINED_DRAWS=0` records every draw inline, and `APS5_EXACT_DRAW_WRITES=0` widens the color and depth ranges to estimates. - A dispatch's resource build runs stage A (binding plan, buffers, descriptor set) without the GPU lock and stage B (image lookups) under it. Between them `VulkanDevice::presync` waits, still without the lock, for recorded work that writes a surface stage B would read on the CPU and for recorded work that writes the DCC keys of an image the dispatch binds (`ShaderResources::PresyncSurfaces`), so the locked `WaitForKeyWriters` finds nothing pending to synchronize with. A key range is waited for only when recorded work writes it, the key-store memo does not give its value (`DccKeyWritersPending`, without the mutex) and the pending stores do not give it either (`DccKeyWriterNeedsSync`, under the mutex, the same test `WaitForKeyWriters` makes before it synchronizes). Stage A's own key scan runs before that wait, and stage B compares it with the keys it reads under the lock as before. `APS5_NO_DCC_PRESYNC=1` leaves the key ranges out; `APS5_NO_PRESYNC=1` disables the whole pre-sync. - `APS5_DRAW_PIPELINE` (any value turns it on, even `0`; off by default, meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`) takes more of a draw off the worker. A `DrawFinisher` thread runs the second half of a direct pipelined draw (stage materialization, the draw cache insert and the hand-off to the committer) while the worker reads the next packets; the worker drains it before the next draw's cache lookup, before packets other than register writes and draws, and before guest reads, and finishes in place a draw whose stages may write memory (`ProgramWritesMemory`) or write through the BDA page table. The committer skips the storage-image layer scans whose inputs match its last commit (`CommitTrims`), and a resource or storage image proved current keeps its proof for the rest of the collect epoch until `GuestMemory::BreakProofs` (a CPU write, a write-back, a recorded write) moves `ProofSerial`. A draw that continues the open render pass with equal color and depth targets takes the previous draw's resident images and attachment views while the collect epoch, `ProofSerial`, `StorageTexture::PendingSerial`, each image's version and storage cache entry and the depth surface serials are unchanged; `APS5_NO_PASS_ATTACHMENT_MEMO=1` looks them up anew and `APS5_VERIFY_PASS_ATTACHMENTS=1` compares a hit with the full lookup. Color metadata passes go through the pipeline with their write ranges (`PipelinedColorMetadataPassWrites`) instead of draining it. A data-only hit whose shape entry belongs to an older draw replaces that entry in place at the second sight of the same read user words. On Linux the main image's pages get a page table entry, and capture pages are pooled across threads. `APS5_VERIFY_DRAW_PIPELINE=1` runs a full check next to 1 in 64 reused proofs and prints `[epoch-proofs]` counts. +- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 233472 image slots that every image binding kind shares, the first 57 holding each kind's absent descriptor, and 2048 sampler slots, per-draw shader data and flattened SRT in a host-visible data pool the shaders reach by address) instead of per-draw descriptor sets. Without the extension, or when the device's heaps cannot hold those slots, the switch has no effect and every draw and dispatch binds per-draw descriptor sets. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; with the switch on, every stage of every draw is GPU-mode and there is no per-draw fallback. A stage whose compiled module does not map onto the heap (`RequireHeapStageMappable`, called at draw capture and at dispatch), a stage whose plan is ineligible, a stage kind the heap does not take and a draw whose stages come out mixed make the draw or dispatch throw. Registration only skips the pipeline-library prebuild of a stage whose module does not map (`PrebuildStageLibrary`); the failure comes when a draw or dispatch uses the stage. `APS5_GPU_HEAP_EXCLUDE` is a debug aid that sends the stages it names through the per-draw path. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A heap slot holds no reference to its texture, storage image, view or sampler: the owner frees its slots when it is destroyed, and every batch that reads a slot keeps the owner alive through its draw's or dispatch's resources, so a slot is never reused while a batch can still read it. With fewer free image or sampler slots than the margin, the recorder submits its batch at the next draw and evicts the slots no pending batch reads (`TakeSlotPressure`); a stage that still finds no free slot throws. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the data pool and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap throws at its dispatch. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the data pool per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers through addresses in its push data instead of storage buffer descriptors, like vkd3d-proton's root descriptors: up to four records of 64-bit address and byte size map as storage buffers (or as uniform buffers when every access is a scalar load at a constant offset), the rest go to a per-draw overflow block; a draw whose buffers are snapshotted pushes the snapshot addresses. - The shader registry maps a code address to every header registered for that code, in registration order. Static, graphics and rectangle ABI resolution pick the header at the bound address (or one equal to it, `SameHeader`, which also takes a hull header fused by `sceAgcFuseShaderHalves` (type 3) as the registered back half (type 7) it copies, the fused registers aside; graphics ABI resolution then uses the fused header's shader registers); draws and dispatches pick the program by the stage's binary type (`RegisteredProgram`), and a front entry matching both type 2 and type 4 throws. Within a type the last registration wins; re-registering an identical earlier header makes its snapshot current again without preparing it again, and changed code drops the older headers. - The snapshot is published as pending. `SourceHandleFor`, `InvocationFor` and `ShaderPreparationTransaction::Edit` / `Read` wait for the pending job before reading `PreparedShaders`, and rethrow its failure. `APS5_SYNC_SHADER_PREPARE=1` prepares on the registering thread instead. - `APS5_LAZY_SHADER_PREPARE=1` retains registration validation and decoding but discards the temporary plan without queueing preparation. The snapshot is deferred, not pending; draws and dispatches prepare and cache it on first use. A compute or pixel stage's explicit ABI resolution (`ResolveShaderAbi`) plans the stage with the ABI's state, records the ABI and leaves its preparation to the shader's first use, which prepares it with that state (`PreparedShaders::deferredAbis`), so a shader that never draws or dispatches stays unprepared; a graphics-stage ABI is still prepared when it is resolved. This opt-in mode takes precedence over synchronous registration preparation and trades background CPU/memory use for possible first-use stalls; disk caches and shader output are unchanged. -- On devices with graphics pipeline libraries (`SpirvTarget::registrationModules`), a pixel artifact is emitted in registration form: the buffer V# words, image modes, swizzles and mip ranges, depth-compare state and export mappings it used to specialize on per draw are read at run time (image `ResourceMetadata` and a few state dwords in the shader data), descriptor heaps keep every element in place (an unused one gets a null or placeholder descriptor), and the pixel stage's bindings live in descriptor set 1 so each stage's library depends only on its own set layout (`INDEPENDENT_SETS`). A vertex artifact is emitted specialized: in registration form each vertex buffer load would decode the V# stride, swizzle, bounds mode and format at run time for every vertex, so its pre-rasterization library is built at its first draw instead. An artifact above `registrationWordLimit` SPIR-V words is re-emitted specialized, and `CompiledShaderArtifact::registrationModule` records which form it has. For artifacts in registration form, `RegistrationResult` materializes the module once, and `PrebuildStageLibrary` builds its fragment-shader library on a separate pool of `max(2, hardware_concurrency() / 2)` threads (`APS5_PREBUILD_THREADS` sets the count, at least 1) with a fixed default state, pairing it with a stub vertex stage. A later draw with that state finds the fragment-shader library in the store. Ahead-of-time dispatch resolution (`resolveGroupAhead` in [`DispatchAhead.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp)) scans the upcoming dispatch run up to the next wait or synchronization packet, moves still-pending registered compute shaders to the front of the registration preparation queue (`PrioritizeRegistrationPreparation`) and queues preparation (`SubmitRegistrationPreparation`) for registered compute shaders that have no prepared entries yet (such as under `APS5_LAZY_SHADER_PREPARE=1`) with the previewed register state and entry offset; when a dispatch resolved ahead misses the dispatch cache in [`Dispatch.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp), `PrebuildComputePipeline` is submitted to the same `APS5_PREBUILD_THREADS` pool so the compute `VkPipeline` is built before the worker reaches the packet. +- On devices with graphics pipeline libraries (`SpirvTarget::registrationModules`), a pixel artifact is emitted in registration form: the buffer V# words, image modes, swizzles and mip ranges, depth-compare state and export mappings it used to specialize on per draw are read at run time (image `ResourceMetadata` and a few state dwords in the shader data), descriptor heaps keep every element in place (an unused one gets a null or placeholder descriptor), and the pixel stage's bindings live in descriptor set 1 so each stage's library depends only on its own set layout (`INDEPENDENT_SETS`). A vertex artifact is emitted specialized: in registration form each vertex buffer load would decode the V# stride, swizzle, bounds mode and format at run time for every vertex, so its pre-rasterization library is built at its first draw instead. A vertex artifact for a descriptor heap stage (`gpuResolvedImages` with `descriptorMemory`) stays in registration form, because the heap stage shares one template module across draws and reads those words from the heap. An artifact above `registrationWordLimit` SPIR-V words is re-emitted specialized, and `CompiledShaderArtifact::registrationModule` records which form it has. For artifacts in registration form, `RegistrationResult` materializes the module once, and `PrebuildStageLibrary` builds its fragment-shader library on a separate pool of `max(2, hardware_concurrency() / 2)` threads (`APS5_PREBUILD_THREADS` sets the count, at least 1) with a fixed default state, pairing it with a stub vertex stage. A later draw with that state finds the fragment-shader library in the store. Ahead-of-time dispatch resolution (`resolveGroupAhead` in [`DispatchAhead.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp)) scans the upcoming dispatch run up to the next wait or synchronization packet, moves still-pending registered compute shaders to the front of the registration preparation queue (`PrioritizeRegistrationPreparation`) and queues preparation (`SubmitRegistrationPreparation`) for registered compute shaders that have no prepared entries yet (such as under `APS5_LAZY_SHADER_PREPARE=1`) with the previewed register state and entry offset; when a dispatch resolved ahead misses the dispatch cache in [`Dispatch.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp), `PrebuildComputePipeline` is submitted to the same `APS5_PREBUILD_THREADS` pool so the compute `VkPipeline` is built before the worker reaches the packet. - A draw or dispatch whose state matches no artifact prepared at registration (a title that builds its static ABI state itself, without `sceAgcDriverResolve*Abi`) gets one prepared at use by `SourceHandleFor` or `InvocationFor`, logged once per artifact and kept in the snapshot for the next use. - A stage that `sceAgcDriverResolve*Abi` cannot prepare for the state the title creates its pipeline with (a compute shader that calls user-data pointers, a descriptor the resource plan rejects) is left to its first use like a stage deferred at registration: `ResolveShaderAbi` and `PrepareGraphicsStages` catch the failure inside their own preparation transaction, so the `ShaderPreparationScope` the title's call runs in still commits, log it once per shader, mark the shader deferred and record the ABI key, so a repeated call prepares nothing; `ResolvePreparedGraphics` skips a deferred stage's rectangles until a draw has prepared it. A draw or dispatch that cannot prepare the stage either fails as before. Driver failures and `ProcessShutdown` still propagate from the ABI call. A stage whose registration preparation stored a failure is logged once with that reason and marked deferred (`DeferFailedRegistration`); the draw or dispatch that uses the stage rethrows the stored failure. - A compute shader whose `s_swappc_b64` calls a user-data pointer cannot be linked at registration, because the callee's address is only known at dispatch. `InvocationFor` in [`ShaderRegistry.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp) reads each callee from guest memory, appends one copy per call after the caller (`LinkUserDataCalls`) and prepares that linked code, so a different callee gets its own prepared entry. diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 4543bf7af1a8..c0ca21af0c19 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -41,6 +41,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_EXACT_RCP` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvAlu/SpirvAluEmitterReciprocal.cpp` | | emits `v_rcp_f32` and `v_rcp_iflag_f32` as the RDNA hardware reciprocal (bit-exact for normal inputs and results) instead of the driver's division; adds about 13k SPIR-V words to each shader that uses them | | `APS5_FAST_F32` | presence | `core/shader/recompiler/Translation/src/DispatchInstructions.cpp` | | set to anything but 0, compiles f32 arithmetic with the host's float rules instead of RDNA's: no emulated denormal flush and no RDNA NaN payloads, which differ only for denormals and NaN results; the shader disk cache keeps the two modes apart | | `APS5_GATHER_CONST` | integer | `core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp` | | integer every non-depth gather returns in all four texels instead of the sampled value | +| `APS5_HEAP_NO_CACHE` | string | `core/shader/recompiler/HeapCacheSwitch.hpp` | | bypasses caches by name for debugging and verification: `all`, `heap` (the GPU heap caches) or a comma-separated list of names such as `templates`, `template-front`, `slots`, `stage-data`, `table-map`, `push-image`, `result-memo`, `draw-key`, `draw-recipe`; output-neutral, so it is kept out of the shader cache key | | `APS5_IMAGE_TABLE_KEY_SCAN` | integer | `core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp` | 256 | number of image-table entries the key scan examines | | `APS5_IMAGE_TABLE_STRICT` | string | `core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp` | | sets image-table materialization to its strict form; 0 leaves it off | | `APS5_NO_ATOMIC_BARRIER` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvFormatConvert.cpp` | | drops the device-scope acquire/release memory barrier emitted after atomics | @@ -57,7 +58,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_PERF_DOMINATOR_TREE` | presence | `core/shader/recompiler/ControlFlow/src/Structurizer.cpp` | | computes the structurizer's dominator and post-dominator sets with the set fixpoint instead of a dominator tree, walks every selection construct instead of testing its members by dominance, and tests every block against each construct when checking the structured constructs instead of walking the construct | | `APS5_NO_PERF_DOM_INTERSECTION` | presence | `core/shader/recompiler/ControlFlow/src/Structurizer.cpp` | | computes dominator intersections into a fresh vector instead of intersecting in place | | `APS5_NO_PERF_ITERATION_SELECTION` | presence | `core/shader/recompiler/ControlFlow/src/Structurizer.cpp` | | recomputes the post-dominator sets when finding a loop's iteration-selection merge instead of reusing them | -| `APS5_NO_RESULT_MEMO` | presence | `core/shader/recompiler/Recompiler.cpp` | | materializes a fresh result for every recompile instead of reusing the result memo | +| `APS5_NO_RESULT_MEMO` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | materializes a fresh result for every recompile instead of reusing the result memo | | `APS5_NO_SCOPED_VECTOR_WINDOW` | presence | `core/shader/recompiler/Translation/src/InstructionTranslator.cpp` | | keeps a program's vector registers in its relative-addressing window in every block instead of only in the blocks between relative accesses | | `APS5_NO_SRT_TAPE` | presence | `core/shader/recompiler/Optimization/src/SrtWalker/SrtTape.cpp` | | runs the runtime-source walk of a plan in the IR evaluator instead of the compiled tape | | `APS5_NO_TABLE_RESOLUTION_REUSE` | presence | `core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp` | | stops a result memo miss from reusing an unchanged image table's resolution, so the table is resolved again | @@ -74,6 +75,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_TRACE_BDA` | presence | `core/shader/recompiler/Optimization/src/ResourceTracker.cpp` | | prints the first few accesses that make a program take the address-based path | | `APS5_TRACE_BUFFER_WRITTEN` | presence | `core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp` | | prints how many guest buffer elements a program may store to and how many it only loads | | `APS5_TRACE_IMAGE_TABLE` | presence | `core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp` | | traces image-table resolution | +| `APS5_VERIFY_IDENTITY` | presence | `core/shader/recompiler/Recompiler.cpp` | | recomputes a shader result's pipeline identity on every lookup of its kept identity and fails if they differ | | `APS5_VERIFY_MASKED_RESULT_MEMO` | presence | `core/shader/recompiler/Recompiler.cpp` | | also materializes every patched result memo hit, prints the first twenty whose patched result differs and counts them in the result memo report of `APS5_PROFILE_DRAW` | | `APS5_VERIFY_SRT_COMPACT` | presence | `core/shader/recompiler/Optimization/src/SrtWalker/SrtDescriptorEvaluation.cpp` | | walks every SRT descriptor a second time through the IR evaluator and throws when the two walks differ | | `APS5_VERIFY_SRT_TAPE` | presence | `core/shader/recompiler/Optimization/src/SrtWalker/SrtTape.cpp` | | walks a plan's runtime sources a second time through the evaluator, adopts its answers where the two differ and prints the first twenty differences | @@ -111,7 +113,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_ADDRESS_COPY_MAX_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 64 | upper bound in MiB on the guest memory one address-based build copies; exceeding it aborts | | `APS5_ALL_BUFFERS_WRITTEN` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | notes every shader buffer element as written, as before bufferWritten existed | | `APS5_ASSERT_GPU_LOCK` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp` | | aborts when a guarded path is reached without holding GuestMemory::GpuMutex, or when the unwatch hook would take it while the thread holds the host imports mutex without it; builds without NDEBUG always check the second | -| `APS5_ASYNC_DRAW_COMPILE` | boolean | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Diagnostics.cpp` | unset | when set to a value other than 0, a draw or dispatch whose shader is not prepared yet, or whose specialization for the captured resources is not ready, is skipped while the work runs on the library prebuild pool, and a later draw or dispatch of the same shader and resources uses the result; unset prepares and specializes every draw and dispatch before it records | +| `APS5_ASYNC_DRAW_COMPILE` | boolean | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Diagnostics.cpp` | unset | when set to a value other than 0, a draw or dispatch whose shader is not prepared yet, or whose specialization for the captured resources is not ready, is skipped while the work runs on the library prebuild pool, and a later draw or dispatch of the same shader and resources uses the result; with `APS5_GPU_HEAP=1` a heap stage whose binding shape has no compiled heap template yet is skipped while the template is built there, and later draws of that shape use it; unset prepares and specializes every draw and dispatch before it records | | `APS5_ATOMIC_STAGE_MAX_KIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 1024 | size cap in KiB on an atomic shader element covered by device-local staging | | `APS5_BACKGROUND_COMPILE_KIB` | integer | `core/libs/prx/libSceAgcDriver/Execution/include/CompileBudget.hpp` | 8192 | KiB of SPIR-V that compute pipelines built ahead of their dispatch (dispatch prebuilds and the pipeline journal's replay) may be compiling at once; a build that does not fit waits, one larger than the limit builds alone, and 0 builds them one at a time. Dispatches that need a pipeline now are not limited | | `APS5_BARRIER_VALIDATE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | counts the barriers a hazard-tracking validator would emit and skip, by class and hazard kind | @@ -208,12 +210,16 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_FULL_BARRIERS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records every barrier instead of merging redundant ones | | `APS5_GPU_CHECKPOINTS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | attaches device diagnostic checkpoints through VK_NV_device_diagnostic_checkpoints, or buffer markers through VK_AMD_buffer_marker on a device without it | | `APS5_GPU_COPY_MAX_KIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 1024 | size cap in KiB on a descriptor sub-range copied through the GPU path, larger ones staying on the CPU | +| `APS5_GPU_HEAP` | boolean | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | unset | when set to a value other than 0, binds the sampled and storage images and samplers of eligible stages through the device's VK_EXT_descriptor_heap heaps; without the extension it does nothing | +| `APS5_GPU_HEAP_EXCLUDE` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | | debug aid: comma list of stage classes that take the per-draw path while the GPU heap stays on: stage names (compute, vertex, hull, domain, geometry, pixel, local, mesh), or tables, storage or sampled for stages whose resource plan has image tables, storage images or sampled images; a draw with an excluded stage takes the per-draw path for all its stages, decided before any stage is built | | `APS5_GPU_NO_WRITEBACK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | skips writing GPU results back into guest memory | | `APS5_GPU_WAIT_TIMEOUT_MS` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp` | 1000 | milliseconds a GPU wait may run before a warning is printed | | `APS5_GROUP_CAPTURE_ALL_QUEUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp` | | resolves group-ahead capture on queue 0 as well | | `APS5_HANDOFF_SPIN_US` | integer | `core/libs/prx/libSceAgcDriver/Execution/include/HandoffSpin.hpp` | | microseconds a thread spins for a handed-off draw's work or for the GPU mutex before blocking, clamped to 0..10000; unset spins 150 us when the process has more than 8 usable processors and not at all otherwise | | `APS5_HEADLESS_PIPELINE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | loads the pipeline cache file on a device without a window too; `agc_frame_replay` sets it by default and clears it with `--cold-pipelines`, including inherited values | | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | +| `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first; 0 means 1 MiB, and values other than an integer from 0 through 1048576 stop the driver with an error naming the variable | +| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a nearly full heap submits the open batch at the next draw or dispatch and evicts the slots that batch no longer uses; values other than an integer from 0 through 4294967295 stop the driver with an error naming the variable | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | | `APS5_HOOK_LOCKED_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | keeps the flush hook's pending-write wait under the GpuMutex | @@ -280,6 +286,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_DCC_PRESYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | leaves the DCC key ranges out of the surfaces a build pre-syncs, so only the surface itself waits for its producer | | `APS5_NO_DEFERRED_DESTRUCTION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | on MoltenVK, destroys buffers and frees device memory as soon as the driver releases them, instead of while the graphics queue is idle (KhronosGroup/MoltenVK#2876) | | `APS5_NO_DCC_WORD_SCAN` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp` | | restores the byte-by-byte DCC key scan instead of the word-at-a-time compare | +| `APS5_EMBEDDED_SAMPLER_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device limit | caps the samplers the GPU heap embeds in pipelines below the device's maxDescriptorHeapEmbeddedSamplers; constant samplers past it read a sampler heap slot at a fixed offset (testing); values other than an integer from 0 through 4294967295 stop the driver with an error naming the variable | | `APS5_NO_DEFERRED_EVICTION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | destroys displaced resource-cache entries under the mutex instead of deferring them to the open batch | | `APS5_NO_DEFERRED_SETTLES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | settles watched private host imports as they open instead of through the deferred block-settling path (Windows only) | | `APS5_NO_DEPTH_PLANE_REUSE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp` | | rebuilds the shader resources of every draw that samples a copy of several depth planes instead of reusing a cached set and repeating the copy's lookup | @@ -292,16 +299,16 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_DISPATCH_MOVE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | leaves a dispatch-cache hit from moving its read-only buffers into the template, so it prepares the dispatch again; also off when APS5_NO_TEMPLATE_DATA_REFRESH is set | | `APS5_NO_DISPATCH_OVERLAP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records every dispatch of a compute ring with its own leading and trailing barrier, also those the title left unordered after the ring's previous dispatch, as before | | `APS5_NO_DISPATCH_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | builds no dispatch recipes, so dispatch-cache hits repeat the recorded work | -| `APS5_NO_DRAW_DATA_HITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | disables draw-cache hits that differ only in ShaderData words | +| `APS5_NO_DRAW_DATA_HITS` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | disables draw-cache hits that differ only in ShaderData words | | `APS5_NO_DRAW_INPUTS_IN_PLACE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | copies draw vertex and index ranges instead of binding them in place from host imports, on any device; wins over `APS5_DRAW_INPUTS_IN_PLACE` | -| `APS5_NO_DRAW_KEY` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | registers no draw key, so every draw decodes its programs instead of hitting the draw cache | +| `APS5_NO_DRAW_KEY` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | registers no draw key, so every draw decodes its programs instead of hitting the draw cache | | `APS5_NO_DRAW_KEY_TRIM` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | keys the render target and index ranges into the draw resource key instead of repeating the alias checks on a hit | | `APS5_NO_DRAW_PRECHECK` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPrecheck.cpp` | | disables the draw precheck that rejects empty or invalid draws early | -| `APS5_NO_DRAW_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | builds no draw recipes, so draw-cache hits repeat the recorded stages | +| `APS5_NO_DRAW_RECIPE` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | builds no draw recipes, so draw-cache hits repeat the recorded stages | | `APS5_NO_DRAW_RELOCATION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp` | | disables draw relocation, which rewrites a draw's moved user words from a learned variant instead of preparing the draw again | -| `APS5_NO_DRAW_RESOURCE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | builds every draw's shader resources instead of reusing a cached identical build | -| `APS5_NO_DRAW_SRT_ENTRIES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | disables the draw cache's SRT entries, so every draw decodes its programs | -| `APS5_NO_DRAW_STAGE_DATA_HITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | disables draw-cache hits that differ only in a stage's ShaderData words | +| `APS5_NO_DRAW_RESOURCE_CACHE` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | builds every draw's shader resources instead of reusing a cached identical build | +| `APS5_NO_DRAW_SRT_ENTRIES` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | disables the draw cache's SRT entries, so every draw decodes its programs | +| `APS5_NO_DRAW_STAGE_DATA_HITS` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | disables draw-cache hits that differ only in a stage's ShaderData words | | `APS5_NO_DRAW_STAGING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | binds a recorded draw's written and atomic buffer elements in place in host memory instead of staging them through a device-local buffer | | `APS5_NO_DYNAMIC_COLOR_WRITE_MASK` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp`, `core/libs/prx/libSceAgcDriver/tests/Recorder.cpp` | | keeps color write masks in the graphics pipelines instead of setting them per draw through `VK_EXT_extended_dynamic_state3` | | `APS5_NO_EARLY_DRAW_KEY` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | builds a pipelined draw's resource-cache key on the draw committer, instead of on the draw finisher before queueing it (a draw that queue worker 0 finishes always leaves the key to the committer) | @@ -367,7 +374,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_MESH_INLINE_FUNCTIONS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | keeps a mesh program's helper functions `DontInline` on NVIDIA's proprietary driver instead of asking the driver to inline every function | | `APS5_NO_MESH_WINDOW_BUFFER` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | keeps a mesh program's relative-addressing window in function arrays on NVIDIA's proprietary driver instead of moving it to a storage buffer | | `APS5_NO_MOVED_BUFFERS_IN_PLACE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | rebuilds the shader resources of a draw whose read-only buffer moved into a range that recorded GPU work still writes, instead of reading the buffer through its host import on the cached set | -| `APS5_NO_MOVED_BUFFER_TEMPLATES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | keys the full descriptor words of read-only guest buffers instead of allowing a hit when they move | +| `APS5_NO_MOVED_BUFFER_TEMPLATES` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | keys the full descriptor words of read-only guest buffers instead of allowing a hit when they move | | `APS5_NO_OBSERVATION_GUARD` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp` | | observes every validated range, not only the ranges whose flush hook waited | | `APS5_NO_OPPORTUNISTIC_REAP` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | skips retiring already-finished batches before a submit | | `APS5_NO_ORDERED_WAITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitStatistics.cpp` | | bumps the collect epoch at every memory wait instead of skipping a wait on an unchanged flag an earlier wait already ordered | @@ -404,7 +411,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_RESIDENT_LINEAR` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | drops the residency of linear color targets, so a target whose address has a host import, or whose import a draw would make, is copied in and out again | | `APS5_NO_RESIDENT_PRESENT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | always presents through guest memory instead of the resident image | | `APS5_NO_RESIDENT_TARGETS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | copies every render target in and out again instead of keeping it resident | -| `APS5_NO_RESOURCE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | disables the shared resource cache, so every dispatch builds its resources fresh | +| `APS5_NO_RESOURCE_CACHE` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | disables the shared resource cache, so every dispatch builds its resources fresh | | `APS5_NO_REWATCH_UNDER_IMAGES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | keeps a settled Windows import compared while a live storage image overlaps it, instead of returning it to the write watch and proving the image's rewatched blocks unchanged by comparison (Windows only) | | `APS5_NO_RUN_MEMO` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | walks the lease for a host import's run of ranges on every lookup instead of reusing the bounds found for the same lease snapshot and import window block | | `APS5_NO_SAMPLED_FROM_STORAGE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | keeps every sampled texture a CPU snapshot instead of viewing the surface's storage image | @@ -412,7 +419,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_SAMPLER_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | creates a sampler per binding instead of caching them | | `APS5_NO_SEPARATE_QUEUED_LABELS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | lets a queued label enter the recorded table and replace a recorded entry of its dword | | `APS5_NO_SETTLED_INDIRECT_READ` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | keeps an indirect draw whose records no unfinished batch writes on the GPU-side path instead of reading the records on the CPU | -| `APS5_NO_SHAPE_MEMO` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | looks up every draw's resident targets and pipeline anew instead of repeating the ones an earlier draw of the same register shape used | +| `APS5_NO_SHAPE_MEMO` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | looks up every draw's resident targets and pipeline anew instead of repeating the ones an earlier draw of the same register shape used | | `APS5_NO_SHARED_FAULT_SLOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp` | | gives every BDA resource object its own full-size fault buffer for its whole life instead of a slot from the device's shared fault chunks that an idle cached object gives back (a 32-byte slot when its programs can write only the fault report) | | `APS5_NO_SHARED_GDS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp` | | keeps the GDS in a private guest mapping, which the GPU cannot import, instead of anonymous shared memory on an integrated GPU with host imports; DMA_DATA into the GDS behind GPU writes to it then drains, and DMA_DATA out of it is read on the CPU | | `APS5_NO_SINGLE_PASS_COLLECT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp` | | walks the written pages once without clearing them and, when any were written, a second time clearing them, instead of one cleared pass | @@ -438,13 +445,13 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_TEMPLATE_DATA_REFRESH` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | keys the ShaderData and FlattenedSrt words into compute keys instead of refreshing a template's data buffers | | `APS5_NO_TEXTURE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | builds every texture and storage-image object fresh instead of caching it | | `APS5_NO_TEXTURE_HASH` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | finds texture-cache entries by scanning the list instead of the hash index | -| `APS5_NO_TIMELINE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | leaves timeline semaphores off, so drains wait under the mutex | +| `APS5_NO_TIMELINE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | leaves timeline semaphores off, so drains wait under the mutex; device creation fails with `APS5_GPU_HEAP`, whose slot eviction needs them | | `APS5_NO_UNIT_SHADOW` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp` | | makes every unit shadow primitive inert | | `APS5_NO_UNLOCKED_DEVICE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp` | | loads the device and runs a dispatch under the GPU mutex instead of using an unlocked device | | `APS5_NO_UNLOCKED_DRAIN` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp` | | keeps the GPU mutex held while draining a packet instead of the unlocked drain | | `APS5_NO_UNLOCKED_VALIDATE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchLookup.cpp` | | keeps the dispatch-cache mutex held while validating a cache entry | | `APS5_NO_UNREGISTERED_DROP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | stores a storage image's pending results even when its memory is no longer registered, instead of dropping them | -| `APS5_NO_VALIDATE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | validates every draw instead of serving the validation memo | +| `APS5_NO_VALIDATE_CACHE` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | validates every draw instead of serving the validation memo | | `APS5_NO_VALIDATE_SKIP` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp` | | syncs every pending write instead of skipping validation on written-element evidence | | `APS5_NO_VOUCHED_VALIDATION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp` | | validates a cached draw or dispatch through its per-run checks instead of its table block's vouch | | `APS5_NO_WAIT_OVERLAP_SUBMIT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp` | | disables the unlocked wait that submits recorded work while overlapping writes are open | @@ -480,6 +487,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_PROFILE_DRAW` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp` | | prints the per-phase driver and draw timing totals | | `APS5_PROFILE_GPU` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records the GPU time of recorded work by key from batch timestamps | | `APS5_PROFILE_GPU_DRAWS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp`, `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | with APS5_PROFILE_GPU, records the GPU time of each recorded draw by its fragment program's variant id and prints a [drawvariant] line with the code address behind each variant id once (draws that do not use a recipe only; the [gputime] line labels each `draw 0x`, the id [drawvariant] prints, and the ranges share the batch's query cap) | +| `APS5_PUSHED_BUFFER_RECORDS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 16 | test cap on the guest buffer records a heap stage keeps in its push data; the rest go to its per-draw overflow block; values other than an integer from 0 through 16 stop the driver with an error naming the variable | | `APS5_READONLY_DEPTH_BOUNDS_COMPARE` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp` | 0 | `1` enables a read-only GREATER_OR_EQUAL comparison at viewport depth 1 for eligible single-sample D32S8 draws with native depth bounds; read once per process; unset or `0` keeps the normal path | | `APS5_REAP_EACH_PACKET` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/DeferredLabels.cpp` | | reaps deferred labels after every packet | | `APS5_REGISTRATION_PREPARE_COMMIT_GB` | number | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp` | half of physical RAM | stops preparing newly registered shaders ahead of use when process-private memory reaches this GiB budget; `0` disables registration-time preparation | @@ -581,6 +589,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_VERIFY_ADDRESS_DRAW_REUSE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | builds the resources of every served read-only address-based draw hit anew, compares its space reuse, BDA table bytes, sampled textures, storage images and set layouts with the hit's, checks that every snapshot lies in a readable range of the hit's table and equals guest memory, and throws on a difference | | `APS5_VERIFY_BDA_TABLES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | checks a reused BDA page table against the one just built | | `APS5_VERIFY_DATA_HITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp` | | recomputes a dispatch data hit and aborts on a disagreement | +| `APS5_VERIFY_DECODE_REUSE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp` | | decodes the vertex stage info of every ring hit again on the finisher and throws when it differs from the info the queue worker kept | | `APS5_VERIFY_DRAW_DATA_HITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | recomputes a draw data hit and aborts on a disagreement | | `APS5_VERIFY_DRAW_ENTRIES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | re-decodes every draw-cache hit through the full path and checks it | | `APS5_VERIFY_DRAW_PIPELINE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | with `APS5_DRAW_PIPELINE` set, runs the full check instead of every 64th reused epoch proof on each thread and prints `[epoch-proofs]` counts | @@ -589,10 +598,12 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_VERIFY_DRAW_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | re-decodes a draw recipe instead of using the cache and checks the result | | `APS5_VERIFY_DRAW_SNAPSHOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | re-reads a reused draw snapshot and counts the ones that differ | | `APS5_VERIFY_EARLY_DRAW_KEY` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | rebuilds the resource-cache key a pipelined draw brought on the committer and requires both to be equal | +| `APS5_VERIFY_GPU_HEAP` | integer | `core/shader/recompiler/HeapCacheSwitch.hpp` | | checks heap slots and GPU-read constants, and rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (0 or no number means every stage); a value that is not a non-negative integer stops the driver with an error naming the variable | | `APS5_VERIFY_GUARD_SPANS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp` | | checks every guard check that the thread's copy of the guard ranges answered without a lock against the guard list and takes the list's answer; a copy that was current, or a copy refilled after the list changed, that still misses an overlapping guard prints a `[guard-spans] verify` line (the first twenty), and a `[guard-spans]` line every 10 s counts the checks and misses (it also prints with `APS5_PROFILE_DRAW`) | | `APS5_VERIFY_KNOWN_VALUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferCopy.cpp` | | serves known values through the hook too and counts mismatches | | `APS5_VERIFY_OWNED_DRAW_INPUTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | compares reused owned input bytes and throws if they differ while the proof still holds | | `APS5_VERIFY_PASS_ATTACHMENTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | looks up the attachments of every pass attachment memo hit anew as well, prints the first twenty that differ and counts the checked hits on the `[pass-attachments]` line of `APS5_PIPELINE_STATS` or `APS5_PROFILE_DRAW` | +| `APS5_VERIFY_PENDING_SERIAL_SKIP` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp` | | checks a dispatch variant that skipped its pending image check at an unchanged serial against the pending images and throws when one overlaps its runs | | `APS5_VERIFY_PROOFS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | runs the full walk beside every own-object refresh proof and aborts on a different decision | | `APS5_VERIFY_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | makes the ordinary prepare path beside a recipe hit and compares the answers | | `APS5_VERIFY_REGISTER_KEYS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp` | | checks the incremental register fingerprint against the full state | diff --git a/docs/dev/debt/changes/fix-9508-review-b.md b/docs/dev/debt/changes/fix-9508-review-b.md new file mode 100644 index 000000000000..ac47ec04ce7f --- /dev/null +++ b/docs/dev/debt/changes/fix-9508-review-b.md @@ -0,0 +1,5 @@ +# libSceAgcDriver + +## change [GPU descriptor heap] + +- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap` and timeline semaphores; without the extension it has no effect. Heap mode has no per-draw path: a stage that needs more image slots than the heap holds, whose module keeps a binding the heap does not map (`RequireHeapStageMappable`) or whose plan is ineligible, and a draw whose stages come out mixed, fail at the draw or dispatch, not at registration (only `APS5_GPU_HEAP_EXCLUDE` sends stages per-draw). With `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind. Heap stages report no BDA fault per use, so the address draw reuse test skips its fault-per-use case with `--heap-stages`. A reused address-based draw whose moved read-only buffer cannot be viewed in place is built again. diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 7f96fd050466..2060fc8095d0 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -391,6 +391,8 @@ Eligible single-sample draws retain native finite bounds inside [0, 1] and use a - [Table S#](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) DISABLE_CUBE_WRAP faults on selection without `VK_EXT_non_seamless_cube_map`: no runtime dimension check, including valid non-cube direct/table T#s. Unselected entries do not fault; with the feature this bit alone is accepted. Table T#/direct S# faults only for cubes needing the missing feature. - An [image table](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) whose record range overlaps a buffer or storage image written by its own dispatch faults (`table written by its dispatch`) when any entry is selected, even if the write misses the selected record. A selected column's range is its record and the bytes of the record before the descriptor. - An [image table](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) T# whose surface has no mapped byte faults when selected instead of becoming a zero texture as a direct T# does; what the console returns for it is not measured. +- A per-dispatch [image table](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) binds every storage element through its float storage view, so a table store through a uint mode (16-bit float and SINT formats written as raw bits) writes zero. The GPU heap gives tables a uint storage column; `agc_driver_image_table_store_gpu_heap` covers it and skips without the heap. +- An [image table](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) entry whose T# is a dynamic-resolution variant of another entry (same address, format, tiling and mips, other width or height) borrows that entry's texture: the one the newest storage write used, else the active depth surface, else the largest accessible by guest bytes, then by extent. Normalized sampling reads the same picture. `image_get_resinfo` (`textureSize`) and texel fetches on a borrower answer with the borrowed texture's extent, not the extent in its own T#, which is not what the console does. The table is not remembered, so it resolves on every use. A cached set repeats the choice on its full walk but not on its fast proof: a write over the surface fails that proof anyway, a depth surface made active over it without a write does not. - An [image table](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) entry whose T# is a dynamic-resolution variant of another entry (same address, format, tiling and mips, other width or height) borrows that entry's texture: the one the newest storage write used, else the active depth surface, else the largest accessible by guest bytes, then by extent. Normalized sampling reads the same picture. `image_get_resinfo` (`textureSize`) and texel fetches on a borrower answer with the borrowed texture's extent, not the extent in its own T#, which is not what the console does. A remembered table is reused only while the same entries would be chosen again. A cached set repeats the choice on its full walk but not on its fast proof: a write over the surface fails that proof anyway, a depth surface made active over it without a write does not. - An [image table](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) entry that reads a surface as a one-layer 2D array, through a T# that differs from a 2D entry's T# of the same table only in its type, binds that entry's texture through a 2D array view instead of a second image. Entries whose T#s differ in any other field, or arrays with more than one layer, still get their own image, and a table that holds such a pair is not remembered for reuse. - [User-data callees](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp) (libSceAgcDriver) - a compute shader's `s_swappc_b64` whose source pair is a user-data pair, or a copy of one made with `s_mov_b32` or `s_mov_b64` in the same block, calls the code at the address that user data holds. At dispatch the callee is read from guest memory up to its `s_setpc_b64` on the link pair, one copy of it is appended per call after the caller's last instruction, and the call is rewritten to `s_call_b64` to that copy. The words after the caller's last instruction are dropped from the recompiled code; in the shaders seen they are metadata or constants the caller reads relative to its program counter, and those reads go to the captured guest code, which linking does not change. A caller that jumps through a table among those words, which the control flow analysis reads from the recompiled code, throws. A copy runs at another program counter than the callee, so a callee that reads its program counter, makes a call, ends the program, jumps through another pair, returns before code it branches to, spans more than 64 KiB or is not readable throws. @@ -483,6 +485,7 @@ Eligible single-sample draws retain native finite bounds inside [0, 1] and use a ### Opt-in draw paths - [Draw finisher](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp) (`APS5_DRAW_PIPELINE`) - opt-in. The Linux main-image page table it adds matches what Windows already does by default. +- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap` and timeline semaphores. Heap mode has no per-draw path: every stage of every draw and dispatch takes the heap, and a stage that needs more image slots than the heap holds, or whose module keeps a binding the heap does not map, fails instead (only the `APS5_GPU_HEAP_EXCLUDE` debug aid sends stages per-draw); with `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind, because the nearly-full margin scales with the cap. Heap stages read guest memory in place and report no BDA fault per use, so the address draw reuse test skips its fault-per-use case with `--heap-stages`. A reused address-based draw whose moved read-only buffer cannot be viewed in place with the alignment offset its build baked into the shader data is built again. - [Multi-submit count overflow and buffer validation](../../../core/libs/prx/libSceAgcDriver/Submit/src/Dcb.cpp) (libSceAgcDriver) - whether the console driver imposes an architectural submission packet limit or allows null buffer pointers with non-zero sizes in multi-submit arrays is unmeasured; AgcDriver::SubmitMany validates count against 32-bit pointer array bounds overflow and rejects null addresses for non-empty command buffers with a runtime exception. - [Native multisample color snapshots](../../../core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp) do not publish guest memory. Guest-footprint snapshots require uncompressed single-layer R_X and a retained initial footprint; low-level view creation without a captured baseline refuses. Raw sample readback does not support EQAA, arrays, volumes or mips. The baseline remains accounted for during the resident target's lifetime, while upload buffers expire after completion. Snapshots preserve padding and guards and reject unexpected guest changes, another active recorder on the same device, and completion reentry. Callers must keep guest mappings alive during comparisons. Automatic consumers, console equivalence, unsynchronized guest writes and large-title costs remain unverified. diff --git a/docs/user/USAGE.md b/docs/user/USAGE.md index 2449f2f875b9..0a520156df28 100644 --- a/docs/user/USAGE.md +++ b/docs/user/USAGE.md @@ -572,12 +572,16 @@ A first run can stop at one very large compute shader while the GPU driver compi ### Pipeline journal -Besides the recompiled shaders, the shader cache directory holds `pipelines.journal`: every Vulkan graphics pipeline the pipeline store kept and every compute pipeline a run built, with the specialized shader modules they were built from. The next run of the title builds those pipelines on background threads while it loads, so a draw or dispatch the earlier run already made does not compile its pipeline when it is first reached. The journal belongs to the GPU and driver that wrote it, like the driver's pipeline cache file next to it: a run on another GPU or driver version starts it over, and the driver's own pipeline cache decides how fast each pipeline is rebuilt. Two runs sharing the directory take turns on `pipelines.journal.lock`; a run that cannot lock it records nothing. `APS5_NO_PIPELINE_JOURNAL=1` disables recording and replay; `APS5_PIPELINE_JOURNAL_THREADS` sets the replay threads (half the CPU threads by default; `0` records without replaying), `APS5_PIPELINE_JOURNAL_ENTRIES` how many pipelines are replayed (4096, the last recorded) and `APS5_PIPELINE_STORE_ENTRIES` how many graphics pipelines stay resident (by default the store grows from 1024 up to 4096 to hold the replay and the pipelines that keep coming back), and `APS5_PIPELINE_JOURNAL_MAX_MIB` (1024) the file size at which recording stops. Deleting the file loses nothing but the head start. With `APS5_PROFILE_DRAW=1` a `[pipeline-journal]` line reports what was loaded, replayed and recorded. +Besides the recompiled shaders, the shader cache directory holds `pipelines.journal` (`pipelines-heap.journal` with `APS5_GPU_HEAP`, whose pipelines differ): every Vulkan graphics pipeline the pipeline store kept and every compute pipeline a run built, with the specialized shader modules they were built from. The next run of the title builds those pipelines on background threads while it loads, so a draw or dispatch the earlier run already made does not compile its pipeline when it is first reached. The journal belongs to the GPU and driver that wrote it, like the driver's pipeline cache file next to it: a run on another GPU or driver version starts it over, and the driver's own pipeline cache decides how fast each pipeline is rebuilt. Two runs sharing the directory take turns on `pipelines.journal.lock`; a run that cannot lock it records nothing. `APS5_NO_PIPELINE_JOURNAL=1` disables recording and replay; `APS5_PIPELINE_JOURNAL_THREADS` sets the replay threads (half the CPU threads by default; `0` records without replaying), `APS5_PIPELINE_JOURNAL_ENTRIES` how many pipelines are replayed (4096, the last recorded) and `APS5_PIPELINE_STORE_ENTRIES` how many graphics pipelines stay resident (by default the store grows from 1024 up to 4096 to hold the replay and the pipelines that keep coming back), and `APS5_PIPELINE_JOURNAL_MAX_MIB` (1024) the file size at which recording stops. Deleting the file loses nothing but the head start. With `APS5_PROFILE_DRAW=1` a `[pipeline-journal]` line reports what was loaded, replayed and recorded. ### Draw pipeline `APS5_DRAW_PIPELINE=1` (off by default) moves more of each draw off the thread that reads the title's command buffers: a second thread finishes each draw while the next one is read, the thread that records draws skips work whose inputs did not change, and checks that a draw's resources are still current are reused until the title or the GPU writes memory. It is meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`. The picture does not change; if it does, that is a bug, and a run without the switch shows whether it is the cause. `APS5_VERIFY_DRAW_PIPELINE=1` runs the full checks next to the reused ones, at a cost in speed, and prints `[epoch-proofs]` lines with how many differed (any nonzero count is a bug). `APS5_PROFILE_DRAW=1` finishes every draw on the reading thread, so a run with it does not measure this switch. To see the hand-off without that, set `APS5_PIPELINE_STATS` (any value; `1` also turns on Vulkan pipeline statistics, which cost time): every 10 s a `[finisher]` line counts the draws handed to the second thread and those finished on the reading thread, and `[finisher-held]` lines count the draws held back by why their writes are not known. +### GPU descriptor heap + +`APS5_GPU_HEAP=1` (off by default) binds the textures and samplers of most draws through one table the GPU indexes, instead of building them again for each draw. It needs a GPU driver with `VK_EXT_descriptor_heap`; without it the switch does nothing. Use it with `APS5_DRAW_PIPELINE=1` and the switches listed there. The first run with the switch compiles its own variant of each shader, so expect the same stutter as with an empty shader cache once. Wrong or missing textures or flicker that go away without the switch are bugs. `APS5_VERIFY_GPU_HEAP=1` checks the table against the bound textures, and builds some draws the old way and compares them; it prints `[heap-slots]` and `[gpu-heap]` lines (a slot holding another texture or a differing draw is a bug). With the switch on there is no per-draw fallback: a stage the heap cannot map (for example one that needs more image slots than the heap holds, or one whose plan is ineligible) fails the draw or dispatch instead of binding its resources the old way. If a title stops with such an error, run it without `APS5_GPU_HEAP`. + ### Texture cache budget Image and buffer memory allocations retry after releasing unused pooled buffers and reclaimable texture cache entries. Recovery preserves storage images with pending GPU results and resources retained by recorded work. `[bufferpool]` recovery and failure lines report the requested allocation, memory released and retry count. An allocation still fails if recovery cannot free enough memory. When the `VK_EXT_memory_budget` budget of the device-local heap has no room for an image, device buffer or resident heap mirror slab, the texture caches first release reclaimable entries for the allocation and what the heap is over its budget; the allocation goes to host memory only if they release less than that and the budget read again still has no room.