diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index c55a4bfe5416..bb2f8334d274 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -3081,7 +3081,7 @@ void VulkanDevice::PrebuildComputePipeline(const ShaderRecompiler::RecompileResu const std::array shaders{{{ShaderRecompiler::ShaderStage::Compute, &shader, 0}}}; const auto pushStages = Graphics::PushConstantStages(shaders); key = ComputePipelineKey::Of(shader, pushStages != 0); - if (shader.spirv.size() < 5 || shader.spirv[0] != 0x07230203u) { + if (shader.spirv.size() < 5) { settle(true); return; } @@ -3127,7 +3127,7 @@ void VulkanDevice::AbandonComputePipelineAhead(const ShaderRecompiler::Recompile } VulkanDevice::PipelineAhead VulkanDevice::ComputePipelineAhead(const ShaderRecompiler::RecompileResult& shader) { - if (shader.spirv.size() < 5 || shader.spirv[0] != 0x07230203u) return PipelineAhead::Unavailable; + if (shader.spirv.size() < 5) return PipelineAhead::Unavailable; const std::array shaders{{{ShaderRecompiler::ShaderStage::Compute, &shader, 0}}}; const auto pushStages = Graphics::PushConstantStages(shaders); if (pushStages != 0 && state->properties.limits.maxPushConstantsSize < Graphics::ComputePushConstantBytes) return PipelineAhead::Unavailable; @@ -5942,7 +5942,7 @@ std::shared_ptr VulkanDevice::PrepareDispatch(const ShaderReco 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; + if (lockedBuild || shader.spirv.size() < 5) return nullptr; static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; const auto start = std::chrono::steady_clock::now(); const Graphics::CompiledShader compute{ShaderRecompiler::ShaderStage::Compute, &shader, 0, registeredImageViews}; @@ -6582,9 +6582,11 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons objects->destroyModule = state->DeviceFunction("vkDestroyShaderModule"); objects->destroyLayout = state->DeviceFunction("vkDestroyPipelineLayout"); 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"); + const auto lease = shader.spirv.Words(); + const std::span words = lease; + if (words.size() < 5 || words[0] != 0x07230203u) throw std::runtime_error("Vulkan compute pipeline: invalid SPIR-V"); + objects->module = Graphics::CreateShaderModule(state->DeviceFunction("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, words.data(), words.size_bytes(), "vkCreateShaderModule"); objects->resourcesLayout = setLayout; - const auto words = shader.spirv.Words(); for (std::size_t cursor = 5; cursor < words.size() && (words[cursor] >> 16u) != 0u && (words[cursor] & 0xffffu) != spv::OpFunction; cursor += words[cursor] >> 16u) { if ((words[cursor] & 0xffffu) == spv::OpDecorate && (words[cursor] >> 16u) == 4u && cursor + 3u < words.size() && words[cursor + 2u] == spv::DecorationSpecId && words[cursor + 3u] == ShaderRecompiler::PipelineSpecialization::StorePages) objects->storePages = true; } @@ -6653,7 +6655,10 @@ VkPipeline VulkanDevice::specializedComputePipeline(const Graphics::Context& con for (std::uint32_t component = 0; component < ShaderRecompiler::PipelineSpecialization::WorkgroupOffsetWords; ++component) replaced.push_back({ShaderRecompiler::PipelineSpecialization::WorkgroupOffsetBase + component, base[component]}); if (storePages) replaced.push_back({ShaderRecompiler::PipelineSpecialization::StorePages, 1u}); const Graphics::PipelineSpecialization specialization(shader, context.atomicLockTable, replaced); - VkShaderModule module = Graphics::CreateShaderModule(state->DeviceFunction("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, shader.spirv.data(), shader.spirv.size() * sizeof(std::uint32_t), "vkCreateShaderModule"); + const auto lease = shader.spirv.Words(); + const std::span words = lease; + if (words.size() < 5 || words[0] != 0x07230203u) throw std::runtime_error("Vulkan compute pipeline: invalid SPIR-V"); + VkShaderModule module = Graphics::CreateShaderModule(state->DeviceFunction("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, words.data(), words.size_bytes(), "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); @@ -6725,7 +6730,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec if (arguments != 0) std::snprintf(groupsText, sizeof(groupsText), "indirect"); else std::snprintf(groupsText, sizeof(groupsText), "%ux%ux%u", x, y, z); APS5_LOG_OUT_DEBUG("Dispatch groups=%s spirvWords=%zu bindings=%zu pushConstants=%zu", groupsText, shader.spirv.size(), shader.bindings.size(), shader.pushConstants.size()); - if (shader.spirv.size() < 5 || shader.spirv[0] != 0x07230203u) { + if (shader.spirv.size() < 5) { throw std::runtime_error("Vulkan dispatch: invalid SPIR-V"); } const std::array shaders{{{ShaderRecompiler::ShaderStage::Compute, &shader, 0, registeredImageViews}}}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp index 730ad1bf7730..73d9559e0432 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp @@ -15,7 +15,7 @@ namespace AgcDriver::Graphics { class PipelineSpecialization { public: static void Validate(const ShaderRecompiler::RecompileResult& shader) { - const auto& words = shader.spirv; + const auto words = shader.spirv.Words(); Require(words.size() >= 5 && words[0] == spv::MagicNumber && words[3] != 0, "invalid specialization module header"); std::set unsignedTypes; std::map constants; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 9cfe5aee066f..1e7bcbab7d06 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -4223,7 +4223,8 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara } for (const auto& shader : shaders) { if (shader.stage != ShaderRecompiler::ShaderStage::Vertex) continue; - Require((shader.program->hostSubgroupSize == 1u || shader.program->hostSubgroupSize == context.subgroup.subgroupSize) && shader.program->spirv.size() >= 5u && shader.program->spirv[1] >= 0x00010000u && shader.program->spirv[1] < 0x00010600u, "stencil replay vertex subgroup contract differs from the physical device"); + const auto words = shader.program->spirv.Words(); + Require((shader.program->hostSubgroupSize == 1u || shader.program->hostSubgroupSize == context.subgroup.subgroupSize) && words.size() >= 5u && words[1] >= 0x00010000u && words[1] < 0x00010600u, "stencil replay vertex subgroup contract differs from the physical device"); } Require(static_cast(draw.firstInstance) + draw.instanceCount <= 0x100000000ull && (draw.indexed || static_cast(draw.firstVertex) + draw.indexCount <= 0x100000000ull), "stencil replay draw indices overflow"); Require(!state.depth || HasStencil(state.depth->format), "stencil replay requires an eight-bit stencil format"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index 1060dc7a0954..b1c1c3c80309 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -446,7 +446,8 @@ std::pair HostDepthBounds(const Context& context, const State& sta } std::vector QuantizeFragmentDepth16(const CompiledShader& shader) { - const auto words = shader.program->spirv.Words(); + const auto lease = shader.program->spirv.Words(); + const std::span words = lease; Require(words.size() >= 5 && words[0] == spv::MagicNumber && words[3] != 0, "invalid fragment SPIR-V header"); std::uint32_t glslStd450Id = 0; std::uint32_t entryPointId = 0; @@ -901,7 +902,8 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput for (std::uint32_t i = 0; i < shaders.size(); ++i) { const auto& shader = *shaders[i].program; const auto patched = (barycentricPatches || state.rectList) && shaders[i].stage == ShaderRecompiler::ShaderStage::Vertex ? DemoteVertexLayerOutput(shader.spirv.Words()) : quantizeDepth16 && shaders[i].stage == ShaderRecompiler::ShaderStage::Fragment ? QuantizeFragmentDepth16(shaders[i]) : std::vector{}; - const auto words = patched.empty() ? shader.spirv.Words() : std::span(patched); + const auto leased = shader.spirv.Words(); + const std::span words = patched.empty() ? std::span(leased) : std::span(patched); _modules[i] = CreateShaderModule(context, words.data(), words.size() * sizeof(std::uint32_t), "vkCreateShaderModule graphics"); const auto stage = VulkanStage(shaders[i].stage); stages[i].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 0c171442ca9c..9feb69493b09 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -192,7 +192,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi Require(binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer && binding.kind == ShaderRecompiler::DescriptorKind::StorageBuffer && binding.descriptorSet == 0 && binding.count == 1 && binding.guestDescriptor.empty() && !binding.readOnly, "invalid rect-list fault buffer contract"); } const auto model = mesh ? spv::ExecutionModelMeshEXT : control ? spv::ExecutionModelTessellationControl : evaluation ? spv::ExecutionModelTessellationEvaluation : geometry ? spv::ExecutionModelGeometry : vertex ? spv::ExecutionModelVertex : spv::ExecutionModelFragment; - const auto& words = shader.spirv; + const auto words = shader.spirv.Words(); Require(words.size() >= 5, "SPIR-V header is truncated: " + std::to_string(words.size()) + " words"); Require(words[0] == spv::MagicNumber, "invalid SPIR-V magic number: " + std::to_string(words[0])); diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index 595995318a2e..de77ba9fb5a8 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -13368,10 +13368,11 @@ void validationTests() { pixel.spirv = ShaderRecompiler::SpecializeSpirv(makeModule({.fragment = true, .terminateInvocation = true})); std::size_t terminates = 0; std::size_t declarations = 0; - for (std::size_t at = 5; at < pixel.spirv.size(); at += pixel.spirv[at] >> 16u) { - const auto op = pixel.spirv[at] & 0xffffu; + const auto words = pixel.spirv.Words(); + for (std::size_t at = 5; at < words.size(); at += words[at] >> 16u) { + const auto op = words[at] & 0xffffu; if (op == spv::OpTerminateInvocation) ++terminates; - if (op == spv::OpExtension && std::string_view(reinterpret_cast(&pixel.spirv[at + 1])) == "SPV_KHR_terminate_invocation") ++declarations; + if (op == spv::OpExtension && std::string_view(reinterpret_cast(&words[at + 1])) == "SPV_KHR_terminate_invocation") ++declarations; } Require(terminates == 1u && declarations == 1u, "specialization dropped OpTerminateInvocation or its extension declaration"); validateTerminate(true); @@ -14743,9 +14744,9 @@ void pipelineJournalTests(bool longPath = false, bool extended = false) { const auto& constFirst = first; auto copy = first; const auto& constCopy = copy; - Require(!constFirst.Identity().Empty() && constFirst.Identity() == constCopy.Identity() && constFirst.spirv.data() == constCopy.spirv.data(), "a copied result did not share its module and identity"); + Require(!constFirst.Identity().Empty() && constFirst.Identity() == constCopy.Identity() && constFirst.spirv.Words().data() == constCopy.spirv.Words().data(), "a copied result did not share its module and identity"); copy.spirv[8] = 99; - Require(!(constCopy.Identity() == constFirst.Identity()) && constCopy.spirv.data() != constFirst.spirv.data() && constFirst.Identity() == module(1).Identity(), "writing a copied module did not give it an identity of its own"); + Require(!(constCopy.Identity() == constFirst.Identity()) && constCopy.spirv.Words().data() != constFirst.spirv.Words().data() && constFirst.Identity() == module(1).Identity(), "writing a copied module did not give it an identity of its own"); auto specialized = module(1); specialized.specialization.push_back({3, 4}); Require(!(specialized.Identity() == constFirst.Identity()), "specialization constants did not enter the identity"); diff --git a/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp b/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp index 4d29eea23004..26ed01c88141 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp @@ -188,7 +188,7 @@ void DrawMesh(AgcDriver::VulkanDevice& device, const MeshDraw& setup) { ShaderRecompiler::GraphicsCompileContext{0, {}, setup.mesh, std::nullopt, {setup.draw.indexAddress, setup.draw.indexCount, setup.draw.indexSize, setup.draw.instanceCount}} }; 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"); + Require(ReadsNumWorkgroups(meshResult.spirv.Words()), "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"); diff --git a/core/libs/prx/libSceAgcDriver/tests/MeshOutputStaging.cpp b/core/libs/prx/libSceAgcDriver/tests/MeshOutputStaging.cpp index fd19e2fe42b3..88827bd03e59 100644 --- a/core/libs/prx/libSceAgcDriver/tests/MeshOutputStaging.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/MeshOutputStaging.cpp @@ -20,7 +20,7 @@ std::uint32_t checkStagingInitialized(const ShaderRecompiler::RecompileResult& r std::uint32_t outputStores = 0; for (std::size_t at = 5; at < words.size() && (words[at] >> 16u) != 0; at += words[at] >> 16u) { const auto op = static_cast(words[at] & 0xffffu); - const auto instruction = words.subspan(at, words[at] >> 16u); + const auto instruction = std::span(words).subspan(at, words[at] >> 16u); if (op == spv::OpVariable) variables[instruction[2]] = instruction; if (op == spv::OpConstantNull || op == spv::OpConstant || op == spv::OpConstantComposite) constants[instruction[2]] = op; if (op == spv::OpAccessChain || op == spv::OpInBoundsAccessChain) { diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp index f45f4ec9a397..7530365cda4e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp @@ -15,6 +15,7 @@ #include "tests/CommandLineArgument.hpp" #include #include +#include #include #include #include @@ -571,6 +572,106 @@ void verifyEntryRoundTrip() { require(ShaderDiskCache::DecodeEntry(incompatibleFile, key, decoded) == ShaderDiskCache::LoadStatus::Rejected, "an entry with an incompatible runtime ABI loads"); } +void verifyZstdRoundTrip() { + SampleRequest sample; + const auto key = sample.Key(); + auto variant = sampleVariant(); + variant.artifact.spirv = std::vector(32768u); + for (std::size_t index = 0; index < variant.artifact.spirv.size(); ++index) variant.artifact.spirv[index] = static_cast(index % 127u) * 0x01010101u; + setEnvironment("APS5_NO_SHADER_CACHE_ZSTD", ""); + const auto compressed = ShaderDiskCache::EncodeEntry(key, variant); + setEnvironment("APS5_NO_SHADER_CACHE_ZSTD", "1"); + const auto raw = ShaderDiskCache::EncodeEntry(key, variant); + setEnvironment("APS5_NO_SHADER_CACHE_ZSTD", ""); + require(compressed.size() * 2u < raw.size(), "SPIR-V zstd did not reduce the encoded entry"); + auto stored = std::make_shared>(compressed); + CompiledVariant decoded; + require(ShaderDiskCache::DecodeEntry(*stored, key, decoded, stored) == ShaderDiskCache::LoadStatus::Loaded, "a compressed entry does not decode"); + require(decoded.artifact.spirv.Compressed() && !decoded.artifact.spirv.Materialized(), "compressed SPIR-V was materialized while loading"); + require(decoded.artifact.spirv.ContentHash() == variant.artifact.spirv.ContentHash() && decoded.artifact.spirv.size() == variant.artifact.spirv.size(), "compressed SPIR-V metadata differs without materialization"); + require(!decoded.artifact.spirv.Materialized(), "compressed SPIR-V metadata materialized the payload"); + { + const auto words = decoded.artifact.spirv.Words(); + require(decoded.artifact.spirv.Materialized() && std::ranges::equal(words, variant.artifact.spirv.Words()), "compressed SPIR-V does not round trip through a lease"); + } + require(!decoded.artifact.spirv.Materialized(), "a released SPIR-V lease retained its decompressed words"); + CompiledVariant rawDecoded; + require(ShaderDiskCache::DecodeEntry(raw, key, rawDecoded) == ShaderDiskCache::LoadStatus::Loaded && !rawDecoded.artifact.spirv.Compressed(), "the zstd kill switch did not write raw SPIR-V"); + requireSameVariant(variant, rawDecoded, "raw kill switch round trip"); + auto journal = sampleResult(); + journal.spirv = std::vector(16384u, 0x12345678u); + std::vector journalBytes; + ShaderDiskCache::EncodeResult(journal, journalBytes); + RecompileResult journalDecoded; + require(ShaderDiskCache::DecodeResult(journalBytes, journalDecoded) && !journalDecoded.spirv.Compressed(), "the pipeline journal SPIR-V codec is compressed instead of raw"); + require(std::ranges::equal(journalDecoded.spirv.Words(), journal.spirv.Words()), "the pipeline journal SPIR-V changed"); + auto corrupt = compressed; + corrupt[corrupt.size() - 5u] ^= std::byte{0x40}; + require(ShaderDiskCache::DecodeEntry(corrupt, key, decoded) == ShaderDiskCache::LoadStatus::Rejected, "a corrupt compressed entry loads"); + require(ShaderDiskCache::DecodeEntry(std::span(compressed).first(compressed.size() / 2u), key, decoded) == ShaderDiskCache::LoadStatus::Rejected, "a truncated compressed entry loads"); + auto oversized = compressed; + constexpr std::size_t fileHeaderBytes = 48; + constexpr std::size_t payloadHashOffset = 40; + constexpr std::size_t spirvWordCountOffset = sizeof(std::uint32_t) * 2u; + const auto payloadOffset = (fileHeaderBytes + key.size() + 7u) / 8u * 8u; + const std::uint64_t tooManyWords = ShaderDiskCache::MaxCachedSpirvWords + 1u; + std::memcpy(oversized.data() + payloadOffset + spirvWordCountOffset, &tooManyWords, sizeof(tooManyWords)); + const auto payloadHash = HashBytes(std::span(oversized).subspan(payloadOffset)); + std::memcpy(oversized.data() + payloadHashOffset, &payloadHash, sizeof(payloadHash)); + require(ShaderDiskCache::DecodeEntry(oversized, key, decoded) == ShaderDiskCache::LoadStatus::Rejected, "a cached SPIR-V count above the word limit loads"); +} + +void verifyZstdConcurrent() { + SampleRequest sample; + const auto key = sample.Key(); + auto variant = sampleVariant(); + variant.artifact.spirv = std::vector(16384u, 0x12345678u); + const auto file = ShaderDiskCache::EncodeEntry(key, variant); + auto stored = std::make_shared>(file); + CompiledVariant decoded; + require(ShaderDiskCache::DecodeEntry(*stored, key, decoded, stored) == ShaderDiskCache::LoadStatus::Loaded && decoded.artifact.spirv.Compressed(), "the concurrent fixture is not compressed"); + std::atomic start{false}; + std::atomic ready{0}; + std::vector> readers; + for (unsigned thread = 0; thread < 8u; ++thread) { + readers.push_back(std::async(std::launch::async, [&] { + ready.fetch_add(1u, std::memory_order_release); + while (!start.load(std::memory_order_acquire)) std::this_thread::yield(); + for (unsigned iteration = 0; iteration < 64u; ++iteration) { + const auto words = decoded.artifact.spirv.Words(); + require(words.size() == variant.artifact.spirv.size() && words.front() == 0x12345678u && words.back() == 0x12345678u, "a concurrent compressed lease returned other words"); + require(decoded.artifact.spirv.ContentHash() == variant.artifact.spirv.ContentHash(), "a concurrent compressed read changed the identity"); + } + })); + } + while (ready.load(std::memory_order_acquire) != readers.size()) std::this_thread::yield(); + start.store(true, std::memory_order_release); + for (auto& reader : readers) reader.get(); + require(!decoded.artifact.spirv.Materialized(), "concurrent readers retained decompressed SPIR-V after their leases"); +} + +void verifyLeaseLifetime() { + const std::vector expected{spv::MagicNumber, 0x00010000u, 1u, 2u, 3u}; + SharedSpirv::Lease raw; + { + SharedSpirv owned(expected); + raw = owned.Words(); + } + require(std::ranges::equal(raw, expected), "a raw SPIR-V lease did not retain its owner"); + SampleRequest sample; + const auto key = sample.Key(); + auto variant = sampleVariant(); + variant.artifact.spirv = std::vector(16384u, 0x12345678u); + const auto file = ShaderDiskCache::EncodeEntry(key, variant); + SharedSpirv::Lease compressed; + { + CompiledVariant decoded; + require(ShaderDiskCache::DecodeEntry(file, key, decoded) == ShaderDiskCache::LoadStatus::Loaded && decoded.artifact.spirv.Compressed(), "the lease lifetime fixture is not compressed"); + compressed = decoded.artifact.spirv.Words(); + } + require(std::ranges::equal(compressed, variant.artifact.spirv.Words()), "a compressed SPIR-V lease did not retain its decompressed owner"); +} + std::vector packBytes(const std::vector, std::vector>>& entries) { using namespace ShaderRecompiler::ShaderDiskCache; std::vector records; @@ -605,30 +706,30 @@ void verifyPrebuiltPackOwnership(const std::filesystem::path& directory) { require(WriteFileAtomically(path, packBytes({{key, EncodeEntry(key, variant)}})), "cannot write the ownership test pack"); CompiledVariant first, second; PackLoadTimings timings; - const std::uint32_t* words = nullptr; + const std::byte* storedWords = nullptr; { CachePack pack(path); require(pack.Valid(), "the ownership test pack is invalid"); require(pack.Load(key, first, timings) == LoadStatus::Loaded, "cannot load the first packed variant"); require(pack.Load(key, second, timings) == LoadStatus::Loaded, "cannot load the second packed variant"); - words = first.artifact.spirv.Words().data(); - require(!first.artifact.spirv.empty() && words == second.artifact.spirv.Words().data(), "packed SPIR-V was copied instead of sharing its mapping"); + storedWords = first.artifact.spirv.MappedBytes().data(); + require(!first.artifact.spirv.empty() && storedWords == second.artifact.spirv.MappedBytes().data(), "packed SPIR-V was copied instead of sharing its mapping"); } requireSameVariant(variant, first, "packed variant outlives its pack"); #ifdef _WIN32 MEMORY_BASIC_INFORMATION region{}; - require(VirtualQuery(words, ®ion, sizeof(region)) == sizeof(region) && region.Type == MEM_MAPPED, "packed SPIR-V lost its mapping after pack destruction"); + require(VirtualQuery(storedWords, ®ion, sizeof(region)) == sizeof(region) && region.Type == MEM_MAPPED, "packed SPIR-V lost its mapping after pack destruction"); #endif auto edited = first.artifact.spirv; edited[0] ^= 1u; - require(edited.Words().data() != words && edited.Words()[0] != first.artifact.spirv.Words()[0], "editing packed SPIR-V modified the shared mapping"); + require(!edited.Compressed() && edited.Words()[0] != first.artifact.spirv.Words()[0], "editing packed SPIR-V modified the shared mapping"); first = {}; requireSameVariant(variant, second, "last packed variant retains its mapping"); std::vector published; require(ReadWholeFile(path, published) && published == packBytes({{key, EncodeEntry(key, variant)}}), "editing packed SPIR-V modified the cache file"); second = {}; #ifdef _WIN32 - require(VirtualQuery(words, ®ion, sizeof(region)) == sizeof(region) && region.State == MEM_FREE, "the final packed variant did not release its mapping"); + require(VirtualQuery(storedWords, ®ion, sizeof(region)) == sizeof(region) && region.State == MEM_FREE, "the final packed variant did not release its mapping"); #endif const auto offset = sizeof(PackHeader) + sizeof(PackRecord); published.insert(published.begin() + offset, std::byte{}); @@ -646,7 +747,9 @@ void verifyPrebuiltPackOwnership(const std::filesystem::path& directory) { CachePack pack(path); require(pack.Valid(), "an unaligned packed entry was rejected"); require(pack.Load(key, first, timings) == LoadStatus::Loaded && pack.Load(key, second, timings) == LoadStatus::Loaded, "an unaligned packed entry did not load"); - require(first.artifact.spirv.Words().data() != second.artifact.spirv.Words().data(), "an unaligned packed module did not use aligned owned storage"); + const auto firstWords = first.artifact.spirv.Words(); + const auto secondWords = second.artifact.spirv.Words(); + require(firstWords.data() != secondWords.data(), "an unaligned packed module did not use aligned owned storage"); } requireSameVariant(variant, first, "unaligned packed variant outlives its pack"); requireSameVariant(variant, second, "second unaligned packed variant outlives its pack"); @@ -1247,6 +1350,22 @@ void verifyStore() { require(ShaderDiskCache::Load(key, loaded), "a rewritten entry does not load"); } +void verifyOversizedStore() { + require(ShaderDiskCache::Enabled(), "the disk cache is not enabled"); + const std::vector key{std::byte{0x6f}, std::byte{0x76}, std::byte{0x72}, std::byte{0x73}, std::byte{0x7a}}; + auto oversized = sampleVariant(); + oversized.artifact.spirv = std::vector(ShaderDiskCache::MaxCachedSpirvWords + 1u); + const auto before = ShaderDiskCache::Totals(); + ShaderDiskCache::Store(key, std::make_shared(std::move(oversized))); + ShaderDiskCache::Flush(); + require(ShaderDiskCache::Totals().writeFailures == before.writeFailures + 1, "an oversized entry was not counted as a write failure"); + require(!std::filesystem::exists(ShaderDiskCache::EntryDirectory() / ShaderDiskCache::EntryName(key)), "an oversized entry was written"); + ShaderDiskCache::Store(key, std::make_shared(sampleVariant())); + ShaderDiskCache::Flush(); + CompiledVariant loaded; + require(ShaderDiskCache::Load(key, loaded), "an entry does not load after a failed oversized write"); +} + void verifySpecializedStore() { require(ShaderDiskCache::Enabled(), "the disk cache is not enabled"); const std::vector key{std::byte{0x73}, std::byte{0x70}, std::byte{0x65}, std::byte{0x63}, std::byte{0x01}}; @@ -1316,20 +1435,20 @@ void verifyPersist() { const auto path = ShaderDiskCache::EntryDirectory() / ShaderDiskCache::EntryName(key); #ifdef _WIN32 MEMORY_BASIC_INFORMATION region{}; - require(VirtualQuery(persisted->artifact.spirv.data(), ®ion, sizeof(region)) == sizeof(region) && region.Type == MEM_MAPPED, "persisted SPIR-V is not a mapped cache entry"); + require(VirtualQuery(persisted->artifact.spirv.MappedBytes().data(), ®ion, sizeof(region)) == sizeof(region) && region.Type == MEM_MAPPED, "persisted SPIR-V is not a mapped cache entry"); const auto close = [](void* handle) { CloseHandle(handle); }; std::unique_ptr writer(CreateFileW(path.c_str(), GENERIC_WRITE | DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr), close); require(writer.get() != INVALID_HANDLE_VALUE, "cannot retain the published cache writer"); CompiledVariant loaded; require(ShaderDiskCache::Load(key, loaded), "cannot load a cache entry while its writer retains rename access"); const auto& loadedWords = loaded.artifact.spirv; - require(VirtualQuery(loadedWords.data(), ®ion, sizeof(region)) == sizeof(region) && region.Type == MEM_MAPPED, "cache loading with a retained writer did not map the entry"); + require(VirtualQuery(loadedWords.MappedBytes().data(), ®ion, sizeof(region)) == sizeof(region) && region.Type == MEM_MAPPED, "cache loading with a retained writer did not map the entry"); writer.reset(); #endif requireSameVariant(variant, *persisted, "persist round trip"); auto detached = persisted->artifact.spirv; detached[0] ^= 1u; - require(detached[0] != persisted->artifact.spirv[0], "changing a copied mapped module changed its owner"); + require(detached[0] != persisted->artifact.spirv.Words()[0], "changing a copied mapped module changed its owner"); #ifdef _WIN32 if (PosixReplaceUnsupported(path.parent_path())) { std::fprintf(stderr, "shader disk cache: %s has no POSIX rename (ERROR_INVALID_PARAMETER), so a mapped persisted entry cannot be replaced there; skipping that check\n", path.parent_path().string().c_str()); @@ -1350,15 +1469,22 @@ void verifyReleaseMapped() { require(!owned.Mapped() && std::ranges::equal(words, owned.Words()), "releasing an owned module changed its words"); SampleRequest sample; const auto key = sample.Key(); - const auto variant = sampleVariant(); + const auto variant = [&] { + auto large = sampleVariant(); + large.artifact.spirv = std::vector(16384u, 0x12345678u); + return large; + }(); const auto persisted = ShaderDiskCache::Persist(key, variant); require(persisted != nullptr, "a persisted entry was not read back"); + require(persisted->artifact.spirv.Compressed() && !persisted->artifact.spirv.Materialized(), "persisting compressed SPIR-V materialized it"); #ifdef _WIN32 require(persisted->artifact.spirv.Mapped(), "persisted SPIR-V is not a mapped cache entry"); #endif ShaderDiskCache::ReleaseMapped(persisted->artifact.spirv); ShaderDiskCache::ReleaseMapped(persisted->artifact.spirv); + require(!persisted->artifact.spirv.Materialized(), "releasing compressed pages materialized SPIR-V"); requireSameArtifact(variant.artifact, persisted->artifact, "a mapped entry whose pages were released"); + require(!persisted->artifact.spirv.Materialized(), "comparing compressed SPIR-V retained its decompressed words"); } #ifdef _WIN32 @@ -1398,7 +1524,7 @@ void verifyLongHostPaths() { "the long-path cache entry was not correctly published before mapping"); require(persisted != nullptr, "a long-path cache entry was not persisted and mapped"); MEMORY_BASIC_INFORMATION region{}; - require(VirtualQuery(persisted->artifact.spirv.data(), ®ion, sizeof(region)) == sizeof(region) && region.Type == MEM_MAPPED, + require(VirtualQuery(persisted->artifact.spirv.MappedBytes().data(), ®ion, sizeof(region)) == sizeof(region) && region.Type == MEM_MAPPED, "long-path persisted SPIR-V is not mapped"); requireSameVariant(variant, *persisted, "long-path persist round trip"); CompiledVariant loaded; @@ -1565,7 +1691,7 @@ void verifyInvocationIsolation() { require(first.variantId != 0 && first.variantId == second.variantId, "a buffer address change did not reuse the artifact"); require(second.cacheHit, "the second invocation missed the compiled cache"); requireSameArtifact(first, second, "invocations sharing an artifact"); - require(first.spirv.data() == second.spirv.data(), "invocations duplicated SPIR-V storage"); + require(first.spirv.Words().data() == second.spirv.Words().data(), "invocations duplicated SPIR-V storage"); require(!sameBindings(first.bindings, second.bindings) || first.pushConstants != second.pushConstants, "the second invocation reused stale resource data"); request.userData[0] -= 0x10000u; const auto restored = Recompile(request.request); @@ -1588,17 +1714,17 @@ void verifyInvocationIsolation() { const auto changed = Recompile(request.request); require(changed.cacheHit && first.variantId == changed.variantId, "buffer metadata changed the compiled variant"); if ((descriptor[0] & 3u) == (original[0] & 3u) && (descriptor[1] & 0xffff0000u) == (original[1] & 0xffff0000u) && descriptor[3] == original[3] && (descriptor[0] != 0u || (descriptor[1] & 0xffffu) != 0u)) { - require(first.spirv.data() == changed.spirv.data() && first.PipelineVariantId() == changed.PipelineVariantId(), "buffer address or size rebuilt the specialized module"); + require(first.spirv.Words().data() == changed.spirv.Words().data() && first.PipelineVariantId() == changed.PipelineVariantId(), "buffer address or size rebuilt the specialized module"); } if (descriptor[2] == 0u) { - require(first.spirv.data() == changed.spirv.data() && first.PipelineVariantId() == changed.PipelineVariantId(), "a null V# did not specialize with the bound slot's substitute"); + require(first.spirv.Words().data() == changed.spirv.Words().data() && first.PipelineVariantId() == changed.PipelineVariantId(), "a null V# did not specialize with the bound slot's substitute"); continue; } ComputeRequest fresh(false); fresh.userData = descriptor; requireSameResult(Recompile(fresh.request), changed, "reused binding plan against fresh compilation"); const auto repeated = Recompile(request.request); - require(changed.spirv.data() == repeated.spirv.data() && changed.PipelineVariantId() == repeated.PipelineVariantId(), "buffer specialization did not reuse its module"); + require(changed.spirv.Words().data() == repeated.spirv.Words().data() && changed.PipelineVariantId() == repeated.PipelineVariantId(), "buffer specialization did not reuse its module"); } request.userData = original; request.userData[3] |= 0x40000000u; @@ -1617,11 +1743,12 @@ void verifyBufferAlignmentSpecialization() { const auto misses = diskMisses(); const auto aligned = Recompile(request.request); const auto countAtomics = [](const RecompileResult& result) { + const auto words = result.spirv.Words(); std::size_t atomics = 0; - for (std::size_t cursor = 5; cursor < result.spirv.size();) { - const auto count = result.spirv[cursor] >> 16u; - require(count != 0u && count <= result.spirv.size() - cursor, "invalid specialized buffer instruction"); - if ((result.spirv[cursor] & 0xffffu) == spv::OpAtomicCompareExchange) ++atomics; + for (std::size_t cursor = 5; cursor < words.size();) { + const auto count = words[cursor] >> 16u; + require(count != 0u && count <= words.size() - cursor, "invalid specialized buffer instruction"); + if ((words[cursor] & 0xffffu) == spv::OpAtomicCompareExchange) ++atomics; cursor += count; } return atomics; @@ -1634,11 +1761,11 @@ void verifyBufferAlignmentSpecialization() { require(countAtomics(unaligned) == 2u, "unaligned DWORD store did not split into two atomic updates"); request.userData[0] += 0x10000u; const auto relocated = Recompile(request.request); - require(unaligned.spirv.data() == relocated.spirv.data(), "relocation with unchanged alignment rebuilt the buffer specialization"); + require(unaligned.spirv.Words().data() == relocated.spirv.Words().data(), "relocation with unchanged alignment rebuilt the buffer specialization"); } request.userData[0] = 0x10000000u; const auto restored = Recompile(request.request); - require(restored.spirv.data() == aligned.spirv.data(), "unaligned buffers replaced the aligned specialization"); + require(restored.spirv.Words().data() == aligned.spirv.Words().data(), "unaligned buffers replaced the aligned specialization"); } void verifyBindingPlanSelection() { @@ -2973,6 +3100,7 @@ std::filesystem::path planEntryPath(PlanFixture& fixture) { int runPlanLoadingProcess(std::string_view mode) { if (mode == "--load-plan-switch") setEnvironment("APS5_TRACE_IMAGE_TABLE", "1"); + if (mode == "--load-plan-zstd-off") setEnvironment("APS5_NO_SHADER_CACHE_ZSTD", "1"); if (mode == "--load-plan-off") setEnvironment("APS5_NO_PERF_DISK_PLANS", "1"); if (mode == "--load-plan-reuse-off") { setEnvironment("APS5_NO_TABLE_SNAPSHOT_REUSE", "1"); @@ -2991,7 +3119,7 @@ int runPlanLoadingProcess(std::string_view mode) { std::cout << "a process with another switch value rebuilt all " << count << " plans\n"; return 0; } - if (mode == "--load-plan") { + if (mode == "--load-plan" || mode == "--load-plan-zstd-off") { require(builds == 0u && totals.planHits == count && totals.planMisses == 0u && totals.planLoadFailures == 0u && totals.hits == count && totals.misses == 0u, "the second process ran the front end" + counts); } else if (mode == "--load-plan-reuse-off") { require(builds == 0u && totals.planHits == count && totals.planMisses == 0u && totals.planLoadFailures == 0u && totals.hits == count && totals.misses == 0u, "turning the image table reuse off changed the stored plan or variant keys" + counts); @@ -3056,6 +3184,7 @@ void verifyPlanAcrossProcesses(const std::filesystem::path& self) { const auto run = [&](const char* mode) { require(RunSelf(self, mode) == 0, std::string("the process ") + mode + " failed"); }; + run("--load-plan-zstd-off"); run("--load-plan"); run("--load-plan-off"); run("--load-plan-reuse-off"); @@ -3141,6 +3270,13 @@ int main(int argc, char** argv) { std::cout << "artifact codec tests passed\n"; return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--zstd-codec") { + verifyZstdRoundTrip(); + verifyZstdConcurrent(); + verifyLeaseLifetime(); + std::cout << "zstd codec tests passed\n"; + return 0; + } #ifdef _WIN32 if (argc == 2 && std::string_view(argv[1]) == "--host-stderr") { verifyHostStandardError(); @@ -3171,6 +3307,9 @@ int main(int argc, char** argv) { verifyResultRoundTrip(); verifyElementFlags(); verifyEntryRoundTrip(); + verifyZstdRoundTrip(); + verifyZstdConcurrent(); + verifyLeaseLifetime(); verifyPrebuiltPack(directory / "packs"); verifyArtifactStorageIsolation(); verifyHashBytes(); @@ -3181,6 +3320,7 @@ int main(int argc, char** argv) { verifyPlanKey(); verifySharedPlans(); verifyStore(); + verifyOversizedStore(); verifySpecializedStore(); verifySpecializedSwitch(argv[0]); verifyPersist(); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 3fea98ed73aa..c07ae499ff3f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -447,7 +447,7 @@ void verifySpecializedModuleRelease() { require(again.specializationId == specializationId, "specialized module release: a module built again from its key got another specialization ID"); require(std::ranges::equal(again.spirv.Words(), words), "specialized module release: a module built again from its key has other words"); const auto shared = Recompile(pixel); - require(shared.spirv.data() == again.spirv.data(), "specialized module release: a second result of a live module copied its words"); + require(shared.spirv.Words().data() == again.spirv.Words().data(), "specialized module release: a second result of a live module copied its words"); } void verifyLayerSpecializationRelease() { @@ -495,7 +495,7 @@ void verifyLayerSpecializationRelease() { require(again.specialization == expected, "layer module release: rebuilding the words lost the layer constants"); require(again.specializationId == specializationId && std::ranges::equal(again.spirv.Words(), words), "layer module release: rebuilding changed the module identity or words"); const auto shared = Recompile(request); - require(shared.specialization == expected && shared.spirv.data() == again.spirv.data(), "layer module release: a live cache hit lost constants or copied the words"); + require(shared.specialization == expected && shared.spirv.Words().data() == again.spirv.Words().data(), "layer module release: a live cache hit lost constants or copied the words"); } const std::vector& resultMemoPixelCode() { @@ -3862,7 +3862,7 @@ void verifyImageTableKeys() { require(mapB[Abi::HeaderTableCount] == 1u && mapB[Abi::TableHeader(0) + Abi::TableKeyCount] == Entries, "image table keys: the large table was not snapshotted whole"); if (code.size() == TableWholeCode.size()) require(mapB[Abi::HeaderElementCount] > 2000u, "image table keys: the large table's entries were not bound"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(a.spirv, request.target.vulkanVersion, request.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(a.spirv.Words(), request.target.vulkanVersion, request.target.spirvVersion)); #endif } } @@ -5423,15 +5423,15 @@ void verifyImageTables() { require(map.at(codes[0] + Abi::ImageRecordElement) == 0u && map.at(codes[1] + Abi::ImageRecordElement) == 1u && modes.at(modeOf(codes[0])).numericClass == IrTextureNumericClass::Float && modes.at(modeOf(codes[1])).numericClass == IrTextureNumericClass::Uint, "image tables: the records are wrong"); require(map.at(codes[1] + Abi::ImageRecordDword3) == heap[1][3], "image tables: the record does not carry the T# swizzle word"); require(result.imageTableFaults == 0u, "image tables: a narrowed table expects faults"); - const auto uniform = ScanTableSpirv(result.spirv); + const auto uniform = ScanTableSpirv(result.spirv.Words()); require(uniform.runtimeArray && uniform.dynamicIndexing && uniform.switched, "image tables: the SPIR-V does not index the table"); require(!uniform.shaderNonUniform && !uniform.nonUniform, "image tables: a single-subgroup workgroup was decorated NonUniform"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(result.spirv, request.target.vulkanVersion, request.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(result.spirv.Words(), request.target.vulkanVersion, request.target.spirvVersion)); #endif const auto split = CompileTable(TableRequest(TableMaterialCode, userData, 64u)); - const auto splitScan = ScanTableSpirv(split.result->spirv); + const auto splitScan = ScanTableSpirv(split.result->spirv.Words()); require(splitScan.shaderNonUniform && splitScan.nonUniform, "image tables: a split wave's table index is not decorated NonUniform"); for (const auto unmapped : {9u, 0xffffffffu}) { @@ -5486,7 +5486,7 @@ void verifyImageTables() { require(queryCodes.size() == 4u && queryCodes[0] == queryCodes[3] && queryCodes[2] == Abi::NullCode && queryCodes[1] != queryCodes[0], "image tables: the queried and sampled table's map is wrong"); require(!query.result->spirv.empty(), "image tables: a T# both queried and sampled did not compile"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(query.result->spirv, request.target.vulkanVersion, request.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(query.result->spirv.Words(), request.target.vulkanVersion, request.target.spirvVersion)); #endif heap[0][3] = (heap[0][3] & 0x0fffffffu) | (1u << 28u); @@ -6498,7 +6498,7 @@ void verifyPointerImageTable() { require((invalidFlags & Abi::PoisonFlag) != 0u && compiled.result->imageTablePoison.at(invalidFlags & ~Abi::PoisonFlag).reason == static_cast(Abi::PoisonReason::NotImage), "pointer image table: an invalid entry is not NotImage poison"); require(compiled.result->imageTableRanges == tables.ranges && map[Abi::TableHeader(0) + Abi::TableBaseLow] == static_cast(base) && map[Abi::TableHeader(0) + Abi::TableBaseHigh] == static_cast(base >> 32u), "pointer image table: the compiled table is wrong"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(compiled.result->spirv, masked.target.vulkanVersion, masked.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(compiled.result->spirv.Words(), masked.target.vulkanVersion, masked.target.spirvVersion)); #endif for (const std::uint32_t addend : {32u, 64u}) { auto offsetCode = maskedCode; @@ -6518,7 +6518,7 @@ void verifyPointerImageTable() { for (std::size_t i = 0; i < snapshot.words.size(); ++i) require(offsetSnapshot.words.at(i).dwords == snapshot.words[i].dwords, "pointer image table masked addend: the descriptor words changed"); require(TableCovered(offsetCompiled.regions, root + Palette / 4u, Entries * 32u), "pointer image table masked addend: the descriptor bytes were not captured"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(offsetCompiled.result->spirv, offsetRequest.target.vulkanVersion, offsetRequest.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(offsetCompiled.result->spirv.Words(), offsetRequest.target.vulkanVersion, offsetRequest.target.spirvVersion)); #endif } @@ -7013,7 +7013,7 @@ void verifyPointerChainImageTable() { const auto& changed = relinked.capture->snapshot.tables.tables.at(0); require(changed.codes[1] == changed.codes[2] && changed.codes[1] != changed.codes[0], "pointer chain image table: changing the second pointer of a record did not change its T#"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(compiled.result->spirv, request.target.vulkanVersion, request.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(compiled.result->spirv.Words(), request.target.vulkanVersion, request.target.spirvVersion)); #endif store(links[1].data() + 4u, address(descriptors[1].data())); @@ -7290,9 +7290,9 @@ void verifyDescriptorPhis() { const auto memoryRegions = memory.Regions(); request.context.memory = memoryRegions; const auto compiled = Recompile(request, *capture); - require(countOps(compiled->spirv, OpImageSampleExplicitLod) == 2u, "descriptor Phi: the specialized SPIR-V does not sample once per edge"); + require(countOps(compiled->spirv.Words(), OpImageSampleExplicitLod) == 2u, "descriptor Phi: the specialized SPIR-V does not sample once per edge"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(compiled->spirv, request.target.vulkanVersion, request.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(compiled->spirv.Words(), request.target.vulkanVersion, request.target.spirvVersion)); #endif return capture; }; @@ -7321,7 +7321,7 @@ void verifyDescriptorPhis() { const auto twoLaneCapture = twoLaneMemory.Capture(twoLane); const auto twoLaneRegions = twoLaneMemory.Regions(); twoLane.context.memory = twoLaneRegions; - require(countOps(Recompile(twoLane, *twoLaneCapture)->spirv, OpImageSampleExplicitLod) == 4u, "descriptor Phi: the specialized two-lane SPIR-V does not sample once per edge and half"); + require(countOps(Recompile(twoLane, *twoLaneCapture)->spirv.Words(), OpImageSampleExplicitLod) == 4u, "descriptor Phi: the specialized two-lane SPIR-V does not sample once per edge and half"); auto dynamic = makeRequest(dynamicCode); const auto dynamicPlan = GetResourcePlan(dynamic); @@ -7332,7 +7332,7 @@ void verifyDescriptorPhis() { dynamic.context.memory = dynamicRegions; const auto dynamicCompiled = Recompile(dynamic, *dynamicCapture); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(dynamicCompiled->spirv, dynamic.target.vulkanVersion, dynamic.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(dynamicCompiled->spirv.Words(), dynamic.target.vulkanVersion, dynamic.target.spirvVersion)); #endif const std::vector loopCode{0xf4080500u, 0xfa000020u, 0xf4080600u, 0xfa000040u, 0xf40c0200u, 0xfa000000u, 0xbe910380u, 0xbf8cc07fu, 0xf09c0f08u, 0x00a20000u, 0xbf8c3f70u, 0xe0700000u, 0x80060000u, 0xbf068011u, 0xbf850003u, 0xf40c0200u, 0xfa000000u, 0xbf820002u, 0xf40c0200u, 0xfa000060u, 0xbf8cc07fu, 0x80118111u, 0xbf0a8211u, 0xbf85fff0u, 0xbf810000u}; @@ -7850,7 +7850,7 @@ void verifyLanesOutsideHostSubgroup() { void verifyFusedExactArithmetic() { using namespace ShaderRecompiler; - const auto pixel = [](bool fused) { + const auto pixel = [](bool fused) -> SharedSpirv::Lease { static const std::vector code{0x7e000200u, 0x10020100u, 0x06040101u, 0x08060302u, 0x7e000303u, 0xf800180fu, 0u, 0xbf810000u}; ShaderPixelStageInfo info{}; info.inputAddr = PixelInputBit(PixelInput::PositionX); @@ -7867,7 +7867,7 @@ void verifyFusedExactArithmetic() { request.target.fusedExactArithmetic = fused; request.layout.pushConstantSizeBytes = 128; request.useCache = false; - return Recompile(request).spirv; + return Recompile(request).spirv.Words(); }; struct Counts { std::uint32_t exactArithmetic = 0; @@ -7901,7 +7901,7 @@ void verifyFusedExactArithmetic() { void verifyHalfWaveReduction() { using namespace ShaderRecompiler; static constexpr std::array capabilities{spv::CapabilityGroupNonUniform, spv::CapabilityGroupNonUniformBallot, spv::CapabilityGroupNonUniformShuffle, spv::CapabilityGroupNonUniformArithmetic, spv::CapabilityClipDistance}; - const auto pixel = [](std::span code, std::uint32_t subgroupSize, bool arithmetic) { + const auto pixel = [](std::span code, std::uint32_t subgroupSize, bool arithmetic) -> SharedSpirv::Lease { ShaderPixelStageInfo info{}; info.inputAddr = PixelInputBit(PixelInput::PositionX); info.posX = true; @@ -7917,7 +7917,7 @@ void verifyHalfWaveReduction() { if (arithmetic) request.target.supportedCapabilities = capabilities; request.layout.pushConstantSizeBytes = 128; request.useCache = false; - return Recompile(request).spirv; + return Recompile(request).spirv.Words(); }; const auto reductions = [](std::span spirv, spv::Op opcode) { std::uint32_t count = 0; @@ -8014,7 +8014,7 @@ void verifyHalfWaveReduction() { const auto wide = "half-wave reduction: a wave64 scan reduced by SPIR-V opcode " + std::to_string(reduction.reduce) + " did not read lanes 31 and 63 as reductions of host invocations 0-31 and 32-63 on 64 lanes"; require(halves(pixel(scan(reduction.identity, reduction.vector, reduction.scalar), 64u, true), reduction.reduce, reduction.identity), wide.c_str()); } - const auto vertex = [](std::vector code, std::uint32_t subgroupSize) { + const auto vertex = [](std::vector code, std::uint32_t subgroupSize) -> SharedSpirv::Lease { *std::find(code.begin(), code.end(), 0xf800180fu) = 0xf80008cfu; RecompileRequest request{}; request.shader = {ShaderStage::Vertex, 0x10000u, code, 0, {}}; @@ -8027,11 +8027,11 @@ void verifyHalfWaveReduction() { request.target.fragmentShaderBarycentricEnabled = false; request.layout.pushConstantSizeBytes = 128; request.useCache = false; - return Recompile(request).spirv; + return Recompile(request).spirv.Words(); }; require(reductions(vertex(scan(0xffffffffu, 0x26000000u, 0x83800000u), 32u), spv::OpGroupNonUniformUMin) == 1u, "half-wave reduction: the wave64 vertex UMin scan, whose entry EXEC is every invocation, did not read lane 31 as a subgroup UMin on 32 lanes"); require(halves(vertex(scan(0x80000000u, 0x24000000u, 0x84000000u), 64u), spv::OpGroupNonUniformSMax, 0x80000000u), "half-wave reduction: the wave64 vertex SMax scan did not read lanes 31 and 63 as reductions of host invocations 0-31 and 32-63 on 64 lanes"); - const auto domain = [](std::vector code, std::uint32_t subgroupSize) { + const auto domain = [](std::vector code, std::uint32_t subgroupSize) -> SharedSpirv::Lease { *std::find(code.begin(), code.end(), 0xf800180fu) = 0xf80008cfu; *std::find(code.begin(), code.end(), 0x7e160f00u) = 0x7e160f01u; RecompileRequest request{}; @@ -8046,7 +8046,7 @@ void verifyHalfWaveReduction() { request.layout.pushConstantSizeBytes = 128; request.graphics = GraphicsCompileContext{0u, {}, std::nullopt, TessellationConfiguration{3u, 3u, 1u, 2u, 2u}, {}}; request.useCache = false; - return Recompile(request).spirv; + return Recompile(request).spirv.Words(); }; require(reductions(domain(scan(0xffffffffu, 0x26000000u, 0x83800000u), 32u), spv::OpGroupNonUniformUMin) == 1u, "half-wave reduction: the wave64 domain UMin scan under s_orn2_saveexec_b64 vcc, exec did not read lane 31 as a subgroup UMin on 32 lanes"); require(halves(domain(scan(0u, 0x38000000u, 0x88000000u), 64u), spv::OpGroupNonUniformBitwiseOr, 0u), "half-wave reduction: the wave64 domain OR scan did not read lanes 31 and 63 as reductions of host invocations 0-31 and 32-63 on 64 lanes"); @@ -8144,7 +8144,7 @@ void verifyEntryLaneProofBudget() { request.target.supportedCapabilities = capabilities; request.layout.pushConstantSizeBytes = 128u; request.useCache = false; - const auto spirv = Recompile(request).spirv; + const auto spirv = Recompile(request).spirv.Words(); std::uint32_t reductions = 0; for (std::size_t cursor = 5; cursor < spirv.size() && (spirv[cursor] >> 16u) != 0u; cursor += spirv[cursor] >> 16u) { if ((spirv[cursor] & 0xffffu) == static_cast(spv::OpGroupNonUniformUMin) && (spirv[cursor] >> 16u) == 6u && spirv[cursor + 4u] == spv::GroupOperationReduce) ++reductions; @@ -8171,8 +8171,8 @@ void verifyNarrowVertexWave() { request.layout.pushConstantSizeBytes = 128; return request; }; - const auto prepared = [&vertex](std::span code, std::uint32_t subgroupSize, std::uint32_t userDataBase = 8u) { - return GetPreparedArtifact(*PrepareShader(vertex(code, 64u, subgroupSize, userDataBase))).spirv; + const auto prepared = [&vertex](std::span code, std::uint32_t subgroupSize, std::uint32_t userDataBase = 8u) -> SharedSpirv::Lease { + return GetPreparedArtifact(*PrepareShader(vertex(code, 64u, subgroupSize, userDataBase))).spirv.Words(); }; const auto prepares = [&prepared](std::span code, std::uint32_t subgroupSize, std::uint32_t userDataBase = 8u) { return !prepared(code, subgroupSize, userDataBase).empty(); @@ -8205,7 +8205,7 @@ void verifyNarrowVertexWave() { const auto otherKeys = patched({{7, 0x360e0a82u}}); auto withoutArithmetic = vertex(otherKeys, 64u, 32u, 8u); withoutArithmetic.target.supportedCapabilities = noArithmetic; - const auto shuffled = GetPreparedArtifact(*PrepareShader(withoutArithmetic)).spirv; + const auto shuffled = GetPreparedArtifact(*PrepareShader(withoutArithmetic)).spirv.Words(); require(!shuffled.empty() && reductions(shuffled) == 0u, "narrow vertex wave: without subgroup arithmetic, the scan did not keep lane 31 as a shuffle with lane 63 read as 0"); require(prepares(patched({{5, 0x7da82aa0u}, {6, 0xbf800000u}}), 32u), "narrow vertex wave: the scan keyed on lanes below 32 did not prepare on 32 lanes"); expectFailure([&] { static_cast(prepares(patched({{5, 0x7da82aa1u}, {6, 0xbf800000u}}), 32u)); }, lane63, "narrow vertex wave: a scan keyed on lanes below 33 read lane 63"); @@ -8388,8 +8388,8 @@ void verifySingleLaneVertexWave() { request.useCache = false; return request; }; - const auto compiled = [&vertex](std::span code, std::uint32_t subgroupSize, bool vertexSubgroups) { - return Recompile(vertex(code, subgroupSize, vertexSubgroups)).spirv; + const auto compiled = [&vertex](std::span code, std::uint32_t subgroupSize, bool vertexSubgroups) -> SharedSpirv::Lease { + return Recompile(vertex(code, subgroupSize, vertexSubgroups)).spirv.Words(); }; const auto usesSubgroups = [](std::span spirv) { for (std::size_t cursor = 5; cursor < spirv.size() && (spirv[cursor] >> 16u) != 0u; cursor += spirv[cursor] >> 16u) { @@ -8488,7 +8488,7 @@ void verifySingleLaneVertexWave() { pixel.target.vertexSubgroups = false; pixel.layout.pushConstantSizeBytes = 128; pixel.useCache = false; - require(usesSubgroups(Recompile(pixel).spirv), "single-lane vertex wave: a pixel program stopped using subgroups when only the vertex stage lacks them"); + require(usesSubgroups(Recompile(pixel).spirv.Words()), "single-lane vertex wave: a pixel program stopped using subgroups when only the vertex stage lacks them"); auto request = vertex(waveInfo, 32u, false); const auto replay = RequestSerializer{}.Deserialize(RequestSerializer{}.Serialize(request)); @@ -8599,8 +8599,8 @@ void verifySingleLaneDomainWave() { request.useCache = false; return request; }; - const auto compiled = [&domain](std::span code, std::uint32_t subgroupSize, bool domainSubgroups) { - return Recompile(domain(code, subgroupSize, domainSubgroups)).spirv; + const auto compiled = [&domain](std::span code, std::uint32_t subgroupSize, bool domainSubgroups) -> SharedSpirv::Lease { + return Recompile(domain(code, subgroupSize, domainSubgroups)).spirv.Words(); }; const auto usesSubgroups = [](std::span spirv) { for (std::size_t cursor = 5; cursor < spirv.size() && (spirv[cursor] >> 16u) != 0u; cursor += spirv[cursor] >> 16u) { @@ -8627,11 +8627,11 @@ void verifySingleLaneDomainWave() { require(withoutSubgroups == compiled(code, 4u, false), "single-lane domain wave: the program without tessellation evaluation subgroups depended on the device subgroup size"); auto vertexOnly = domain(code, 32u, true); vertexOnly.target.vertexSubgroups = false; - require(usesSubgroups(Recompile(vertexOnly).spirv), "single-lane domain wave: a domain program stopped using subgroups when only the vertex stage lacks them"); + require(usesSubgroups(Recompile(vertexOnly).spirv.Words()), "single-lane domain wave: a domain program stopped using subgroups when only the vertex stage lacks them"); auto vertex = domain(code, 32u, false); vertex.shader.stage = ShaderStage::Vertex; vertex.graphics.reset(); - require(usesSubgroups(Recompile(vertex).spirv), "single-lane domain wave: a vertex program stopped using subgroups when only the tessellation evaluation stage lacks them"); + require(usesSubgroups(Recompile(vertex).spirv.Words()), "single-lane domain wave: a vertex program stopped using subgroups when only the tessellation evaluation stage lacks them"); } expectFailure([&] { static_cast(compiled(lane31, 32u, false)); }, "v_readlane_b32 of lane 31 is outside the 1-lane host subgroup", "single-lane domain wave: a domain program without tessellation evaluation subgroups read lane 31"); require(!compiled(lane31, 32u, true).empty(), "single-lane domain wave: lane 31 of a 32-lane tessellation evaluation subgroup did not build"); @@ -10380,7 +10380,7 @@ void verifyComputedTexelOffsets() { }; const auto computed = program(0x100u, 0u); const auto constant = program(0xffu, 0x3fu | (1u << 8u)); - const auto recompile = [&](std::span code, bool offsets) { + const auto recompile = [&](std::span code, bool offsets) -> SharedSpirv::Lease { RecompileRequest request{}; request.shader = {ShaderStage::Compute, 0x30000u, code, 0, {}}; request.target = BufferTarget(); @@ -10399,7 +10399,7 @@ void verifyComputedTexelOffsets() { static_cast(memory.Capture(request)); const auto memoryRegions = memory.Regions(); request.context.memory = memoryRegions; - return Recompile(request).spirv; + return Recompile(request).spirv.Words(); }; const auto sampleOperands = [](std::span words) { std::uint32_t mask = 0; @@ -10450,7 +10450,7 @@ void verifyShaderClockScopes() { static_cast(memory.Capture(request)); const auto memoryRegions = memory.Regions(); request.context.memory = memoryRegions; - const auto words = Recompile(request).spirv; + const auto words = Recompile(request).spirv.Words(); std::map constants; std::vector scopeIds; for (std::size_t cursor = 5; cursor < words.size();) { @@ -10565,38 +10565,38 @@ void verifyInt64AtomicCapabilities() { }; for (const auto* code : {&globalSwap, &globalSwapBufferInc}) { const auto lockedGlobal = compile(*code, spv::CapabilityShader); - require(!declares(lockedGlobal.spirv, spv::CapabilityInt64Atomics), "64-bit atomics: a global_atomic_swap_x2 compiled without shaderBufferInt64Atomics declares Int64Atomics"); + require(!declares(lockedGlobal.spirv.Words(), spv::CapabilityInt64Atomics), "64-bit atomics: a global_atomic_swap_x2 compiled without shaderBufferInt64Atomics declares Int64Atomics"); require(asksForLockTable(lockedGlobal), "64-bit atomics: a global_atomic_swap_x2 compiled without shaderBufferInt64Atomics does not ask for the atomic lock table"); const auto nativeGlobal = compile(*code, spv::CapabilityInt64Atomics); - require(declares(nativeGlobal.spirv, spv::CapabilityInt64Atomics), "64-bit atomics: a global_atomic_swap_x2 does not declare Int64Atomics"); + require(declares(nativeGlobal.spirv.Words(), spv::CapabilityInt64Atomics), "64-bit atomics: a global_atomic_swap_x2 does not declare Int64Atomics"); require(!asksForLockTable(nativeGlobal), "64-bit atomics: a global_atomic_swap_x2 compiled with shaderBufferInt64Atomics asks for the atomic lock table"); } const auto lockedBuffer = compile(bufferAtomic, spv::CapabilityShader); - require(!declares(lockedBuffer.spirv, spv::CapabilityInt64Atomics), "64-bit atomics: a buffer_atomic_inc_x2 compiled without shaderBufferInt64Atomics declares Int64Atomics"); + require(!declares(lockedBuffer.spirv.Words(), spv::CapabilityInt64Atomics), "64-bit atomics: a buffer_atomic_inc_x2 compiled without shaderBufferInt64Atomics declares Int64Atomics"); require(asksForLockTable(lockedBuffer), "64-bit atomics: a buffer_atomic_inc_x2 compiled without shaderBufferInt64Atomics does not ask for the atomic lock table"); - require(declares(compile(bufferAtomic, spv::CapabilityInt64Atomics).spirv, spv::CapabilityInt64Atomics), "64-bit atomics: a buffer_atomic_inc_x2 does not declare Int64Atomics"); + require(declares(compile(bufferAtomic, spv::CapabilityInt64Atomics).spirv.Words(), spv::CapabilityInt64Atomics), "64-bit atomics: a buffer_atomic_inc_x2 does not declare Int64Atomics"); const std::array*, spv::Op>, 3> bitwise{{{&bufferOr, spv::OpAtomicOr}, {&bufferAnd, spv::OpAtomicAnd}, {&bufferXor, spv::OpAtomicXor}}}; for (const auto& [code, atomic] : bitwise) { const auto split = compile(*code, spv::CapabilityShader); - require(!declares(split.spirv, spv::CapabilityInt64Atomics), "64-bit atomics: an unused-result bitwise buffer atomic declares Int64Atomics on a device without it"); + require(!declares(split.spirv.Words(), spv::CapabilityInt64Atomics), "64-bit atomics: an unused-result bitwise buffer atomic declares Int64Atomics on a device without it"); require(!asksForLockTable(split), "64-bit atomics: an unused-result bitwise buffer atomic asks for the atomic lock table on a device without Int64Atomics"); - verifySplit(split.spirv, atomic); - require(declares(compile(*code, spv::CapabilityInt64Atomics).spirv, spv::CapabilityInt64Atomics), "64-bit atomics: an unused-result bitwise buffer atomic does not use the 64-bit atomic where the device has it"); + verifySplit(split.spirv.Words(), atomic); + require(declares(compile(*code, spv::CapabilityInt64Atomics).spirv.Words(), spv::CapabilityInt64Atomics), "64-bit atomics: an unused-result bitwise buffer atomic does not use the 64-bit atomic where the device has it"); } - require(!declares(compile(bufferOrTwice, spv::CapabilityShader).spirv, spv::CapabilityInt64Atomics), "64-bit atomics: two buffer_atomic_or_x2 of one program declare Int64Atomics on a device without it"); + require(!declares(compile(bufferOrTwice, spv::CapabilityShader).spirv.Words(), spv::CapabilityInt64Atomics), "64-bit atomics: two buffer_atomic_or_x2 of one program declare Int64Atomics on a device without it"); const auto lockedPair = compile(bufferOrAnd, spv::CapabilityShader); - require(!declares(lockedPair.spirv, spv::CapabilityInt64Atomics) && asksForLockTable(lockedPair), "64-bit atomics: a buffer_atomic_or_x2 and a buffer_atomic_and_x2 of one program compiled without shaderBufferInt64Atomics do not take the atomic lock table"); - require(declares(compile(bufferOrAnd, spv::CapabilityInt64Atomics).spirv, spv::CapabilityInt64Atomics), "64-bit atomics: a buffer_atomic_or_x2 and a buffer_atomic_and_x2 of one program do not use the 64-bit atomics where the device has them"); + require(!declares(lockedPair.spirv.Words(), spv::CapabilityInt64Atomics) && asksForLockTable(lockedPair), "64-bit atomics: a buffer_atomic_or_x2 and a buffer_atomic_and_x2 of one program compiled without shaderBufferInt64Atomics do not take the atomic lock table"); + require(declares(compile(bufferOrAnd, spv::CapabilityInt64Atomics).spirv.Words(), spv::CapabilityInt64Atomics), "64-bit atomics: a buffer_atomic_or_x2 and a buffer_atomic_and_x2 of one program do not use the 64-bit atomics where the device has them"); const auto locked = compile(imageAtomic, spv::CapabilityShader); - require(!declares(locked.spirv, spv::CapabilityInt64ImageEXT) && !declares(locked.spirv, spv::CapabilityInt64Atomics), "64-bit atomics: an image_atomic_swap on a 32_32 image compiled without shaderImageInt64Atomics declares 64-bit atomics"); + require(!declares(locked.spirv.Words(), spv::CapabilityInt64ImageEXT) && !declares(locked.spirv.Words(), spv::CapabilityInt64Atomics), "64-bit atomics: an image_atomic_swap on a 32_32 image compiled without shaderImageInt64Atomics declares 64-bit atomics"); require(asksForLockTable(locked), "64-bit atomics: an image_atomic_swap on a 32_32 image compiled without shaderImageInt64Atomics does not ask for the atomic lock table"); - require(declares(locked.spirv, spv::CapabilityStorageImageExtendedFormats) && !declares(locked.spirv, spv::CapabilityStorageImageReadWithoutFormat) && !declares(locked.spirv, spv::CapabilityStorageImageWriteWithoutFormat), "64-bit atomics: an image_atomic_swap on a 32_32 image compiled without shaderImageInt64Atomics does not declare its image as Rg32ui"); + require(declares(locked.spirv.Words(), spv::CapabilityStorageImageExtendedFormats) && !declares(locked.spirv.Words(), spv::CapabilityStorageImageReadWithoutFormat) && !declares(locked.spirv.Words(), spv::CapabilityStorageImageWriteWithoutFormat), "64-bit atomics: an image_atomic_swap on a 32_32 image compiled without shaderImageInt64Atomics does not declare its image as Rg32ui"); const auto native = compile(imageAtomic, spv::CapabilityInt64ImageEXT); - require(declares(native.spirv, spv::CapabilityInt64ImageEXT), "64-bit atomics: an image_atomic_swap on a 32_32 image does not declare Int64ImageEXT"); + require(declares(native.spirv.Words(), spv::CapabilityInt64ImageEXT), "64-bit atomics: an image_atomic_swap on a 32_32 image does not declare Int64ImageEXT"); require(!asksForLockTable(native), "64-bit atomics: an image_atomic_swap on a 32_32 image compiled with shaderImageInt64Atomics asks for the atomic lock table"); const std::array*, const char*>, 2> updates{{{&imageAtomicInc, "image_atomic_inc"}, {&imageAtomicDec, "image_atomic_dec"}}}; for (const auto& [code, name] : updates) { - const auto words = compile(*code, spv::CapabilityInt64ImageEXT).spirv; + const auto words = compile(*code, spv::CapabilityInt64ImageEXT).spirv.Words(); std::set texelPointers; std::size_t exchanges = 0; std::size_t loads = 0; @@ -10708,7 +10708,7 @@ void verifyCoherentGds() { request.target.fragmentShaderBarycentricEnabled = false; request.layout.pushConstantSizeBytes = 128; request.useCache = false; - const auto words = Recompile(request).spirv; + const auto words = Recompile(request).spirv.Words(); std::uint32_t gds = 0u; std::map> decorations; for (std::size_t cursor = 5; cursor < words.size();) { @@ -10759,7 +10759,7 @@ void verifyCoherentBufferAccesses() { request.target.fragmentShaderBarycentricEnabled = false; request.layout.pushConstantSizeBytes = 128; request.useCache = false; - const auto words = Recompile(request).spirv; + const auto words = Recompile(request).spirv.Words(); Module module; std::map bases; const auto base = [&](std::uint32_t pointer) { @@ -11341,7 +11341,7 @@ void verifyTwoLaneUniformValues() { const auto capture = memory.Capture(request); const auto memoryRegions = memory.Regions(); request.context.memory = memoryRegions; - const auto words = Recompile(request, *capture)->spirv; + const auto words = Recompile(request, *capture)->spirv.Words(); std::size_t count = 0; for (std::size_t cursor = 5; cursor < words.size();) { const auto length = words[cursor] >> 16u; @@ -11363,7 +11363,7 @@ void verifyBdaReadFallbackFunctions() { alignas(256) static std::array output{}; const auto outputAddress = static_cast(reinterpret_cast(output.data())); const std::array userData{0x10000000u, 0u, 0u, 0u, static_cast(outputAddress), static_cast((outputAddress >> 32u) & 0xffffu), 128u, 0x01016facu}; - const auto compile = [&](std::uint32_t loads, bool barrier, bool coherent, std::uint32_t stride) { + const auto compile = [&](std::uint32_t loads, bool barrier, bool coherent, std::uint32_t stride) -> SharedSpirv::Lease { std::vector code{0x7e020200u, 0x7e040201u}; for (std::uint32_t load = 0; load < loads; ++load) { code.push_back(0xdc308000u | (coherent ? 0x10000u : 0u) | (stride * load + 4u)); @@ -11388,7 +11388,7 @@ void verifyBdaReadFallbackFunctions() { request.target.fragmentShaderBarycentricEnabled = false; request.layout.pushConstantSizeBytes = 128; request.useCache = false; - return Recompile(request).spirv; + return Recompile(request).spirv.Words(); }; for (const bool barrier : {false, true}) { for (const bool coherent : {false, true}) { @@ -11486,7 +11486,7 @@ void verifyBdaAnchors() { alignas(256) static std::array output{}; const auto outputAddress = static_cast(reinterpret_cast(output.data())); const std::array userData{0x10000000u, 0u, 0u, 0u, static_cast(outputAddress), static_cast((outputAddress >> 32u) & 0xffffu), 128u, 0x01016facu}; - const auto compile = [&](std::uint32_t scalarBase, std::uint32_t stride) { + const auto compile = [&](std::uint32_t scalarBase, std::uint32_t stride) -> SharedSpirv::Lease { std::vector code{0x7e020200u, 0x7e040201u}; for (std::uint32_t load = 0; load < scalarBase; ++load) { code.push_back(0xdc308000u | (stride * load + 4u)); @@ -11512,7 +11512,7 @@ void verifyBdaAnchors() { request.target.fragmentShaderBarycentricEnabled = false; request.layout.pushConstantSizeBytes = 128; request.useCache = false; - return Recompile(request).spirv; + return Recompile(request).spirv.Words(); }; for (const std::uint32_t stride : {4u, 32u}) { for (const std::uint32_t loads : {0u, 1u, 2u, 4u}) { @@ -11564,7 +11564,7 @@ void verifyBdaAnchors() { plain.target.fragmentShaderBarycentricEnabled = false; plain.layout.pushConstantSizeBytes = 128; plain.useCache = false; - const auto plainWords = Recompile(plain).spirv; + const auto plainWords = Recompile(plain).spirv.Words(); for (std::size_t cursor = 5; cursor < plainWords.size();) { const auto length = plainWords[cursor] >> 16u; require(length != 0 && length <= plainWords.size() - cursor, "BDA anchors: truncated SPIR-V instruction"); @@ -11985,7 +11985,7 @@ void verifyGuardedDirectRoot() { const auto validResult = Recompile(branch.request, *valid); require(validResult->poisonedSrtReads == 0u, "guarded direct root: the mapped program reports poison"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(validResult->spirv, branch.request.target.vulkanVersion, branch.request.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(validResult->spirv.Words(), branch.request.target.vulkanVersion, branch.request.target.spirvVersion)); #endif std::cout << "guarded direct root: mapped taken load passed\n"; root[4] = 0u; @@ -11997,7 +11997,7 @@ void verifyGuardedDirectRoot() { const auto mappedSkippedResult = Recompile(branch.request, *mappedSkipped); require(mappedSkippedResult->poisonedSrtReads == 0u, "guarded direct root: the mapped skipped program reports poison"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(mappedSkippedResult->spirv, branch.request.target.vulkanVersion, branch.request.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(mappedSkippedResult->spirv.Words(), branch.request.target.vulkanVersion, branch.request.target.spirvVersion)); #endif std::cout << "guarded direct root: mapped skipped load passed\n"; root[4] = 1u; @@ -12083,7 +12083,7 @@ void verifyGuardedDirectRoot() { const auto skippedResult = Recompile(branch.request, *skipped); require(skippedResult->poisonedSrtReads == 0u, "guarded direct root: the skipped program reports poison"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(skippedResult->spirv, branch.request.target.vulkanVersion, branch.request.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(skippedResult->spirv.Words(), branch.request.target.vulkanVersion, branch.request.target.spirvVersion)); #endif std::cout << "guarded direct root: inaccessible skipped load passed\n"; #ifdef _WIN32 @@ -12191,7 +12191,7 @@ void verifyGuardedNullPointers() { require(replay.poisonedSrtReads == condition && samePipeline(replay, *result), "guarded pointer: a replay of the captured regions did not reproduce the poison"); verifyResult(*result, replay); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(result->spirv, branch.request.target.vulkanVersion, branch.request.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(result->spirv.Words(), branch.request.target.vulkanVersion, branch.request.target.spirvVersion)); #endif } } @@ -12326,7 +12326,7 @@ void verifyGuardedNullPointers() { const auto result = Recompile(vertex.request, *capture); require(result->poisonedSrtReads == guard * 4u && faultBinding(*result) && !result->spirv.empty(), "guarded pointer: a vertex capture has the wrong poison count or no fault buffer"); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ValidateAndOptimizeSpirv(result->spirv, vertex.request.target.vulkanVersion, vertex.request.target.spirvVersion)); + static_cast(ValidateAndOptimizeSpirv(result->spirv.Words(), vertex.request.target.vulkanVersion, vertex.request.target.spirvVersion)); #endif } NestedRequest rootless(branchCode, nullptr); @@ -13063,11 +13063,11 @@ void verifySpannedShuffleThroughMemory() { const std::span straight{code}; const auto native = compile(straight, 32u, true, false); require(native.fullSubgroups, "spanned shuffle: the wave64 compute program did not span two 32-lane subgroups"); - const auto nativeCounts = count(native.spirv); + const auto nativeCounts = count(native.spirv.Words()); require(nativeCounts.shuffles >= 1u && nativeCounts.subgroupBarriers == 0u, "spanned shuffle: without the flag the lane read is not the native subgroup shuffle"); const auto exchanged = compile(straight, 32u, true, true); require(exchanged.fullSubgroups, "spanned shuffle: the flagged wave64 compute program did not span two 32-lane subgroups"); - const auto exchangedCounts = count(exchanged.spirv); + const auto exchangedCounts = count(exchanged.spirv.Words()); require(exchangedCounts.shuffles == 0u, "spanned shuffle: with the flag the lane read still uses OpGroupNonUniformShuffle, which NVIDIA's compiler crashes on in the title's shader"); require(exchangedCounts.workgroupVariables >= 1u && exchangedCounts.workgroupBarriers >= nativeCounts.workgroupBarriers + 2u, "spanned shuffle: with the flag the lane read does not go through a workgroup array between two more workgroup-scope barriers"); require(exchangedCounts.subgroupBarriers == 0u, "spanned shuffle: with the flag the exchange uses a subgroup-scope barrier, which did not make LDS writes visible on NVIDIA"); @@ -13076,9 +13076,9 @@ void verifySpannedShuffleThroughMemory() { require(!unspanned.fullSubgroups && unspanned.spirv == unspannedNative.spirv, "spanned shuffle: the flag changed a program that does not span subgroups"); const auto predicatedNative = compile(lanePredicated, 32u, true, false); const auto predicated = compile(lanePredicated, 32u, true, true); - require(predicated.fullSubgroups && count(predicated.spirv).shuffles == 0u && count(predicated.spirv).workgroupBarriers >= count(predicatedNative.spirv).workgroupBarriers + 2u, "spanned shuffle: a lane-predicated lane read did not go through the workgroup exchange"); - require(!SpannedBarrierInDivergentFlow(predicated.spirv).has_value(), "spanned shuffle: the exchange's workgroup barriers of a lane-predicated lane read sit in divergent control flow, which would hang instead of crash"); - require(!SpannedBarrierInDivergentFlow(exchanged.spirv).has_value(), "spanned shuffle: the exchange's workgroup barriers sit in divergent control flow, which would hang instead of crash"); + require(predicated.fullSubgroups && count(predicated.spirv.Words()).shuffles == 0u && count(predicated.spirv.Words()).workgroupBarriers >= count(predicatedNative.spirv.Words()).workgroupBarriers + 2u, "spanned shuffle: a lane-predicated lane read did not go through the workgroup exchange"); + require(!SpannedBarrierInDivergentFlow(predicated.spirv.Words()).has_value(), "spanned shuffle: the exchange's workgroup barriers of a lane-predicated lane read sit in divergent control flow, which would hang instead of crash"); + require(!SpannedBarrierInDivergentFlow(exchanged.spirv.Words()).has_value(), "spanned shuffle: the exchange's workgroup barriers sit in divergent control flow, which would hang instead of crash"); } void verifyPixelQuadPermReads() { @@ -14209,48 +14209,50 @@ int main(int argc, char** argv) { auto invalidSpirv = first.spirv; invalidSpirv[0] = 0; expectFailure([&] { static_cast(ValidateAndOptimizeSpirv(invalidSpirv, request.target.vulkanVersion, request.target.spirvVersion)); }, "SPIR-V validation before optimization failed", "invalid SPIR-V passed validation"); - expectFailure([&] { static_cast(ValidateAndOptimizeSpirv(first.spirv, 0x00400000u, 0x00010600u)); }, "unsupported Vulkan/SPIR-V target", "incompatible target accepted"); - expectFailure([&] { static_cast(ValidateAndOptimizeSpirv(first.spirv, 0x00405000u, 0x00010600u)); }, "unsupported Vulkan target", "unknown Vulkan target accepted"); + expectFailure([&] { static_cast(ValidateAndOptimizeSpirv(first.spirv.Words(), 0x00400000u, 0x00010600u)); }, "unsupported Vulkan/SPIR-V target", "incompatible target accepted"); + expectFailure([&] { static_cast(ValidateAndOptimizeSpirv(first.spirv.Words(), 0x00405000u, 0x00010600u)); }, "unsupported Vulkan target", "unknown Vulkan target accepted"); #endif const auto readOnly = [&](const char* name) { + const auto words = first.spirv.Words(); std::optional id; bool decorated = false; - for (std::size_t at = 5; at < first.spirv.size() && (first.spirv[at] >> 16u) != 0u; at += first.spirv[at] >> 16u) { - const auto opcode = first.spirv[at] & 0xffffu; - if (opcode == spv::OpName && std::strcmp(reinterpret_cast(&first.spirv[at + 2u]), name) == 0) id = first.spirv[at + 1u]; + for (std::size_t at = 5; at < words.size() && (words[at] >> 16u) != 0u; at += words[at] >> 16u) { + const auto opcode = words[at] & 0xffffu; + if (opcode == spv::OpName && std::strcmp(reinterpret_cast(&words[at + 2u]), name) == 0) id = words[at + 1u]; } - for (std::size_t at = 5; id && at < first.spirv.size() && (first.spirv[at] >> 16u) != 0u; at += first.spirv[at] >> 16u) { - decorated = decorated || ((first.spirv[at] & 0xffffu) == spv::OpDecorate && first.spirv[at + 1u] == *id && first.spirv[at + 2u] == spv::DecorationNonWritable); + for (std::size_t at = 5; id && at < words.size() && (words[at] >> 16u) != 0u; at += words[at] >> 16u) { + decorated = decorated || ((words[at] & 0xffffu) == spv::OpDecorate && words[at + 1u] == *id && words[at + 2u] == spv::DecorationNonWritable); } return std::pair{id.has_value(), decorated}; }; require(readOnly("flattened_srt") == std::pair{true, true}, "the flattened SRT is not decorated NonWritable"); { + const auto words = first.spirv.Words(); std::uint32_t srtId = 0u; - for (std::size_t at = 5; at < first.spirv.size() && (first.spirv[at] >> 16u) != 0u; at += first.spirv[at] >> 16u) { - if ((first.spirv[at] & 0xffffu) == spv::OpName && std::strcmp(reinterpret_cast(&first.spirv[at + 2u]), "flattened_srt") == 0) srtId = first.spirv[at + 1u]; + for (std::size_t at = 5; at < words.size() && (words[at] >> 16u) != 0u; at += words[at] >> 16u) { + if ((words[at] & 0xffffu) == spv::OpName && std::strcmp(reinterpret_cast(&words[at + 2u]), "flattened_srt") == 0) srtId = words[at + 1u]; } require(srtId != 0u, "the flattened SRT variable is not named"); std::set chains; std::size_t srtUses = 0; - for (std::size_t at = 5; at < first.spirv.size() && (first.spirv[at] >> 16u) != 0u; at += first.spirv[at] >> 16u) { - const auto opcode = first.spirv[at] & 0xffffu; - const auto count = first.spirv[at] >> 16u; + for (std::size_t at = 5; at < words.size() && (words[at] >> 16u) != 0u; at += words[at] >> 16u) { + const auto opcode = words[at] & 0xffffu; + const auto count = words[at] >> 16u; if (opcode == spv::OpName || opcode == spv::OpDecorate || opcode == spv::OpEntryPoint || opcode == spv::OpVariable) continue; for (std::size_t operand = 1; operand < count; ++operand) { - if (first.spirv[at + operand] != srtId) continue; + if (words[at + operand] != srtId) continue; ++srtUses; - require((opcode == spv::OpAccessChain || opcode == spv::OpInBoundsAccessChain) && operand == 3u, "the flattened SRT is used by something other than the base of an access chain"); - chains.insert(first.spirv[at + 2u]); + require((opcode == spv::OpAccessChain || opcode == spv::OpInBoundsAccessChain) && operand == 3u, "a flattened SRT is used by something other than the base of an access chain"); + chains.insert(words[at + 2u]); } } require(srtUses != 0u && !chains.empty(), "the flattened SRT is never read through an access chain"); - for (std::size_t at = 5; at < first.spirv.size() && (first.spirv[at] >> 16u) != 0u; at += first.spirv[at] >> 16u) { - const auto opcode = first.spirv[at] & 0xffffu; - const auto count = first.spirv[at] >> 16u; + for (std::size_t at = 5; at < words.size() && (words[at] >> 16u) != 0u; at += words[at] >> 16u) { + const auto opcode = words[at] & 0xffffu; + const auto count = words[at] >> 16u; if (opcode == spv::OpName || opcode == spv::OpAccessChain || opcode == spv::OpInBoundsAccessChain) continue; for (std::size_t operand = 1; operand < count; ++operand) { - if (chains.contains(first.spirv[at + operand])) require(opcode == spv::OpLoad && operand == 3u, "a flattened SRT access chain is used by something other than a load"); + if (chains.contains(words[at + operand])) require(opcode == spv::OpLoad && operand == 3u, "a flattened SRT access chain is used by something other than a load"); } } } diff --git a/core/libs/prx/libSceAgcDriver/tests/SpirvModule.cpp b/core/libs/prx/libSceAgcDriver/tests/SpirvModule.cpp index f5cf180e1334..89f42d1cf47b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/SpirvModule.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/SpirvModule.cpp @@ -511,13 +511,17 @@ void testInternedSpirvSharesEqualWords() { const auto first = InternSpirv(words); const auto second = InternSpirv(words); const auto other = InternSpirv(changed); - check(std::ranges::equal(first.Words(), words) && std::ranges::equal(other.Words(), changed), "interned SPIR-V changed its words"); - check(first.data() == second.data(), "two equal specialized modules kept separate copies of their words"); - check(first.data() != other.data(), "different SPIR-V was interned into one copy"); + const auto firstWords = first.Words(); + const auto secondWords = second.Words(); + const auto otherWords = other.Words(); + check(std::ranges::equal(firstWords, words) && std::ranges::equal(otherWords, changed), "interned SPIR-V changed its words"); + check(firstWords.data() == secondWords.data(), "two equal specialized modules kept separate copies of their words"); + check(firstWords.data() != otherWords.data(), "different SPIR-V was interned into one copy"); auto edited = second; edited[6] = spv::CapabilityFloat64; const auto again = InternSpirv(words); - check(edited[6] == spv::CapabilityFloat64 && first[6] == spv::CapabilityShader && again.data() == first.data(), "a write to one holder of interned SPIR-V changed the others"); + const auto againWords = again.Words(); + check(edited[6] == spv::CapabilityFloat64 && firstWords[6] == spv::CapabilityShader && againWords.data() == firstWords.data(), "a write to one holder of interned SPIR-V changed the others"); } void testInternedSpirvReleasesUnusedWords() { @@ -526,7 +530,9 @@ void testInternedSpirvReleasesUnusedWords() { { const auto first = InternSpirv(words); const auto second = InternSpirv(words); - check(first.data() == second.data(), "two equal specialized modules kept separate copies of their words"); + const auto firstWords = first.Words(); + const auto secondWords = second.Words(); + check(firstWords.data() == secondWords.data(), "two equal specialized modules kept separate copies of their words"); released = first.Weaken(); } check(released.Expired(), "the SPIR-V interning table kept words no holder uses"); diff --git a/core/libs/prx/libSceAgcDriver/tests/VertexLayerExport.cpp b/core/libs/prx/libSceAgcDriver/tests/VertexLayerExport.cpp index 1b8f7150659c..098127f96d65 100644 --- a/core/libs/prx/libSceAgcDriver/tests/VertexLayerExport.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/VertexLayerExport.cpp @@ -64,7 +64,7 @@ Module recompile(std::uint32_t control, bool layerExtension) { else request.target.supportedCapabilities = without; request.layout.pushConstantSizeBytes = 128; request.useCache = false; - return inspect(Recompile(request).spirv); + return inspect(Recompile(request).spirv.Words()); } } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/BdaAnchorReads.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/BdaAnchorReads.cpp index 9bd219d26731..cdd1d2322d20 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/BdaAnchorReads.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/BdaAnchorReads.cpp @@ -123,7 +123,8 @@ ShaderRecompiler::RecompileResult Recompile(std::uint32_t waveSize, std::span(spirv.data()), spirv.size() * sizeof(std::uint32_t)); + const auto words = spirv.Words(); + const std::string_view text(reinterpret_cast(words.data()), words.size_bytes()); return text.find("bda_anchor_range") != std::string_view::npos; } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GdsIntegerAtomics64.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GdsIntegerAtomics64.cpp index c5fd04c51856..66437872ce16 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GdsIntegerAtomics64.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GdsIntegerAtomics64.cpp @@ -541,7 +541,8 @@ void CheckAliasedView(std::span words) { void CheckRequirements(AgcDriver::VulkanDevice& device) { auto code = OperationCode(Threads, false); const auto result = Compile(device, code, 32); - const std::span words(result.spirv.Words()); + const auto leased = result.spirv.Words(); + const std::span words(leased); CheckAliasedView(words); std::vector widths(words[3]); std::vector constants(words[3]); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GpuBufferFormat.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GpuBufferFormat.cpp index 5e588cb79fa0..540685c9a48b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GpuBufferFormat.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GpuBufferFormat.cpp @@ -672,7 +672,7 @@ int main() { if (!device) return VulkanTestSkipped; GuestBlock guest; const auto shader = Compile(*device, guest); - const auto privateArrays = PrivateArrays(shader.spirv); + const auto privateArrays = PrivateArrays(shader.spirv.Words()); if (std::getenv("APS5_PRIVATE_BUFFER_FORMAT_TABLE") == nullptr) Require(privateArrays == 0u, "gpu buffer format: a run-time buffer format is looked up through a Private array, which drivers keep in per-invocation local memory"); else Require(privateArrays == 1u, "gpu buffer format: APS5_PRIVATE_BUFFER_FORMAT_TABLE did not bring the Private format table back"); for (const auto& test : Cases) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/LayeredVolumeDraw.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/LayeredVolumeDraw.cpp index 3465c3842040..cedec1ee7605 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/LayeredVolumeDraw.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/LayeredVolumeDraw.cpp @@ -195,9 +195,10 @@ void Run(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarget if (mesh) { for (const auto required : {ShaderRecompiler::PipelineSpecialization::MeshLayerBase, ShaderRecompiler::PipelineSpecialization::MeshLayerCount}) { bool found = false; - for (std::size_t at = 5; at < geometryResult.spirv.size();) { - const auto length = geometryResult.spirv[at] >> 16u; - if ((geometryResult.spirv[at] & 0xffffu) == 71u && length == 4u && geometryResult.spirv[at + 2u] == 1u && geometryResult.spirv[at + 3u] == required) found = true; + const auto words = geometryResult.spirv.Words(); + for (std::size_t at = 5; at < words.size();) { + const auto length = words[at] >> 16u; + if ((words[at] & 0xffffu) == 71u && length == 4u && words[at + 2u] == 1u && words[at + 3u] == required) found = true; at += length; } Require(found, "mesh layer specialization was frozen: " + std::to_string(required)); @@ -247,7 +248,7 @@ void Run(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarget state.blends = {state.blend}; state.blendConstants = {}; if (mesh) { - Require(DeclaresLayer(geometryResult.spirv), "the mesh program declares no Layer output"); + Require(DeclaresLayer(geometryResult.spirv.Words()), "the mesh program declares no Layer output"); if (!executeMesh) return; } if (mesh) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MeshWaves.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MeshWaves.cpp index 5fb78c619863..83dc653e4ee8 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MeshWaves.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MeshWaves.cpp @@ -137,7 +137,8 @@ FunctionControls HelperFunctions(const ShaderRecompiler::SpirvTarget& target, st }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); - const std::span words(result.spirv.Words()); + const auto leased = result.spirv.Words(); + const std::span words(leased); std::vector entries; FunctionControls controls; for (std::size_t at = 5; at < words.size() && (words[at] >> 16u) != 0; at += words[at] >> 16u) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PackedIntegerNative.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PackedIntegerNative.cpp index 1605962af73e..3d622dff9ff6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PackedIntegerNative.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PackedIntegerNative.cpp @@ -168,7 +168,8 @@ std::size_t Run(AgcDriver::VulkanDevice& device, const std::vector(result.spirv.Words()); + const auto leased = result.spirv.Words(); + const auto words = std::span(leased); const auto declarations = Int16Declarations(words); Require(int16 ? declarations == 2u : declarations == 0u, std::string("packed integer native: the ") + (int16 ? "Int16" : "lane") + " build declares " + std::to_string(declarations) + " Int16 capabilities and 16-bit integer types"); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedExports.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedExports.cpp index bdbfd1362805..687f33604313 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedExports.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedExports.cpp @@ -84,15 +84,17 @@ void Run(AgcDriver::VulkanDevice& device, bool integer) { for (const bool cached : {true, false}) { request.useCache = cached; const auto materialized = MaterializeShader(request, *capture, *handle); - Require(materialized->spirv.data() == pixel->spirv.data() && materialized->PipelineVariantId() == pixel->PipelineVariantId(), "export mapping did not reuse its specialized module"); + const auto materializedWords = materialized->spirv.Words(); + const auto pixelWords = pixel->spirv.Words(); + Require(materializedWords.data() == pixelWords.data() && materialized->PipelineVariantId() == pixel->PipelineVariantId(), "export mapping did not reuse its specialized module"); if (device.Target().registrationModules) { Require(materialized->PipelineVariantId() == first->PipelineVariantId(), "registration modules: the export mapping specialized the fragment module"); continue; } - for (std::size_t cursor = 5; cursor < materialized->spirv.size();) { - const auto count = materialized->spirv[cursor] >> 16u; - Require(count != 0u && count <= materialized->spirv.size() - cursor, "invalid specialized fragment instruction"); - Require((materialized->spirv[cursor] & 0xffffu) != static_cast(spv::OpVectorExtractDynamic), "fragment export retained a dynamic channel selection"); + for (std::size_t cursor = 5; cursor < materializedWords.size();) { + const auto count = materializedWords[cursor] >> 16u; + Require(count != 0u && count <= materializedWords.size() - cursor, "invalid specialized fragment instruction"); + Require((materializedWords[cursor] & 0xffffu) != static_cast(spv::OpVectorExtractDynamic), "fragment export retained a dynamic channel selection"); cursor += count; } } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp index 02c7b13a2462..95591b164725 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp @@ -228,7 +228,7 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path } if (!dump.empty()) { for (std::size_t index = 0; index < stages.size(); ++index) { - const auto& words = GetPreparedArtifact(*stages[index].entry.handle).spirv; + const auto words = GetPreparedArtifact(*stages[index].entry.handle).spirv.Words(); const auto name = dump / (std::to_string(static_cast(path)) + "-" + std::to_string(index) + ".spv"); std::ofstream output(name, std::ios::binary); output.write(reinterpret_cast(words.data()), static_cast(words.size() * sizeof(std::uint32_t))); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedPublication.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedPublication.cpp index 226f32e3e5be..d1d738d1b706 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedPublication.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedPublication.cpp @@ -366,7 +366,10 @@ void Registration(AgcDriver::VulkanDevice& device) { Require(!old.expired(), "in-flight submission released its snapshot early"); submission.reset(); Require(!old.expired() && registry->at(0x10000).size() == 2, "registration discarded an earlier header for shared code"); - Require(invocation.Materialize(*capture)->spirv.data() == result->spirv.data(), "prepared handle did not retain its artifact"); + const auto repeated = invocation.Materialize(*capture); + const auto repeatedWords = repeated->spirv.Words(); + const auto resultWords = result->spirv.Words(); + Require(repeatedWords.data() == resultWords.data(), "prepared handle did not retain its artifact"); auto changed = makeSnapshot(); changed->headerAddress = replacement->headerAddress; changed->code.Mutable()[0] ^= 1; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp index 4c45b7d81f36..4dd66a298a62 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp @@ -98,7 +98,7 @@ 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"); + Require(snapshot.prepared->entries.size() == 1 && result->variantId == artifact.variantId && result->spirv.Words().data() == artifact.spirv.Words().data(), "unregistered compute invocation replaced its cached artifact"); device.Dispatch(*result, 1, 1, 1); } device.WaitIdle(); @@ -149,7 +149,7 @@ 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"); + Require(result->variantId == artifact.variantId && result->spirv.Words().data() == artifact.spirv.Words().data(), "invocation replaced the prepared artifact"); device.Dispatch(*result, 1, 1, 1); } device.WaitIdle(); @@ -173,7 +173,7 @@ void Run(AgcDriver::VulkanDevice& device) { users[0] += 1; const auto changedCapture = invocation.Capture(preparedRuntime); const auto changedResult = invocation.Materialize(*changedCapture); - Require(changedResult != firstResult && changedResult->spirv.data() == firstResult->spirv.data(), "prepared invocation did not distinguish changed runtime data"); + Require(changedResult != firstResult && changedResult->spirv.Words().data() == firstResult->spirv.Words().data(), "prepared invocation did not distinguish changed runtime data"); users[0] -= 1; Require(invocation.Materialize(*preparedCapture) == firstResult, "prepared invocation evicted the previous runtime data"); auto replacement = OpenVulkanTestDevice(); @@ -185,7 +185,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.Words().data() == artifact.spirv.Words().data(), "device replacement recompiled the prepared shader"); replacement->Dispatch(*replacementResult, 1, 1, 1); replacement->WaitIdle(); replacementRequest.target.nonConstantImageOffsets = !replacementRequest.target.nonConstantImageOffsets; @@ -405,25 +405,26 @@ void PrepareMultisampledStorage(AgcDriver::VulkanDevice& device) { } const auto handle = PrepareShader(request); const auto& artifact = GetPreparedArtifact(*handle); + const auto words = artifact.spirv.Words(); std::vector samples; - for (std::size_t offset = 5; offset < artifact.spirv.size(); offset += artifact.spirv[offset] >> 16u) { - const auto instruction = artifact.spirv[offset]; + for (std::size_t offset = 5; offset < words.size(); offset += words[offset] >> 16u) { + const auto instruction = words[offset]; if ((instruction & 0xffffu) == spv::OpImageWrite) { - Require(variant < 3u && (instruction >> 16u) == 6u && artifact.spirv[offset + 4] == spv::ImageOperandsSampleMask, "MSAA storage write lost its sample operand"); - samples.push_back(artifact.spirv[offset + 5]); + Require(variant < 3u && (instruction >> 16u) == 6u && words[offset + 4] == spv::ImageOperandsSampleMask, "MSAA storage write lost its sample operand"); + samples.push_back(words[offset + 5]); } if ((instruction & 0xffffu) == spv::OpImageTexelPointer) { Require(variant >= 3u && (instruction >> 16u) == 6u, "MSAA atomic lost its sample operand"); - samples.push_back(artifact.spirv[offset + 5]); + samples.push_back(words[offset + 5]); } } Require(!samples.empty(), "MSAA storage shader has no image writes or atomics"); const auto expectedSample = variant == 0u ? 0u : variant % 2u != 0u ? 3u : 2u; for (const auto sample : samples) { bool found = false; - for (std::size_t offset = 5; offset < artifact.spirv.size(); offset += artifact.spirv[offset] >> 16u) { - if ((artifact.spirv[offset] & 0xffffu) != spv::OpConstant || artifact.spirv[offset + 2] != sample) continue; - Require(artifact.spirv[offset + 3] == expectedSample, "MSAA storage operation addresses the wrong sample"); + for (std::size_t offset = 5; offset < words.size(); offset += words[offset] >> 16u) { + if ((words[offset] & 0xffffu) != spv::OpConstant || words[offset + 2] != sample) continue; + Require(words[offset + 3] == expectedSample, "MSAA storage operation addresses the wrong sample"); found = true; } Require(found, "MSAA sample constant is missing"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/RectListCorner.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/RectListCorner.cpp index a91c4bd7283a..17c920ccbc7f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/RectListCorner.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/RectListCorner.cpp @@ -149,8 +149,8 @@ int Run(AgcDriver::VulkanDevice& device, std::uint32_t maximumVersion) { vertex.spirv = ShaderRecompiler::SharedSpirv(Emitter(target.spirvVersion).Vertex()); fragment.spirv = ShaderRecompiler::SharedSpirv(Emitter(target.spirvVersion).Fragment()); #if ANYPS5_ENABLE_SPIRV_TOOLS - static_cast(ShaderRecompiler::ValidateAndOptimizeSpirv(vertex.spirv, target.vulkanVersion, target.spirvVersion, target.nonConstantImageOffsets, false)); - static_cast(ShaderRecompiler::ValidateAndOptimizeSpirv(fragment.spirv, target.vulkanVersion, target.spirvVersion, target.nonConstantImageOffsets, false)); + static_cast(ShaderRecompiler::ValidateAndOptimizeSpirv(vertex.spirv.Words(), target.vulkanVersion, target.spirvVersion, target.nonConstantImageOffsets, false)); + static_cast(ShaderRecompiler::ValidateAndOptimizeSpirv(fragment.spirv.Words(), target.vulkanVersion, target.spirvVersion, target.nonConstantImageOffsets, false)); #endif vertex.parameterExports = {0u}; fragment.fragmentParameters = {{0u, 0u, false, false}}; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/RuntimeBufferSpans.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/RuntimeBufferSpans.cpp index 6f166987d837..568a8d58e676 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/RuntimeBufferSpans.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/RuntimeBufferSpans.cpp @@ -154,15 +154,16 @@ std::vector Code(std::uint32_t components, bool coherent, bool ba } bool HasVectorSpan(const ShaderRecompiler::SharedSpirv& spirv, std::uint32_t mask) { + const auto words = spirv.Words(); std::map names; std::map constants; - for (std::size_t at = 5; at < spirv.size();) { - const auto count = spirv[at] >> 16u; - const auto opcode = spirv[at] & 0xffffu; - Require(count != 0u && count <= spirv.size() - at, "runtime buffer spans: malformed SPIR-V"); - if (opcode == spv::OpName && count >= 3u) names[spirv[at + 1u]] = reinterpret_cast(spirv.data() + at + 2u); - if (opcode == spv::OpConstant && count == 4u) constants[spirv[at + 2u]] = spirv[at + 3u]; - if (opcode == spv::OpFunctionCall && count == 8u && names[spirv[at + 3u]].starts_with("read_bda_span") && constants[spirv[at + 6u]] == mask) return true; + for (std::size_t at = 5; at < words.size();) { + const auto count = words[at] >> 16u; + const auto opcode = words[at] & 0xffffu; + Require(count != 0u && count <= words.size() - at, "runtime buffer spans: malformed SPIR-V"); + if (opcode == spv::OpName && count >= 3u) names[words[at + 1u]] = reinterpret_cast(words.data() + at + 2u); + if (opcode == spv::OpConstant && count == 4u) constants[words[at + 2u]] = words[at + 3u]; + if (opcode == spv::OpFunctionCall && count == 8u && names[words[at + 3u]].starts_with("read_bda_span") && constants[words[at + 6u]] == mask) return true; at += count; } return false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp index a467c4542b54..68ca4cf89744 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp @@ -546,7 +546,7 @@ bool DeclaresCapability(std::span words, spv::Capability ca std::vector> RunLoad(AgcDriver::VulkanDevice& device, const std::array& texture, bool arrayed, std::uint32_t fragments) { std::vector userData; const auto program = CompileLoad(device, texture, userData, arrayed); - Require(!DeclaresCapability(program.spirv, spv::CapabilityImageMSArray), "the multisampled image_load declared ImageMSArray, which only multisampled arrayed storage images need"); + Require(!DeclaresCapability(program.spirv.Words(), spv::CapabilityImageMSArray), "the multisampled image_load declared ImageMSArray, which only multisampled arrayed storage images need"); std::vector> loaded(Side * Side * fragments); const auto codeAddress = reinterpret_cast((arrayed ? ArrayLoadCode : LoadCode).data()); for (std::uint32_t first = 0; first < loaded.size(); first += Threads) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp index 0359abebcc3a..2da0c0789f39 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp @@ -294,7 +294,7 @@ 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(std::span(result.spirv.Words())); 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"); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); @@ -343,7 +343,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(std::span(result.spirv.Words())); 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/StencilNullFeedback.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StencilNullFeedback.cpp index b706fc42dd67..90f709f2fb82 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StencilNullFeedback.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StencilNullFeedback.cpp @@ -271,10 +271,11 @@ void Draw(AgcDriver::VulkanDevice& device, std::span pixelC } if (!pixelResult.stencilReferences.empty()) { Require(pixelResult.stencilReferenceDword * sizeof(std::uint32_t) + sizeof(std::uint32_t) == pixelResult.pushConstants.size(), "dynamic reference is not reserved after the stage payload"); - for (std::size_t cursor = 5; cursor < pixelResult.spirv.size();) { - const auto count = pixelResult.spirv[cursor] >> 16u; - Require(count != 0u && count <= pixelResult.spirv.size() - cursor, "invalid materialized replay module"); - Require((pixelResult.spirv[cursor] & 0xffffu) != spv::OpSpecConstant, "expected reference remains a pipeline specialization"); + const auto words = pixelResult.spirv.Words(); + for (std::size_t cursor = 5; cursor < words.size();) { + const auto count = words[cursor] >> 16u; + Require(count != 0u && count <= words.size() - cursor, "invalid materialized replay module"); + Require((words[cursor] & 0xffffu) != spv::OpSpecConstant, "expected reference remains a pipeline specialization"); cursor += count; } } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StencilReplay.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StencilReplay.cpp index 4de08e7da185..fc78db08748d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StencilReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StencilReplay.cpp @@ -156,11 +156,12 @@ void Draw(AgcDriver::VulkanDevice& device, std::span pixelC if (!pixelResult.stencilReferences.empty()) { Require(pixelResult.stencilReferenceDword * sizeof(std::uint32_t) + sizeof(std::uint32_t) == pixelResult.pushConstants.size(), "dynamic reference is not reserved after the stage payload"); LastReplayStored = false; - for (std::size_t cursor = 5; cursor < pixelResult.spirv.size();) { - const auto count = pixelResult.spirv[cursor] >> 16u; - LastReplayStored = LastReplayStored || (pixelResult.spirv[cursor] & 0xffffu) == spv::OpConvertUToPtr; - Require(count != 0u && count <= pixelResult.spirv.size() - cursor, "invalid materialized replay module"); - Require((pixelResult.spirv[cursor] & 0xffffu) != spv::OpSpecConstant, "expected reference remains a pipeline specialization"); + const auto pixelWords = pixelResult.spirv.Words(); + for (std::size_t cursor = 5; cursor < pixelWords.size();) { + const auto count = pixelWords[cursor] >> 16u; + LastReplayStored = LastReplayStored || (pixelWords[cursor] & 0xffffu) == spv::OpConvertUToPtr; + Require(count != 0u && count <= pixelWords.size() - cursor, "invalid materialized replay module"); + Require((pixelWords[cursor] & 0xffffu) != spv::OpSpecConstant, "expected reference remains a pipeline specialization"); cursor += count; } } diff --git a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp index 9af289fdbc7f..fe4cef9167ce 100644 --- a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp @@ -235,9 +235,9 @@ bool Replay(const char* path) { phase = "materialize"; const auto result = invocation->Materialize(*capture); std::printf(" materialized: %zu SPIR-V words\n", result->spirv.size()); - return OutputSpirv(path, result->spirv); + return OutputSpirv(path, result->spirv.Words()); } - return OutputSpirv(path, ShaderRecompiler::GetPreparedArtifact(*handle).spirv); + return OutputSpirv(path, ShaderRecompiler::GetPreparedArtifact(*handle).spirv.Words()); } catch (const ShaderRecompiler::NanSpeculationRetry& retry) { if (retried) { std::printf(" %s failed after the retry: %s\n", phase, FirstLine(retry.what()).c_str()); @@ -262,7 +262,7 @@ bool Replay(const char* path) { } } } - return OutputSpirv(path, result.spirv); + return OutputSpirv(path, result.spirv.Words()); } catch (const std::exception& error) { std::printf(" recompile failed: %s\n", FirstLine(error.what()).c_str()); return false; diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index dd4fa9d77c37..0781896322c3 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -405,6 +405,8 @@ function(add_shader_recompiler target runtimeTarget) glslang SPIRV ) + target_link_libraries(${target} PRIVATE libzstd_static) + target_include_directories(${target} SYSTEM PRIVATE "${PROJECT_SOURCE_DIR}/3rdparty/zstd/lib") if(ANYPS5_ENABLE_SPIRV_TOOLS) target_link_libraries(${target} PRIVATE SPIRV-Tools-opt SPIRV-Tools-static) diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 59ce75c8a7f2..9689a88c3fc2 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -999,13 +999,13 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) const bool embedded = !result.vertexInputs.empty() && inputInfo.vertex != nullptr && inputInfo.vertex->fetchEmbedded; if (embedded) PrepareVertexInputSpecialization(result); #if ANYPS5_ENABLE_SPIRV_TOOLS - result.spirv = ValidateAndOptimizeSpirv(result.spirv, request.target.vulkanVersion, request.target.spirvVersion, request.target.nonConstantImageOffsets, !embedded); + result.spirv = ValidateAndOptimizeSpirv(result.spirv.Words(), request.target.vulkanVersion, request.target.spirvVersion, request.target.nonConstantImageOffsets, !embedded); if (embedded) { std::array classes{}; for (std::uint32_t kind = 1u; kind < 3u; ++kind) { classes.fill(kind); const auto specialized = SpecializeVertexInputTypes(result, classes); - static_cast(ValidateAndOptimizeSpirv(specialized, request.target.vulkanVersion, request.target.spirvVersion, request.target.nonConstantImageOffsets, false)); + static_cast(ValidateAndOptimizeSpirv(specialized.Words(), request.target.vulkanVersion, request.target.spirvVersion, request.target.nonConstantImageOffsets, false)); } } #endif diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 9002f904eac0..1906e7fd118b 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -825,20 +826,49 @@ class SharedSpirv { struct Holder; public: + using Materialize = std::shared_ptr> (*)(std::span, std::size_t, SpirvContentHash); + + class Lease { + public: + using iterator = std::span::iterator; + + Lease() = default; + Lease(std::span words, std::shared_ptr owner = nullptr) : words(words), owner(std::move(owner)) {} + [[nodiscard]] const std::uint32_t* data() const { return words.data(); } + [[nodiscard]] std::size_t size() const { return words.size(); } + [[nodiscard]] std::size_t size_bytes() const { return words.size_bytes(); } + [[nodiscard]] bool empty() const { return words.empty(); } + [[nodiscard]] const std::uint32_t& front() const { return words.front(); } + [[nodiscard]] const std::uint32_t& back() const { return words.back(); } + [[nodiscard]] const std::uint32_t& operator[](std::size_t index) const { return words[index]; } + [[nodiscard]] iterator begin() const { return words.begin(); } + [[nodiscard]] iterator end() const { return words.end(); } + [[nodiscard]] operator std::span() const { return words; } + friend bool operator==(const Lease& left, const Lease& right) { return std::ranges::equal(left.words, right.words); } + + private: + std::span words; + std::shared_ptr owner; + }; + SharedSpirv() = default; SharedSpirv(std::vector words) : holder(std::make_shared(std::move(words), nullptr, std::span{})) {} SharedSpirv(std::shared_ptr owner, std::span view) : holder(std::make_shared(std::vector{}, std::move(owner), view)) {} + SharedSpirv(std::shared_ptr owner, std::span bytes, std::size_t wordCount, SpirvContentHash hash, bool mapped, Materialize materialize) : holder(std::make_shared(std::move(owner), bytes, wordCount, hash, mapped, std::move(materialize))) {} SharedSpirv& operator=(std::vector other) { holder = std::make_shared(std::move(other), nullptr, std::span{}); return *this; } - [[nodiscard]] std::span Words() const { return holder ? holder->Words() : std::span{}; } - [[nodiscard]] bool Mapped() const { return holder != nullptr && holder->owner != nullptr; } + [[nodiscard]] Lease Words() const { return holder ? holder->Words(holder) : Lease{}; } + [[nodiscard]] bool Mapped() const { return holder != nullptr && holder->mapped; } + [[nodiscard]] bool Compressed() const { return holder != nullptr && holder->compressed; } + [[nodiscard]] bool Materialized() const { return holder != nullptr && holder->Materialized(); } + [[nodiscard]] std::span MappedBytes() const { return holder ? holder->MappedBytes() : std::span{}; } [[nodiscard]] SpirvContentHash ContentHash() const { if (holder == nullptr) return {}; if (holder->hashed.load(std::memory_order_acquire)) return {holder->hashLow.load(std::memory_order_relaxed), holder->hashHigh.load(std::memory_order_relaxed)}; - const auto words = holder->Words(); + const auto words = holder->Words(holder); if (words.empty()) return {}; const SpirvContentHash hash{HashSpirvWords(words, 0x5eed5a1d00000001ull), HashSpirvWords(words, 0x5eed5a1d00000002ull)}; holder->hashLow.store(hash.low, std::memory_order_relaxed); @@ -846,20 +876,25 @@ class SharedSpirv { holder->hashed.store(true, std::memory_order_release); return hash; } - [[nodiscard]] std::vector Copy() const { return {Words().begin(), Words().end()}; } - [[nodiscard]] std::size_t size() const { return Words().size(); } - [[nodiscard]] bool empty() const { return Words().empty(); } - [[nodiscard]] const std::uint32_t* data() const { return Words().data(); } + [[nodiscard]] std::vector Copy() const { + const auto words = Words(); + return {words.begin(), words.end()}; + } + [[nodiscard]] std::size_t size() const { return holder ? holder->Size() : 0u; } + [[nodiscard]] bool empty() const { return size() == 0u; } [[nodiscard]] std::uint32_t* data() { return Mutable().data(); } - [[nodiscard]] const std::uint32_t& operator[](std::size_t index) const { return Words()[index]; } [[nodiscard]] std::uint32_t& operator[](std::size_t index) { return Mutable()[index]; } - [[nodiscard]] std::span::iterator begin() const { return Words().begin(); } - [[nodiscard]] std::span::iterator end() const { return Words().end(); } [[nodiscard]] std::vector::iterator begin() { return Mutable().begin(); } [[nodiscard]] std::vector::iterator end() { return Mutable().end(); } void resize(std::size_t count) { Mutable().resize(count); } std::vector::iterator insert(std::vector::const_iterator where, std::initializer_list values) { return Mutable().insert(where, values); } - friend bool operator==(const SharedSpirv& left, const SharedSpirv& right) { return std::ranges::equal(left.Words(), right.Words()); } + friend bool operator==(const SharedSpirv& left, const SharedSpirv& right) { + const auto leftWords = left.Words(); + const auto rightWords = right.Words(); + return std::ranges::equal(leftWords, rightWords); + } + friend bool operator==(const SharedSpirv& left, const Lease& right) { return left.Words() == right; } + friend bool operator==(const Lease& left, const SharedSpirv& right) { return left == right.Words(); } class Weak { public: @@ -882,11 +917,43 @@ class SharedSpirv { private: struct Holder { - Holder(std::vector words, std::shared_ptr owner, std::span view) : words(std::move(words)), owner(std::move(owner)), view(view) {} - [[nodiscard]] std::span Words() const { return owner ? view : std::span(words); } + Holder(std::vector words, std::shared_ptr owner, std::span view) : words(std::move(words)), owner(std::move(owner)), view(view), mapped(this->owner != nullptr) {} + Holder(std::shared_ptr owner, std::span bytes, std::size_t wordCount, SpirvContentHash hash, bool mapped, Materialize materialize) : owner(std::move(owner)), mapped(mapped), compressed(true), compressedBytes(bytes), wordCount(wordCount), materialize(std::move(materialize)) { + hashLow.store(hash.low, std::memory_order_relaxed); + hashHigh.store(hash.high, std::memory_order_relaxed); + hashed.store(true, std::memory_order_release); + } + [[nodiscard]] Lease Words(const std::shared_ptr& self) const { + if (!compressed) return owner ? Lease(view, self) : Lease(words, self); + std::lock_guard lock(mutex); + auto current = materialized.lock(); + if (current == nullptr) { + current = materialize(compressedBytes, wordCount, {hashLow.load(std::memory_order_relaxed), hashHigh.load(std::memory_order_relaxed)}); + materialized = current; + } + const std::span view(*current); + return Lease(view, std::move(current)); + } + [[nodiscard]] bool Materialized() const { + if (!compressed) return false; + std::lock_guard lock(mutex); + return !materialized.expired(); + } + [[nodiscard]] std::size_t Size() const { return compressed ? wordCount : owner ? view.size() : words.size(); } + [[nodiscard]] std::span MappedBytes() const { + if (!mapped) return {}; + return compressed ? compressedBytes : std::as_bytes(view); + } std::vector words; std::shared_ptr owner; std::span view; + bool mapped = false; + bool compressed = false; + std::span compressedBytes; + std::size_t wordCount = 0; + Materialize materialize; + mutable std::mutex mutex; + mutable std::weak_ptr> materialized; mutable std::atomic hashLow{0}; mutable std::atomic hashHigh{0}; mutable std::atomic hashed{false}; diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index 3deca90ab758..d303e86ded20 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -44,6 +44,7 @@ #include #include #include +#include namespace ShaderRecompiler { @@ -173,6 +174,27 @@ struct FileHeader { std::uint64_t payloadHash; }; +enum class SpirvCodec : std::uint32_t { + Raw, + Zstd, +}; + +bool ZstdEnabled() { + const char* disabled = std::getenv("APS5_NO_SHADER_CACHE_ZSTD"); + return disabled == nullptr || *disabled == '\0' || std::strcmp(disabled, "0") == 0; +} + +std::shared_ptr> MaterializeZstd(std::span bytes, std::size_t wordCount, SpirvContentHash expectedHash) { + auto words = std::make_shared>(wordCount); + const auto expectedBytes = wordCount * sizeof(std::uint32_t); + const auto written = ZSTD_decompress(words->data(), expectedBytes, bytes.data(), bytes.size()); + if (ZSTD_isError(written)) throw std::runtime_error(std::string("shader disk cache: zstd SPIR-V decompression failed: ") + ZSTD_getErrorName(written)); + if (written != expectedBytes) throw std::runtime_error("shader disk cache: zstd SPIR-V returned a different byte count"); + const SpirvContentHash hash{HashSpirvWords(*words, 0x5eed5a1d00000001ull), HashSpirvWords(*words, 0x5eed5a1d00000002ull)}; + if (hash != expectedHash) throw std::runtime_error("shader disk cache: decompressed SPIR-V content hash differs"); + return words; +} + std::size_t PayloadOffset(std::size_t keyBytes) { constexpr std::size_t alignment = 8; return (sizeof(FileHeader) + keyBytes + alignment - 1) / alignment * alignment; @@ -306,6 +328,29 @@ class Writer { out.insert(out.end(), bytes.begin(), bytes.end()); } + void Spirv(const SharedSpirv& spirv, bool compress) { + const auto words = spirv.Words(); + if (words.size() > MaxCachedSpirvWords) throw std::runtime_error("shader disk cache: SPIR-V exceeds the cached-entry word limit"); + const auto raw = std::as_bytes(std::span(words)); + const auto hash = spirv.ContentHash(); + SpirvCodec codec = SpirvCodec::Raw; + std::vector compressed; + if (compress && ZstdEnabled() && !words.empty()) { + compressed.resize(ZSTD_compressBound(raw.size())); + const auto written = ZSTD_compress(compressed.data(), compressed.size(), raw.data(), raw.size(), 1); + if (ZSTD_isError(written)) throw std::runtime_error(std::string("shader disk cache: zstd SPIR-V compression failed: ") + ZSTD_getErrorName(written)); + compressed.resize(written); + if (written < raw.size()) codec = SpirvCodec::Zstd; + } + Value(codec); + Value(words.size()); + Value(hash.low); + Value(hash.high); + const auto stored = codec == SpirvCodec::Zstd ? std::span(compressed) : raw; + Value(stored.size()); + out.insert(out.end(), stored.begin(), stored.end()); + } + void Flags(const ElementFlags& flags) { Value(flags.size()); for (const bool flag : flags) Value(flag); @@ -396,15 +441,46 @@ class Reader { } SharedSpirv Spirv() { - const auto count = Count(sizeof(std::uint32_t)); - const auto* first = bytes.data() + position; - position += count * sizeof(std::uint32_t); - if (owner != nullptr && reinterpret_cast(first) % alignof(std::uint32_t) == 0) { - return SharedSpirv(owner, std::span(reinterpret_cast(first), count)); + const auto codec = Get(); + const auto encodedCount = Get(); + const SpirvContentHash hash{Get(), Get()}; + const auto byteCount = Count(1); + if (!ok || encodedCount > MaxCachedSpirvWords || encodedCount > std::numeric_limits::max() / sizeof(std::uint32_t)) { + ok = false; + return {}; + } + const auto wordCount = static_cast(encodedCount); + const auto expectedBytes = wordCount * sizeof(std::uint32_t); + auto payload = bytes.subspan(position, byteCount); + position += byteCount; + if (codec == SpirvCodec::Raw) { + if (byteCount != expectedBytes) { + ok = false; + return {}; + } + const auto* first = payload.data(); + if (owner != nullptr && reinterpret_cast(first) % alignof(std::uint32_t) == 0) return SharedSpirv(owner, std::span(reinterpret_cast(first), wordCount)); + std::vector words(wordCount); + if (wordCount != 0) std::memcpy(words.data(), first, expectedBytes); + return SharedSpirv(std::move(words)); } - std::vector words(count); - if (count != 0) std::memcpy(words.data(), first, count * sizeof(std::uint32_t)); - return SharedSpirv(std::move(words)); + if (codec != SpirvCodec::Zstd || wordCount == 0u || payload.empty()) { + ok = false; + return {}; + } + const auto frameBytes = ZSTD_findFrameCompressedSize(payload.data(), payload.size()); + const auto contentBytes = ZSTD_getFrameContentSize(payload.data(), payload.size()); + if (ZSTD_isError(frameBytes) || frameBytes != payload.size() || contentBytes != expectedBytes) { + ok = false; + return {}; + } + std::shared_ptr storage = owner; + if (storage == nullptr) { + auto copy = std::make_shared>(payload.begin(), payload.end()); + payload = std::span(*copy); + storage = std::move(copy); + } + return SharedSpirv(std::move(storage), payload, wordCount, hash, owner != nullptr, MaterializeZstd); } void Flags(ElementFlags& flags) { @@ -558,9 +634,9 @@ void decodeBinding(Reader& reader, DescriptorBinding& binding) { reader.List(binding.imageOverwrites, 133, [](Reader& in, ImageOverwrite& proof) { decodeOverwrite(in, proof); }); } -void encodeArtifact(Writer& writer, const CompiledShaderArtifact& result) { +void encodeArtifact(Writer& writer, const CompiledShaderArtifact& result, bool compressSpirv) { writer.Value(result.runtimeAbiVersion); - writer.Values(std::span(result.spirv.Words())); + writer.Spirv(result.spirv, compressSpirv); writer.Value(result.bdaAbiVersion); writer.Value(result.windowLaneGuards); writer.Value(result.descriptorFaults); @@ -1474,6 +1550,7 @@ constexpr std::string_view NeutralSwitches[] = { "APS5_DUMP_SPIRV", "APS5_NO_CODE_HASH_KEY", "APS5_NO_FAILURE_MEMO", + "APS5_NO_SHADER_CACHE_ZSTD", "APS5_NO_PERF_FRONTEND_PAIR", "APS5_NO_PERF_DISK_PLANS", "APS5_NO_PERF_DOM_INTERSECTION", @@ -1605,7 +1682,14 @@ class DiskStore { std::shared_ptr Persist(std::span key, const CompiledVariant& variant) { const auto path = directory / EntryName(key); - const auto file = EncodeEntry(key, variant); + std::vector file; + try { + file = EncodeEntry(key, variant); + } catch (const std::exception& error) { + const auto failures = writeFailures.fetch_add(1, std::memory_order_relaxed); + if (failures < 4) std::fprintf(stderr, "[shader-disk-cache] cannot encode %s: %s\n", path.string().c_str(), error.what()); + return nullptr; + } if (!WriteFileAtomically(path, file)) return nullptr; writes.fetch_add(1, std::memory_order_relaxed); bytesWritten.fetch_add(file.size(), std::memory_order_relaxed); @@ -1845,7 +1929,14 @@ class DiskStore { } void write(const Job& job) { - const auto file = job.plan != nullptr ? EncodePlanEntry(job.key, *job.plan) : !job.words.empty() ? wrapEntry(job.key, std::as_bytes(std::span(job.words))) : EncodeEntry(job.key, *job.variant); + std::vector file; + try { + file = job.plan != nullptr ? EncodePlanEntry(job.key, *job.plan) : !job.words.empty() ? wrapEntry(job.key, std::as_bytes(std::span(job.words))) : EncodeEntry(job.key, *job.variant); + } catch (const std::exception& error) { + const auto failures = writeFailures.fetch_add(1, std::memory_order_relaxed); + if (failures < 4) std::fprintf(stderr, "[shader-disk-cache] cannot encode %s: %s\n", (directory / EntryName(job.key)).string().c_str(), error.what()); + return; + } if (!file.empty() && WriteFileAtomically(directory / EntryName(job.key), file)) { (job.plan != nullptr ? planWrites : !job.words.empty() ? specializedWrites : writes).fetch_add(1, std::memory_order_relaxed); bytesWritten.fetch_add(file.size(), std::memory_order_relaxed); @@ -2065,7 +2156,7 @@ std::string EntryName(std::span key) { void EncodeResult(const RecompileResult& result, std::vector& out) { Writer writer(out); - encodeArtifact(writer, result); + encodeArtifact(writer, result, false); encodeInvocation(writer, result); writer.Value(result.workgroupMemoryDwords); writer.Values(std::span(result.shaderDataUserWords)); @@ -2086,7 +2177,7 @@ std::vector EncodeEntry(std::span key, const Compile std::vector payload; payload.reserve(variant.artifact.spirv.size() * sizeof(std::uint32_t) + 4096); Writer writer(payload); - encodeArtifact(writer, variant.artifact); + encodeArtifact(writer, variant.artifact, true); encodeInfo(writer, variant.info); encodeAllocation(writer, variant.bindings); return wrapEntry(key, payload); @@ -2195,16 +2286,15 @@ void Flush() { } void ReleaseMapped(const SharedSpirv& spirv) noexcept { - if (!spirv.Mapped()) return; - const auto words = spirv.Words(); - if (words.empty()) return; + const auto bytes = spirv.MappedBytes(); + if (bytes.empty()) return; #ifdef _WIN32 - VirtualUnlock(const_cast(words.data()), words.size_bytes()); + VirtualUnlock(const_cast(bytes.data()), bytes.size()); #else const auto page = static_cast(sysconf(_SC_PAGESIZE)); - const auto first = reinterpret_cast(words.data()); + const auto first = reinterpret_cast(bytes.data()); const auto begin = first / page * page; - madvise(reinterpret_cast(begin), first + words.size_bytes() - begin, MADV_DONTNEED); + madvise(reinterpret_cast(begin), first + bytes.size() - begin, MADV_DONTNEED); #endif } diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index c05773ee146a..08f4ee83b224 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -17,7 +17,8 @@ struct NanSpeculationConfig; namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 98; +inline constexpr std::uint32_t FormatVersion = 99; +inline constexpr std::size_t MaxCachedSpirvWords = 16u * 1024u * 1024u; enum class LoadStatus { Loaded, diff --git a/core/shader/recompiler/SpirvBackend/src/BarycentricGeometryShader.cpp b/core/shader/recompiler/SpirvBackend/src/BarycentricGeometryShader.cpp index 00cc69e1095a..5f90aaf9baaf 100644 --- a/core/shader/recompiler/SpirvBackend/src/BarycentricGeometryShader.cpp +++ b/core/shader/recompiler/SpirvBackend/src/BarycentricGeometryShader.cpp @@ -434,7 +434,7 @@ RecompileResult BuildBarycentricGeometryShader(const RecompileResult& vertex, co RecompileResult result; result.spirv = emitter.Emit(emulated.passed, emulated.perVertex, emulated.layout); #if ANYPS5_ENABLE_SPIRV_TOOLS - result.spirv = ValidateAndOptimizeSpirv(result.spirv, target.vulkanVersion, target.spirvVersion); + result.spirv = ValidateAndOptimizeSpirv(result.spirv.Words(), target.vulkanVersion, target.spirvVersion); #endif return result; } @@ -462,8 +462,8 @@ BarycentricTessellationShaders BuildBarycentricTessellationShaders(const Recompi shaders.control.spirv = BarycentricTessellationEmitter(target.spirvVersion, clipDistances).EmitControl(sources); shaders.evaluation.spirv = BarycentricTessellationEmitter(target.spirvVersion, clipDistances).EmitEvaluation(sources, emulated.passed, emulated.passedFlat, emulated.perVertex, emulated.layout, provokingVertex); #if ANYPS5_ENABLE_SPIRV_TOOLS - shaders.control.spirv = ValidateAndOptimizeSpirv(shaders.control.spirv, target.vulkanVersion, target.spirvVersion); - shaders.evaluation.spirv = ValidateAndOptimizeSpirv(shaders.evaluation.spirv, target.vulkanVersion, target.spirvVersion); + shaders.control.spirv = ValidateAndOptimizeSpirv(shaders.control.spirv.Words(), target.vulkanVersion, target.spirvVersion); + shaders.evaluation.spirv = ValidateAndOptimizeSpirv(shaders.evaluation.spirv.Words(), target.vulkanVersion, target.spirvVersion); #endif return shaders; } diff --git a/core/shader/recompiler/SpirvBackend/src/RectListShaders.cpp b/core/shader/recompiler/SpirvBackend/src/RectListShaders.cpp index ec21aa9e8d04..fa6b7fcac024 100644 --- a/core/shader/recompiler/SpirvBackend/src/RectListShaders.cpp +++ b/core/shader/recompiler/SpirvBackend/src/RectListShaders.cpp @@ -528,15 +528,15 @@ RectListShaders BuildRectListShaders(const RecompileResult& vertex, const Recomp shaders.control.bdaAbiVersion = BdaAbi::Version; shaders.evaluation.spirv = evaluation.EmitEvaluation(); #if ANYPS5_ENABLE_SPIRV_TOOLS - shaders.control.spirv = ValidateAndOptimizeSpirv(shaders.control.spirv, target.vulkanVersion, target.spirvVersion); - shaders.evaluation.spirv = ValidateAndOptimizeSpirv(shaders.evaluation.spirv, target.vulkanVersion, target.spirvVersion); + shaders.control.spirv = ValidateAndOptimizeSpirv(shaders.control.spirv.Words(), target.vulkanVersion, target.spirvVersion); + shaders.evaluation.spirv = ValidateAndOptimizeSpirv(shaders.evaluation.spirv.Words(), target.vulkanVersion, target.spirvVersion); #endif shaders.lastVertexControl = shaders.control; if (std::any_of(parameters.begin(), parameters.end(), [](const Parameter& parameter) { return parameter.flat && !parameter.missing; })) { RectListEmitter lastVertexControl(parameters, emulation, spv::ExecutionModelTessellationControl, target.spirvVersion, faultBinding, clipDistances); shaders.lastVertexControl.spirv = lastVertexControl.EmitControl(2u); #if ANYPS5_ENABLE_SPIRV_TOOLS - shaders.lastVertexControl.spirv = ValidateAndOptimizeSpirv(shaders.lastVertexControl.spirv, target.vulkanVersion, target.spirvVersion); + shaders.lastVertexControl.spirv = ValidateAndOptimizeSpirv(shaders.lastVertexControl.spirv.Words(), target.vulkanVersion, target.spirvVersion); #endif } return shaders; diff --git a/core/shader/recompiler/SpirvBackend/src/TessellationCaptureShader.cpp b/core/shader/recompiler/SpirvBackend/src/TessellationCaptureShader.cpp index bef354231e5a..eceac4c7f6c5 100644 --- a/core/shader/recompiler/SpirvBackend/src/TessellationCaptureShader.cpp +++ b/core/shader/recompiler/SpirvBackend/src/TessellationCaptureShader.cpp @@ -160,7 +160,7 @@ RecompileResult BuildTessellationCaptureGeometryShader(const MeshConfiguration& RecompileResult result; result.spirv = emitter.Emit(geometry.esgsItemSize, geometry.primitivesPerGroup); #if ANYPS5_ENABLE_SPIRV_TOOLS - result.spirv = ValidateAndOptimizeSpirv(result.spirv, target.vulkanVersion, target.spirvVersion); + result.spirv = ValidateAndOptimizeSpirv(result.spirv.Words(), target.vulkanVersion, target.spirvVersion); #endif return result; } diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 07c20909b413..9612a6958875 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -44,6 +44,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti |------|------|--------|---------|-------------| | `ANYPS5_NO_SHADER_CACHE` | string | `core/shader/recompiler/ShaderDiskCache.cpp` | | disables the on-disk shader cache when set to a non-empty value other than 0 | | `ANYPS5_SHADER_CACHE_DIR` | string | `core/shader/recompiler/ShaderDiskCache.cpp` | | directory for the on-disk shader cache, overriding the one beside the executable | +| `APS5_NO_SHADER_CACHE_ZSTD` | string | `core/shader/recompiler/ShaderDiskCache.cpp` | | writes uncompressed SPIR-V payloads when set to a non-empty value other than 0; compressed and raw entries in the current format remain readable | | `APS5_BDA_BYTE_READS` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp` | | forces one address lookup and byte load per byte for BDA reads instead of a wide dword load | | `APS5_BDA_DWORD_STORES` | presence | `core/shader/recompiler/Translation/src/MemoryInstructions/FlatInstructions.cpp` | | reverts BDA writes to one address store per dword instead of a wide multi-dword store | | `APS5_COHERENT_ATOMIC_LOADS` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp` | | emits `glc` buffer loads as device-scope relaxed atomic loads instead of volatile loads, for compute programs that wait for another workgroup's flag ([shader debt](debt/shader.md)) | diff --git a/tools/frame_capture_minimize.py b/tools/frame_capture_minimize.py index c52bd9c1457b..374c26c6cebb 100644 --- a/tools/frame_capture_minimize.py +++ b/tools/frame_capture_minimize.py @@ -159,6 +159,9 @@ def drain_replay_group(process): os.killpg(process.pid, 0) except ProcessLookupError: return + except PermissionError: + if sys.platform != "darwin": + raise if time.monotonic() >= deadline: raise RuntimeError("replay process group remains after termination") time.sleep(0.02) diff --git a/tools/tests/test_frame_capture_minimize_replay.py b/tools/tests/test_frame_capture_minimize_replay.py index 7c68f401faed..7ecc9db16a70 100644 --- a/tools/tests/test_frame_capture_minimize_replay.py +++ b/tools/tests/test_frame_capture_minimize_replay.py @@ -375,5 +375,36 @@ def test_process_group_that_remains_after_termination_is_fatal_and_bounded(self) self.assertEqual(killpg.call_args_list, [call(123, 9), call(123, 0)]) process.wait.assert_called_once_with(timeout=1) + def test_darwin_probe_retries_until_the_process_group_disappears(self): + process = Mock(pid=123) + with ( + patch.object(frame_capture_minimize.sys, "platform", "darwin"), + patch.object(frame_capture_minimize.signal, "SIGKILL", 9, create=True), + patch.object(frame_capture_minimize.os, "killpg", create=True, + side_effect=[None, PermissionError("not allowed"), ProcessLookupError()]) as killpg, + patch.object(frame_capture_minimize.time, "sleep"), + ): + frame_capture_minimize.drain_replay_group(process) + self.assertEqual(killpg.call_args_list, [call(123, 9), call(123, 0), call(123, 0)]) + process.wait.assert_called_once() + + def test_darwin_probe_does_not_accept_persistent_permission_failure(self): + process = Mock(pid=123) + denied = PermissionError("not allowed") + with ( + patch.object(frame_capture_minimize.sys, "platform", "darwin"), + patch.object(frame_capture_minimize.signal, "SIGKILL", 9, create=True), + patch.object(frame_capture_minimize.os, "killpg", create=True, + side_effect=[None, denied, denied]) as killpg, + patch.object(frame_capture_minimize, "REPLAY_DRAIN_SECONDS", 1), + patch.object(frame_capture_minimize.time, "monotonic", side_effect=[0, 0, 0.5, 1]), + patch.object(frame_capture_minimize.time, "sleep"), + ): + with self.assertRaisesRegex(frame_capture_minimize.ReplayCleanupError, "group remains"): + frame_capture_minimize.drain_replay_group(process) + self.assertEqual(killpg.call_args_list, [call(123, 9), call(123, 0), call(123, 0)]) + process.wait.assert_called_once_with(timeout=1) + + if __name__ == "__main__": unittest.main()