feat(shader): version runtime abi + freeze device capabilities

This commit is contained in:
boykopovar
2026-10-05 10:55:58 +03:00
parent ae9a36e075
commit 27439c43cc
19 changed files with 355 additions and 25 deletions
+9 -1
View File
@@ -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
@@ -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 <string>
#include <vector>
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<std::uint32_t> capabilities;
std::vector<std::string> extensions;
std::vector<std::string_view> extensionViews;
};
}
#endif
@@ -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<const Graphics::GuestMemorySnapshot> snapshots, std::uint64_t programAddress, std::shared_ptr<PreparedDispatch> prepared, std::shared_ptr<const Recipe>* recipe);
@@ -0,0 +1,75 @@
#include "prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp"
#include "BdaAbi.hpp"
#include <spirv/unified1/spirv.hpp>
#include <algorithm>
namespace AgcDriver {
namespace {
template<typename TFeatures>
const TFeatures* findFeatures(const void* chain, VkStructureType type) {
auto* current = static_cast<const VkBaseInStructure*>(chain);
while (current != nullptr) {
if (current->sType == type) return reinterpret_cast<const TFeatures*>(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<VkPhysicalDeviceBufferDeviceAddressFeatures>(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES);
const auto* bytes = findFeatures<VkPhysicalDevice8BitStorageFeatures>(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES);
const auto* indexing = findFeatures<VkPhysicalDeviceDescriptorIndexingFeatures>(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES);
const auto* barycentric = findFeatures<VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR>(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR);
const auto* mesh = findFeatures<VkPhysicalDeviceMeshShaderFeaturesEXT>(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT);
const auto* clock = findFeatures<VkPhysicalDeviceShaderClockFeaturesKHR>(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR);
const auto* maintenance8 = findFeatures<VkPhysicalDeviceMaintenance8FeaturesKHR>(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<std::uint32_t>(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;
}
}
@@ -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<std::uint32_t> capabilities{1};
std::vector<std::string_view> spirvExtensions;
std::unique_ptr<const ShaderDeviceProfile> 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<const ShaderDeviceProfile>(buildTarget(), deviceInfo, state->properties.limits);
check(state->InstanceFunction<PFN_vkCreateDevice>("vkCreateDevice")(selected, &deviceInfo, nullptr, &state->device), "vkCreateDevice");
state->shaderProfile = std::move(shaderProfile);
state->DeviceFunction<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(state->device, family, 0, &state->queue);
APS5_LOG_OUT("Vulkan device ready device=%p queue=%p family=%u", reinterpret_cast<void*>(state->device), reinterpret_cast<void*>(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<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::shared_ptr<const DrawRecipe>* 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<const std::pair<std::uint64_t, std
}
std::shared_ptr<PreparedDispatch> VulkanDevice::PrepareDispatch(const ShaderRecompiler::RecompileResult& shader, std::span<const Graphics::GuestMemorySnapshot> 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<const Graphics::GuestMemorySnapshot> snapshots, std::uint64_t programAddress, std::shared_ptr<PreparedDispatch> prepared, std::shared_ptr<const Recipe>* 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<RecipeHit>& hit, IndirectOutcome& outcome, const std::shared_ptr<PreparedDispatch>& verify, bool refreshByWords) {
ShaderRecompiler::RuntimeAbi::RequireVersion(shader.runtimeAbiVersion);
PerformanceTimer timing("Vulkan.DispatchRecipe");
outcome = {0, 0};
char groupsText[40];
@@ -898,6 +898,7 @@ void ShaderResources::buildPrepare(std::span<const CompiledShader> shaders, cons
std::set<std::uint32_t> 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;
@@ -0,0 +1,127 @@
#include "prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp"
#include "BdaAbi.hpp"
#include <spirv/unified1/spirv.hpp>
#include <algorithm>
#include <array>
#include <iostream>
#include <set>
#include <stdexcept>
#include <string>
#include <type_traits>
namespace {
using AgcDriver::Graphics::Require;
struct ProfileInput {
std::vector<std::uint32_t> capabilities{spv::CapabilityShader, spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess};
std::array<std::string, 2> extensionStrings{"SPV_KHR_physical_storage_buffer", "SPV_KHR_8bit_storage"};
std::array<std::string_view, 2> 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<typename TAction>
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<AgcDriver::ShaderDeviceProfile> && !std::is_move_constructible_v<AgcDriver::ShaderDeviceProfile>);
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<std::uint32_t> bindings;
for (std::uint32_t stage = 0u; stage < ShaderRecompiler::RuntimeAbi::StageCount; ++stage) {
for (std::uint32_t binding = 0u; binding < static_cast<std::uint32_t>(Binding::Count); ++binding) {
Require(bindings.insert(BindingNumber(static_cast<Stage>(stage), static_cast<Binding>(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<Stage>(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;
}
}
@@ -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<std::byte>(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() {
@@ -6,6 +6,7 @@
#include <cstdint>
#include <cstring>
#include <iostream>
#include <string>
namespace {
@@ -21,6 +22,22 @@ constexpr std::array<std::uint32_t, 11> vertexCode{0xf4080100u, 0xfa000000u, 0x4
constexpr std::array<std::uint32_t, 5> 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<AgcDriver::Graphics::CompiledShader, 1> incompatibleShaders{{{ShaderStage::Vertex, &incompatible, 0u}}};
rejectAbi([&] { device.Draw({}, {}, incompatibleShaders); });
std::array<std::uint32_t, 4> descriptor{};
const auto tableAddress = reinterpret_cast<std::uintptr_t>(descriptor.data());
std::array<std::uint32_t, 4> userData{static_cast<std::uint32_t>(tableAddress), static_cast<std::uint32_t>(tableAddress >> 32u), 1u, 1u};
+1
View File
@@ -218,6 +218,7 @@ function(add_shader_recompiler target runtimeTarget)
RecompileResult
ResolveSource
ResourceMaterializer::SpecializationNanoseconds
RuntimeAbi::RequireVersion
SetDebugProbeActive
ShaderCacheDirectory
SrgbDecodeBit
+2
View File
@@ -13,6 +13,7 @@ class RecompileCacheKey {
public:
static void Build(const RecompileRequest& request, std::vector<std::uint64_t>& 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<std::vector<std::uint64_t>, ContextKeyStorage>();
key.clear();
append(key, RuntimeAbi::Version);
append(key, request.shader.stage);
append(key, request.context.waveSize);
append(key, request.context.userDataBaseRegister);
@@ -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 <array>
#include <cstdint>
#include <limits>
@@ -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<std::uint32_t>::max();
std::array<std::uint32_t, DwordCount> dwords {};
@@ -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<std::uint32_t>(kind) + group * static_cast<std::uint32_t>(DescriptorBindingKind::Count);
return RuntimeAbi::BindingNumber(static_cast<RuntimeAbi::Stage>(group), kind);
}
ImageResourceClass ImageBindingResourceClass(DescriptorBindingKind kind) {
@@ -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) {
@@ -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<std::uint32_t>(logical.resources.size());
physical.kind = PhysicalKindFor(logical.kind);
+2
View File
@@ -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 <array>
#include <cstddef>
#include <cstdint>
@@ -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<VertexInput> vertexInputs;
std::int32_t vertexOffsetSgpr = -1;
std::int32_t instanceOffsetSgpr = -1;
+47
View File
@@ -0,0 +1,47 @@
#ifndef CORE_SHADER_RECOMPILER_RUNTIMEABI_HPP
#define CORE_SHADER_RECOMPILER_RUNTIMEABI_HPP
#include <cstdint>
#include <stdexcept>
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<std::uint32_t>(stage);
const auto index = static_cast<std::uint32_t>(binding);
const auto count = static_cast<std::uint32_t>(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<std::uint32_t>(Binding::Samplers));
}
#endif
+6 -4
View File
@@ -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<const std::uint32_t>(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<std::uint32_t> words;
reader.Values(words);
result.spirv = std::move(words);
@@ -849,7 +851,7 @@ bool DecodeResult(std::span<const std::byte> bytes, RecompileResult& result) {
decodeArtifact(reader, result);
decodeInvocation(reader, result);
result.cacheHit = false;
return reader.Done();
return reader.Done() && result.runtimeAbiVersion == RuntimeAbi::Version;
}
std::vector<std::byte> EncodeEntry(std::span<const std::byte> key, const CompiledVariant& variant) {
@@ -884,7 +886,7 @@ LoadStatus DecodeEntry(std::span<const std::byte> file, std::span<const std::byt
decodeArtifact(reader, decoded.artifact);
decodeInfo(reader, decoded.info);
decodeAllocation(reader, decoded.bindings);
if (!reader.Done()) return LoadStatus::Rejected;
if (!reader.Done() || decoded.artifact.runtimeAbiVersion != RuntimeAbi::Version) return LoadStatus::Rejected;
variant.info = std::move(decoded.info);
variant.bindings = std::move(decoded.bindings);
variant.artifact = std::move(decoded.artifact);
+1 -1
View File
@@ -12,7 +12,7 @@
namespace ShaderRecompiler::ShaderDiskCache {
inline constexpr std::uint32_t FormatVersion = 8;
inline constexpr std::uint32_t FormatVersion = 9;
enum class LoadStatus {
Loaded,