From 27439c43cc893f3371427dc6355d664d4abd186d Mon Sep 17 00:00:00 2001 From: boykopovar Date: Mon, 5 Oct 2026 10:55:58 +0300 Subject: [PATCH] feat(shader): version runtime abi + freeze device capabilities --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 10 +- .../Execution/include/ShaderDeviceProfile.hpp | 29 ++++ .../Execution/include/VulkanDevice.hpp | 1 + .../Execution/src/ShaderDeviceProfile.cpp | 75 +++++++++++ .../Execution/src/VulkanDevice.cpp | 16 +++ .../Graphics/src/ShaderResources.cpp | 1 + .../tests/ShaderDeviceProfile.cpp | 127 ++++++++++++++++++ .../libSceAgcDriver/tests/ShaderDiskCache.cpp | 12 +- .../tests/execution/VertexFetch.cpp | 17 +++ core/shader/recompiler/CMakeLists.txt | 1 + core/shader/recompiler/CacheKey.hpp | 2 + .../IrMetadata/DescriptorBinding.hpp | 22 +-- .../src/IrProgram.cpp | 2 +- .../Optimization/src/BindingAllocator.cpp | 2 +- .../src/DescriptorBindingBuilder.cpp | 2 +- core/shader/recompiler/Recompiler.hpp | 2 + core/shader/recompiler/RuntimeAbi.hpp | 47 +++++++ core/shader/recompiler/ShaderDiskCache.cpp | 10 +- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- 19 files changed, 355 insertions(+), 25 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp create mode 100644 core/libs/prx/libSceAgcDriver/Execution/src/ShaderDeviceProfile.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp create mode 100644 core/shader/recompiler/RuntimeAbi.hpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 8e6fb4aae..0cdc88a27 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -127,6 +127,7 @@ set(agcDriverSources ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/ShaderMemory.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/BdaFeatures.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/SubgroupClock.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/ShaderDeviceProfile.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Pm4.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/VulkanDevice.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/AspectFit.cpp @@ -381,6 +382,12 @@ target_link_libraries(agc_shader_disk_cache_tests PRIVATE shader_recompiler_agc_ set_target_properties(agc_shader_disk_cache_tests PROPERTIES CXX_EXTENSIONS OFF) configure_windows_unwind(agc_shader_disk_cache_tests) +add_test_executable(agc_shader_device_profile_tests EXCLUDE_FROM_ALL tests/ShaderDeviceProfile.cpp Execution/src/ShaderDeviceProfile.cpp) +target_include_directories(agc_shader_device_profile_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/3rdparty/Vulkan-Headers/include) +target_link_libraries(agc_shader_device_profile_tests PRIVATE shader_recompiler_agc_driver libc) +set_target_properties(agc_shader_device_profile_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_shader_device_profile_tests) + add_test_executable(agc_shader_control_flow_tests EXCLUDE_FROM_ALL tests/ControlFlow.cpp ) @@ -600,7 +607,7 @@ foreach(agcExecutionTestSource IN LISTS agcExecutionTestSources) endforeach() if(BUILD_TESTING) - foreach(agcTest IN ITEMS agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_spirv_module_tests agc_dpp_write_tests agc_masked_select_tests agc_vop1_control_decode_tests agc_validate_program_tests agc_shader_disk_cache_tests agc_shader_control_flow_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests agc_driver_bda_device_tests ${agcExecutionTests}) + foreach(agcTest IN ITEMS agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_spirv_module_tests agc_dpp_write_tests agc_masked_select_tests agc_vop1_control_decode_tests agc_validate_program_tests agc_shader_disk_cache_tests agc_shader_device_profile_tests agc_shader_control_flow_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests agc_driver_bda_device_tests ${agcExecutionTests}) if(agcTest STREQUAL "agc_driver_constant_store_tests") continue() endif() @@ -685,6 +692,7 @@ if(AGC_BUILD_VISUAL_TEST) Execution/src/GuestMemory.cpp Execution/src/BdaFeatures.cpp Execution/src/SubgroupClock.cpp + Execution/src/ShaderDeviceProfile.cpp Graphics/src/Draw.cpp Graphics/src/DepthSurface.cpp Graphics/src/ColorTargetLayout.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp new file mode 100644 index 000000000..47a154e17 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp @@ -0,0 +1,29 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_SHADERDEVICEPROFILE_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_SHADERDEVICEPROFILE_HPP + +#include "Recompiler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Context.hpp" +#include +#include + +namespace AgcDriver { + +class ShaderDeviceProfile { +public: + ShaderDeviceProfile(const ShaderRecompiler::SpirvTarget& target, const VkDeviceCreateInfo& deviceInfo, const VkPhysicalDeviceLimits& limits); + ShaderDeviceProfile(const ShaderDeviceProfile&) = delete; + ShaderDeviceProfile& operator=(const ShaderDeviceProfile&) = delete; + ShaderRecompiler::SpirvTarget Target() const { return target; } + const VkPhysicalDeviceLimits& Limits() const { return limits; } + +private: + ShaderRecompiler::SpirvTarget target; + const VkPhysicalDeviceLimits limits; + std::vector capabilities; + std::vector extensions; + std::vector extensionViews; +}; + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp index ca9536125..696cfbdc1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp @@ -300,6 +300,7 @@ private: // 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; + ShaderRecompiler::SpirvTarget buildTarget() const; Graphics::Context buildContext() const; // Body of Dispatch and DispatchIndirect: `arguments` 0 dispatches x, y, z groups. IndirectOutcome dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t arguments, std::span snapshots, std::uint64_t programAddress, std::shared_ptr prepared, std::shared_ptr* recipe); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/ShaderDeviceProfile.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/ShaderDeviceProfile.cpp new file mode 100644 index 000000000..6777cf37b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/src/ShaderDeviceProfile.cpp @@ -0,0 +1,75 @@ +#include "prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp" +#include "BdaAbi.hpp" +#include +#include + +namespace AgcDriver { +namespace { + +template +const TFeatures* findFeatures(const void* chain, VkStructureType type) { + auto* current = static_cast(chain); + while (current != nullptr) { + if (current->sType == type) return reinterpret_cast(current); + current = current->pNext; + } + return nullptr; +} + +} + +ShaderDeviceProfile::ShaderDeviceProfile(const ShaderRecompiler::SpirvTarget& target, const VkDeviceCreateInfo& deviceInfo, const VkPhysicalDeviceLimits& limits) : target(target), limits(limits), capabilities(target.supportedCapabilities.begin(), target.supportedCapabilities.end()) { + using Graphics::Require; + Require(deviceInfo.pEnabledFeatures != nullptr, "shader device profile requires enabled core features"); + const auto& core = *deviceInfo.pEnabledFeatures; + const auto* bda = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES); + const auto* bytes = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES); + const auto* indexing = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES); + const auto* barycentric = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR); + const auto* mesh = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT); + const auto* clock = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR); + const auto* maintenance8 = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR); + Require(target.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version, "shader device profile has an incompatible BDA ABI"); + Require(bda != nullptr && bda->bufferDeviceAddress == VK_TRUE && core.shaderInt64 == VK_TRUE, "shader runtime requires enabled bufferDeviceAddress and shaderInt64"); + Require(bytes != nullptr && bytes->storageBuffer8BitAccess == VK_TRUE, "shader runtime requires enabled storageBuffer8BitAccess"); + Require(core.vertexPipelineStoresAndAtomics == VK_TRUE && core.fragmentStoresAndAtomics == VK_TRUE, "shader runtime requires enabled graphics stores and atomics"); + Require(limits.maxPushConstantsSize >= ShaderRecompiler::RuntimeAbi::PushConstantDwords * sizeof(std::uint32_t) && limits.maxBoundDescriptorSets > ShaderRecompiler::RuntimeAbi::DescriptorSet, "shader runtime ABI exceeds device limits"); + std::ranges::sort(capabilities); + capabilities.erase(std::unique(capabilities.begin(), capabilities.end()), capabilities.end()); + const auto hasCapability = [&](spv::Capability capability) { return std::ranges::binary_search(capabilities, static_cast(capability)); }; + Require(hasCapability(spv::CapabilityShader) && hasCapability(spv::CapabilityInt64) && hasCapability(spv::CapabilityPhysicalStorageBufferAddresses) && hasCapability(spv::CapabilityStorageBuffer8BitAccess), "shader device profile is missing runtime capabilities"); + const auto checkFeature = [&](spv::Capability capability, bool enabled, const char* name) { + Require(!hasCapability(capability) || enabled, std::string("shader device profile advertises a disabled feature: ") + name); + }; + checkFeature(spv::CapabilityFloat64, core.shaderFloat64 == VK_TRUE, "shaderFloat64"); + checkFeature(spv::CapabilityTessellation, core.tessellationShader == VK_TRUE, "tessellationShader"); + checkFeature(spv::CapabilityImageGatherExtended, core.shaderImageGatherExtended == VK_TRUE, "shaderImageGatherExtended"); + checkFeature(spv::CapabilityMinLod, core.shaderResourceMinLod == VK_TRUE, "shaderResourceMinLod"); + checkFeature(spv::CapabilityStorageImageReadWithoutFormat, core.shaderStorageImageReadWithoutFormat == VK_TRUE, "shaderStorageImageReadWithoutFormat"); + checkFeature(spv::CapabilityStorageImageWriteWithoutFormat, core.shaderStorageImageWriteWithoutFormat == VK_TRUE, "shaderStorageImageWriteWithoutFormat"); + checkFeature(spv::CapabilitySampledImageArrayDynamicIndexing, core.shaderSampledImageArrayDynamicIndexing == VK_TRUE, "shaderSampledImageArrayDynamicIndexing"); + checkFeature(spv::CapabilityStorageImageArrayDynamicIndexing, core.shaderStorageImageArrayDynamicIndexing == VK_TRUE, "shaderStorageImageArrayDynamicIndexing"); + const bool sampledNonUniform = indexing != nullptr && indexing->shaderSampledImageArrayNonUniformIndexing == VK_TRUE; + const bool storageNonUniform = indexing != nullptr && indexing->shaderStorageImageArrayNonUniformIndexing == VK_TRUE; + checkFeature(spv::CapabilitySampledImageArrayNonUniformIndexing, sampledNonUniform, "shaderSampledImageArrayNonUniformIndexing"); + checkFeature(spv::CapabilityStorageImageArrayNonUniformIndexing, storageNonUniform, "shaderStorageImageArrayNonUniformIndexing"); + checkFeature(spv::CapabilityShaderNonUniform, sampledNonUniform || storageNonUniform, "descriptor indexing"); + const bool barycentricEnabled = barycentric != nullptr && barycentric->fragmentShaderBarycentric == VK_TRUE; + const bool meshEnabled = mesh != nullptr && mesh->meshShader == VK_TRUE; + checkFeature(spv::CapabilityFragmentBarycentricKHR, barycentricEnabled, "fragmentShaderBarycentric"); + checkFeature(spv::CapabilityMeshShadingEXT, meshEnabled, "meshShader"); + checkFeature(spv::CapabilityShaderClockKHR, clock != nullptr && clock->shaderSubgroupClock == VK_TRUE && clock->shaderDeviceClock == VK_TRUE, "shader clock"); + Require(!target.fragmentShaderBarycentricEnabled || barycentricEnabled, "shader device profile exposes disabled barycentrics"); + Require(!target.mesh || meshEnabled, "shader device profile exposes disabled mesh shaders"); + Require(!target.nonConstantImageOffsets || (maintenance8 != nullptr && maintenance8->maintenance8 == VK_TRUE), "shader device profile exposes disabled maintenance8"); + Require(!target.tessellation || core.tessellationShader == VK_TRUE, "shader device profile exposes disabled tessellation"); + for (const auto extension : target.supportedExtensions) extensions.emplace_back(extension); + std::ranges::sort(extensions); + extensions.erase(std::unique(extensions.begin(), extensions.end()), extensions.end()); + for (const auto& extension : extensions) extensionViews.emplace_back(extension); + Require(std::ranges::find(extensionViews, "SPV_KHR_physical_storage_buffer") != extensionViews.end() && std::ranges::find(extensionViews, "SPV_KHR_8bit_storage") != extensionViews.end(), "shader device profile is missing runtime extensions"); + this->target.supportedCapabilities = capabilities; + this->target.supportedExtensions = extensionViews; +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 46d037fe7..9fc9e6434 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -6,6 +6,7 @@ #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/BdaFeatures.hpp" #include "prx/libSceAgcDriver/Execution/include/SubgroupClock.hpp" +#include "prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp" #include "prx/libSceAgcDriver/Execution/include/PresentationScaler.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp" @@ -188,6 +189,7 @@ struct VulkanDevice::State { VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES}; std::vector capabilities{1}; std::vector spirvExtensions; + std::unique_ptr shaderProfile; bool tessellationShader = false; bool meshShader = false; bool fragmentShaderBarycentric = false; @@ -1106,7 +1108,9 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window) : state(std::make_u } bdaFeatures.pNext = &byteFeatures; deviceInfo.pNext = &bdaFeatures; + auto shaderProfile = std::make_unique(buildTarget(), deviceInfo, state->properties.limits); check(state->InstanceFunction("vkCreateDevice")(selected, &deviceInfo, nullptr, &state->device), "vkCreateDevice"); + state->shaderProfile = std::move(shaderProfile); state->DeviceFunction("vkGetDeviceQueue")(state->device, family, 0, &state->queue); APS5_LOG_OUT("Vulkan device ready device=%p queue=%p family=%u", reinterpret_cast(state->device), reinterpret_cast(state->queue), family); VkCommandPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; @@ -2429,6 +2433,11 @@ std::string VulkanDevice::DeviceName() const { } ShaderRecompiler::SpirvTarget VulkanDevice::Target() const { + require(state->shaderProfile != nullptr, "shader device profile is unavailable"); + return state->shaderProfile->Target(); +} + +ShaderRecompiler::SpirvTarget VulkanDevice::buildTarget() const { const auto& limits = state->properties.limits; ShaderRecompiler::SpirvTarget target{VK_API_VERSION_1_1, state->meshShader ? 0x00010400u : 0x00010300u, state->subgroup.subgroupSize, ShaderRecompiler::BdaAbi::Version, state->capabilities, state->spirvExtensions, false, {limits.maxComputeWorkGroupSize[0], limits.maxComputeWorkGroupSize[1], limits.maxComputeWorkGroupSize[2]}, limits.maxComputeWorkGroupInvocations, limits.maxComputeSharedMemorySize, {}, {}}; target.fragmentShaderBarycentricEnabled = state->fragmentShaderBarycentric; @@ -2529,6 +2538,10 @@ void VulkanDevice::ColorMetadataPass(const Graphics::ColorMetadataPass& pass) { } void VulkanDevice::Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, std::shared_ptr* recipe) { + for (const auto& shader : shaders) { + require(shader.program != nullptr, "missing compiled shader"); + ShaderRecompiler::RuntimeAbi::RequireVersion(shader.program->runtimeAbiVersion); + } // Two stdout lines per draw cost ~1.3 ms per frame of the queue-0 worker (part of it under the // GPU mutex); APS5_TRACE_DRAWS=1 restores them. static const bool trace = std::getenv("APS5_TRACE_DRAWS") != nullptr; @@ -3038,6 +3051,7 @@ std::uint64_t VulkanDevice::presync(std::span VulkanDevice::PrepareDispatch(const ShaderRecompiler::RecompileResult& shader, std::span snapshots) { + ShaderRecompiler::RuntimeAbi::RequireVersion(shader.runtimeAbiVersion); // APS5_LOCKED_BUILD=1: the whole build under the mutex, as before the split. static const bool lockedBuild = std::getenv("APS5_LOCKED_BUILD") != nullptr; if (lockedBuild || shader.spirv.size() < 5 || shader.spirv[0] != 0x07230203u) return nullptr; @@ -3330,6 +3344,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { } VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t arguments, std::span snapshots, std::uint64_t programAddress, std::shared_ptr prepared, std::shared_ptr* recipeOut) { + ShaderRecompiler::RuntimeAbi::RequireVersion(shader.runtimeAbiVersion); PerformanceTimer timing("Vulkan.Dispatch"); if (recipeOut != nullptr) *recipeOut = nullptr; // Group counts for the trace lines; an indirect dispatch does not know them. @@ -3618,6 +3633,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec } 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) { + ShaderRecompiler::RuntimeAbi::RequireVersion(shader.runtimeAbiVersion); PerformanceTimer timing("Vulkan.DispatchRecipe"); outcome = {0, 0}; char groupsText[40]; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 257497d32..e9eb5b444 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -898,6 +898,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons std::set occupied; for (const auto& shader : shaders) { Require(shader.program != nullptr, "missing compiled shader"); + ShaderRecompiler::RuntimeAbi::RequireVersion(shader.program->runtimeAbiVersion); const VkShaderStageFlags flags = VulkanStage(shader.stage); std::uint64_t stageStorageBuffers = 0; std::uint64_t stageResources = 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp new file mode 100644 index 000000000..cfe9f52de --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp @@ -0,0 +1,127 @@ +#include "prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp" +#include "BdaAbi.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; + +struct ProfileInput { + std::vector capabilities{spv::CapabilityShader, spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess}; + std::array extensionStrings{"SPV_KHR_physical_storage_buffer", "SPV_KHR_8bit_storage"}; + std::array extensions{extensionStrings[0], extensionStrings[1]}; + VkPhysicalDeviceDescriptorIndexingFeatures indexing{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES}; + VkPhysicalDevice8BitStorageFeatures bytes{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES, &indexing, VK_TRUE}; + VkPhysicalDeviceBufferDeviceAddressFeatures bda{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES, &bytes, VK_TRUE}; + VkPhysicalDeviceFeatures core{}; + VkDeviceCreateInfo device{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; + VkPhysicalDeviceLimits limits{}; + + ProfileInput() { + core.shaderInt64 = VK_TRUE; + core.vertexPipelineStoresAndAtomics = VK_TRUE; + core.fragmentStoresAndAtomics = VK_TRUE; + device.pEnabledFeatures = &core; + device.pNext = &bda; + limits.maxPushConstantsSize = 128u; + limits.maxBoundDescriptorSets = 1u; + } + + ShaderRecompiler::SpirvTarget Target() const { + ShaderRecompiler::SpirvTarget target{}; + target.bdaAbiVersion = ShaderRecompiler::BdaAbi::Version; + target.supportedCapabilities = capabilities; + target.supportedExtensions = extensions; + return target; + } +}; + +template +void Reject(TAction action, const char* expected) { + try { + action(); + } catch (const std::runtime_error& error) { + Require(std::string(error.what()).find(expected) != std::string::npos, "unexpected profile validation error"); + return; + } + throw std::runtime_error("invalid shader device profile was accepted"); +} + +void CheckProfile() { + ProfileInput input; + const AgcDriver::ShaderDeviceProfile profile(input.Target(), input.device, input.limits); + input.capabilities.clear(); + input.extensionStrings[0] = "changed"; + input.core.shaderInt64 = VK_FALSE; + input.limits.maxPushConstantsSize = 0u; + const auto target = profile.Target(); + Require(target.supportedCapabilities.size() == 4u && std::ranges::is_sorted(target.supportedCapabilities), "profile capabilities were not frozen"); + Require(std::ranges::find(target.supportedExtensions, "SPV_KHR_physical_storage_buffer") != target.supportedExtensions.end(), "profile extension storage is borrowed"); + Require(profile.Limits().maxPushConstantsSize == 128u, "profile limits were not frozen"); + static_assert(!std::is_copy_constructible_v && !std::is_move_constructible_v); + const auto invalid = [](auto mutate, const char* expected) { + ProfileInput candidate; + mutate(candidate); + Reject([&] { AgcDriver::ShaderDeviceProfile rejected(candidate.Target(), candidate.device, candidate.limits); }, expected); + }; + invalid([](auto& value) { value.device.pEnabledFeatures = nullptr; }, "enabled core features"); + invalid([](auto& value) { value.bda.bufferDeviceAddress = VK_FALSE; }, "bufferDeviceAddress"); + invalid([](auto& value) { value.device.pNext = nullptr; }, "bufferDeviceAddress"); + invalid([](auto& value) { value.core.shaderInt64 = VK_FALSE; }, "shaderInt64"); + invalid([](auto& value) { value.bytes.storageBuffer8BitAccess = VK_FALSE; }, "storageBuffer8BitAccess"); + invalid([](auto& value) { value.core.fragmentStoresAndAtomics = VK_FALSE; }, "graphics stores and atomics"); + invalid([](auto& value) { value.limits.maxPushConstantsSize = 127u; }, "exceeds device limits"); + invalid([](auto& value) { value.limits.maxBoundDescriptorSets = 0u; }, "exceeds device limits"); + invalid([](auto& value) { value.capabilities.clear(); }, "missing runtime capabilities"); + invalid([](auto& value) { value.extensions[0] = "missing"; }, "missing runtime extensions"); + invalid([](auto& value) { value.capabilities.push_back(spv::CapabilitySampledImageArrayDynamicIndexing); }, "shaderSampledImageArrayDynamicIndexing"); + invalid([](auto& value) { value.capabilities.push_back(spv::CapabilityStorageImageArrayNonUniformIndexing); }, "shaderStorageImageArrayNonUniformIndexing"); + invalid([](auto& value) { value.capabilities.push_back(spv::CapabilityStorageImageReadWithoutFormat); }, "shaderStorageImageReadWithoutFormat"); + invalid([](auto& value) { value.capabilities.push_back(spv::CapabilityFragmentBarycentricKHR); }, "fragmentShaderBarycentric"); + invalid([](auto& value) { value.capabilities.push_back(spv::CapabilityMeshShadingEXT); }, "meshShader"); + ProfileInput enabled; + enabled.capabilities.push_back(spv::CapabilitySampledImageArrayDynamicIndexing); + enabled.capabilities.push_back(spv::CapabilityStorageImageArrayNonUniformIndexing); + enabled.core.shaderSampledImageArrayDynamicIndexing = VK_TRUE; + enabled.indexing.shaderStorageImageArrayNonUniformIndexing = VK_TRUE; + const AgcDriver::ShaderDeviceProfile accepted(enabled.Target(), enabled.device, enabled.limits); + Require(accepted.Target().supportedCapabilities.size() == 6u, "enabled descriptor indexing was rejected"); +} + +void CheckAbi() { + using ShaderRecompiler::RuntimeAbi::Binding; + using ShaderRecompiler::RuntimeAbi::BindingNumber; + using ShaderRecompiler::RuntimeAbi::Stage; + std::set bindings; + for (std::uint32_t stage = 0u; stage < ShaderRecompiler::RuntimeAbi::StageCount; ++stage) { + for (std::uint32_t binding = 0u; binding < static_cast(Binding::Count); ++binding) { + Require(bindings.insert(BindingNumber(static_cast(stage), static_cast(binding))).second, "runtime ABI bindings overlap"); + } + } + Require(BindingNumber(Stage::Main, Binding::ShaderData) == 49u && BindingNumber(Stage::Fragment, Binding::ShaderData) == 99u, "runtime ABI binding numbers changed"); + Reject([] { BindingNumber(static_cast(4u), Binding::Buffers); }, "invalid stage or binding"); + Reject([] { BindingNumber(Stage::Main, Binding::Count); }, "invalid stage or binding"); + Reject([] { ShaderRecompiler::RuntimeAbi::RequireVersion(0u); }, "incompatible version"); + ShaderRecompiler::RuntimeAbi::RequireVersion(ShaderRecompiler::RuntimeAbi::Version); +} + +} + +int main() { + try { + CheckAbi(); + CheckProfile(); + std::cout << "shader runtime ABI and device profile 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/ShaderDiskCache.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp index 18009f385..20828f3b4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp @@ -48,6 +48,7 @@ void requireSameArtifact(const CompiledShaderArtifact& left, const CompiledShade const std::string prefix = std::string(what) + ": "; require(left.spirv.Words() == right.spirv.Words(), prefix + "SPIR-V differs"); require(left.bdaAbiVersion == right.bdaAbiVersion, prefix + "BDA ABI version differs"); + require(left.runtimeAbiVersion == right.runtimeAbiVersion, prefix + "runtime ABI version differs"); require(left.memoryOffsetDword == right.memoryOffsetDword, prefix + "memory offset differs"); require(left.hostSubgroupSize == right.hostSubgroupSize, prefix + "host subgroup size differs"); require(left.vertexInputs == right.vertexInputs, prefix + "vertex inputs differ"); @@ -266,6 +267,11 @@ void verifyResultRoundTrip() { ShaderDiskCache::EncodeResult(RecompileResult{}, bytes); require(ShaderDiskCache::DecodeResult(bytes, decoded), "an empty result does not decode"); requireSameResult(RecompileResult{}, decoded, "empty result round trip"); + auto incompatible = result; + incompatible.runtimeAbiVersion = RuntimeAbi::Version + 1u; + bytes.clear(); + ShaderDiskCache::EncodeResult(incompatible, bytes); + require(!ShaderDiskCache::DecodeResult(bytes, decoded), "an incompatible runtime ABI result decodes"); } void verifyEntryRoundTrip() { @@ -296,8 +302,12 @@ void verifyEntryRoundTrip() { otherKey.back() ^= std::byte{1}; require(ShaderDiskCache::DecodeEntry(file, otherKey, decoded) == ShaderDiskCache::LoadStatus::KeyMismatch, "an entry for another key loads"); auto previousVersion = file; - previousVersion[4] = std::byte{4}; + previousVersion[4] = static_cast(ShaderDiskCache::FormatVersion - 1u); require(ShaderDiskCache::DecodeEntry(previousVersion, key, decoded) == ShaderDiskCache::LoadStatus::Rejected, "an entry with the previous format version loads"); + auto incompatible = variant; + incompatible.artifact.runtimeAbiVersion = RuntimeAbi::Version + 1u; + const auto incompatibleFile = ShaderDiskCache::EncodeEntry(key, incompatible); + require(ShaderDiskCache::DecodeEntry(incompatibleFile, key, decoded) == ShaderDiskCache::LoadStatus::Rejected, "an entry with an incompatible runtime ABI loads"); } void verifyArtifactStorageIsolation() { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/VertexFetch.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/VertexFetch.cpp index f107acf81..52cf32df3 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/VertexFetch.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/VertexFetch.cpp @@ -6,6 +6,7 @@ #include #include #include +#include namespace { @@ -21,6 +22,22 @@ constexpr std::array vertexCode{0xf4080100u, 0xfa000000u, 0x4 constexpr std::array pixelCode{0x7e0002f2u, 0x7e020280u, 0xf800180fu, 0x00010100u, 0xbf810000u}; void Run(AgcDriver::VulkanDevice& device) { + ShaderRecompiler::RecompileResult incompatible; + incompatible.runtimeAbiVersion = ShaderRecompiler::RuntimeAbi::Version + 1u; + const auto rejectAbi = [](auto action) { + try { + action(); + } catch (const std::runtime_error& error) { + Require(std::string(error.what()).find("incompatible version") != std::string::npos, "unexpected runtime ABI validation error"); + return; + } + throw std::runtime_error("driver accepted an incompatible shader runtime ABI"); + }; + rejectAbi([&] { device.PrepareDispatch(incompatible, {}); }); + rejectAbi([&] { device.Dispatch(incompatible, 1u, 1u, 1u); }); + rejectAbi([&] { device.DispatchIndirect(incompatible, 0u); }); + const std::array incompatibleShaders{{{ShaderStage::Vertex, &incompatible, 0u}}}; + rejectAbi([&] { device.Draw({}, {}, incompatibleShaders); }); std::array descriptor{}; const auto tableAddress = reinterpret_cast(descriptor.data()); std::array userData{static_cast(tableAddress), static_cast(tableAddress >> 32u), 1u, 1u}; diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index 85ee56d4b..eb2a95b22 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -218,6 +218,7 @@ function(add_shader_recompiler target runtimeTarget) RecompileResult ResolveSource ResourceMaterializer::SpecializationNanoseconds + RuntimeAbi::RequireVersion SetDebugProbeActive ShaderCacheDirectory SrgbDecodeBit diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index 5bd42f165..39fd71127 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -13,6 +13,7 @@ class RecompileCacheKey { public: static void Build(const RecompileRequest& request, std::vector& key) { key.clear(); + append(key, RuntimeAbi::Version); append(key, request.shader.stage); // The code enters as a hash rather than word by word: the key is built, hashed and compared // on every dispatch and draw. The cache verifies a match against the code it stored. @@ -44,6 +45,7 @@ public: struct ContextKeyStorage {}; auto& key = HostThreadLocal, ContextKeyStorage>(); key.clear(); + append(key, RuntimeAbi::Version); append(key, request.shader.stage); append(key, request.context.waveSize); append(key, request.context.userDataBaseRegister); diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp index bd2c34d3b..6f2ea6d90 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp @@ -1,6 +1,7 @@ #ifndef CORE_SHADER_RECOMPILIER_INTERMEDIATEREPRESENTATION_INCLUDE_INTERMEDIATEREPRESENTATION_IRMETADATA_DESCRIPTORBINDING_HPP #define CORE_SHADER_RECOMPILIER_INTERMEDIATEREPRESENTATION_INCLUDE_INTERMEDIATEREPRESENTATION_IRMETADATA_DESCRIPTORBINDING_HPP +#include "RuntimeAbi.hpp" #include #include #include @@ -8,24 +9,15 @@ namespace ShaderRecompiler { -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 = 48u; +inline constexpr std::uint32_t FirstImageBinding = RuntimeAbi::FirstImageBinding; +inline constexpr std::uint32_t FirstComparisonImageBinding = RuntimeAbi::FirstComparisonImageBinding; +inline constexpr std::uint32_t FirstStorageImageBinding = RuntimeAbi::FirstStorageImageBinding; +inline constexpr std::uint32_t ImageBindingCount = RuntimeAbi::ImageBindingCount; -enum class DescriptorBindingKind : std::uint32_t { - Buffers = 0u, - Samplers = FirstImageBinding + ImageBindingCount, - Gds, - BdaPagetable, - FaultBuffer, - FlattenedSrt, - ShaderData, - Count, -}; +using DescriptorBindingKind = RuntimeAbi::Binding; struct PushData { - static constexpr std::uint32_t DwordCount = 32; + static constexpr std::uint32_t DwordCount = RuntimeAbi::PushConstantDwords; static constexpr std::uint32_t MeshDrawDwordCount = 6; static constexpr std::uint32_t NoStart = std::numeric_limits::max(); std::array dwords {}; diff --git a/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp b/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp index 15aed9410..dd154ab5d 100644 --- a/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp +++ b/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp @@ -827,7 +827,7 @@ PositionExportComponent DecodePositionExportComponent(std::uint32_t control, std std::uint32_t NativeBinding(IrShaderStage stage, DescriptorBindingKind kind) { const std::uint32_t group = stage == IrShaderStage::Pixel ? 1u : stage == IrShaderStage::TessellationControl ? 2u : stage == IrShaderStage::TessellationEvaluation ? 3u : 0u; - return static_cast(kind) + group * static_cast(DescriptorBindingKind::Count); + return RuntimeAbi::BindingNumber(static_cast(group), kind); } ImageResourceClass ImageBindingResourceClass(DescriptorBindingKind kind) { diff --git a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp index ed0b6987d..96a917dad 100644 --- a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp +++ b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp @@ -73,7 +73,7 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin fail(metadata.shaderInfoComplete ? "shader binding layout failed: binding layout already allocated" : "shader binding layout failed: shader info is not ready"); } - if (layout.descriptorSet != 0u) { + if (layout.descriptorSet != RuntimeAbi::DescriptorSet) { fail("shader binding layout failed: descriptor set must be 0"); } if (layout.firstBinding != 0u) { diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index 226a3fe63..3a5664747 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -311,7 +311,7 @@ void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, con std::size_t readOnlyHere = 0; for (const IrDescriptorBinding& logical : layout.descriptors) { DescriptorBinding physical; - physical.descriptorSet = 0u; + physical.descriptorSet = RuntimeAbi::DescriptorSet; physical.binding = NativeBinding(stage, logical.kind); physical.count = logical.resources.empty() ? 1u : static_cast(logical.resources.size()); physical.kind = PhysicalKindFor(logical.kind); diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 0ecb1e90f..a675fccad 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -1,6 +1,7 @@ #ifndef CORE_SHADER_RECOMPILIER_INCLUDE_SHADER_RECOMPILIER_RECOMPILER_HPP #define CORE_SHADER_RECOMPILIER_INCLUDE_SHADER_RECOMPILIER_RECOMPILER_HPP +#include "RuntimeAbi.hpp" #include #include #include @@ -411,6 +412,7 @@ struct CompiledShaderArtifact { SharedSpirv spirv; std::uint32_t memoryOffsetDword = 0; std::uint32_t bdaAbiVersion = 0; + std::uint32_t runtimeAbiVersion = RuntimeAbi::Version; std::vector vertexInputs; std::int32_t vertexOffsetSgpr = -1; std::int32_t instanceOffsetSgpr = -1; diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp new file mode 100644 index 000000000..1f3dcbfa9 --- /dev/null +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -0,0 +1,47 @@ +#ifndef CORE_SHADER_RECOMPILER_RUNTIMEABI_HPP +#define CORE_SHADER_RECOMPILER_RUNTIMEABI_HPP + +#include +#include + +namespace ShaderRecompiler::RuntimeAbi { + +inline constexpr std::uint32_t Version = 1u; +inline constexpr std::uint32_t DescriptorSet = 0u; +inline constexpr std::uint32_t StageCount = 4u; +inline constexpr std::uint32_t PushConstantDwords = 32u; +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 = 43u; + +enum class Binding : std::uint32_t { + Buffers = 0u, + Samplers = 44u, + Gds = 45u, + BdaPagetable = 46u, + FaultBuffer = 47u, + FlattenedSrt = 48u, + ShaderData = 49u, + Count = 50u +}; + +enum class Stage : std::uint32_t { Main, Fragment, TessellationControl, TessellationEvaluation }; + +inline void RequireVersion(std::uint32_t version) { + if (version != Version) throw std::runtime_error("Shader runtime ABI: incompatible version"); +} + +inline std::uint32_t BindingNumber(Stage stage, Binding binding) { + const auto group = static_cast(stage); + const auto index = static_cast(binding); + const auto count = static_cast(Binding::Count); + if (group >= StageCount || index >= count) throw std::runtime_error("Shader runtime ABI: invalid stage or binding"); + return group * count + index; +} + +static_assert(FirstImageBinding + ImageBindingCount == static_cast(Binding::Samplers)); + +} + +#endif diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index 72306b163..d57e1376f 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -63,9 +63,9 @@ std::filesystem::path ShaderCacheDirectory() { namespace ShaderRecompiler::ShaderDiskCache { #if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__) -static_assert(sizeof(CompiledShaderArtifact) == 120, "CompiledShaderArtifact changed: update the artifact encoder"); +static_assert(sizeof(CompiledShaderArtifact) == 128, "CompiledShaderArtifact changed: update the artifact encoder"); static_assert(sizeof(ShaderInvocation) == 72, "ShaderInvocation changed: update the invocation encoder"); -static_assert(sizeof(RecompileResult) == 200, "RecompileResult changed: update EncodeResult and DecodeResult"); +static_assert(sizeof(RecompileResult) == 208, "RecompileResult changed: update EncodeResult and DecodeResult"); static_assert(sizeof(DescriptorBinding) == 448, "DescriptorBinding changed: update the binding encoder"); static_assert(sizeof(VertexAttribute) == 28, "VertexAttribute changed: update the attribute encoder"); static_assert(sizeof(VertexInput) == 12, "VertexInput changed: update the vertex input encoder"); @@ -284,6 +284,7 @@ void decodeBinding(Reader& reader, DescriptorBinding& binding) { } void encodeArtifact(Writer& writer, const CompiledShaderArtifact& result) { + writer.Value(result.runtimeAbiVersion); writer.Values(std::span(result.spirv.Words())); writer.Value(result.bdaAbiVersion); writer.Value(result.memoryOffsetDword); @@ -310,6 +311,7 @@ void encodeArtifact(Writer& writer, const CompiledShaderArtifact& result) { } void decodeArtifact(Reader& reader, CompiledShaderArtifact& result) { + reader.Value(result.runtimeAbiVersion); std::vector words; reader.Values(words); result.spirv = std::move(words); @@ -849,7 +851,7 @@ bool DecodeResult(std::span bytes, RecompileResult& result) { decodeArtifact(reader, result); decodeInvocation(reader, result); result.cacheHit = false; - return reader.Done(); + return reader.Done() && result.runtimeAbiVersion == RuntimeAbi::Version; } std::vector EncodeEntry(std::span key, const CompiledVariant& variant) { @@ -884,7 +886,7 @@ LoadStatus DecodeEntry(std::span file, std::span