#include "prx/libSceAgcDriver/Graphics/include/InlineList.hpp" #include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" #include "prx/libc/include/RunReport.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetTransfer.hpp" #include "prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp" #include "prx/libSceAgcDriver/Graphics/include/VertexInput.hpp" #include "prx/libSceAgcDriver/Graphics/include/VertexPlanScratch.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" #include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/StagedMerge.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp" #include "prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp" #include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/TracyZone.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileCounter.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/ThreadScratch.hpp" #include "ThreadOwned.hpp" #include "prx/libc/include/General.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "Optimization/include/Optimization/ShaderStageInputInfo.hpp" #include "SpirvBackend/SpirvAnalysis.hpp" #include "ThreadOwned.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace AgcDriver::Graphics { void WriteCheckpointMarker(const Context& context, VkCommandBuffer commands, std::uint64_t serial, std::uint32_t queue); void WriteNvCheckpointToken(const Context& context, VkCommandBuffer commands, std::uint64_t token, std::uint32_t queue); namespace { enum class VkDrawKind : std::size_t { Direct, Indexed, Indirect, Mesh, Count }; std::array, static_cast(VkDrawKind::Count)> vkDrawCounts{}; void CountVkDraw(VkDrawKind kind) { vkDrawCounts[static_cast(kind)].fetch_add(1, std::memory_order_relaxed); } bool DrawFaultTokens() { static const bool enabled = std::getenv("APS5_GPU_CHECKPOINTS") != nullptr; return enabled; } void noteDrawFaultToken(const Context& context, Recorder& recorder, VkCommandBuffer commands, std::span shaders, const Pm4::DrawParameters& draw, std::uint32_t stage, const Pm4::DrawParameters::IndirectDraw* args) { try { if (!DrawFaultTokens()) return; const auto queue = GuestMemory::GpuLockThreadTag(); if (queue != 0) return; const auto faultToken = AgcDriver::FaultTokenRing::Instance().Claim(); if (faultToken == 0) return; if (auto* entry = AgcDriver::FaultTokenRing::Instance().Mutable(faultToken)) { entry->submitSerial = recorder.OpenSerial(); entry->programAddress = 0; std::uint64_t variant = 0; for (const auto& shader : shaders) { if (shader.program != nullptr && (variant == 0 || shader.stage == ShaderRecompiler::ShaderStage::Fragment)) variant = shader.program->variantId; } entry->variantId = variant; entry->stage = stage; entry->argBuffer = 0; entry->argOffset = 0; entry->argStride = 0; entry->argCount = 0; for (auto& word : entry->argWords) word = 0; if (args != nullptr) { entry->argBuffer = args->arguments; entry->argOffset = 0; entry->argStride = args->stride; try { constexpr std::uint32_t argWordLimit = 4; const auto first = Pm4::ReadDrawArgumentsUnsynced(*args, 0); entry->argWords[0] = first.count; entry->argWords[1] = first.instances; entry->argWords[2] = first.firstVertexOrIndex; entry->argWords[3] = draw.indexed ? first.vertexOffset : first.firstInstance; entry->argCount = argWordLimit; } catch (...) { entry->argCount = 0; } } std::snprintf(entry->desc, sizeof(entry->desc), "draw%s%s c=%u i=%u", draw.indexed ? " indexed" : "", args != nullptr ? " indirect" : "", draw.indexCount, draw.instanceCount); recorder.NoteFaultToken(faultToken); std::atomic_ref(entry->token).store(faultToken, std::memory_order_release); } WriteCheckpointMarker(context, commands, faultToken, queue); WriteNvCheckpointToken(context, commands, faultToken, queue); } catch (...) { } } struct PixelFunctionLdsPool { Context context{}; VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; VkDescriptorPool descriptorPool = VK_NULL_HANDLE; VkDescriptorSet set = VK_NULL_HANDLE; VkDescriptorSetLayout empty = VK_NULL_HANDLE; VkDescriptorSetLayout bufferLayout = VK_NULL_HANDLE; std::uint32_t* header = nullptr; std::uint32_t subgroupSize = 0; std::uint32_t slots = 0; bool announced = false; }; std::mutex& PixelLdsMutex() { static std::mutex mutex; return mutex; } std::unordered_map& PixelLdsPools() { static std::unordered_map pools; return pools; } struct MeshWindowPool { Context context{}; VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; VkDescriptorPool descriptorPool = VK_NULL_HANDLE; VkDescriptorSet set = VK_NULL_HANDLE; VkDescriptorSetLayout layout = VK_NULL_HANDLE; }; std::mutex& MeshWindowMutex() { static std::mutex mutex; return mutex; } std::unordered_map& MeshWindowPools() { static std::unordered_map pools; return pools; } void DestroyMeshWindow(MeshWindowPool& pool) { if (pool.descriptorPool != VK_NULL_HANDLE) pool.context.Function("vkDestroyDescriptorPool")(pool.context.device, pool.descriptorPool, nullptr); if (pool.buffer != VK_NULL_HANDLE) pool.context.Function("vkDestroyBuffer")(pool.context.device, pool.buffer, nullptr); if (pool.memory != VK_NULL_HANDLE) MemoryAccounting::Free(pool.context, pool.memory); if (pool.layout != VK_NULL_HANDLE) pool.context.Function("vkDestroyDescriptorSetLayout")(pool.context.device, pool.layout, nullptr); pool = MeshWindowPool{}; } void DestroyPixelFunctionLds(PixelFunctionLdsPool& pool) { if (pool.header != nullptr) pool.context.Function("vkUnmapMemory")(pool.context.device, pool.memory); if (pool.descriptorPool != VK_NULL_HANDLE) pool.context.Function("vkDestroyDescriptorPool")(pool.context.device, pool.descriptorPool, nullptr); if (pool.buffer != VK_NULL_HANDLE) pool.context.Function("vkDestroyBuffer")(pool.context.device, pool.buffer, nullptr); if (pool.memory != VK_NULL_HANDLE) MemoryAccounting::Free(pool.context, pool.memory); if (pool.bufferLayout != VK_NULL_HANDLE) pool.context.Function("vkDestroyDescriptorSetLayout")(pool.context.device, pool.bufferLayout, nullptr); if (pool.empty != VK_NULL_HANDLE) pool.context.Function("vkDestroyDescriptorSetLayout")(pool.context.device, pool.empty, nullptr); pool.header = nullptr; pool.descriptorPool = VK_NULL_HANDLE; pool.set = VK_NULL_HANDLE; pool.buffer = VK_NULL_HANDLE; pool.memory = VK_NULL_HANDLE; pool.bufferLayout = VK_NULL_HANDLE; pool.empty = VK_NULL_HANDLE; } } PixelFunctionLdsLayouts PixelFunctionLdsSetLayouts(const Context& context) { std::lock_guard lock(PixelLdsMutex()); auto& pool = PixelLdsPools()[context.device]; if (pool.bufferLayout == VK_NULL_HANDLE) { pool.context = context; VkDescriptorSetLayoutCreateInfo emptyInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; Check(context.Function("vkCreateDescriptorSetLayout")(context.device, &emptyInfo, nullptr, &pool.empty), "vkCreateDescriptorSetLayout pixel function LDS empty"); const VkDescriptorSetLayoutBinding binding{0u, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; VkDescriptorSetLayoutCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; info.bindingCount = 1u; info.pBindings = &binding; Check(context.Function("vkCreateDescriptorSetLayout")(context.device, &info, nullptr, &pool.bufferLayout), "vkCreateDescriptorSetLayout pixel function LDS"); } return {pool.empty, pool.bufferLayout}; } void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, std::uint32_t subgroupSize) { const auto operations = VK_SUBGROUP_FEATURE_BASIC_BIT | VK_SUBGROUP_FEATURE_BALLOT_BIT; Require((context.subgroup.supportedStages & VK_SHADER_STAGE_FRAGMENT_BIT) != 0 && (context.subgroup.supportedOperations & operations) == operations, "pixel function LDS needs fragment subgroup elect, ballot and broadcast"); Require(subgroupSize != 0u && subgroupSize == context.subgroup.subgroupSize, "pixel function LDS subgroup size does not match the device"); std::lock_guard lock(PixelLdsMutex()); auto& pool = PixelLdsPools()[context.device]; Require(pool.bufferLayout != VK_NULL_HANDLE, "pixel function LDS descriptor set layout was not created"); if (pool.buffer == VK_NULL_HANDLE) { const auto stride = static_cast(subgroupSize) * ShaderRecompiler::FunctionLdsDwordLimit * 4ull; const auto budget = std::min(context.limits.maxStorageBufferRange, 2ull << 30); Require(budget > 16ull + stride, "pixel function LDS does not fit in the device storage buffer range"); pool.slots = static_cast((budget - 16ull) / stride); pool.subgroupSize = subgroupSize; const auto bytes = 16ull + stride * pool.slots; VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bufferInfo.size = bytes; bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; Check(context.Function("vkCreateBuffer")(context.device, &bufferInfo, nullptr, &pool.buffer), "vkCreateBuffer pixel function LDS"); VkMemoryRequirements requirements{}; context.Function("vkGetBufferMemoryRequirements")(context.device, pool.buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; allocation.allocationSize = requirements.size; constexpr auto hostCoherent = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; constexpr auto deviceLocalHost = hostCoherent | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; std::optional deviceLocalType; std::optional hostOnlyType; for (std::uint32_t i = 0; i < context.memory.memoryTypeCount; ++i) { if ((requirements.memoryTypeBits & (1u << i)) == 0) continue; const auto flags = context.memory.memoryTypes[i].propertyFlags; const auto heap = context.memory.memoryTypes[i].heapIndex; if (!deviceLocalType && (flags & deviceLocalHost) == deviceLocalHost && context.memory.memoryHeaps[heap].size >= requirements.size) { deviceLocalType = i; } if (!hostOnlyType && (flags & hostCoherent) == hostCoherent && (flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) { hostOnlyType = i; } } const auto hostType = hostOnlyType.value_or(context.MemoryType(requirements.memoryTypeBits, hostCoherent)); allocation.memoryTypeIndex = deviceLocalType.value_or(hostType); auto allocated = MemoryAccounting::Allocate(context, allocation, "pixel function LDS", &pool.memory); if (allocated != VK_SUCCESS && deviceLocalType && allocation.memoryTypeIndex == *deviceLocalType && hostType != *deviceLocalType) { allocation.memoryTypeIndex = hostType; allocated = MemoryAccounting::Allocate(context, allocation, "pixel function LDS", &pool.memory); } if (allocated != VK_SUCCESS) { context.Function("vkDestroyBuffer")(context.device, pool.buffer, nullptr); pool.buffer = VK_NULL_HANDLE; pool.memory = VK_NULL_HANDLE; Check(allocated, "vkAllocateMemory pixel function LDS"); } Check(context.Function("vkBindBufferMemory")(context.device, pool.buffer, pool.memory, 0), "vkBindBufferMemory pixel function LDS"); Check(context.Function("vkMapMemory")(context.device, pool.memory, 0, 16, 0, reinterpret_cast(&pool.header)), "vkMapMemory pixel function LDS"); pool.header[0] = 0u; pool.header[1] = 0u; pool.header[2] = pool.slots; const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u}; VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; poolInfo.maxSets = 1u; poolInfo.poolSizeCount = 1u; poolInfo.pPoolSizes = &size; Check(context.Function("vkCreateDescriptorPool")(context.device, &poolInfo, nullptr, &pool.descriptorPool), "vkCreateDescriptorPool pixel function LDS"); VkDescriptorSetAllocateInfo sets{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; sets.descriptorPool = pool.descriptorPool; sets.descriptorSetCount = 1u; sets.pSetLayouts = &pool.bufferLayout; Check(context.Function("vkAllocateDescriptorSets")(context.device, &sets, &pool.set), "vkAllocateDescriptorSets pixel function LDS"); const VkDescriptorBufferInfo buffer{pool.buffer, 0, bytes}; VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; write.dstSet = pool.set; write.dstBinding = 0u; write.descriptorCount = 1u; write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &buffer; context.Function("vkUpdateDescriptorSets")(context.device, 1u, &write, 0u, nullptr); std::fprintf(stderr, "[gpu] pixel function LDS pool: %u subgroups, %llu MiB, stride %u lanes\n", pool.slots, static_cast(bytes >> 20u), subgroupSize); pool.announced = true; } Require(pool.subgroupSize == subgroupSize, "pixel function LDS subgroup size does not match the pool"); const VkMemoryBarrier beforeFill{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT}; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &beforeFill, 0, nullptr, 0, nullptr); context.Resolved(&DeviceFunctions::cmdFillBuffer, "vkCmdFillBuffer")(commands, pool.buffer, 0, 4, 0u); const VkMemoryBarrier afterFill{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT}; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 1, &afterFill, 0, nullptr, 0, nullptr); } bool UsesMeshWindow(std::span shaders) { return std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->meshWindowBuffer; }); } VkDescriptorSetLayout MeshWindowSetLayout(const Context& context) { std::lock_guard lock(MeshWindowMutex()); auto& pool = MeshWindowPools()[context.device]; if (pool.layout == VK_NULL_HANDLE) { pool.context = context; const VkDescriptorSetLayoutBinding binding{0u, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u, VK_SHADER_STAGE_MESH_BIT_EXT, nullptr}; VkDescriptorSetLayoutCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; info.bindingCount = 1u; info.pBindings = &binding; Check(context.Function("vkCreateDescriptorSetLayout")(context.device, &info, nullptr, &pool.layout), "vkCreateDescriptorSetLayout mesh window"); } return pool.layout; } void PrepareMeshWindow(const Context& context) { std::lock_guard lock(MeshWindowMutex()); auto& pool = MeshWindowPools()[context.device]; Require(pool.layout != VK_NULL_HANDLE, "mesh window descriptor set layout was not created"); if (pool.set != VK_NULL_HANDLE) return; try { const auto bytes = (static_cast(ShaderRecompiler::MeshWindowHeaderDwords) + static_cast(ShaderRecompiler::MeshWindowSlots) * ShaderRecompiler::MeshWindowSlotDwords) * 4ull; Require(bytes <= context.limits.maxStorageBufferRange, "mesh window pool does not fit in the device storage buffer range"); VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bufferInfo.size = bytes; bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; Check(context.Function("vkCreateBuffer")(context.device, &bufferInfo, nullptr, &pool.buffer), "vkCreateBuffer mesh window"); VkMemoryRequirements requirements{}; context.Function("vkGetBufferMemoryRequirements")(context.device, pool.buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; allocation.allocationSize = requirements.size; allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Check(MemoryAccounting::Allocate(context, allocation, "mesh window", &pool.memory), "vkAllocateMemory mesh window"); Check(context.Function("vkBindBufferMemory")(context.device, pool.buffer, pool.memory, 0), "vkBindBufferMemory mesh window"); const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u}; VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; poolInfo.maxSets = 1u; poolInfo.poolSizeCount = 1u; poolInfo.pPoolSizes = &size; Check(context.Function("vkCreateDescriptorPool")(context.device, &poolInfo, nullptr, &pool.descriptorPool), "vkCreateDescriptorPool mesh window"); VkDescriptorSetAllocateInfo sets{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; sets.descriptorPool = pool.descriptorPool; sets.descriptorSetCount = 1u; sets.pSetLayouts = &pool.layout; VkDescriptorSet set = VK_NULL_HANDLE; Check(context.Function("vkAllocateDescriptorSets")(context.device, &sets, &set), "vkAllocateDescriptorSets mesh window"); const VkDescriptorBufferInfo buffer{pool.buffer, 0, bytes}; VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; write.dstSet = set; write.dstBinding = 0u; write.descriptorCount = 1u; write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &buffer; context.Function("vkUpdateDescriptorSets")(context.device, 1u, &write, 0u, nullptr); CommandBatch batch(context); const auto commands = batch.Handle(); context.Function("vkCmdFillBuffer")(commands, pool.buffer, 0, ShaderRecompiler::MeshWindowHeaderDwords * 4u, 0u); const VkMemoryBarrier afterFill{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT}; context.Function("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &afterFill, 0, nullptr, 0, nullptr); batch.SubmitAndWait(); pool.set = set; std::fprintf(stderr, "[gpu] mesh window pool: %u workgroup slots, %llu MiB\n", ShaderRecompiler::MeshWindowSlots, static_cast(bytes >> 20u)); } catch (...) { const auto layout = pool.layout; pool.layout = VK_NULL_HANDLE; DestroyMeshWindow(pool); pool.context = context; pool.layout = layout; throw; } } void BindMeshWindow(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout) { std::lock_guard lock(MeshWindowMutex()); const auto& pool = MeshWindowPools().at(context.device); Require(pool.set != VK_NULL_HANDLE, "mesh window buffer was not prepared"); context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::MeshWindowDescriptorSet, 1, &pool.set, 0, nullptr); } void ReleaseMeshWindow(VkDevice device) { std::lock_guard lock(MeshWindowMutex()); const auto found = MeshWindowPools().find(device); if (found == MeshWindowPools().end()) return; DestroyMeshWindow(found->second); MeshWindowPools().erase(found); } std::uint32_t PixelFunctionLdsSubgroup(std::span shaders) { std::uint32_t subgroup = 0u; for (const auto& shader : shaders) { if (shader.program != nullptr && shader.program->functionLdsBuffer) subgroup = shader.program->hostSubgroupSize; } return subgroup; } void BindPixelFunctionLds(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout) { std::lock_guard lock(PixelLdsMutex()); const auto& pool = PixelLdsPools().at(context.device); Require(pool.set != VK_NULL_HANDLE, "pixel function LDS buffer was not prepared"); context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::PixelFunctionLdsDescriptorSet, 1, &pool.set, 0, nullptr); } void CheckPixelFunctionLds(const Context& context) { std::lock_guard lock(PixelLdsMutex()); const auto found = PixelLdsPools().find(context.device); if (found == PixelLdsPools().end() || found->second.header == nullptr) return; const auto exhausted = found->second.header[1] != 0u; found->second.header[1] = 0u; if (exhausted) throw std::runtime_error("AGC graphics: pixel function LDS subgroup slots exhausted"); } void ReleasePixelFunctionLds(VkDevice device) { std::lock_guard lock(PixelLdsMutex()); const auto found = PixelLdsPools().find(device); if (found == PixelLdsPools().end()) return; DestroyPixelFunctionLds(found->second); PixelLdsPools().erase(found); } std::uint64_t DrawRenderPassKey(const Context& context, const State& state, std::span targetViews) { std::uint64_t key = 14695981039346656037ull; const auto mix = [&](std::uint64_t value) { key ^= value; key *= 1099511628211ull; }; for (const auto view : targetViews) mix(reinterpret_cast(view)); if (state.blends.size() != state.colors.size()) { mix(state.blends.size()); for (const auto& color : state.colors) mix(color.exportIndex); } for (const auto& color : state.colors) { if (color.partialWriteMask != 0u) mix(0x6d65726765000000ull | color.exportIndex); } mix(state.renderExtent.width); mix(state.renderExtent.height); mix(state.samples); mix(state.mergedCoverage); mix(state.truncatedCoverage); mix(state.customSampleLocations); if (state.customSampleLocations) { mix(state.sampleLocationGrid); for (const auto location : state.sampleLocations) mix(location); } if (!context.provokingVertexModePerPipeline) mix(state.provokingVertexMode); if (state.rasterizerDiscard) mix(0x6469736361726400ull); return key; } namespace { bool writesStencilTarget(const State& state) { const auto keeps = [](const VkStencilOpState& face) { return face.writeMask == 0u || (face.failOp == VK_STENCIL_OP_KEEP && face.passOp == VK_STENCIL_OP_KEEP && face.depthFailOp == VK_STENCIL_OP_KEEP); }; return state.stencilTest && (!keeps(state.stencilFront) || !keeps(state.stencilBack)); } bool writesDepthTarget(const State& state) { return state.depthWrite || writesStencilTarget(state); } std::optional overwrittenStencil(const State& state) { const auto replaces = [](const VkStencilOpState& face) { return face.compareOp == VK_COMPARE_OP_ALWAYS && face.passOp == VK_STENCIL_OP_REPLACE && face.writeMask == 0xffu; }; if (!state.depthTest || !state.depthWrite || state.depthCompare != VK_COMPARE_OP_ALWAYS || state.depthBoundsTest || !state.stencilTest) return std::nullopt; if (!replaces(state.stencilFront) || !replaces(state.stencilBack) || state.stencilFront.reference != state.stencilBack.reference) return std::nullopt; return static_cast(state.stencilFront.reference); } std::size_t colorKeyCount(const ColorTarget& color, std::size_t bytes) { if (color.mipCount == 1 && color.depth == 1 && color.dccPipeAligned) return DccKeyCount(ColorTextureTileMode(color.tileMode), color.elementBytes, color.extent.width, color.extent.height, bytes); if (color.mipCount > 1 && color.depth == 1 && color.dccPipeAligned && ColorTextureTileMode(color.tileMode) == TextureTileMode::kR64KBX) return DccMipKeySlice(color.extent.width, color.extent.height, color.elementBytes); return DccKeyBytes(bytes); } std::array clearTexel(const ColorTarget& color, DccKeys keys) { std::array texel{}; const auto elementBytes = static_cast(color.elementBytes); Require(elementBytes != 0 && elementBytes <= texel.size(), "unexpected color element size"); if (keys == DccKeys::ClearRegister) { Require(elementBytes <= sizeof(color.clearWords), "the DCC register clear of a texel over 64 bits is not modeled"); std::memcpy(texel.data(), color.clearWords.data(), elementBytes); } else { Require(FillDccClear(color.format, keys, color.dccAlphaOnMsb, std::span(texel.data(), elementBytes)), "the target's format has no encoding of its DCC clear code"); } return texel; } bool clearToTexel(StorageTexture& image, const std::array& texel, std::uint32_t elementBytes, const char*& refusal, bool allowRegisterClear = false) { std::array repeated{}; for (std::size_t offset = 0; offset + elementBytes <= repeated.size(); offset += elementBytes) std::memcpy(repeated.data() + offset, texel.data(), elementBytes); std::array pattern{}; std::memcpy(pattern.data(), repeated.data(), repeated.size()); return image.FillClear(std::span(pattern), StorageTexture::WholeImage, refusal, allowRegisterClear); } void writeTexels(const ColorTarget& color, const std::array& texel) { const auto elementBytes = static_cast(color.elementBytes); std::vector texels(color.bytes); for (std::size_t offset = 0; offset + elementBytes <= texels.size(); offset += elementBytes) std::memcpy(texels.data() + offset, texel.data(), elementBytes); GuestMemory::Write(color.address, texels); } void storeClearTexels(const Context& context, const ColorTarget& color, const std::array& texel) { StorageTexture::FlushPending(color.address, color.bytes, nullptr, "fast-clear materialization"); const auto keys = ReadDccKeys(color.dccAddress, color.bytes); if (!IsDccClear(keys)) return; writeTexels(color, keys == DccKeys::ClearRegister ? texel : clearTexel(color, keys)); MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes)); } void storeSingleTexels(const Context& context, const ColorTarget& color) { Require(!ColorTileModeIsLinear(color.tileMode), "comp-to-single DCC keys of a linear color target"); const ColorTargetLayout surface(color.extent.width, color.extent.height, color.tileMode, color.elementBytes, color.pipeBankXor); Require(surface.Bytes() == color.bytes, "comp-to-single DCC keys over a color target whose layout differs from its surface"); StorageTexture::FlushPending(color.address, color.bytes, nullptr, "comp-to-single expansion"); std::vector texels(color.bytes); GuestMemory::Read(color.address, texels, surface.Alignment()); constexpr std::size_t BlockBytes = 256; for (std::uint32_t y = 0; y < color.extent.height; ++y) { for (std::uint32_t x = 0; x < color.extent.width; ++x) { const auto offset = surface.Offset(x, y); const auto first = offset / BlockBytes * BlockBytes; if (offset != first) std::memcpy(texels.data() + offset, texels.data() + first, color.elementBytes); } } GuestMemory::Write(color.address, texels, surface.Alignment()); MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes)); } void materializeRegisterClear(const Context& context, const ColorTarget& color, StorageTexture& resident) { if (color.dccAddress == 0 || resident.Descriptor().dccAddress != color.dccAddress) return; if (ProvedCurrentDccKeys(color.dccAddress, color.bytes, resident.TargetKeyProof()) != DccKeys::ClearRegister) return; const auto texel = clearTexel(color, DccKeys::ClearRegister); const char* refusal = nullptr; const bool pendingKeysKnown = KnownPendingDccKeys(color.dccAddress, color.bytes) == DccKeys::ClearRegister; bool cleared = clearToTexel(resident, texel, color.elementBytes, refusal, pendingKeysKnown); const auto keyBytes = static_cast(color.bytes / 256); if (!cleared && keyBytes != 0) { if (auto* recorder = Recorder::Active(); recorder != nullptr && recorder->PendingWriteOverlaps(color.dccAddress, keyBytes)) { Recorder::CountSync(2); recorder->SyncThrough(color.dccAddress, keyBytes); if (CurrentDccKeys(color.dccAddress, color.bytes) != DccKeys::ClearRegister) return; cleared = clearToTexel(resident, texel, color.elementBytes, refusal); } } if (cleared) { MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes)); return; } storeClearTexels(context, color, texel); resident.Refresh(); } enum class CmaskState { Expanded, Cleared, Partial }; struct CmaskProof { std::size_t bytes = 0; std::uint64_t generation = 0; }; AgcDriver::Mutex& cmaskProofMutex() { static AgcDriver::Mutex mutex; return mutex; } std::unordered_map& cmaskProofs() { static std::unordered_map proofs; return proofs; } bool cmaskProved(std::uint64_t address, std::size_t bytes) { if (GuestMemory::CollectWrites(address, bytes) == 0) return false; std::lock_guard lock(cmaskProofMutex()); const auto found = cmaskProofs().find(address); return found != cmaskProofs().end() && found->second.bytes == bytes && !GuestMemory::StoredOver(address, bytes, found->second.generation); } void proveCmask(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { std::lock_guard lock(cmaskProofMutex()); if (generation == 0) cmaskProofs().erase(address); else cmaskProofs()[address] = {bytes, generation}; } void requireCmaskCodes(std::uint32_t codes) { Require((codes & 1u) == 0, "a CMASK fast clear of a DCC color target, whose clear belongs in its DCC keys, was recorded"); } CmaskState readCmask(const ColorTarget& color, const CmaskLayout& layout, std::vector& cleared) { const auto address = color.cmaskAddress; const auto bytes = layout.Bytes(); const bool locked = GuestMemory::GpuMutex().HeldByThisThread(); auto* recorder = Recorder::Active(); if (locked && recorder != nullptr && recorder->PendingWriteOverlaps(address, bytes)) { Recorder::CountSync(2); recorder->SyncThrough(address, bytes); } if (AnyShadowedOverlaps(address, bytes)) { Require(locked, "a CMASK under a unit shadow must be read under the device lock"); PublishShadow(address, bytes, PublishScope::Whole, PublishReason::Keys); if (recorder != nullptr) { Recorder::CountSync(2); recorder->Sync(); } } std::vector mask(bytes); GuestMemory::Read(address, mask, CmaskLayout::Alignment); const auto uniform = [&](std::byte value) { return std::all_of(mask.begin(), mask.end(), [&](std::byte entry) { return entry == value; }); }; if (color.coverageSamples > color.samples) { for (std::uint32_t tileY = 0; tileY < layout.TilesY(); ++tileY) { for (std::uint32_t tileX = 0; tileX < layout.TilesX(); ++tileX) { const auto nibble = layout.Nibble(tileX, tileY); const auto code = (std::to_integer(mask[nibble / 2u]) >> ((nibble % 2u) * 4u)) & 0xfu; if (code != 0u && (code >> 2u) != 3u) { char text[128]; std::snprintf(text, sizeof(text), "AGC graphics: CMASK code 0x%x of a one-fragment color target is not implemented", code); throw std::runtime_error(text); } } } } if (uniform(std::byte{0xff})) return CmaskState::Expanded; if (uniform(std::byte{0})) return CmaskState::Cleared; for (std::uint32_t tileY = 0; tileY < layout.TilesY(); ++tileY) { for (std::uint32_t tileX = 0; tileX < layout.TilesX(); ++tileX) { const auto nibble = layout.Nibble(tileX, tileY); const auto code = (std::to_integer(mask[nibble / 2u]) >> ((nibble % 2u) * 4u)) & 0xfu; if (code == 0u) cleared.push_back(tileY * layout.TilesX() + tileX); } } if (cleared.empty()) return CmaskState::Expanded; if (cleared.size() == static_cast(layout.TilesX()) * layout.TilesY()) return CmaskState::Cleared; return CmaskState::Partial; } void storeCmaskClearTexels(const ColorTarget& color, const CmaskLayout& layout, const std::vector* tiles, const std::array& texel) { StorageTexture::FlushPending(color.address, color.bytes, nullptr, "fast-clear materialization"); const ColorTargetLayout surface(color.extent.width, color.extent.height, color.tileMode, color.elementBytes); Require(surface.Bytes() == color.bytes, "CMASK fast clear over a color target whose layout differs from its surface"); std::vector texels(surface.Bytes()); GuestMemory::Read(color.address, texels, surface.Alignment()); const auto fill = [&](std::uint32_t tile) { const auto x0 = (tile % layout.TilesX()) * 8u; const auto y0 = (tile / layout.TilesX()) * 8u; for (auto y = y0; y < std::min(y0 + 8u, color.extent.height); ++y) { for (auto x = x0; x < std::min(x0 + 8u, color.extent.width); ++x) std::memcpy(texels.data() + surface.Offset(x, y), texel.data(), color.elementBytes); } }; if (tiles != nullptr) { for (const auto tile : *tiles) fill(tile); } else { for (std::uint32_t tile = 0; tile < layout.TilesX() * layout.TilesY(); ++tile) fill(tile); } GuestMemory::Write(color.address, texels, surface.Alignment()); } void recordCmaskClear(const Context& context, Recorder& recorder, const HostImport& import, const ColorTarget& color, const CmaskLayout& layout, const std::shared_ptr& resident, VkImageView view) { const auto address = color.cmaskAddress; const auto bytes = layout.Bytes(); StorageTexture::FlushPending(address, bytes, nullptr, "fast-clear materialization"); if (AnyShadowedOverlaps(address, bytes)) PublishShadow(address, bytes, PublishScope::Whole, PublishReason::Keys); recorder.FlushKeyStoresOverlapping(address, bytes); const auto commands = recorder.Commands(); if (resident != nullptr && !resident->Cached()) recorder.KeepBytes(resident.get(), static_cast(resident->BudgetBytes())); recorder.Keep(resident); context.detiler->DispatchCmaskClear(commands, import.buffer, HostImportOffset(import, address), bytes, view, color.extent.width, color.extent.height, color.elementBytes, color.clearWords, color.dccAddress == 0); recorder.NotePendingWrite(address, bytes); proveCmask(address, bytes, GuestMemory::MarkWritten(address, bytes)); } bool materializeCmaskClear(const Context& context, const ColorTarget& color, const std::shared_ptr& resident) { if (color.cmaskAddress == 0) return false; if (context.detiler != nullptr) requireCmaskCodes(context.detiler->CmaskErrors()); const CmaskLayout layout(color.extent.width, color.extent.height); const auto bytes = layout.Bytes(); Require(color.cmaskBytes == bytes, "CMASK size differs from the color target's CMASK layout"); if (cmaskProved(color.cmaskAddress, bytes)) return false; if (color.coverageSamples > color.samples) { std::vector codes; static_cast(readCmask(color, layout, codes)); } auto* recorder = Recorder::Active(); if (resident != nullptr && context.detiler != nullptr && recorder != nullptr && GuestMemory::GpuMutex().HeldByThisThread()) { const auto* import = HostImportFor(context, color.cmaskAddress, bytes); const auto view = import != nullptr ? resident->ElementView() : VK_NULL_HANDLE; if (view != VK_NULL_HANDLE) { recordCmaskClear(context, *recorder, *import, color, layout, resident, view); return true; } } const auto collected = GuestMemory::CollectWrites(color.cmaskAddress, bytes); std::vector cleared; const auto state = readCmask(color, layout, cleared); if (state == CmaskState::Expanded) { proveCmask(color.cmaskAddress, bytes, collected); return false; } Require(color.dccAddress == 0, "CMASK fast clear of a DCC color target, whose clear belongs in its DCC keys"); const auto texel = clearTexel(color, DccKeys::ClearRegister); const char* refusal = nullptr; const bool filled = state == CmaskState::Cleared && color.mipCount == 1 && resident != nullptr && clearToTexel(*resident, texel, color.elementBytes, refusal); if (!filled) { storeCmaskClearTexels(color, layout, state == CmaskState::Cleared ? nullptr : &cleared, texel); if (resident != nullptr) resident->Refresh(); } const std::vector expanded(bytes, std::byte{0xff}); GuestMemory::Write(color.cmaskAddress, expanded, CmaskLayout::Alignment); proveCmask(color.cmaskAddress, bytes, GuestMemory::CollectWrites(color.cmaskAddress, bytes)); return filled; } void imageBarrier(const Context& context, VkCommandBuffer commands, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout, VkPipelineStageFlags sourceStage, VkPipelineStageFlags destinationStage, VkAccessFlags sourceAccess, VkAccessFlags destinationAccess, VkImageSubresourceRange subresources = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}) { VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; barrier.srcAccessMask = sourceAccess; barrier.dstAccessMask = destinationAccess; barrier.oldLayout = oldLayout; barrier.newLayout = newLayout; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = image; barrier.subresourceRange = subresources; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, sourceStage, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &barrier); } void memoryBarrier(const Context& context, VkCommandBuffer commands, VkPipelineStageFlags sourceStage, VkPipelineStageFlags destinationStage, VkAccessFlags sourceAccess, VkAccessFlags destinationAccess) { const VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, sourceAccess, destinationAccess}; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, sourceStage, destinationStage, 0, 1, &barrier, 0, nullptr, 0, nullptr); } // The color surface as one untailed SW_64KB_R_X mip for the GPU detiler, with tightly packed linear rows. TileMipLayout ColorTargetMip(const ColorTarget& color, const ColorTargetLayout& layout) { TileMipLayout mip{}; mip.width = color.extent.width; mip.height = color.extent.height; mip.blocksPerRow = layout.BlocksPerRow(); mip.pitchBytes = color.extent.width * color.elementBytes; mip.tiledSize = layout.Bytes(); mip.linearSize = layout.LinearBytes(); return mip; } // APS5_PROFILE_DRAW: per-draw phase timers in microseconds (a recorded draw's phases are far below // the millisecond the old print rounded to), totalled over 10 s in the [draws] line. enum DrawPhase : std::size_t { PhaseValidate, PhaseVertex, PhaseSetup, PhaseReadTarget, PhasePrepare, PhaseLookup, PhaseResources, PhasePipeline, PhaseRecord, PhaseKeep, PhaseSync, PhaseWriteBack, PhaseDescribe, PhaseCount }; constexpr std::array DrawPhaseNames{"validate", "vertex", "setup", "readTarget", "prepare", "lookup", "resources", "pipeline", "record", "keep", "sync", "writeBack", "describe"}; // Why a draw did not go into the recorder without a wait (counted in the [draws] line): its targets // are not all resident, no recorder is active, a switch (APS5_SYNC_DRAWS, APS5_DUMP_TARGETS, // APS5_SYNC_COMPLETION_DRAWS) forced it, or its completion work writes copied guest buffers or // releases an address-based build's lease, which the CPU must not outrun (see `recorded` in Draw). enum SyncReason : std::size_t { SyncNone, SyncNotResident, SyncNoRecorder, SyncDisabled, SyncCopiedWrites, SyncLease, SyncCount }; constexpr std::array SyncReasonNames{"none", "non-resident target", "no recorder", "disabled", "copied writes", "lease"}; constexpr std::size_t IndirectPathCount = static_cast(IndirectDrawPath::Count); constexpr std::array IndirectDrawPathNames{"gpu-side", "patched SGPR not folded", "fetch offset unknown", "non-vertex path", "GE_INDX_OFFSET", "draw index", "vertex range too large", "feature gap", "pending image results", "pending label or copied write", "not imported", "disabled", "index range not fully readable", "index limit unknown", "records settled"}; // What became of one draw, for the totals. struct DrawOutcome { // In the recorder; `waited` when the recorder was synced right after (copied writes or a lease). bool recorded = false; bool waited = false; bool completion = false; // A recorded draw began a render pass of its own, or continued the previous draw's. bool passBegun = false; bool passContinued = false; PassBreak passBreak = PassBreak::Continued; bool keyStoresFlushed = false; bool storesFlushed = false; bool addressDraw = false; SyncReason reason = SyncNone; // Shader validation memo (see CachedFragmentOutputs). bool validateMemoized = false; bool validateHit = false; // A build that acquired the allocation registry lease (BDA), whose cost sits outside the // build's own sub-phases. bool addressBased = false; // Resident target lookups, and those that took a millisecond or more. Whether a slow one // re-uploaded the image or just walked its pages under contention is not visible from here // (StorageTexture::Version advances on every MarkDirty as well as on an upload, and Generation // is stamped afresh by every write-watch walk): the [texture] line's "reused" and "direct // uploads" counters and APS5_TRACE_UPLOAD name the actual uploads. std::uint64_t targetLookups = 0; std::uint64_t slowLookups = 0; double slowLookupUs = 0; // The lookups by whether the draw's scissor covers the whole target (an area-scoped proof // would change nothing for those), the pages their write-watch collects walked and their time. std::uint64_t fullScissorLookups = 0; std::uint64_t partialLookups = 0; std::uint64_t pagesWalked = 0; double lookupUs = 0; // How the draw's resources came about (DrawKind), for the per-kind averages. std::size_t kind = 0; // The flush hook's fence waits made inside this draw (index and vertex reads, the target // lookups' flushes, the build's texture lookups): nested in the draw's GpuMutex hold, so they // are the part of the hold that is waiting rather than working. The draw's own syncs (a // recorded-then-waited draw's recorder Sync, a synchronous draw's SubmitAndWait) are kept apart // in ownSyncUs: those wait by design and would otherwise count as nested hook waits. double hookWaitUs = 0; double ownSyncUs = 0; }; // The resources of a draw: a recipe hit (reserved for the draw recipe step), a resource-cache // template hit, a build, or an address-based (BDA) build. enum DrawKind : std::size_t { KindRecipeHit, KindTemplateHit, KindBuild, KindBda, KindCount }; constexpr std::array DrawKindNames{"recipe hit", "template hit", "build", "BDA"}; struct DrawProfile { AgcDriver::Mutex mutex; std::array kindUs{}; std::array kindCounts{}; std::uint64_t fullScissorLookups = 0; std::uint64_t partialLookups = 0; std::uint64_t pagesWalked = 0; double lookupUs = 0; std::array totalsUs{}; // The longest single draw's time per phase, and the longest draw: the [lock] line's 'draw' // hold max (tens of ms against an average well under a millisecond) needs a phase name. std::array maxUs{}; double maxDrawUs = 0; double hookWaitUs = 0; double maxHookWaitUs = 0; double ownSyncUs = 0; // The resources build's sub-phases (ShaderResources::Timing) of draws only; dispatches report // theirs in the [resources] line. `other` is the rest of the build (prepareAddressBindings: // the registry lease and snapshots of an address-based build, the BDA table, the layout // lookup), and how much of it address-based builds account for. double bindingsUs = 0; double uploadUs = 0; double descriptorsUs = 0; double otherUs = 0; double addressOtherUs = 0; std::uint64_t addressBuilds = 0; std::uint64_t draws = 0; std::uint64_t recorded = 0; std::uint64_t waited = 0; // Recorded draws whose write-back (BDA fault check) runs as a completion action instead of // making the draw synchronous (see APS5_SYNC_COMPLETION_DRAWS). std::uint64_t completion = 0; // Render passes recorded draws began, and draws that continued the previous draw's pass. std::uint64_t passesBegun = 0; std::uint64_t passesContinued = 0; std::array passTotals{}; std::array passBreaks{}; std::array reportedPassBreaks{}; std::array reasons{}; // The CPU inside Graphics::Draw, split by outcome: a synchronous draw costs ten times a recorded // one, so one average would only show the synchronous population. double recordedUs = 0; double waitedUs = 0; double synchronousUs = 0; std::uint64_t targetLookups = 0; std::uint64_t slowLookups = 0; double slowLookupUs = 0; // Resource cache outcomes: hits, misses (built and inserted when reusable), entries that failed // Revalidate, and draws that could not use the cache (synchronous, no variant id, or disabled). // Which key words the misses differ in is the cache's own "[rescache] miss churn" line // (ResourceCache::noteMiss compares each miss with the last key of the same variants). std::uint64_t cacheHits = 0; std::uint64_t cacheMisses = 0; std::uint64_t cacheInvalidated = 0; std::uint64_t uncacheable = 0; // Shader validation memo (see CachedFragmentOutputs). std::uint64_t validateHits = 0; std::uint64_t validateMisses = 0; // Draw recipe outcomes (DrawWithRecipe): hits, and misses by DrawRecipeMiss. std::uint64_t recipeHits = 0; std::array(DrawRecipeMiss::Count)> recipeMisses{}; // Indirect draws by path (IndirectDrawPath), the GPU-side ones whose records were rewritten // with a constant, and the time of the CPU record reads (their syncs). std::array indirect{}; std::uint64_t indirectRewritten = 0; std::uint64_t indirectEmpty = 0; double indirectReadUs = 0; // Draw packets that drew nothing, by DrawSkip, and their time. std::array(DrawSkip::Count)> skips{}; std::array(DrawSkip::Count)> skipUs{}; AddressDrawReuseCounts addressSeen{}; std::chrono::steady_clock::time_point lastReport = std::chrono::steady_clock::now(); }; constexpr std::array(DrawSkip::Count)> DrawSkipNames{"nothing to draw", "prechecked", "thrown"}; constexpr std::array(AddressDrawReuse::Count)> AddressDrawReuseNames{"reused", "built", "not read-only", "not space-only", "snapshot outside the space (copied)", "partial overlap", "snapshot changed", "moved GuestBuffers element", "patched data word", "space or epoch change", "in use", "revalidation"}; std::array, static_cast(AddressDrawReuse::Count)>& addressDrawReuses() { static std::array, static_cast(AddressDrawReuse::Count)> counts{}; return counts; } void countAddressDrawReuse(AddressDrawReuse outcome) { addressDrawReuses()[static_cast(outcome)].fetch_add(1, std::memory_order_relaxed); } std::atomic& addressDrawReuseVerifications() { static std::atomic verifications{0}; return verifications; } void completeSnapshotWrites(std::span snapshots) { auto* recorder = Recorder::Active(); if (recorder == nullptr || Recorder::InCompletion()) return; for (const auto& snapshot : snapshots) { if (snapshot.bytes.empty() || !recorder->PendingWriteOverlaps(snapshot.address, snapshot.bytes.size())) continue; Recorder::CountSync(4); recorder->SyncThrough(snapshot.address, snapshot.bytes.size()); } } DrawProfile& Profile() { static DrawProfile profile; return profile; } // Adds one draw's phases to the totals and prints the [draws] and [rescache] lines every 10 s. void reportDraw(const std::array& us, const ShaderResources::BuildTiming* built, const DrawOutcome& outcome) { auto& profile = Profile(); std::lock_guard lock(profile.mutex); double drawUs = 0; for (std::size_t i = 0; i < PhaseCount; ++i) { profile.totalsUs[i] += us[i]; profile.maxUs[i] = std::max(profile.maxUs[i], us[i]); drawUs += us[i]; } profile.maxDrawUs = std::max(profile.maxDrawUs, drawUs); profile.hookWaitUs += outcome.hookWaitUs; profile.maxHookWaitUs = std::max(profile.maxHookWaitUs, outcome.hookWaitUs); profile.ownSyncUs += outcome.ownSyncUs; if (built != nullptr) { profile.bindingsUs += built->bindingsMs * 1000.0; profile.uploadUs += built->uploadMs * 1000.0; profile.descriptorsUs += built->descriptorsMs * 1000.0; const auto other = std::max(0.0, us[PhaseResources] - (built->bindingsMs + built->uploadMs + built->descriptorsMs) * 1000.0); profile.otherUs += other; if (outcome.addressBased) { profile.addressOtherUs += other; ++profile.addressBuilds; } } ++profile.draws; if (outcome.recorded) ++(outcome.waited ? profile.waited : profile.recorded); if (outcome.completion) ++profile.completion; if (outcome.passBegun) ++profile.passesBegun; if (outcome.passBegun) ++profile.passBreaks[static_cast(outcome.passBreak)]; if (outcome.passContinued) ++profile.passesContinued; if (outcome.recorded) { auto& totals = profile.passTotals[outcome.addressDraw ? 1 : 0]; ++totals.draws; if (outcome.passBegun) ++totals.passesBegun; if (outcome.passContinued) ++totals.passesContinued; if (outcome.keyStoresFlushed) ++totals.keyStoreFlushes; if (outcome.storesFlushed) ++totals.storeFlushes; } ++profile.reasons[outcome.reason]; (outcome.recorded ? (outcome.waited ? profile.waitedUs : profile.recordedUs) : profile.synchronousUs) += drawUs; profile.targetLookups += outcome.targetLookups; profile.slowLookups += outcome.slowLookups; profile.slowLookupUs += outcome.slowLookupUs; profile.fullScissorLookups += outcome.fullScissorLookups; profile.partialLookups += outcome.partialLookups; profile.pagesWalked += outcome.pagesWalked; profile.lookupUs += outcome.lookupUs; if (outcome.kind < KindCount) { ++profile.kindCounts[outcome.kind]; profile.kindUs[outcome.kind] += drawUs; } if (outcome.validateMemoized) ++(outcome.validateHit ? profile.validateHits : profile.validateMisses); const auto now = std::chrono::steady_clock::now(); if (now - profile.lastReport < std::chrono::seconds(10)) return; profile.lastReport = now; const auto synchronous = profile.draws - profile.recorded - profile.waited; const auto average = [](double total, std::uint64_t count) { return count != 0 ? total / static_cast(count) : 0.0; }; char line[2048]; int n = std::snprintf(line, sizeof(line), "[draws] %llu draws over 10 s (%llu recorded avg %.0f us, of them %llu with completion; %llu recorded then waited avg %.0f us; %llu synchronous avg %.0f us; render passes %llu begun", static_cast(profile.draws), static_cast(profile.recorded), average(profile.recordedUs, profile.recorded), static_cast(profile.completion), static_cast(profile.waited), average(profile.waitedUs, profile.waited), static_cast(synchronous), average(profile.synchronousUs, synchronous), static_cast(profile.passesBegun)); const auto room = [&] { return n > 0 && static_cast(n) < sizeof(line); }; bool listed = false; for (std::size_t i = 1; i < PassBreakCount && room(); ++i) { const auto count = profile.passBreaks[i] - profile.reportedPassBreaks[i]; if (count == 0) continue; n += std::snprintf(line + n, sizeof(line) - static_cast(n), "%s%s %llu", listed ? ", " : " (", PassBreakNames[i], static_cast(count)); listed = true; } if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast(n), "%s, %llu draws continued one; waited or synchronous because:", listed ? ")" : "", static_cast(profile.passesContinued)); for (std::size_t i = SyncNone + 1; i < SyncCount && room(); ++i) { if (profile.reasons[i] != 0) n += std::snprintf(line + n, sizeof(line) - static_cast(n), " %s %llu", SyncReasonNames[i], static_cast(profile.reasons[i])); } if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast(n), "):"); for (std::size_t i = 0; i < PhaseCount && room(); ++i) { if (profile.totalsUs[i] <= 0) continue; n += std::snprintf(line + n, sizeof(line) - static_cast(n), " %s=%.1fms", DrawPhaseNames[i], profile.totalsUs[i] / 1000.0); if (i == PhaseResources && room()) n += std::snprintf(line + n, sizeof(line) - static_cast(n), " (bindings %.1f, upload %.1f, descriptors %.1f, other %.1f of which %.1f in %llu address-based builds)", profile.bindingsUs / 1000.0, profile.uploadUs / 1000.0, profile.descriptorsUs / 1000.0, profile.otherUs / 1000.0, profile.addressOtherUs / 1000.0, static_cast(profile.addressBuilds)); if (i == PhaseReadTarget && room()) n += std::snprintf(line + n, sizeof(line) - static_cast(n), " (%llu resident lookups, %llu of them >= 1 ms = %.1f; target lookups: full-scissor %llu / partial %llu / pages walked %llu / %.0f us)", static_cast(profile.targetLookups), static_cast(profile.slowLookups), profile.slowLookupUs / 1000.0, static_cast(profile.fullScissorLookups), static_cast(profile.partialLookups), static_cast(profile.pagesWalked), profile.lookupUs); } if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast(n), "; per kind (avg us, count):"); for (std::size_t kind = 0; kind < KindCount && room(); ++kind) { n += std::snprintf(line + n, sizeof(line) - static_cast(n), " %s %.0f (%llu)", DrawKindNames[kind], average(profile.kindUs[kind], profile.kindCounts[kind]), static_cast(profile.kindCounts[kind])); } // The longest draw and the longest single phase of any draw (which phase a long 'draw' hold // was), plus the hook waits nested inside the draws. if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast(n), "; longest draw %.1f ms, longest phase of any draw:", profile.maxDrawUs / 1000.0); for (std::size_t i = 0; i < PhaseCount && room(); ++i) { if (profile.maxUs[i] < 500.0) continue; n += std::snprintf(line + n, sizeof(line) - static_cast(n), " %s %.1f", DrawPhaseNames[i], profile.maxUs[i] / 1000.0); } if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast(n), "; hook waits inside draws %.1f ms (max %.1f; the draws' own syncs, %.1f ms, not counted)", profile.hookWaitUs / 1000.0, profile.maxHookWaitUs / 1000.0, profile.ownSyncUs / 1000.0); std::uint64_t indirectCpu = 0; for (std::size_t i = 1; i < IndirectPathCount; ++i) indirectCpu += profile.indirect[i]; if ((profile.indirect[0] != 0 || indirectCpu != 0 || profile.indirectEmpty != 0) && room()) { n += std::snprintf(line + n, sizeof(line) - static_cast(n), "; indirect: gpu-side %llu (%llu rewritten), cpu-side %llu (", static_cast(profile.indirect[0]), static_cast(profile.indirectRewritten), static_cast(indirectCpu)); for (std::size_t i = 1; i < IndirectPathCount && room(); ++i) { if (profile.indirect[i] != 0) n += std::snprintf(line + n, sizeof(line) - static_cast(n), " %s %llu", IndirectDrawPathNames[i], static_cast(profile.indirect[i])); } if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast(n), "), empty skipped before their stages %llu, argument reads %.1f ms", static_cast(profile.indirectEmpty), profile.indirectReadUs / 1000.0); } if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast(n), "; skipped packets:"); for (std::size_t i = 0; i < profile.skips.size() && room(); ++i) { n += std::snprintf(line + n, sizeof(line) - static_cast(n), " %s %llu in %.1f ms", DrawSkipNames[i], static_cast(profile.skips[i]), profile.skipUs[i] / 1000.0); } if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast(n), "; recipe hits %llu, misses by reason:", static_cast(profile.recipeHits)); for (std::size_t i = 1; i < profile.recipeMisses.size() && room(); ++i) { n += std::snprintf(line + n, sizeof(line) - static_cast(n), " %s %llu", DrawRecipeMissName(static_cast(i)), static_cast(profile.recipeMisses[i])); } AgcDriver::ProfilePrint_nid_no_patch("%s\n", line); AgcDriver::ProfilePrint_nid_no_patch("[rescache] draws: %llu hits, %llu misses, %llu invalidated, %llu uncacheable; validation memo %llu hits / %llu misses (which key words the misses differ in: the miss churn line)\n", static_cast(profile.cacheHits), static_cast(profile.cacheMisses), static_cast(profile.cacheInvalidated), static_cast(profile.uncacheable), static_cast(profile.validateHits), static_cast(profile.validateMisses)); const auto address = AddressDrawReuseCounters(); if (address != profile.addressSeen) { char reuse[512]; const auto seen = [&](AddressDrawReuse outcome) { return static_cast(address[static_cast(outcome)] - profile.addressSeen[static_cast(outcome)]); }; int at = std::snprintf(reuse, sizeof(reuse), "[rescache] address-based draws (10 s): reused %llu, built %llu; refused:", seen(AddressDrawReuse::Reused), seen(AddressDrawReuse::Built)); for (auto outcome = static_cast(AddressDrawReuse::NotReadOnly); outcome < address.size() && at > 0 && static_cast(at) < sizeof(reuse); ++outcome) { at += std::snprintf(reuse + at, sizeof(reuse) - static_cast(at), "%s %s %llu", outcome == static_cast(AddressDrawReuse::NotReadOnly) ? "" : ",", AddressDrawReuseNames[outcome], seen(static_cast(outcome))); } AgcDriver::ProfilePrint_nid_no_patch("%s\n", reuse); profile.addressSeen = address; } profile.totalsUs.fill(0); profile.maxUs.fill(0); profile.maxDrawUs = profile.hookWaitUs = profile.maxHookWaitUs = profile.ownSyncUs = 0; profile.bindingsUs = profile.uploadUs = profile.descriptorsUs = profile.otherUs = profile.addressOtherUs = 0; profile.addressBuilds = 0; profile.draws = profile.recorded = profile.waited = profile.completion = 0; profile.passesBegun = profile.passesContinued = 0; profile.reportedPassBreaks = profile.passBreaks; profile.reasons.fill(0); profile.recordedUs = profile.waitedUs = profile.synchronousUs = 0; profile.targetLookups = profile.slowLookups = 0; profile.slowLookupUs = 0; profile.fullScissorLookups = profile.partialLookups = profile.pagesWalked = 0; profile.lookupUs = 0; profile.kindUs.fill(0); profile.kindCounts.fill(0); profile.cacheHits = profile.cacheMisses = profile.cacheInvalidated = profile.uncacheable = 0; profile.validateHits = profile.validateMisses = 0; profile.recipeHits = 0; profile.recipeMisses.fill(0); profile.indirect.fill(0); profile.indirectRewritten = 0; profile.indirectReadUs = 0; profile.skips.fill(0); profile.skipUs.fill(0); } void countCache(std::uint64_t DrawProfile::*counter) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; if (!profile) return; auto& stats = Profile(); std::lock_guard lock(stats.mutex); ++(stats.*counter); } } // ValidateShaders decodes every SPIR-V instruction of every stage on every draw. Its outcome depends // only on the stages' compiled variants (a variant id names identical SPIR-V and binding layout), // their push constant placement and vertex attribute shapes, and the state fields it checks, so the // fragment output set is remembered by exactly those. Nothing here is keyed by pointer: the results // a draw hands in live in a per-draw vector. A stage without a variant id is validated as before, // except the rect-list control and evaluation stages, which are generated from the vertex and // fragment results the key already names (the pipeline key treats them the same way). `memoized` // says whether the memo applied, `hit` whether it answered. APS5_NO_VALIDATE_CACHE=1 validates // every draw. bool ValidationKey(const Context& context, std::span shaders, const State& state, std::vector& key) { using Stage = ShaderRecompiler::ShaderStage; static const bool disabled = std::getenv("APS5_NO_VALIDATE_CACHE") != nullptr; const auto add = [&](auto value) { key.push_back(static_cast(value)); }; bool keyed = !disabled; if (keyed) { key.reserve(40 + shaders.size() * 12); add(shaders.size()); const bool patches = BarycentricPatches(state, shaders); add(patches ? static_cast(state.provokingVertexMode) + 1u : 0u); for (const auto& shader : shaders) { Require(shader.program != nullptr, "missing compiled shader"); const auto& program = *shader.program; const bool generated = ((state.rectList || patches) && (shader.stage == Stage::TessellationControl || shader.stage == Stage::TessellationEvaluation)) || shader.stage == Stage::Geometry; if (!generated && program.PipelineVariantId() == 0) { keyed = false; break; } add(shader.stage); add(generated ? std::uint64_t{0} : program.PipelineVariantId()); add(KeyedPushOffset(shader)); add(program.pushConstants.size()); add(program.bdaAbiVersion); add(program.vertexAttributes.size()); for (const auto& attribute : program.vertexAttributes) { add(attribute.location); add(attribute.components); add(attribute.fetchIndex); add(attribute.formatComponents); // The data format bits of the V# decide the attribute's signature. add((attribute.resource.fields[3] >> 12u) & 0x7fu); } } } if (keyed) { add(state.stages.path); add(state.rectList); add(state.topology); add(state.cullMode); add(state.polygonMode); add(state.lineWidth); add(state.blends.size()); add(context.subgroup.subgroupSize); add(context.subgroup.supportedStages); add(context.subgroup.supportedOperations); add(context.fragmentShaderBarycentric); add(context.shaderClipDistance); add(context.shaderCullDistance); add(context.viewportIndexLayer); add(context.shaderTerminateInvocation); add(state.paClVsOutCntl); add(state.vertexPoints); add(state.stages.mesh.has_value()); if (state.stages.mesh) { const auto& mesh = *state.stages.mesh; add(mesh.inputPrimitive); add(mesh.primitivesPerGroup); add(mesh.verticesPerGroup); add(mesh.maxVertices); add(mesh.maxPrimitives); add(mesh.threadsPerGroup); add(mesh.ldsSizeDwords); add(mesh.provokingVertex); add(mesh.outputPrimitiveSize); } add(state.stages.tessellation.has_value()); if (state.stages.tessellation) { const auto& tessellation = *state.stages.tessellation; add(tessellation.inputControlPoints); add(tessellation.outputControlPoints); add(tessellation.domain); add(tessellation.partitioning); add(tessellation.outputTopology); add(tessellation.patchesPerGroup); add(tessellation.primitiveGroupSize); add(tessellation.breakAtInstance ? 1u : 0u); } } return keyed; } namespace { AgcDriver::Mutex& validationMutex() { static AgcDriver::Mutex mutex; return mutex; } std::map, std::string>& validationFailures() { static std::map, std::string> failures; return failures; } std::vector& validationKeyScratch() { thread_local std::vector* keySlot = nullptr; auto& key = ShaderRecompiler::ThreadOwned(keySlot); key.clear(); return key; } struct LastFragmentOutputs { std::vector key; std::uint32_t outputs = 0; bool valid = false; FragmentOutputLookups lookups; }; struct LastFragmentOutputsTag {}; bool LastFragmentOutputsEnabled() { static const bool enabled = std::getenv("APS5_NO_LAST_FRAGMENT_OUTPUTS") == nullptr; return enabled; } std::uint32_t CachedFragmentOutputs(const Context& context, std::span shaders, const State& state, bool& memoized, bool& hit) { memoized = false; hit = false; auto& key = validationKeyScratch(); const bool keyed = ValidationKey(context, shaders, state, key); static std::map, std::uint32_t> memo; auto& last = ThreadScratch(); const bool remembers = keyed && LastFragmentOutputsEnabled(); if (remembers && last.valid && key == last.key) { memoized = true; hit = true; ++last.lookups.last; return last.outputs; } const auto remember = [&](std::uint32_t outputs) { if (!remembers) return; last.key = key; last.outputs = outputs; last.valid = true; }; if (keyed) { memoized = true; std::optional found; { std::lock_guard lock(validationMutex()); if (const auto entry = memo.find(key); entry != memo.end()) found = entry->second; } if (found) { hit = true; ++last.lookups.memo; remember(*found); return *found; } } ++last.lookups.validated; std::uint32_t outputs = 0; try { for (const auto location : ValidateShaders(shaders, state, context.subgroup, context.fragmentShaderBarycentric, context.descriptorIndexing, context.imageInt64Atomics, context.geometryShader, context.sampleRateShading, context.bufferInt64Atomics, context.shaderClipDistance, context.shaderCullDistance, context.viewportIndexLayer, context.runtimeDescriptorArray, context.demoteToHelperInvocation, context.shaderTerminateInvocation, context.meshShader, context.shaderResourceMinLod, context.fmaFloat16)) { Require(location < 32, "fragment output location exceeds the output mask"); outputs |= 1u << location; } } catch (const std::exception& error) { if (keyed) { std::lock_guard lock(validationMutex()); auto& failures = validationFailures(); if (failures.size() >= 1024) failures.clear(); failures.emplace(key, error.what()); } throw; } if (keyed) { std::lock_guard lock(validationMutex()); // A handful of configurations recur; a runaway key space is dropped wholesale. if (memo.size() >= 1024) memo.clear(); memo.emplace(key, outputs); } remember(outputs); return outputs; } // The resource cache key of a recorded draw: a marker no compute key starts with (those begin with // the stage), the device handle (the cache is process-wide and the driver replaces the headless // device with the windowed one while workers may still use the old one: an entry's descriptor set // and pooled buffers belong to the device that built it) and every stage's content key // (ResourceCache::noteMiss walks this layout to attribute misses, so it changes together with it). // With `ranges`, also the render target and the index buffer the build's alias checks compared the // guest buffers against; without it the checks are repeated for a hit (CheckBufferAliases), since // neither range is part of the descriptor set (the target is attached, the index buffer copied per // draw), so a target or index ring that moves per frame does not miss on every draw. That guards a // workload with such rings; in the profiled menu stage every draw was DRAW_INDEX_AUTO (index range // 0) onto one fixed target, so its misses come from the stages' descriptor words themselves. bool MovableBuffers() { static const bool enabled = std::getenv("APS5_NO_MOVED_BUFFER_TEMPLATES") == nullptr; return enabled; } ResourceCache::Key DrawResourceKey(const Context& context, std::span shaders, const ColorTarget& target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::uint64_t indexBytes, bool ranges) { ResourceCache::Key key; key.reserve(256); key.push_back(0xffffffffu); const auto append64 = [&](std::uint64_t value) { key.push_back(static_cast(value)); key.push_back(static_cast(value >> 32u)); }; append64(reinterpret_cast(context.device)); key.push_back(static_cast(shaders.size())); for (const auto& shader : shaders) { const auto sizeAt = key.size(); key.push_back(0u); auto& memo = shader.program->drawKeyMemo.words; if (auto words = memo.load(std::memory_order_acquire); words != nullptr) { key.insert(key.end(), words->begin(), words->end()); } else { ShaderResources::AppendContentKey(shader, true, MovableBuffers(), key); memo.store(std::make_shared>(key.begin() + static_cast(sizeAt + 1u), key.end()), std::memory_order_release); } key[sizeAt] = static_cast(key.size() - sizeAt - 1u); } key.push_back(colorAttachments); if (ranges) { append64(target.address | target.pipeBankXor); append64(target.bytes); append64(indexAddress); append64(indexBytes); } return key; } // The alias checks the build makes for every guest buffer descriptor (ShaderResources:: // addGuestBuffer), repeated for a cached build whose own checks compared the buffers against // another draw's render target and index buffer. The same conditions and messages, so a draw that // would have failed its build fails its hit. void CheckBufferAliases(std::span shaders, const ColorTarget& target, std::uint64_t indexAddress, std::uint64_t indexBytes) { const auto overlap = [](std::uint64_t first, std::uint64_t firstSize, std::uint64_t second, std::uint64_t secondSize) { return first < second + secondSize && second < first + firstSize; }; const auto targetAddress = target.MemoryAddress(); for (const auto& shader : shaders) { for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; const auto& words = binding.guestDescriptor; for (std::size_t offset = 0; offset + 4 <= words.size(); offset += 4) { const ShaderRecompiler::ShaderBufferResource descriptor{{words[offset], words[offset + 1], words[offset + 2], words[offset + 3]}}; const auto address = descriptor.Base48(); auto size = descriptor.GetSize(); if (size == 0 || address == 0) continue; const auto element = offset / 4; const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; if (!written) size = ShaderResources::BytesUpToTarget(address, size, descriptor.Stride(), &target); Require(!overlap(address, size, targetAddress, target.bytes), "shader buffer aliases the render target"); Require(!written || !overlap(address, size, indexAddress, indexBytes), "writable shader buffer aliases the index buffer"); } } } } } std::array MeshIndexBufferDescriptor(const Pm4::DrawParameters& draw) { constexpr std::uint32_t RawWord3 = 0x31016facu; if (!draw.indexed) return {0u, 0u, 0u, RawWord3}; const auto address = draw.indexAddress; const auto bytes = (static_cast(draw.indexCount) * draw.indexSize + 3u) & ~std::uint64_t{3}; Require(address != 0 && bytes != 0 && bytes <= 0xffffffffu && (address >> 48u) == 0, "invalid mesh index buffer range"); return {static_cast(address), static_cast(address >> 32u) & 0xffffu, static_cast(bytes), RawWord3}; } MeshArgumentRules MeshArgumentRulesFor(const Context& context, const ShaderRecompiler::MeshConfiguration& mesh, std::uint32_t indexCount) { const auto inputSize = mesh.inputPrimitive == 1 ? 1u : mesh.inputPrimitive == 2 ? 2u : 3u; const auto step = mesh.inputPrimitive == 5 || mesh.inputPrimitive == 6 ? 1u : inputSize; Require(mesh.primitivesPerGroup != 0, "mesh pipeline groups no primitive (zero primitives per group)"); return {indexCount, inputSize, step, mesh.primitivesPerGroup, context.meshLimits.maxMeshWorkGroupCount[0], context.meshLimits.maxMeshWorkGroupCount[1], context.meshLimits.maxMeshWorkGroupTotalCount, 0u}; } MeshArgumentRules MeshArgumentRulesFor(const Context& context, const ShaderRecompiler::MeshConfiguration& mesh, const Pm4::DrawParameters& draw) { if (draw.indexed) return MeshArgumentRulesFor(context, mesh, draw.indexCount); auto rules = MeshArgumentRulesFor(context, mesh, std::numeric_limits::max()); rules.firstIgnored = 1u; return rules; } std::optional MeshGridFor(const Context& context, std::uint32_t groups, std::uint32_t instances) { const auto& limits = context.meshLimits; if (groups == 0 || instances > limits.maxMeshWorkGroupCount[1] || limits.maxMeshWorkGroupCount[0] == 0) return std::nullopt; const auto across = groups <= limits.maxMeshWorkGroupCount[0] ? groups : std::min(limits.maxMeshWorkGroupCount[0], ShaderRecompiler::MeshLayerStrideLimit); const auto layers = (groups - 1u) / across + 1u; const auto columns = (groups - 1u) / layers + 1u; if (layers > limits.maxMeshWorkGroupCount[2] || (instances != 0 && columns > limits.maxMeshWorkGroupTotalCount / instances / layers)) return std::nullopt; return MeshGrid{columns, instances, layers, layers > 1u ? columns : 0u}; } MeshArguments ResolveMeshArguments(const Pm4::DrawArguments& record, const MeshArgumentRules& rules) { const auto first = rules.firstIgnored != 0u ? 0u : record.firstVertexOrIndex; const auto effective = first < rules.indexCount ? std::min(record.count, rules.indexCount - first) : 0u; std::uint32_t groups = 0; if (effective >= rules.inputSize && record.instances != 0) { groups = (effective - rules.inputSize) / rules.step / rules.primitivesPerGroup + 1u; if (groups > rules.maxGroups || record.instances > rules.maxInstances || groups > rules.maxTotal / record.instances) groups = 0; } return {groups, groups != 0 ? record.instances : 0u, groups != 0 ? 1u : 0u, effective, first}; } std::shared_ptr>> DrawCopiedWriters() { // Never destroyed: a completion action of a batch still in flight at static teardown may erase from it. static auto* const writers = new std::shared_ptr>>(std::make_shared>>()); return *writers; } const char* IndirectDrawPathName(IndirectDrawPath path) { return IndirectDrawPathNames[static_cast(path)]; } void CountIndirectDraw(IndirectDrawPath path, double readMs, bool rewritten) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; if (!profile) return; auto& stats = Profile(); std::lock_guard lock(stats.mutex); ++stats.indirect[static_cast(path)]; if (rewritten) ++stats.indirectRewritten; stats.indirectReadUs += readMs * 1000.0; } static void CountIndirectDraw(std::optional path, double readMs, bool rewritten = false) { if (path) AgcDriver::Graphics::CountIndirectDraw(*path, readMs, rewritten); } std::array IndirectDrawCounts() { auto& stats = Profile(); std::lock_guard lock(stats.mutex); return stats.indirect; } void CountEmptyIndirectDraw(double readMs) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; if (!profile) return; auto& stats = Profile(); std::lock_guard lock(stats.mutex); ++stats.indirectEmpty; stats.indirectReadUs += readMs * 1000.0; } std::uint64_t EmptyIndirectDrawCount() { auto& stats = Profile(); std::lock_guard lock(stats.mutex); return stats.indirectEmpty; } std::array DrawPassTotals() { auto& stats = Profile(); std::lock_guard lock(stats.mutex); return stats.passTotals; } std::array DrawPassBreaks() { auto& stats = Profile(); std::lock_guard lock(stats.mutex); return stats.passBreaks; } void CountDrawSkip(DrawSkip kind, double us) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; if (!profile) return; auto& stats = Profile(); std::lock_guard lock(stats.mutex); ++stats.skips[static_cast(kind)]; stats.skipUs[static_cast(kind)] += us; } bool DrawRecipes() { static const bool noDrawRecipe = std::getenv("APS5_NO_DRAW_RECIPE") != nullptr; return !noDrawRecipe; } const char* DrawRecipeMissName(DrawRecipeMiss miss) { constexpr std::array(DrawRecipeMiss::Count)> names{"none", "not recordable", "target gone", "template gone", "objects gone", "proof", "buffers"}; return names[static_cast(miss)]; } namespace { // APS5_PROFILE_DRAW: the per-phase timers of one draw (DrawPhase), shared by Draw's parts and // DrawWithRecipe. struct DrawTimer { bool profile; std::chrono::steady_clock::time_point phaseStart; std::array us{}; explicit DrawTimer(bool profile) : profile(profile), phaseStart(profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}) {} void phase(DrawPhase which) { if (!profile) return; const auto now = std::chrono::steady_clock::now(); us[which] += std::chrono::duration(now - phaseStart).count(); phaseStart = now; } void charge(DrawPhase which, std::chrono::steady_clock::time_point start) { if (!profile) return; const auto now = std::chrono::steady_clock::now(); us[which] += std::chrono::duration(now - start).count(); phaseStart += now - start; } }; // One line per draw with the phases that took time (APS5_TRACE_DRAWS), and the 10 s totals. // `waitedBefore` is the thread's GPU waits at the draw's start and `ownWaitedMs` the draw's own // syncs (see DrawOutcome::hookWaitUs). void reportDrawEnd(const State& state, const DrawTimer& timer, const ShaderResources::BuildTiming* built, DrawOutcome& outcome, double waitedBefore, double ownWaitedMs, const char* suffix) { if (!timer.profile) return; static const bool traceDraws = std::getenv("APS5_TRACE_DRAWS") != nullptr; outcome.hookWaitUs = std::max(0.0, Recorder::ThreadWaitedMs() - waitedBefore - ownWaitedMs) * 1000.0; outcome.ownSyncUs = ownWaitedMs * 1000.0; if (traceDraws) { char line[512]; int n = std::snprintf(line, sizeof(line), "[draw] %ux%u %zu targets%s:", state.renderExtent.width, state.renderExtent.height, state.colors.size(), suffix); for (std::size_t i = 0; i < PhaseCount && n > 0 && static_cast(n) < sizeof(line); ++i) { if (timer.us[i] <= 0) continue; n += std::snprintf(line + n, sizeof(line) - static_cast(n), " %s=%.0fus", DrawPhaseNames[i], timer.us[i]); } std::fprintf(stderr, "%s\n", line); } reportDraw(timer.us, built, outcome); } bool vertexCopyTailReadable(const Recorder& recorder, std::uint64_t address, std::size_t bytes, std::size_t grown) { const auto tail = address + bytes; const auto extra = grown - bytes; if (!GuestMemory::Accessible(reinterpret_cast(address), grown) || recorder.GuestWritesPendingIn(tail, extra)) return false; const std::array, 1> range{{{tail, tail + extra}}}; if (StorageTexture::AnyPendingOverlaps(range) || AnyShadowedOverlaps(range) || ResidentDepthGuardOverlaps_nid_no_patch(tail, extra)) return false; return HostOnlySampleRanges(tail, extra).empty(); } } std::size_t GrownVertexCopyBytes(std::size_t bytes, std::size_t growLimit) { if (growLimit <= bytes) return bytes; const auto grown = bytes + std::min(bytes / 4u, growLimit - bytes); return grown <= Recorder::DrawInputBudget ? grown : bytes; } std::uint64_t VertexCopyGrowEnd(const State& state, std::uint64_t end, std::uint64_t limit) { limit = std::max(limit, end); const auto cut = [&](std::uint64_t target) { if (target >= end && target < limit) limit = target; }; if (state.hasColorTarget) cut(state.color.MemoryAddress()); for (const auto& color : state.colors) cut(color.MemoryAddress()); if (state.depth) { cut(state.depth->address); cut(state.depth->stencilAddress); cut(state.depth->htileAddress); } return limit; } bool BindsIndexCopy(const State& state) { return !state.stages.mesh; } DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uint64_t address, std::size_t bytes, std::size_t alignment, Recorder::SnapshotUse use, std::size_t from, bool hostOnly, std::size_t growLimit) { Require(use != Recorder::SnapshotUse::Storage, "a draw input is a vertex or index buffer"); Require(from == 0 || (use == Recorder::SnapshotUse::Vertex && from < bytes), "only a vertex input starts past its address"); DrawInputCopy copy; copy.from = from; std::size_t copied = bytes; if (recorder != nullptr && bytes != 0) { GuestMemory::FlushGpuWrites(address, bytes); #ifdef _WIN32 const bool owned = !RuntimeSwitches::Set(RuntimeSwitch::NoOwnedDrawInputs); #else constexpr bool owned = false; #endif if (owned && recorder->OwnedDrawInputEntries() != 0) copy.buffer = recorder->ReusableOwnedDrawInput(address, bytes, use, ©.derived, from, ©.lowest); if (copy.buffer != nullptr) { copy.reused = true; return copy; } copy.registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); copy.generation = GuestMemory::CollectWrites(address, bytes); if (copy.generation != 0) copy.buffer = recorder->ReusableDrawSnapshot(address, bytes, use, ©.derived, 0, nullptr, from, ©.lowest, !hostOnly); else if (owned) copy.owned = recorder->ArmOwnedDrawInput(address, bytes); if (copy.buffer != nullptr) { copy.reused = true; return copy; } if (const auto grown = GrownVertexCopyBytes(bytes, growLimit); copy.generation != 0 && use == Recorder::SnapshotUse::Vertex && grown > bytes && recorder->ShorterDrawSnapshotKept(address, bytes, use) && vertexCopyTailReadable(*recorder, address, bytes, grown)) { if (const auto generation = GuestMemory::CollectWrites(address, grown); generation != 0) { copy.generation = generation; copied = grown; } } } copy.buffer = std::make_shared(context, copied, (use == Recorder::SnapshotUse::Vertex ? VK_BUFFER_USAGE_VERTEX_BUFFER_BIT : VK_BUFFER_USAGE_INDEX_BUFFER_BIT) | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); static const bool poisonPrefix = std::getenv("APS5_POISON_VERTEX_PREFIX") != nullptr; const auto held = copy.buffer->Bytes(); if (poisonPrefix) std::fill(held.begin(), held.begin() + static_cast(from), std::byte{0x7f}); GuestMemory::Read(address + from, held.subspan(from, bytes - from), alignment); if (copied > bytes) GuestMemory::CopyGuestBytes(held.data() + bytes, reinterpret_cast(address + bytes), copied - bytes); return copy; } DrawInputCopy CopyZeroPaddedDrawInput(const Context& context, std::uint64_t address, std::size_t bytes, std::size_t validBytes, std::size_t stride) { Require(validBytes <= bytes, "the valid bytes of a vertex fetch exceed the fetch"); auto readable = validBytes; if (stride != 0 && !GuestMemory::Accessible(reinterpret_cast(address), validBytes)) { const auto ranges = GuestMemory::CommittedRanges(address, validBytes); const std::size_t prefix = !ranges.empty() && ranges.front().first == address ? static_cast(ranges.front().second - address) : 0; if (validBytes - prefix < stride) readable = prefix; } if (readable != 0) GuestMemory::FlushGpuWrites(address, readable); DrawInputCopy copy; auto* recorder = context.recorder; const bool keep = recorder != nullptr && readable != 0 && readable <= std::numeric_limits::max(); if (keep) { copy.registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); copy.generation = GuestMemory::CollectWrites(address, readable); std::uint32_t keptReadable = 0; if (copy.generation != 0) copy.buffer = recorder->ReusableDrawSnapshot(address, bytes, Recorder::SnapshotUse::PaddedVertex, &keptReadable); if (copy.buffer != nullptr && keptReadable == readable) { copy.reused = true; return copy; } copy.buffer = nullptr; } copy.buffer = std::make_shared(context, bytes, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); const auto span = copy.buffer->Bytes(); GuestMemory::Read(address, span.subspan(0, readable), 1); std::fill(span.begin() + static_cast(readable), span.end(), std::byte{0}); if (keep) recorder->KeepDrawSnapshot(address, bytes, copy.generation, copy.registryGeneration, copy.buffer, Recorder::SnapshotUse::PaddedVertex, static_cast(readable)); return copy; } void KeepDrawInput(Recorder* recorder, std::uint64_t address, const DrawInputCopy& copy, Recorder::SnapshotUse use, std::uint32_t derived, std::uint32_t lowest) { if (recorder == nullptr || copy.reused || copy.buffer == nullptr) return; if (copy.generation == 0) { if (!copy.owned.words.empty() && !RuntimeSwitches::Set(RuntimeSwitch::NoOwnedDrawInputs)) recorder->KeepOwnedDrawInput(address, copy.buffer->Bytes().size(), copy.owned, copy.buffer, use, derived, copy.from, lowest); return; } recorder->KeepDrawSnapshot(address, copy.buffer->Bytes().size(), copy.generation, copy.registryGeneration, copy.buffer, use, derived, copy.from, lowest); } const HostImport* InPlaceDrawInput(const Context& context, std::uint64_t address, std::size_t bytes, std::size_t alignment, bool* behindGpuWrite, std::size_t fetched, std::uint64_t reads) { auto* recorder = context.recorder; static const bool copyBehindGpuWrite = std::getenv("APS5_NO_BEHIND_INPUTS_IN_PLACE") != nullptr || std::getenv("APS5_NO_DRAW_INPUTS_IN_PLACE") != nullptr; const bool small = std::min(fetched, bytes) <= context.drawInputsInPlaceBelow && reads <= InPlaceDrawInputMaxReads; static const std::size_t largeInput = [] { const char* value = std::getenv("APS5_LARGE_INPUT_IN_PLACE_MIB"); return static_cast(value != nullptr ? std::strtoull(value, nullptr, 10) : 8u) << 20u; }(); const bool large = behindGpuWrite != nullptr && largeInput != 0 && bytes >= largeInput; if (recorder == nullptr || bytes == 0 || (!context.drawInputsInPlace && !small && !large && (behindGpuWrite == nullptr || copyBehindGpuWrite))) return nullptr; bool behind = false; if (behindGpuWrite == nullptr) { GuestMemory::FlushGpuWrites(address, bytes); if (recorder->PendingWriteOverlaps(address, bytes)) return nullptr; } else { StorageTexture::FlushPending(address, bytes, nullptr, "in-place vertex input"); behind = recorder->PendingWriteOverlaps(address, bytes); if (!behind && !context.drawInputsInPlace && !small && !large) return nullptr; } if (recorder->PendingLabelIn(address, bytes) || recorder->QueuedStoreOverlaps(address, bytes)) return nullptr; const auto overlaps = [&](const auto& writer) { return writer->WritesOverlap(address, bytes); }; if (context.copiedWriters != nullptr && std::any_of(context.copiedWriters->begin(), context.copiedWriters->end(), overlaps)) return nullptr; const auto drawWriters = DrawCopiedWriters(); if (std::any_of(drawWriters->begin(), drawWriters->end(), overlaps)) return nullptr; const auto* import = HostImportFor(context, address, bytes); if (import == nullptr || HostImportOffset(*import, address) % alignment != 0) return nullptr; recorder->NotePendingRead(address, bytes, Recorder::ReadKind::DrawInput); if (behindGpuWrite != nullptr && behind) *behindGpuWrite = true; return import; } namespace { constexpr std::array(IndexBehindWriter::Count)> IndexBehindWriterNames{ "taken", "off", "no writer", "index limit", "mesh stage", "primitive restart", "vertex offset", "unit shadow", "pending storage", "label or store", "copied writer", "no import", "refused" }; std::array(IndexBehindWriter::Count)>& indexBehindWriterEvents() { static std::array(IndexBehindWriter::Count)> events; return events; } const bool indexBehindWriterProfiled = std::getenv("APS5_PROFILE_DRAW") != nullptr; void reportIndexBehindWriter() { using Clock = std::chrono::steady_clock; static std::atomic reported{Clock::now().time_since_epoch().count()}; static std::array(IndexBehindWriter::Count)> previous{}; const auto now = Clock::now().time_since_epoch().count(); auto last = reported.load(std::memory_order_relaxed); if (Clock::duration(now - last) < std::chrono::seconds(10) || !reported.compare_exchange_strong(last, now, std::memory_order_relaxed)) return; std::string line; for (std::size_t index = 0; index < previous.size(); ++index) { const auto total = indexBehindWriterEvents()[index].Sum(); const auto count = total - previous[index]; previous[index] = total; if (count == 0) continue; line += (line.empty() ? " " : ", ") + std::string(IndexBehindWriterNames[index]) + " " + std::to_string(count); } AgcDriver::ProfilePrint_nid_no_patch("[index-behind-writer] (10 s, all threads, index ranges behind a pending GPU writer):%s\n", line.empty() ? " none" : line.c_str()); } } std::array(IndexBehindWriter::Count)> IndexBehindWriterCounts() { std::array(IndexBehindWriter::Count)> counts{}; for (std::size_t index = 0; index < counts.size(); ++index) counts[index] = indexBehindWriterEvents()[index].Sum(); return counts; } const HostImport* InPlaceIndexBehindWriter(const Context& context, std::uint64_t address, std::size_t bytes, std::uint32_t indexSize, bool meshStage, bool primitiveRestart, std::uint32_t firstVertex, IndexBehindWriter* outcome) { const bool enabled = RuntimeSwitches::Set(RuntimeSwitch::IndexInPlaceBehindWriter); const auto leave = [&](IndexBehindWriter result, const HostImport* import) { if (outcome != nullptr) *outcome = result; if (enabled) { indexBehindWriterEvents()[static_cast(result)].Add(1); if (indexBehindWriterProfiled) reportIndexBehindWriter(); } return import; }; auto* recorder = context.recorder; if (!enabled || recorder == nullptr || (indexSize != 2 && indexSize != 4) || bytes < indexSize) return leave(IndexBehindWriter::Off, nullptr); if (!recorder->PendingWriteOverlaps(address, bytes)) return leave(IndexBehindWriter::NoWriter, nullptr); if (context.limits.maxDrawIndexedIndexValue != std::numeric_limits::max()) return leave(IndexBehindWriter::IndexLimit, nullptr); if (meshStage) return leave(IndexBehindWriter::MeshStage, nullptr); if (primitiveRestart) return leave(IndexBehindWriter::PrimitiveRestart, nullptr); const std::uint32_t largestIndex = indexSize == 2 ? 0xffffu : std::numeric_limits::max(); if (firstVertex > std::numeric_limits::max() - largestIndex) return leave(IndexBehindWriter::VertexOffset, nullptr); if (AnyShadowedOverlaps(address, bytes)) return leave(IndexBehindWriter::UnitShadow, nullptr); if (PendingStorageOverlaps(address, bytes, nullptr)) return leave(IndexBehindWriter::PendingStorage, nullptr); if (recorder->PendingLabelIn(address, bytes) || recorder->CompletionLabelIn(address, bytes) || recorder->QueuedStoreOverlaps(address, bytes)) return leave(IndexBehindWriter::LabelOrStore, nullptr); const auto overlaps = [&](const auto& writer) { return writer->WritesOverlap(address, bytes); }; const auto drawWriters = DrawCopiedWriters(); if ((context.copiedWriters != nullptr && std::any_of(context.copiedWriters->begin(), context.copiedWriters->end(), overlaps)) || std::any_of(drawWriters->begin(), drawWriters->end(), overlaps)) return leave(IndexBehindWriter::CopiedWriter, nullptr); const auto* existing = ExistingHostImportFor(context, address, bytes); if (existing == nullptr || HostImportOffset(*existing, address) % indexSize != 0) return leave(IndexBehindWriter::NoImport, nullptr); auto inPlace = context; inPlace.drawInputsInPlace = true; bool behind = false; const auto* import = InPlaceDrawInput(inPlace, address, bytes, indexSize, &behind); return leave(import != nullptr ? IndexBehindWriter::Taken : IndexBehindWriter::Refused, import); } InPlaceIndices InPlaceIndexRange(Recorder& recorder, std::uint64_t address, std::size_t bytes, std::uint32_t indexSize, bool skipRestart) { const std::span range(reinterpret_cast(address), bytes); InPlaceIndices indices; const auto scan = [&] { const auto bounds = DrawIndexRange(range, indexSize, skipRestart); if (!bounds) return; indices.highest = bounds->highest; indices.lowest = bounds->lowest; }; if (bytes < Recorder::KeptIndexRangeIndices * indexSize) { scan(); return indices; } const auto use = indexSize == 2 ? (skipRestart ? Recorder::SnapshotUse::Index16Restart : Recorder::SnapshotUse::Index16) : (skipRestart ? Recorder::SnapshotUse::Index32Restart : Recorder::SnapshotUse::Index32); const auto registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); const auto generation = GuestMemory::CollectWrites(address, bytes); if (generation != 0 && recorder.KnownHighestIndex(address, bytes, use, indices.highest, &indices.lowest)) { indices.reused = true; return indices; } scan(); recorder.KeepHighestIndex(address, bytes, use, generation, registryGeneration, indices.highest, indices.lowest); return indices; } namespace { // The draw's inputs before its resources (prepareDrawInputs): the validated parameters, the index // buffer copy with its highest index, the vertex buffer copies and their layout, the fragment // outputs and the pipeline stages. struct DrawInputs { DrawResult result = DrawResult::Handled; // An empty auto draw: nothing to record. bool nothing = false; std::uint64_t indexBytes = 0; std::shared_ptr indices; VkBuffer indexHandle = VK_NULL_HANDLE; VkDeviceSize indexOffset = 0; std::uint32_t maxIndex = 0; std::uint32_t minIndex = 0; std::optional indexCount; std::uint32_t listRestartPrimitive = 0; VertexInputLayout vertexInput; std::shared_ptr retainedVertexInput; std::vector> vertexBuffers; std::vector vertexHandles; std::vector vertexOffsets; std::vector> inPlaceReads; bool vertexInputBehindGpuWrite = false; bool indexInputBehindGpuWrite = false; std::uint32_t fragmentOutputs = 0; VkPipelineStageFlags shaderStages = 0; std::uint32_t meshGroups = 0; std::uint32_t meshLayers = 1; std::uint32_t meshLayerStride = 0; std::vector restartTable; std::uint32_t expandedIndexCount = 0; const VertexInputLayout& VertexLayout() const { return retainedVertexInput != nullptr ? *retainedVertexInput : vertexInput; } }; bool StripPatches(const State& state, std::span shaders) { return state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP && BarycentricPatches(state, shaders); } std::shared_ptr zeroVertexBuffer(const Context& context, std::size_t bytes) { auto zero = std::make_shared(context, bytes, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); std::fill(zero->Bytes().begin(), zero->Bytes().end(), std::byte{0}); return zero; } // Draw's validation, index and vertex phases. With `recipe` the fragment outputs, the pipeline // stages and the vertex input layout are the recipe's (derived from the same compiled stages) // instead of computed. bool autoRangeFits(std::uint32_t first, std::uint32_t count) { return count == 0 || first <= std::numeric_limits::max() - (count - 1u); } bool indexAliasesColor(const State& state, const Pm4::DrawParameters& draw, std::uint64_t indexBytes) { if (!draw.indexed || !state.hasColorTarget || !indexBytes || !state.color.bytes) return false; const auto target = state.color.MemoryAddress(); return draw.indexAddress <= target ? target - draw.indexAddress < indexBytes : draw.indexAddress - target < state.color.bytes; } struct DrawPlan { bool nothing = false; std::uint64_t indexBytes = 0; std::uint32_t fragmentOutputs = 0; VkPipelineStageFlags shaderStages = 0; std::uint32_t meshGroups = 0; std::uint32_t meshLayers = 1; std::uint32_t meshLayerStride = 0; VertexInputLayout vertexInput; std::shared_ptr retainedVertexInput; bool candidate = false; bool keyed = false; ResourceCache::Key contentKey; const VertexInputLayout& VertexLayout() const { return retainedVertexInput != nullptr ? *retainedVertexInput : vertexInput; } }; bool EarlyDrawKeys() { static const bool enabled = std::getenv("APS5_NO_EARLY_DRAW_KEY") == nullptr; return enabled; } bool KeyForDevice(const std::vector& key, VkDevice device) { const auto handle = reinterpret_cast(device); return key.size() >= 3 && key[0] == 0xffffffffu && key[1] == static_cast(handle) && key[2] == static_cast(handle >> 32u); } DrawPlan planDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, const DrawRecipe* recipe, DrawOutcome& outcome, DrawTimer& timer, const std::vector* earlyKey = nullptr) { DrawPlan plan; APS5_LOG_OUT_DEBUG("Draw indices=%u instances=%u indexSize=%u flags=%u indexAddress=0x%llx", draw.indexCount, draw.instanceCount, draw.indexSize, draw.flags, static_cast(draw.indexAddress)); APS5_LOG_OUT_DEBUG("State colorTarget=%u render=%ux%u colorAddress=0x%llx colorBytes=%llu colorExtent=%ux%u", state.hasColorTarget ? 1u : 0u, state.renderExtent.width, state.renderExtent.height, static_cast(state.color.address), static_cast(state.color.bytes), state.color.extent.width, state.color.extent.height); APS5_LOG_OUT_DEBUG("Viewport x=%f y=%f w=%f h=%f minDepth=%f maxDepth=%f", state.viewport.x, state.viewport.y, state.viewport.width, state.viewport.height, state.viewport.minDepth, state.viewport.maxDepth); APS5_LOG_OUT_DEBUG("Scissor x=%d y=%d w=%u h=%u topology=%u cullMode=0x%x frontFace=%u", state.scissor.offset.x, state.scissor.offset.y, state.scissor.extent.width, state.scissor.extent.height, static_cast(state.topology), static_cast(state.cullMode), static_cast(state.frontFace)); const auto* args = draw.indirect ? &*draw.indirect : nullptr; Require(draw.indexed ? draw.flags == 0 : (draw.flags & ~0x20u) == 0, "draw modifiers are unsupported"); if (draw.indexed) { Require(draw.indexSize == 2 || draw.indexSize == 4, "only uint16 and uint32 index buffers are supported"); } else { Require(draw.indexAddress == 0 && draw.indexSize == 0, "auto draw must not reference an index buffer"); if (args == nullptr) { if (draw.indexCount == 0 || draw.instanceCount == 0) { plan.nothing = true; return plan; } Require(autoRangeFits(draw.firstVertex, draw.indexCount), "auto draw vertex range overflow"); Require(autoRangeFits(draw.firstInstance, draw.instanceCount), "auto draw instance range overflow"); } } if (args == nullptr) { if (draw.indexCount == 0 || draw.instanceCount == 0) { plan.nothing = true; return plan; } } else Require(!state.stages.tessellation && !state.quadList, "indirect draw on a non-vertex path must be resolved by the driver"); plan.indexBytes = static_cast(draw.indexCount) * draw.indexSize; const auto indexBytes = plan.indexBytes; APS5_LOG_OUT_DEBUG("Index buffer bytes=%llu", static_cast(indexBytes)); Require(indexBytes <= std::numeric_limits::max(), "index buffer size overflow"); Require(!indexAliasesColor(state, draw, indexBytes), "index buffer aliases the render target"); APS5_LOG_CHARS_OUT_DEBUG("ValidateShaders"); if (recipe != nullptr) { plan.fragmentOutputs = recipe->fragmentOutputs; plan.shaderStages = recipe->shaderStages; } else { plan.fragmentOutputs = CachedFragmentOutputs(context, shaders, state, outcome.validateMemoized, outcome.validateHit); plan.shaderStages = PipelineStages(shaders); } APS5_LOG_CHARS_OUT_DEBUG("ValidateShaders OK"); APS5_LOG_OUT_DEBUG("PipelineStages=0x%x", static_cast(plan.shaderStages)); if (state.stages.mesh) { APS5_LOG_CHARS_OUT_DEBUG("Mesh path"); Require(context.meshShader, "device does not support mesh shaders"); const auto& mesh = *state.stages.mesh; const auto inputSize = mesh.inputPrimitive == 1 ? 1u : mesh.inputPrimitive == 2 ? 2u : 3u; Require(mesh.primitivesPerGroup != 0, "mesh pipeline groups no primitive (zero primitives per group)"); Require(((state.stages.registerValue >> 19u) & 3u) == 0 || !draw.indexed, "indexed fast-launch draws are unsupported"); if (args == nullptr && draw.indexCount < inputSize) { plan.nothing = true; return plan; } if (args == nullptr) { const auto step = mesh.inputPrimitive == 5 || mesh.inputPrimitive == 6 ? 1u : inputSize; const auto primitives = (draw.indexCount - inputSize) / step + 1u; const auto groups = (primitives - 1u) / mesh.primitivesPerGroup + 1u; const auto grid = MeshGridFor(context, groups, draw.instanceCount); Require(grid.has_value(), "mesh draw exceeds workgroup count limits"); APS5_LOG_OUT_DEBUG("Mesh primitives=%u groups=%u as %u x %u", primitives, groups, grid->groups, grid->layers); plan.meshGroups = grid->groups; plan.meshLayers = grid->layers; plan.meshLayerStride = grid->layerStride; } } if (state.stages.tessellation) Require(draw.indexCount % state.stages.tessellation->inputControlPoints == 0, "incomplete tessellation patch"); ValidateViewport(context, state.viewport); for (const auto& viewport : state.extraViewports) ValidateViewport(context, viewport); ValidateDepthBounds(context, state); ValidateSampleMask(context, state, shaders); timer.phase(PhaseValidate); const auto layoutStart = timer.profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const auto& attributes = shaders.front().program->vertexAttributes; if (recipe != nullptr) { plan.vertexInput = recipe->vertexInput; } else if (!attributes.empty()) { if (context.vertexInputs != nullptr) plan.retainedVertexInput = context.vertexInputs->TryGet(shaders.front().program->variantId, attributes); if (plan.retainedVertexInput == nullptr) plan.vertexInput = BuildVertexInputLayout(context, attributes); } timer.charge(PhaseVertex, layoutStart); static const bool noDrawResourceCache = std::getenv("APS5_NO_DRAW_RESOURCE_CACHE") != nullptr; static const bool noTextureCache = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr; static const bool trimKey = std::getenv("APS5_NO_DRAW_KEY_TRIM") == nullptr; plan.candidate = recipe == nullptr && !noDrawResourceCache && !noTextureCache && std::all_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->PipelineVariantId() != 0; }); plan.keyed = plan.candidate && !ShaderResources::NeverReusable(shaders); if (plan.keyed) { const auto keyStart = timer.profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; if (earlyKey != nullptr && KeyForDevice(*earlyKey, context.device)) { plan.contentKey = *earlyKey; static const bool verify = std::getenv("APS5_VERIFY_EARLY_DRAW_KEY") != nullptr; if (verify) Require(plan.contentKey == DrawResourceKey(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, indexBytes, !trimKey), "the draw resource key made before the commit differs from the commit's"); } else { plan.contentKey = DrawResourceKey(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, indexBytes, !trimKey); } timer.charge(PhaseLookup, keyStart); } return plan; } bool VerifyDrawPlan() { static const bool verify = std::getenv("APS5_VERIFY_DRAW_PLAN") != nullptr; return verify; } void requireDrawPlanRepeats(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, const DrawPlan& plan) { DrawOutcome scratch; DrawTimer scratchTimer(false); const auto again = planDraw(context, state, draw, shaders, nullptr, scratch, scratchTimer); const auto sameBinding = [](const VkVertexInputBindingDescription& a, const VkVertexInputBindingDescription& b) { return a.binding == b.binding && a.stride == b.stride && a.inputRate == b.inputRate; }; const auto sameAttribute = [](const VkVertexInputAttributeDescription& a, const VkVertexInputAttributeDescription& b) { return a.location == b.location && a.binding == b.binding && a.format == b.format && a.offset == b.offset; }; const auto& layout = plan.VertexLayout(); const auto& repeated = again.VertexLayout(); Require(again.nothing == plan.nothing && again.indexBytes == plan.indexBytes && again.fragmentOutputs == plan.fragmentOutputs && again.shaderStages == plan.shaderStages && again.meshGroups == plan.meshGroups && again.meshLayers == plan.meshLayers && again.meshLayerStride == plan.meshLayerStride && again.candidate == plan.candidate && again.keyed == plan.keyed && again.contentKey == plan.contentKey && std::ranges::equal(repeated.bindings, layout.bindings, sameBinding) && std::ranges::equal(repeated.attributes, layout.attributes, sameAttribute), "APS5_VERIFY_DRAW_PLAN: the plan built after the draw's record-time work differs from the plan the draw used"); } DrawInputs prepareDrawInputs(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, const DrawPlan& drawPlan, DrawTimer& timer, PerformanceTimer& timing) { DrawInputs inputs; const auto reads = draw.indirect ? std::numeric_limits::max() : static_cast(draw.indexCount) * draw.instanceCount; inputs.indexBytes = drawPlan.indexBytes; inputs.fragmentOutputs = drawPlan.fragmentOutputs; inputs.shaderStages = drawPlan.shaderStages; inputs.meshGroups = drawPlan.meshGroups; inputs.meshLayers = drawPlan.meshLayers; inputs.meshLayerStride = drawPlan.meshLayerStride; inputs.vertexInput = drawPlan.vertexInput; inputs.retainedVertexInput = drawPlan.retainedVertexInput; const auto* args = draw.indirect ? &*draw.indirect : nullptr; const auto indexBytes = inputs.indexBytes; if (draw.indexed) GuestMemory::CheckRange(reinterpret_cast(draw.indexAddress), static_cast(indexBytes), draw.indexSize); APS5_LOG_CHARS_OUT_DEBUG("Index buffer range OK"); if (draw.indexed) RequireNoMultisampleTarget(draw.indexAddress, static_cast(indexBytes), "an index buffer read", DepthReadCause::Reuse); if (state.pixelKill && !state.pixelEarlyZ && std::ranges::any_of(state.colors, [](const ColorTarget& color) { return color.partialWriteMask != 0; })) { const auto* recorder = Recorder::Active(); Require(recorder == nullptr || !recorder->CountingSamples(), "a partial write of a packed color target merges inside the pixel shader after early depth and stencil tests, which a shader that kills pixels under late tests cannot use while occlusion queries count samples: the early tests would count the pixels it kills"); } timer.phase(PhaseValidate); timing.Mark("validate"); inputs.maxIndex = draw.indexed ? 0u : draw.firstVertex + draw.indexCount - 1u; inputs.minIndex = draw.indexed ? 0u : draw.firstVertex; if (state.quadList || StripPatches(state, shaders)) { Require(!draw.indirect, state.quadList ? "indirect quad-list draw is unsupported" : "an indirect triangle strip through emulated barycentric patches is unsupported"); Require(state.quadList || !draw.indexed || !state.primitiveRestart, "an indexed triangle strip with primitive restart through emulated barycentric patches is unsupported"); const std::uint32_t primitives = state.quadList ? draw.indexCount / 4u : draw.indexCount >= 3u ? draw.indexCount - 2u : 0u; if (primitives == 0u || draw.instanceCount == 0u) { inputs.nothing = true; return inputs; } const std::uint32_t corners = state.quadList ? 6u : 3u; Require(primitives <= std::numeric_limits::max() / corners, "expanded index count overflow"); const std::uint32_t outputIndexCount = primitives * corners; const std::size_t expandedIndexBytes = static_cast(outputIndexCount) * sizeof(std::uint32_t); auto indexCopy = std::make_shared(context, expandedIndexBytes, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); auto* outIndices = reinterpret_cast(indexCopy->Bytes().data()); std::uint32_t maxIdx = 0; const bool lastProvoking = state.provokingVertexMode == VK_PROVOKING_VERTEX_MODE_LAST_VERTEX_EXT; const auto expand = [&](const auto& source) { for (std::uint32_t primitive = 0; primitive < primitives; ++primitive) { auto* out = outIndices + static_cast(primitive) * corners; if (state.quadList) { const auto i0 = source(primitive * 4u + 0u); const auto i1 = source(primitive * 4u + 1u); const auto i2 = source(primitive * 4u + 2u); const auto i3 = source(primitive * 4u + 3u); if (lastProvoking) { out[0] = i0; out[1] = i1; out[2] = i3; out[3] = i1; out[4] = i2; out[5] = i3; } else { out[0] = i0; out[1] = i1; out[2] = i2; out[3] = i0; out[4] = i2; out[5] = i3; } } else { const std::uint32_t odd = primitive & 1u; if (lastProvoking) { out[0] = source(primitive + odd); out[1] = source(primitive + 1u - odd); out[2] = source(primitive + 2u); } else { out[0] = source(primitive); out[1] = source(primitive + 1u + odd); out[2] = source(primitive + 2u - odd); } } for (std::uint32_t corner = 0; corner < corners; ++corner) maxIdx = std::max(maxIdx, out[corner]); } }; if (draw.indexed) { GuestMemory::FlushGpuWrites(draw.indexAddress, static_cast(indexBytes)); GuestMemory::CheckRange(reinterpret_cast(draw.indexAddress), static_cast(indexBytes), draw.indexSize); const auto readIndex = [&](std::uint32_t idx) -> std::uint32_t { if (draw.indexSize == 2) { std::uint16_t v = 0; GuestMemory::Read(draw.indexAddress + static_cast(idx) * 2u, std::as_writable_bytes(std::span(&v, 1)), 2); return v; } else { std::uint32_t v = 0; GuestMemory::Read(draw.indexAddress + static_cast(idx) * 4u, std::as_writable_bytes(std::span(&v, 1)), 4); return v; } }; expand(readIndex); Require(draw.firstVertex <= std::numeric_limits::max() - maxIdx, "indexed draw vertex range overflow"); } else { const std::uint32_t lastVertex = state.quadList ? primitives * 4u - 1u : primitives + 1u; Require(draw.firstVertex <= std::numeric_limits::max() - lastVertex, "auto draw vertex range overflow"); expand([](std::uint32_t idx) { return idx; }); } inputs.maxIndex = draw.indexed ? maxIdx : maxIdx + draw.firstVertex; Require(inputs.maxIndex <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit"); inputs.indexHandle = indexCopy->Handle(); inputs.indexOffset = 0; inputs.expandedIndexCount = outputIndexCount; inputs.indices = std::move(indexCopy); } else if (draw.indexed && state.primitiveRestart && !context.primitiveListRestart && !state.stages.mesh && (state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST)) { if (indexBytes == 0) { inputs.nothing = true; return inputs; } GuestMemory::FlushGpuWrites(draw.indexAddress, static_cast(indexBytes)); auto compacted = std::make_shared(context, static_cast(indexBytes), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); const auto bytes = compacted->Bytes().first(static_cast(indexBytes)); GuestMemory::Read(draw.indexAddress, bytes, draw.indexSize); const auto primitiveSize = state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST ? 1u : state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST ? 2u : 3u; const auto count = draw.indirect ? draw.indexCount : CompactListRestart(bytes, draw.indexSize, primitiveSize); const auto kept = bytes.first(static_cast(count) * draw.indexSize); const bool restartLeft = draw.indirect.has_value(); auto bounds = DrawIndexRange(kept, draw.indexSize, restartLeft); constexpr std::uint32_t ZeroFetchSlack = 0x10000u; if (const auto zeroFrom = bounds && !shaders.front().program->vertexAttributes.empty() ? ZeroFetchVertex(shaders.front().program->vertexAttributes) : std::nullopt) { const auto limit = *zeroFrom > draw.firstVertex ? *zeroFrom - draw.firstVertex : 0u; if (bounds->highest >= limit && bounds->highest - limit >= ZeroFetchSlack) bounds = ClampDrawIndices(kept, draw.indexSize, restartLeft, limit); } if (!bounds) { inputs.nothing = true; return inputs; } Require(bounds->highest <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit"); inputs.maxIndex = bounds->highest; inputs.minIndex = bounds->lowest; inputs.indexCount = count; inputs.listRestartPrimitive = primitiveSize; inputs.indices = std::move(compacted); inputs.indexHandle = inputs.indices->Handle(); inputs.indexOffset = 0; } else if (draw.indexed) { const bool listTopology = state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; const bool skipRestart = state.primitiveRestart && (!listTopology || context.primitiveListRestart || state.stages.mesh); const auto use = draw.indexSize == 2 ? (skipRestart ? Recorder::SnapshotUse::Index16Restart : Recorder::SnapshotUse::Index16) : (skipRestart ? Recorder::SnapshotUse::Index32Restart : Recorder::SnapshotUse::Index32); const bool restartTable = skipRestart && state.stages.mesh && (state.stages.mesh->inputPrimitive == 5 || state.stages.mesh->inputPrimitive == 6); const auto* behindWriter = InPlaceIndexBehindWriter(context, draw.indexAddress, static_cast(indexBytes), draw.indexSize, static_cast(state.stages.mesh), skipRestart, draw.firstVertex); const auto* import = behindWriter != nullptr ? behindWriter : InPlaceDrawInput(context, draw.indexAddress, static_cast(indexBytes), draw.indexSize, nullptr, static_cast(indexBytes), reads); DrawInputCopy copy; if (import == nullptr) copy = CopyDrawInput(context, context.recorder, draw.indexAddress, static_cast(indexBytes), draw.indexSize, use, 0, !BindsIndexCopy(state)); else GuestMemory::CheckRange(reinterpret_cast(draw.indexAddress), static_cast(indexBytes), draw.indexSize); std::optional highest; std::uint32_t lowest = 0; if (behindWriter != nullptr) { highest = draw.indexSize == 2 ? 0xffffu : std::numeric_limits::max(); inputs.indexInputBehindGpuWrite = true; } else if (import != nullptr) { const std::uint32_t largestIndex = draw.indexSize == 2 ? 0xffffu : std::numeric_limits::max(); if (shaders.front().program->vertexAttributes.empty() && !skipRestart && !state.stages.mesh && draw.indexCount != 0 && largestIndex <= context.limits.maxDrawIndexedIndexValue && draw.firstVertex <= std::numeric_limits::max() - largestIndex) { highest = largestIndex; lowest = 0u; } else { const auto range = InPlaceIndexRange(*context.recorder, draw.indexAddress, static_cast(indexBytes), draw.indexSize, skipRestart); highest = range.highest; lowest = range.lowest; } } else if (!copy.reused) { if (const auto bounds = DrawIndexRange(copy.buffer->Bytes().first(static_cast(indexBytes)), draw.indexSize, skipRestart)) { highest = bounds->highest; lowest = bounds->lowest; } KeepDrawInput(context.recorder, draw.indexAddress, copy, use, skipRestart ? (highest ? *highest + 1u : 0u) : highest.value_or(0u), lowest); } else { lowest = copy.lowest; if (!skipRestart) highest = copy.derived; else if (copy.derived != 0) highest = copy.derived - 1u; } if (!highest) { inputs.nothing = true; return inputs; } constexpr std::uint32_t ZeroFetchSlack = 0x10000u; if (const auto zeroFrom = state.stages.mesh || shaders.front().program->vertexAttributes.empty() ? std::nullopt : ZeroFetchVertex(shaders.front().program->vertexAttributes)) { const auto limit = *zeroFrom > draw.firstVertex ? *zeroFrom - draw.firstVertex : 0u; if (*highest >= limit && *highest - limit >= ZeroFetchSlack) { GuestMemory::FlushGpuWrites(draw.indexAddress, static_cast(indexBytes)); auto clamped = std::make_shared(context, static_cast(indexBytes), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); const auto bytes = clamped->Bytes().first(static_cast(indexBytes)); GuestMemory::Read(draw.indexAddress, bytes, draw.indexSize); const auto clampedBounds = ClampDrawIndices(bytes, draw.indexSize, skipRestart, limit); import = nullptr; copy = DrawInputCopy{}; copy.buffer = std::move(clamped); if (!clampedBounds) { inputs.nothing = true; return inputs; } highest = clampedBounds->highest; lowest = clampedBounds->lowest; } } Require(*highest <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit"); inputs.maxIndex = *highest; inputs.minIndex = lowest; if (restartTable) { const auto indexSpan = import != nullptr ? std::span(reinterpret_cast(draw.indexAddress), static_cast(indexBytes)) : copy.buffer->Bytes().first(static_cast(indexBytes)); inputs.restartTable = MeshRestartTable(indexSpan, draw.indexSize); } if (import != nullptr) { inputs.indexHandle = import->buffer; inputs.indexOffset = HostImportOffset(*import, draw.indexAddress); inputs.inPlaceReads.emplace_back(draw.indexAddress, draw.indexAddress + indexBytes); } else { inputs.indices = std::move(copy.buffer); inputs.indexHandle = inputs.indices->Handle(); } } APS5_LOG_CHARS_OUT_DEBUG("Index validation OK"); timing.Mark("index_upload"); const auto& attributes = shaders.front().program->vertexAttributes; const bool wholeRange = args != nullptr || inputs.indexInputBehindGpuWrite; inputs.vertexOffsets.assign(attributes.size(), 0); inputs.vertexHandles.reserve(attributes.size()); // An indexed draw's vertex offset moves every fetch: the copy must reach the last one. if (draw.indexed) { Require(draw.firstVertex <= std::numeric_limits::max() - inputs.maxIndex, "indexed draw vertex range overflow"); inputs.maxIndex += draw.firstVertex; inputs.minIndex += draw.firstVertex; } const VertexPlanLease planLease; auto& fetches = planLease->fetches; auto& fetchValid = planLease->fetchValid; auto& fetchOf = planLease->fetchOf; auto& zeroed = planLease->zeroed; auto& fetchLimit = planLease->fetchLimit; fetches.reserve(attributes.size()); fetchValid.reserve(attributes.size()); fetchLimit.reserve(attributes.size()); fetchOf.assign(attributes.size(), 0); zeroed.resize(attributes.size()); const auto& layout = inputs.VertexLayout(); for (std::size_t i = 0; i < attributes.size(); ++i) { const auto& attribute = attributes[i]; const auto described = std::find_if(layout.attributes.begin(), layout.attributes.end(), [&](const auto& entry) { return entry.location == attribute.location; }); Require(described != layout.attributes.end(), "vertex attribute missing from its input layout"); if (VertexFetchOutOfRange(attribute)) { zeroed[i] = zeroVertexBuffer(context, ZeroVertexFormat(attribute).bytes); continue; } const auto narrow = DecodeVertexFormat(attribute); const std::size_t widened = described->format == narrow.format ? 0u : VertexReadBytes(attribute, described->format) - narrow.bytes; if (NullVertexDescriptor(attribute)) { zeroed[i] = zeroVertexBuffer(context, narrow.bytes + widened); continue; } // An indirect draw's counts are unknown here: the descriptor's whole range is copied. const auto bytes = (wholeRange ? VertexBufferExtent(attribute) : VertexBufferReadSize(attribute, inputs.maxIndex, draw.instanceCount, draw.firstInstance)) + widened; const auto& fields = attribute.resource.fields; const auto address = fields[0] | (static_cast(fields[1] & 0xffffu) << 32u); const auto firstByte = !wholeRange ? VertexBufferReadOffset(attribute, draw.firstVertex, draw.firstInstance) : 0; const bool aliasesTarget = state.hasColorTarget && address + bytes > state.color.MemoryAddress() && state.color.MemoryAddress() + state.color.bytes > address + firstByte; if (aliasesTarget && args != nullptr && args->capturedRecords) { // The full descriptor can overlap even when every record fetches a disjoint prefix. inputs.result = DrawResult::NeedsIndividualRecords; return inputs; } Require(!aliasesTarget, "vertex buffer aliases the render target"); const auto stride = (fields[1] >> 16u) & 0x3fffu; fetchOf[i] = fetches.size(); fetches.push_back({address, address + bytes, stride, attribute.fetchIndex, DecodeVertexFormat(attribute).alignment}); const auto recordBytes = static_cast(fields[2]) * stride; fetchValid.push_back(!wholeRange && stride != 0 ? static_cast(std::min(recordBytes, static_cast(bytes))) : bytes); fetchLimit.push_back(args == nullptr ? std::max(VertexDescriptorEnd(attribute, widened), address + bytes) : address + bytes); } const auto soloFetches = SoloZeroPaddedFetchIndices(fetches, fetchValid); auto& isSolo = planLease->isSolo; auto& plannedFetches = planLease->plannedFetches; auto& plannedOf = planLease->plannedOf; isSolo.assign(fetches.size(), false); for (const auto f : soloFetches) isSolo[f] = true; plannedFetches.reserve(fetches.size()); plannedOf.assign(fetches.size(), 0); for (std::size_t f = 0; f < fetches.size(); ++f) { if (isSolo[f]) continue; plannedOf[f] = plannedFetches.size(); plannedFetches.push_back(fetches[f]); } const auto plan = PlanVertexCopies(plannedFetches); const auto rangeFrom = !wholeRange && !state.stages.mesh ? VertexCopyStarts(plan, plannedFetches, inputs.minIndex, draw.firstInstance) : std::vector(plan.copies.size(), 0); auto& rangeLimit = planLease->rangeLimit; rangeLimit.assign(plan.copies.size(), std::numeric_limits::max()); for (std::size_t f = 0; f < fetches.size(); ++f) { if (!isSolo[f]) rangeLimit[plan.copyOf[plannedOf[f]]] = std::min(rangeLimit[plan.copyOf[plannedOf[f]]], fetchLimit[f]); } auto& rangeHandles = planLease->rangeHandles; auto& rangeOffsets = planLease->rangeOffsets; rangeHandles.reserve(plan.copies.size()); rangeOffsets.reserve(plan.copies.size()); for (std::size_t range = 0; range < plan.copies.size(); ++range) { const auto [begin, end] = plan.copies[range]; const auto bytes = static_cast(end - begin); GuestMemory::CheckRange(reinterpret_cast(begin), bytes, 1); RequireNoMultisampleTarget(begin, bytes, "a vertex buffer read", DepthReadCause::Reuse); if (const auto* import = InPlaceDrawInput(context, begin, bytes, plan.alignments[range], &inputs.vertexInputBehindGpuWrite, bytes - std::min(rangeFrom[range], bytes), reads)) { rangeHandles.push_back(import->buffer); rangeOffsets.push_back(HostImportOffset(*import, begin)); inputs.inPlaceReads.emplace_back(begin, end); continue; } const auto limit = VertexCopyGrowEnd(state, end, rangeLimit[range]); auto copy = CopyDrawInput(context, context.recorder, begin, bytes, 1, Recorder::SnapshotUse::Vertex, rangeFrom[range], false, static_cast(limit - begin)); KeepDrawInput(context.recorder, begin, copy, Recorder::SnapshotUse::Vertex, 0); rangeHandles.push_back(copy.buffer->Handle()); rangeOffsets.push_back(0); inputs.vertexBuffers.push_back(std::move(copy.buffer)); } std::vector soloHandles(fetches.size(), VK_NULL_HANDLE); for (const auto f : soloFetches) { const auto begin = fetches[f].begin; const auto bytes = static_cast(fetches[f].end - begin); auto copy = CopyZeroPaddedDrawInput(context, begin, bytes, fetchValid[f], fetches[f].stride); soloHandles[f] = copy.buffer->Handle(); inputs.vertexBuffers.push_back(std::move(copy.buffer)); } for (std::size_t i = 0; i < attributes.size(); ++i) { if (zeroed[i] != nullptr) { inputs.vertexHandles.push_back(zeroed[i]->Handle()); inputs.vertexOffsets[i] = 0; inputs.vertexBuffers.push_back(std::move(zeroed[i])); continue; } const auto f = fetchOf[i]; if (isSolo[f]) { inputs.vertexHandles.push_back(soloHandles[f]); inputs.vertexOffsets[i] = 0; continue; } const auto j = plannedOf[f]; inputs.vertexHandles.push_back(rangeHandles[plan.copyOf[j]]); inputs.vertexOffsets[i] = rangeOffsets[plan.copyOf[j]] + plan.offsets[j]; } timer.phase(PhaseVertex); timing.Mark("vertex_upload"); return inputs; } // The resident-target proof of one attachment (StorageTexture::Refresh: FlushPending, CollectWrites // over the target's pages, the DCC key scan of TextureClearKeys, then UnchangedSince), with the // [draws] target-lookup accounting. `lookup` makes (or finds) the image; DrawWithRecipe refreshes // the stored object instead. bool materializeMipClear(const Context& context, const ColorTarget& color, std::shared_ptr& resident) { if (color.dccAddress == 0 || color.mipCount <= 1 || color.mipTail) return false; const auto keyCount = std::max(colorKeyCount(color, color.bytes), 1u); const auto landed = LandedDccKeys(color.dccAddress, color.bytes, keyCount); DccKeys keys; bool verified; if (landed == DccKeys::Unreadable) { keys = CurrentDccKeys(color.dccAddress, color.bytes, keyCount); verified = false; } else { keys = landed; verified = true; } if (!IsDccClear(keys) || keys == DccKeys::ClearSingle || (keys == DccKeys::ClearRegister && color.elementBytes > 8u)) return false; const auto texel = clearTexel(color, keys); if (resident != nullptr) { const char* refusal = nullptr; if (resident->ClearMip(texel, color.mip, verified, refusal)) { MarkDccUncompressed(context, color.dccAddress, color.bytes, keyCount); return true; } MarkDccUncompressed(context, color.dccAddress, color.bytes, keyCount); } StorageTexture::FlushPending(color.address, color.bytes, nullptr, "fast-clear materialization"); writeTexels(color, texel); return true; } template std::shared_ptr refreshResidentTarget(const Context& context, const State& state, const ColorTarget& color, DrawOutcome& outcome, bool profile, const TLookup& lookup) { const auto lookupStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const auto walkedBefore = profile ? GuestMemory::ThreadCollectedBytes() : 0; std::shared_ptr resident; try { resident = lookup(); if (resident != nullptr) materializeRegisterClear(context, color, *resident); } catch (const std::exception& error) { resident = nullptr; static AgcDriver::Mutex reportMutex; static std::set reported; std::lock_guard lock(reportMutex); if (reported.insert(color.address).second) std::fprintf(stderr, "[gpu] color target 0x%llx stays non-resident: %s\n", static_cast(color.address), error.what()); } if (resident != nullptr) materializeCmaskClear(context, color, resident); if (resident != nullptr) materializeMipClear(context, color, resident); if (profile) { const auto lookupUs = std::chrono::duration(std::chrono::steady_clock::now() - lookupStart).count(); ++outcome.targetLookups; if (lookupUs >= 1000.0) { ++outcome.slowLookups; outcome.slowLookupUs += lookupUs; } outcome.lookupUs += lookupUs; outcome.pagesWalked += (GuestMemory::ThreadCollectedBytes() - walkedBefore) / 4096; const bool fullScissor = state.scissor.offset.x <= 0 && state.scissor.offset.y <= 0 && state.scissor.extent.width >= color.extent.width && state.scissor.extent.height >= color.extent.height; ++(fullScissor ? outcome.fullScissorLookups : outcome.partialLookups); } return resident; } // A draw's resources (resolveDrawResources): the resource-cache template a recordable draw's // stages repeat, or a fresh build. struct ResolvedResources { std::shared_ptr resources; std::vector moved; ResourceCache::Key contentKey; bool cacheable = false; const ShaderResources::BuildTiming* built = nullptr; }; enum class AddressStages { None, ReadOnly, Storing }; AddressStages addressStages(std::span shaders) { auto stages = AddressStages::None; for (const auto& shader : shaders) { if (shader.program == nullptr || std::none_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable; })) continue; if (ShaderStoresThroughAddresses(shader.program->spirv)) return AddressStages::Storing; stages = AddressStages::ReadOnly; } return stages; } bool verifyAddressDrawReuse() { static const bool verify = std::getenv("APS5_VERIFY_ADDRESS_DRAW_REUSE") != nullptr; return verify; } bool snapshotsInTable(std::span table, std::span snapshots) { ShaderRecompiler::BdaAbi::Header header{}; if (table.size() < sizeof(header)) return snapshots.empty(); std::memcpy(&header, table.data(), sizeof(header)); if (header.entryBytes != sizeof(ShaderRecompiler::BdaAbi::Range) || (table.size() - sizeof(header)) / sizeof(ShaderRecompiler::BdaAbi::Range) < header.count) return false; std::vector ranges(header.count); if (!ranges.empty()) std::memcpy(ranges.data(), table.data() + sizeof(header), ranges.size() * sizeof(ranges.front())); return std::ranges::all_of(snapshots, [&](const GuestMemorySnapshot& snapshot) { auto at = snapshot.address; const auto end = snapshot.address + snapshot.bytes.size(); for (const auto& range : ranges) { if (at >= end || range.begin > at) break; if (range.end > at && (range.permissions & ShaderRecompiler::BdaAbi::Read) != 0u) at = range.end; } return at >= end; }); } bool snapshotsEqualMemory(std::span snapshots) { return std::ranges::all_of(snapshots, [](const GuestMemorySnapshot& snapshot) { return snapshot.bytes.empty() || std::memcmp(reinterpret_cast(snapshot.address), snapshot.bytes.data(), snapshot.bytes.size()) == 0; }); } void verifyServedSpace(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, std::uint64_t indexBytes, const ShaderResources& served) { const ShaderResources fresh(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, static_cast(indexBytes), snapshots); const auto servedTable = served.AddressTableBytes(); const auto freshTable = fresh.AddressTableBytes(); const char* what = !fresh.SpaceReuse() ? "space reuse" : !std::ranges::equal(servedTable, freshTable) ? "BDA table" : !snapshotsInTable(servedTable, snapshots) ? "snapshot ranges" : !snapshotsEqualMemory(snapshots) ? "snapshot bytes" : served.SampledTextures() != fresh.SampledTextures() ? "sampled textures" : served.StorageImages() != fresh.StorageImages() ? "storage images" : served.LayoutKey() != fresh.LayoutKey() || served.FragmentLayoutKey() != fresh.FragmentLayoutKey() ? "set layouts" : nullptr; addressDrawReuseVerifications().fetch_add(1, std::memory_order_relaxed); if (what == nullptr) return; char message[320]; std::snprintf(message, sizeof(message), "APS5_VERIFY_ADDRESS_DRAW_REUSE: a served address-based draw hit disagrees with a fresh build or guest memory in its %s (BDA table %zu bytes served, %zu fresh; %zu / %zu sampled textures; %zu snapshots)", what, servedTable.size(), freshTable.size(), served.SampledTextures().size(), fresh.SampledTextures().size(), snapshots.size()); throw std::runtime_error(message); } bool drawStagingEnabled() { static const bool disabled = std::getenv("APS5_NO_DRAW_STAGING") != nullptr; return !disabled; } ResolvedResources resolveDrawResources(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, std::uint64_t indexBytes, bool recordable, const DrawPlan& plan, DrawOutcome& outcome, DrawTimer& timer) { ResolvedResources resolved; APS5_LOG_CHARS_OUT_DEBUG("Creating ShaderResources"); // A recordable draw whose stages' compiled content repeats an earlier one binds that build's // descriptor set when it is still valid (see ResourceCache; the dispatch path does the same). // Only recordable draws take part: a synchronous draw writes its resources back, which a shared // object must never do. Revalidate proves a hit by texture identity, which needs the texture // caches. Push constants still come from this draw's stages. APS5_NO_DRAW_RESOURCE_CACHE=1 // builds every draw's resources as before. // The render target and index ranges stay out of the key (see DrawResourceKey); a hit repeats // the alias checks instead. Debug aid: APS5_NO_DRAW_KEY_TRIM=1 keys them as before. static const bool trimKey = std::getenv("APS5_NO_DRAW_KEY_TRIM") == nullptr; const bool candidate = recordable && plan.candidate; resolved.cacheable = recordable && plan.keyed; const auto address = candidate && !ShaderResources::SpaceReuseDisabled() ? addressStages(shaders) : AddressStages::None; std::optional reuse; if (address == AddressStages::Storing) reuse = AddressDrawReuse::NotReadOnly; else if (address == AddressStages::ReadOnly && !resolved.cacheable) reuse = AddressDrawReuse::NotSpaceOnly; if (resolved.cacheable) { resolved.contentKey = plan.contentKey; if (auto cached = SharedResourceCache().Find(resolved.contentKey)) { const auto releaseSpace = [](ShaderResources* resources) { static_cast(resources->ReleaseSpace()); }; std::unique_ptr heldSpace(nullptr, releaseSpace); const bool counted = address == AddressStages::ReadOnly && cached->SpaceReuse(); bool spaceHeld = !cached->SpaceReuse(); bool inUse = false; if (!spaceHeld) { if (auto* active = Recorder::Active(); active != nullptr) { GuestBufferMemory::ReleaseRetainedSpaces(active->Id(), active->CompletedThrough()); static_cast(cached->ReleaseCompletedSpace(active->Id(), active->CompletedThrough())); } if (cached->SpaceHeld()) { inUse = true; reuse = AddressDrawReuse::InUse; } else if (!cached->RetakeSpace()) { reuse = AddressDrawReuse::SpaceChanged; } else { heldSpace.reset(cached.get()); if (!cached->AddressTableGuardCurrent()) { reuse = AddressDrawReuse::SpaceChanged; static_cast(cached->ReleaseSpace()); } else { completeSnapshotWrites(snapshots); const auto service = cached->SnapshotsServedInPlace(snapshots); spaceHeld = service == SnapshotService::Served; if (!spaceHeld) { reuse = service == SnapshotService::Partial ? AddressDrawReuse::PartialOverlap : service == SnapshotService::Changed ? AddressDrawReuse::SnapshotChanged : AddressDrawReuse::SnapshotOutside; static_cast(cached->ReleaseSpace()); } } } } const bool valid = spaceHeld && cached->Revalidate(shaders); if (counted && spaceHeld && !valid) reuse = AddressDrawReuse::Revalidation; auto* recorder = Recorder::Active(); std::optional> moved; bool patched = false; if (valid && recorder != nullptr) moved = cached->MovedReadOnlyBuffers(shaders, *recorder, &state.color, &patched); if (moved.has_value()) { if (trimKey) CheckBufferAliases(shaders, state.color, draw.indexAddress, indexBytes); if (counted && verifyAddressDrawReuse()) verifyServedSpace(context, state, draw, shaders, snapshots, indexBytes, *cached); static_cast(heldSpace.release()); resolved.resources = std::move(cached); resolved.moved = std::move(*moved); outcome.kind = KindTemplateHit; countCache(&DrawProfile::cacheHits); if (counted) reuse = AddressDrawReuse::Reused; } else if (valid || inUse) { if (valid && cached->SpaceReuse()) static_cast(cached->ReleaseSpace()); if (valid && counted) reuse = patched ? AddressDrawReuse::PatchedData : AddressDrawReuse::MovedBuffer; countCache(&DrawProfile::cacheMisses); } else { if (cached->SpaceReuse()) static_cast(cached->ReleaseSpace()); SharedResourceCache().Remove(resolved.contentKey); countCache(&DrawProfile::cacheInvalidated); } } } else { countCache(&DrawProfile::uncacheable); } timer.phase(PhaseLookup); if (resolved.resources == nullptr) { resolved.resources = std::make_shared(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, static_cast(indexBytes), snapshots, recordable && drawStagingEnabled()); resolved.built = &resolved.resources->Timing(); outcome.addressBased = resolved.resources->HoldsLease(); outcome.kind = outcome.addressBased ? KindBda : KindBuild; if (resolved.cacheable) countCache(&DrawProfile::cacheMisses); if (address == AddressStages::ReadOnly && !reuse.has_value()) reuse = resolved.resources->SpaceReuse() ? AddressDrawReuse::Built : AddressDrawReuse::NotSpaceOnly; } if (reuse.has_value()) countAddressDrawReuse(*reuse); timer.phase(PhaseResources); APS5_LOG_CHARS_OUT_DEBUG("ShaderResources created"); return resolved; } // A GPU-side indirect draw's records (Draw's recorded path; a recipe draw has none) as recordDraw // takes them: the arguments, how they are read, their host imports and, on the CPU path, the // records read. struct IndirectRecord { const Pm4::DrawParameters::IndirectDraw* args = nullptr; std::optional path = IndirectDrawPath::Gpu; const HostImport* argumentImport = nullptr; const HostImport* countImport = nullptr; std::span records; double readMs = 0; }; void CompactIndirectListRestart(const Context& context, const Pm4::DrawParameters& draw, DrawInputs& inputs, std::vector& records) { const auto bound = inputs.indexCount.value_or(draw.indexCount); const auto raw = inputs.indices->Bytes(); std::uint64_t total = 0; for (const auto& record : records) { if (record.count != 0 && record.instances != 0 && record.firstVertexOrIndex < bound) total += std::min(record.count, bound - record.firstVertexOrIndex); } Require(total <= std::numeric_limits::max(), "indirect list restart index count overflow"); auto compacted = std::make_shared(context, static_cast(std::max(total, 1u) * draw.indexSize), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); const auto out = compacted->Bytes(); std::uint32_t cursor = 0; for (auto& record : records) { if (record.count == 0 || record.instances == 0 || record.firstVertexOrIndex >= bound) { record.count = 0; continue; } const auto count = std::min(record.count, bound - record.firstVertexOrIndex); const auto at = out.subspan(static_cast(cursor) * draw.indexSize, static_cast(count) * draw.indexSize); std::memcpy(at.data(), raw.data() + static_cast(record.firstVertexOrIndex) * draw.indexSize, at.size()); record.count = CompactListRestart(at, draw.indexSize, inputs.listRestartPrimitive); record.firstVertexOrIndex = cursor; cursor += record.count; } inputs.indexCount = cursor; inputs.indices = std::move(compacted); inputs.indexHandle = inputs.indices->Handle(); inputs.indexOffset = 0; } // The draw commands of one draw: the vertex and index buffer binds, then the direct draw, the // GPU-side indirect draw from `argumentBuffer` or the CPU-read records with the driver's rules. bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, const IndirectRecord* indirect, VkBuffer argumentBuffer, VkDeviceSize argumentOffset, const DrawTraceContext* trace, std::uint32_t& subdraw, std::optional pieceFirstIndex = std::nullopt) { bool emitted = false; if (context.recorder != nullptr) context.recorder->NoteSampledDraw(commands); const auto recorded = [&](std::uint32_t index) { if (trace != nullptr && context.recorder != nullptr) { context.recorder->NoteDrawTraceToken(trace->token); CaptureTrace::Log("draw-recorded token=%llu batch=%llu submission=%llu queue=%u offset=%zu target=%llx subdraw=%u", static_cast(trace->token), static_cast(context.recorder->OpenBatchSerial()), static_cast(trace->submission), trace->queue, trace->offset, static_cast(trace->target), index); } }; const auto* args = indirect != nullptr ? indirect->args : nullptr; if (state.stages.mesh && (args != nullptr || state.tessellationCapture != nullptr)) { CountVkDraw(VkDrawKind::Mesh); context.Function("vkCmdDrawMeshTasksIndirectEXT")(commands, argumentBuffer, argumentOffset, 1, sizeof(VkDrawMeshTasksIndirectCommandEXT)); recorded(subdraw++); emitted = true; return true; } if (state.stages.mesh) { APS5_LOG_OUT_DEBUG("vkCmdDrawMeshTasksEXT groups=%u instances=%u layers=%u", inputs.meshGroups, draw.instanceCount, inputs.meshLayers); CountVkDraw(VkDrawKind::Mesh); context.Function("vkCmdDrawMeshTasksEXT")(commands, inputs.meshGroups, draw.instanceCount, inputs.meshLayers); recorded(subdraw++); emitted = true; return true; } if (!inputs.vertexHandles.empty()) context.Resolved(&DeviceFunctions::cmdBindVertexBuffers, "vkCmdBindVertexBuffers")(commands, 0, static_cast(inputs.vertexHandles.size()), inputs.vertexHandles.data(), inputs.vertexOffsets.data()); if (inputs.expandedIndexCount != 0u) { context.Resolved(&DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, VK_INDEX_TYPE_UINT32); CountVkDraw(VkDrawKind::Indexed); context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, inputs.expandedIndexCount, draw.instanceCount, 0, static_cast(draw.firstVertex), draw.firstInstance); emitted = true; return true; } if (draw.indexed) context.Resolved(&DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, draw.indexSize == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); if (args == nullptr) { if (draw.indexed) { CountVkDraw(VkDrawKind::Indexed); context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, pieceFirstIndex ? draw.indexCount : inputs.indexCount.value_or(draw.indexCount), draw.instanceCount, pieceFirstIndex.value_or(0u), static_cast(draw.firstVertex), draw.firstInstance); recorded(subdraw++); emitted = true; } else { CountVkDraw(VkDrawKind::Direct); context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, draw.indexCount, draw.instanceCount, draw.firstVertex, draw.firstInstance); recorded(subdraw++); emitted = true; } } else if (indirect->path == IndirectDrawPath::Gpu) { emitted = true; if (args->countIndirect) { CountVkDraw(VkDrawKind::Indirect); if (draw.indexed) context.Function("vkCmdDrawIndexedIndirectCountKHR")(commands, argumentBuffer, argumentOffset, indirect->countImport->buffer, HostImportOffset(*indirect->countImport, args->countAddress), args->count, args->stride); else context.Function("vkCmdDrawIndirectCountKHR")(commands, argumentBuffer, argumentOffset, indirect->countImport->buffer, HostImportOffset(*indirect->countImport, args->countAddress), args->count, args->stride); } else if (args->count <= 1 || context.multiDrawIndirect) { CountVkDraw(VkDrawKind::Indirect); if (draw.indexed) context.Resolved(&DeviceFunctions::cmdDrawIndexedIndirect, "vkCmdDrawIndexedIndirect")(commands, argumentBuffer, argumentOffset, args->count, args->stride); else context.Resolved(&DeviceFunctions::cmdDrawIndirect, "vkCmdDrawIndirect")(commands, argumentBuffer, argumentOffset, args->count, args->stride); } else { for (std::uint32_t record = 0; record < args->count; ++record) { const auto offset = argumentOffset + static_cast(record) * args->stride; CountVkDraw(VkDrawKind::Indirect); if (draw.indexed) context.Resolved(&DeviceFunctions::cmdDrawIndexedIndirect, "vkCmdDrawIndexedIndirect")(commands, argumentBuffer, offset, 1, args->stride); else context.Resolved(&DeviceFunctions::cmdDrawIndirect, "vkCmdDrawIndirect")(commands, argumentBuffer, offset, 1, args->stride); } } } else { // The CPU-read records with the driver's rules: an InPlace dimension takes the record's // value, a Constant one (the CP writes nowhere) the constant. using Rule = Pm4::DrawParameters::IndirectDraw::Rule; for (const auto& record : indirect->records) { if (record.count == 0 || record.instances == 0) continue; const auto firstInstance = args->instanceRule == Rule::InPlace ? record.firstInstance : args->instanceConstant; if (draw.indexed) { // The CP clamps the index range to INDEX_BUFFER_SIZE (the bound copy). const auto boundCount = inputs.indexCount.value_or(draw.indexCount); if (record.firstVertexOrIndex >= boundCount) continue; const auto vertexOffset = args->vertexRule == Rule::InPlace ? record.vertexOffset : args->vertexConstant; emitted = true; CountVkDraw(VkDrawKind::Indexed); context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, std::min(record.count, boundCount - record.firstVertexOrIndex), record.instances, record.firstVertexOrIndex, static_cast(vertexOffset), firstInstance); } else { const auto firstVertex = args->vertexRule == Rule::InPlace ? record.firstVertexOrIndex : args->vertexConstant; emitted = true; CountVkDraw(VkDrawKind::Direct); context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, record.count, record.instances, firstVertex, firstInstance); } } } return emitted; } void NoteGuestWorkIn(const Context& context, VkCommandBuffer commands) { static const bool reporting = LibcRunReportEnabled_nid_no_patch(); if (!reporting) return; if (context.recorder != nullptr && context.recorder->NoteGuestWork(commands)) return; NoteGuestWorkOnCommandBuffer(commands); } void recordDrawCommands(const Context& context, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, const IndirectRecord* indirect, VkBuffer argumentBuffer, VkDeviceSize argumentOffset, const DrawTraceContext* trace, std::uint32_t& subdraw, std::optional pieceFirstIndex = std::nullopt) { if (recordDrawCommandsImpl(context, commands, state, draw, inputs, indirect, argumentBuffer, argumentOffset, trace, subdraw, pieceFirstIndex)) NoteGuestWorkIn(context, commands); } // The GPU-side records of an indirect draw, recorded outside the render pass: the stores that // produced them (a dispatch in place, a fill, the host) precede the indirect read, as for // DISPATCH_INDIRECT; a Constant dimension is rewritten in a scratch copy (vkCmdDrawIndirect reads // the record's dword as the first vertex / instance, and the constant is what the fixed-function // fetch must start at). The scratch is kept until the batch completed. Returns whether a copy was // rewritten; `argumentBuffer`/`argumentOffset` receive where the draw reads the records. bool recordIndirectArguments(const Context& context, VkCommandBuffer commands, Recorder* recorder, bool recorded, const IndirectRecord& indirect, std::unique_ptr& scratch, std::shared_ptr& snapshot, VkBuffer& argumentBuffer, VkDeviceSize& argumentOffset, const std::function& countBarrier) { using Rule = Pm4::DrawParameters::IndirectDraw::Rule; const auto* args = indirect.args; RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT); countBarrier(1); const bool rewritten = args->vertexRule == Rule::Constant || args->instanceRule == Rule::Constant; const auto bytes = static_cast(args->RangeBytes()); const auto* source = reinterpret_cast(args->arguments); if (!args->countIndirect && bytes != 0 && !Recorder::SnapshotWriteOverlaps(args->arguments, bytes) && (recorder == nullptr || recorder->PendingLeaseSerial(args->arguments, bytes) == 0) && GuestMemory::Accessible(source, bytes, false)) { snapshot = std::make_shared(context, bytes, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT); const auto out = snapshot->Bytes(); std::memcpy(out.data(), source, bytes); for (std::uint32_t record = 0; record < args->count; ++record) { const auto base = static_cast(record) * args->stride; if (args->vertexRule == Rule::Constant) std::memcpy(out.data() + base + args->VertexDwordOffset(), &args->vertexConstant, 4); if (args->instanceRule == Rule::Constant) std::memcpy(out.data() + base + args->InstanceDwordOffset(), &args->instanceConstant, 4); } argumentBuffer = snapshot->Handle(); argumentOffset = 0; return rewritten; } if (recorded) { // Read in place from the import when the batch runs (a synchronous draw waits for its own). recorder->NotePendingRead(args->arguments, static_cast(args->RangeBytes()), Recorder::ReadKind::Indirect); if (args->countIndirect) recorder->NotePendingRead(args->countAddress, 4, Recorder::ReadKind::Indirect); } argumentBuffer = indirect.argumentImport->buffer; argumentOffset = HostImportOffset(*indirect.argumentImport, args->arguments); if (!rewritten) return false; scratch = std::make_unique(context, bytes, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); CopyBuffer(context, commands, argumentBuffer, argumentOffset, scratch->Handle(), 0, bytes); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); countBarrier(1); const auto update = context.Resolved(&DeviceFunctions::cmdUpdateBuffer, "vkCmdUpdateBuffer"); for (std::uint32_t record = 0; record < args->count; ++record) { const VkDeviceSize base = static_cast(record) * args->stride; if (args->vertexRule == Rule::Constant) update(commands, scratch->Handle(), base + args->VertexDwordOffset(), 4, &args->vertexConstant); if (args->instanceRule == Rule::Constant) update(commands, scratch->Handle(), base + args->InstanceDwordOffset(), 4, &args->instanceConstant); } RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT); countBarrier(1); argumentBuffer = scratch->Handle(); argumentOffset = 0; return true; } void recordCaptureBarrier(const Context& context, VkCommandBuffer commands) { RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_MESH_SHADER_BIT_EXT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_SHADER_READ_BIT); } std::shared_ptr meshArgumentBuffer(const Context& context, std::span restartTable) { const auto tableBytes = restartTable.empty() ? 0u : sizeof(std::uint32_t) * (restartTable.size() + 1u); auto arguments = std::make_shared(context, ShaderRecompiler::MeshArgumentBytes + tableBytes, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); if (!restartTable.empty()) { Require(restartTable.size() <= std::numeric_limits::max(), "mesh restart table is too large"); const auto length = static_cast(restartTable.size()); auto* bytes = arguments->Bytes().data() + ShaderRecompiler::MeshArgumentBytes; std::memcpy(bytes, &length, sizeof(length)); std::memcpy(bytes + sizeof(length), restartTable.data(), restartTable.size_bytes()); } return arguments; } std::shared_ptr directMeshArguments(const Context& context, const Pm4::DrawParameters& draw, std::span restartTable) { auto arguments = meshArgumentBuffer(context, restartTable); const MeshArguments resolved{0u, 0u, 0u, draw.indexCount, 0u}; std::memcpy(arguments->Bytes().data(), &resolved, sizeof(resolved)); return arguments; } std::shared_ptr recordMeshArguments(const Context& context, VkCommandBuffer commands, Recorder* recorder, bool recorded, const State& state, const Pm4::DrawParameters& draw, const IndirectRecord& indirect, const std::function& countBarrier, std::span restartTable) { const auto* args = indirect.args; const auto rules = MeshArgumentRulesFor(context, *state.stages.mesh, draw); auto arguments = meshArgumentBuffer(context, restartTable); if (indirect.path == IndirectDrawPath::Gpu && recorder != nullptr && indirect.argumentImport->address != 0) { const std::array words{rules.indexCount, rules.inputSize, rules.step, rules.primitivesPerGroup, rules.maxGroups, rules.maxInstances, rules.maxTotal, rules.firstIgnored}; if (recorder->RecordMeshArguments(commands, indirect.argumentImport->address + (args->arguments - indirect.argumentImport->base), arguments->DeviceAddress(), words)) { countBarrier(2); if (recorded) recorder->NotePendingRead(args->arguments, static_cast(args->RangeBytes()), Recorder::ReadKind::Indirect); return arguments; } } const auto record = !indirect.records.empty() ? indirect.records.front() : Pm4::ReadDrawArguments(*args, 0); const auto resolved = ResolveMeshArguments(record, rules); std::memcpy(arguments->Bytes().data(), &resolved, sizeof(resolved)); return arguments; } // Debug aid: APS5_CHECK_INDIRECT_ARGS=1 reads the records of a GPU-side draw back on the CPU once // its batch completed (the GPU has finished writing them by then) and prints the first 16, counting // records whose Constant dimension holds a value the hardware would have ignored. Empty otherwise. std::function indirectRecordCheck(const IndirectRecord* indirect) { static const bool checkArguments = std::getenv("APS5_CHECK_INDIRECT_ARGS") != nullptr; if (indirect == nullptr || indirect->args == nullptr || indirect->path != IndirectDrawPath::Gpu || !checkArguments) return {}; return [args = *indirect->args] { using Rule = Pm4::DrawParameters::IndirectDraw::Rule; static std::atomic printed{0}; static std::atomic ignoredValues{0}; static std::atomic checked{0}; try { for (std::uint32_t record = 0; record < args.count; ++record) { const auto arguments = Pm4::ReadDrawArguments(args, record); const bool ignoredVertex = args.vertexRule == Rule::Constant && (args.recordBytes == 20 ? arguments.vertexOffset : arguments.firstVertexOrIndex) != 0; const bool ignoredInstance = args.instanceRule == Rule::Constant && arguments.firstInstance != 0; ++checked; if (ignoredVertex || ignoredInstance) ++ignoredValues; if (printed.fetch_add(1) < 16) std::fprintf(stderr, "[draw] indirect record 0x%llx: count %u instances %u first %u vertexOffset %u startInstance %u (vertex %s, instance %s)\n", static_cast(args.arguments + static_cast(record) * args.stride), arguments.count, arguments.instances, arguments.firstVertexOrIndex, arguments.vertexOffset, arguments.firstInstance, args.vertexRule == Rule::Constant ? "const: record value ignored" : "in-place", args.instanceRule == Rule::Constant ? "const: record value ignored" : "in-place"); } } catch (const std::exception& error) { std::fprintf(stderr, "[draw] indirect record read-back failed: %s\n", error.what()); } if (checked % 64 == 0) std::fprintf(stderr, "[draw] indirect records checked %llu, with a value in a Constant dimension %llu\n", static_cast(checked.load()), static_cast(ignoredValues.load())); }; } std::atomic spaceKeepFailures{0}; std::atomic stopAfterResolve{0}; std::shared_ptr> reserveSpaceKeep(Recorder& recorder, const ShaderResources& resources) { if (!resources.SpaceReuse()) return nullptr; if (spaceKeepFailures.load(std::memory_order_relaxed) != 0) { spaceKeepFailures.fetch_sub(1, std::memory_order_relaxed); throw std::bad_alloc(); } auto slot = std::make_shared>(); recorder.Keep(slot); return slot; } void keepRecordedDraw(Recorder& recorder, const std::shared_ptr& resources, const std::shared_ptr& pipeline, const std::shared_ptr& framebuffer, DrawInputs& inputs, std::span> residents, std::span> slices, VkRect2D scissor, std::unique_ptr scratch, std::function checkRecords, bool listed, bool completion, const DrawOutcome& outcome, std::shared_ptr use, std::shared_ptr* spaceKeep) { std::shared_ptr scratchOwner(std::move(scratch)); recorder.ReserveRetention(4 + inputs.vertexBuffers.size() + residents.size() + (scratchOwner != nullptr ? 1u : 0u)); resources->KeepStorageImageBytes(recorder); for (const auto& target : residents) { if (target != nullptr && !target->Cached()) recorder.KeepBytes(target.get(), static_cast(target->BudgetBytes())); } recorder.Retain(resources); recorder.Retain(pipeline); recorder.Retain(framebuffer); recorder.Retain(inputs.indices); for (const auto& buffer : inputs.vertexBuffers) recorder.Retain(buffer); if (scratchOwner != nullptr) recorder.Keep(std::move(scratchOwner)); for (const auto& target : residents) recorder.Retain(target); if (resources != nullptr) recorder.KeepBytes(resources.get(), resources->CopiedBytes()); if (checkRecords) recorder.OnComplete(std::move(checkRecords)); // Counted for the [address-sync] line: a lease released by the completion (the pin waiter // finishes the recorder up to the open batch, which holds the kept resources and gets the // next serial), or waited for by the caller (any wait releases it at once). if (resources->HoldsLease()) CountLeaseOutcome(outcome.waited, outcome.waited ? 0 : recorder.Submissions() + 1, !resources->BdaReadOnly()); // Every use of a (possibly shared) resources object registers its GPU writes anew. resources->MarkGpuWrites(recorder); if (spaceKeep != nullptr) *spaceKeep = resources->ReleaseSpace(); // The write-back (fault check, copied buffers) runs when the batch completed; a fault is // reported by the recorder ("deferred write-back failed") instead of thrown out of the draw. if (listed && resources->HasCopiedWrites()) { // As VulkanDevice::dispatch lists its copied writers: delisted before the write-back // (one that fails must not keep indirect dispatches on the CPU), listed after the // registration (a throw there leaves nothing behind). auto writers = DrawCopiedWriters(); recorder.OnComplete([resources, writers] { writers->erase(std::remove(writers->begin(), writers->end(), resources), writers->end()); resources->WriteBackBuffers(); }); recorder.OnDiscard([resources, writers] { writers->erase(std::remove(writers->begin(), writers->end(), resources), writers->end()); }); writers->push_back(resources); GuestMemory::BreakProofs(); } else if (completion) { if (use != nullptr) recorder.OnComplete([resources, use] { resources->CompleteDrawUse(*use); }); else if (resources->Reusable()) recorder.OnComplete([resources] { resources->CheckFaults(); }); else recorder.OnComplete([resources] { resources->WriteBackBuffers(); }); } InlineList storeFlags; for (std::size_t index = 0; index < residents.size(); ++index) storeFlags.EmplaceBack(0); auto storeNow = storeFlags.Span(); for (std::size_t index = 0; index < residents.size(); ++index) { if (residents[index] == nullptr) continue; if (residents[index]->Descriptor().tileMode == TextureTileMode::kLinear) storeNow[index] = !residents[index]->MarkDrawn(index < slices.size() ? slices[index].first : 0u, index < slices.size() ? slices[index].second : 0u, scissor) || !residents[index]->Cached(); else if (index < slices.size()) residents[index]->MarkSliceDirty(slices[index].first, slices[index].second); else residents[index]->MarkDirty(); } for (std::size_t index = 0; index < residents.size(); ++index) { if (storeNow[index]) StorageTexture::FlushPending(residents[index]->Descriptor().baseAddress, static_cast(residents[index]->GuestBytes()), nullptr, "linear target"); } } // What recordDraw records from: the recorder, the resources, the pipeline and framebuffer, the // resident targets with their views, the indirect records (null for a direct draw), how the // completion work is handled (`listed`, `completion`, `waited`: see Draw) and, from a recipe, the // push constant block (else assembled from the stages). struct StagedWrite { std::shared_ptr temporary; VkImageView target = VK_NULL_HANDLE; std::uint16_t mask = 0; std::uint32_t samples = 1; VkRect2D area{}; }; struct BorrowedDraw { BorrowedDraw(const std::shared_ptr& resources, const std::shared_ptr& pipeline, const std::shared_ptr& framebuffer) : resources(resources), pipeline(pipeline), framebuffer(framebuffer) {} BorrowedDraw(const BorrowedDraw&) = delete; BorrowedDraw(BorrowedDraw&&) = delete; BorrowedDraw& operator=(const BorrowedDraw&) = delete; BorrowedDraw& operator=(BorrowedDraw&&) = delete; const std::shared_ptr& resources; const std::shared_ptr& pipeline; const std::shared_ptr& framebuffer; Recorder* recorder = nullptr; const State* masked = nullptr; std::span targetViews; std::span> targets; std::span> targetSlices; std::vector> multisampleTargets; std::vector> proxies; std::vector multisampleImages; std::vector staged; const IndirectRecord* indirect = nullptr; std::span moved; bool listed = false; bool completion = false; bool waited = false; const std::array* pushBytes = nullptr; VkShaderStageFlags pushStages = 0; std::vector>> stencilReplay; std::vector reordered; SampleOrderPass reorderPass; std::optional depthLocations; std::shared_ptr>* spaceKeep = nullptr; }; // A remapped viewport depth range reads its scale and offset from the draw's push block (the vertex shader's // RemapPositionDepth), so draws that differ only in them share one pipeline; the draw's own state supplies them. void patchDepthRemapPush(std::array& block, const State& state) { if (state.depthRemap.mode == 0u) return; static_assert(ShaderRecompiler::DepthRemapPushOffsetBytes + ShaderRecompiler::DepthRemapPushBytes <= PipelinePushSlotBytes); const std::array words{state.depthRemap.scale, state.depthRemap.offset}; std::memcpy(block.data() + ShaderRecompiler::DepthRemapPushOffsetBytes, words.data(), sizeof(words)); } VkFrontFace FlippedFrontFace(VkFrontFace face) { return face == VK_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; } bool StencilReplayStrip(const Context& context, const State& state, std::span shaders) { const auto same = [](const VkStencilOpState& left, const VkStencilOpState& right) { return left.failOp == right.failOp && left.passOp == right.passOp && left.depthFailOp == right.depthFailOp && left.compareOp == right.compareOp && left.compareMask == right.compareMask && left.writeMask == right.writeMask && left.reference == right.reference; }; return state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP && (state.cullMode == VK_CULL_MODE_NONE || context.graphicsPipelineLibrary) && same(state.stencilFront, state.stencilBack) && std::ranges::all_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && std::ranges::none_of(shader.program->fragmentParameters, [](const ShaderRecompiler::FragmentParameter& parameter) { return parameter.flat || parameter.perVertex || parameter.flatP10 || parameter.flatP20 || parameter.vertexOrder; }); }); } struct StencilReplayPass { std::uint32_t word; std::uint32_t reference; std::uint32_t stencilBits; bool colorAndDepth; }; std::vector StencilReplayPasses(const State& state, const Pipeline& pipeline, std::span>> replay, bool& bitwise) { std::uint32_t bits = 0; for (const auto& [reference, unused] : replay) bits |= reference; bits &= (state.stencilFront.writeMask | state.stencilBack.writeMask) & 0xffu; const auto replaces = [&](const VkStencilOpState& face) { return face.compareOp == VK_COMPARE_OP_ALWAYS && face.passOp == VK_STENCIL_OP_REPLACE && (face.depthFailOp == VK_STENCIL_OP_KEEP || !state.depthTest); }; bitwise = state.stencilTest && replaces(state.stencilFront) && replaces(state.stencilBack) && pipeline.MasksStencilReplayPasses(state) && 2u + static_cast(std::popcount(bits)) < replay.size(); std::vector passes; if (!bitwise) { for (const auto& [reference, unused] : replay) passes.push_back({reference, reference, 0xffu, true}); return passes; } passes.push_back({0xff00u, 0u, 0xffu, false}); for (std::uint32_t bit = 1u; bit <= 0x80u; bit <<= 1u) { if ((bits & bit) != 0u) passes.push_back({bit | ((~bit & 0xffu) << 8u), 0xffu, bit, false}); } passes.push_back({0xff00u, 0u, 0u, true}); static std::once_flag logged; std::call_once(logged, [&] { APS5_LOG_OUT("Stencil replay: a draw writes its exported stencil one bit per pass, recording %zu passes per triangle and instance in place of %zu", passes.size(), replay.size()); }); return passes; } void recordStencilReplay(const Context& context, CommandState& recording, const State& state, const State* masked, const Pm4::DrawParameters& draw, const DrawInputs& inputs, std::span>> replay, std::span shaders, const ShaderResources& resources, const std::array* bytes = nullptr, VkShaderStageFlags stages = 0) { const auto commands = recording.Commands(); State selected = state; auto block = bytes != nullptr ? *bytes : AssemblePushConstants(shaders); if (bytes == nullptr) { resources.PatchPushConstants(block); stages = PushConstantStages(shaders); } patchDepthRemapPush(block, state); const auto fragment = std::ranges::find_if(shaders, [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::Fragment && !shader.program->stencilReferences.empty(); }); Require(fragment != shaders.end(), "stencil replay fragment stage is missing"); const auto referenceOffset = fragment->pushConstantOffset + fragment->program->stencilReferenceDword * sizeof(std::uint32_t); Require(referenceOffset <= block.size() - sizeof(std::uint32_t), "stencil replay reference exceeds the push block"); const bool faceDynamic = state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP && state.cullMode != VK_CULL_MODE_NONE; Require(!replay.empty(), "stencil replay has no reference values"); const auto& pipeline = *replay.front().second; bool bitwise = false; const auto passes = StencilReplayPasses(state, pipeline, replay, bitwise); const auto run = [&](const Pm4::DrawParameters& piece, std::optional firstIndex, bool reversed) { std::uint32_t unusedSubdraw = 0; for (const auto& pass : passes) { selected.stencilReplayReference = pass.reference; if (faceDynamic) recording.SetFrontFace(context, reversed ? FlippedFrontFace(state.frontFace) : state.frontFace); if (bitwise) pipeline.SetStencilReplayMasks(recording, state, masked, pass.colorAndDepth, pass.stencilBits); selected.stencilFront.reference = pass.reference; selected.stencilBack.reference = pass.reference; recording.SetStencilReference(context, VK_STENCIL_FACE_FRONT_AND_BACK, pass.reference); std::memcpy(block.data() + referenceOffset, &pass.word, sizeof(pass.word)); pipeline.PushConstants(commands, stages, block); recordDrawCommands(context, commands, selected, piece, inputs, nullptr, VK_NULL_HANDLE, 0, nullptr, unusedSubdraw, firstIndex); } }; if (passes.size() == 1u) { run(draw, std::nullopt, false); return; } const auto indexCount = draw.indexed ? inputs.indexCount.value_or(draw.indexCount) : draw.indexCount; const bool strip = state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; const std::uint32_t triangles = strip ? (indexCount >= 3u ? indexCount - 2u : 0u) : indexCount / 3u; for (std::uint32_t instance = 0; instance < draw.instanceCount; ++instance) { for (std::uint32_t triangle = 0; triangle < triangles; ++triangle) { const std::uint32_t first = strip ? triangle : triangle * 3u; auto piece = draw; piece.instanceCount = 1u; piece.firstInstance = draw.firstInstance + instance; piece.indexCount = 3u; if (!draw.indexed) piece.firstVertex += first; run(piece, draw.indexed ? first : 0u, strip && (triangle & 1u) != 0u); } } if (bitwise) pipeline.SetStencilReplayMasks(recording, state, masked, true, 0xffu); } void pushDrawConstants(const Pipeline& pipeline, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, std::span shaders, const ShaderResources& resources, const std::array* bytes, VkShaderStageFlags stages, VkDeviceAddress meshArguments = 0, bool restartTable = false, std::uint32_t meshLayerStride = 0) { auto block = bytes != nullptr ? *bytes : AssemblePushConstants(shaders); if (bytes == nullptr) { resources.PatchPushConstants(block); stages = PushConstantStages(shaders); } patchDepthRemapPush(block, state); if (state.stages.tessellation) { for (const auto& shader : shaders) Require(shader.program->pushConstants.empty() || shader.pushConstantOffset >= PipelinePushSlotBytes || shader.pushConstantOffset + shader.program->pushConstants.size() <= ShaderRecompiler::TessellationLevelPushOffsetBytes, "a stage's push constants overlap the tessellation levels"); const std::array levels{state.stages.minTessellationLevel, state.stages.maxTessellationLevel}; static_assert(ShaderRecompiler::TessellationLevelPushOffsetBytes + ShaderRecompiler::TessellationLevelPushBytes == PipelinePushSlotBytes); std::memcpy(block.data() + ShaderRecompiler::TessellationLevelPushOffsetBytes, levels.data(), sizeof(levels)); } const auto capturedItems = state.tessellationCapture != nullptr ? state.tessellationCapture->items->DeviceAddress() : 0; if (!state.stages.mesh) { if (state.tessellationCapture != nullptr) { for (const auto& shader : shaders) Require(shader.program->pushConstants.empty() || shader.pushConstantOffset >= PipelinePushSlotBytes || shader.pushConstantOffset + shader.program->pushConstants.size() <= ShaderRecompiler::MeshDrawPushOffsetBytes, "a stage's push constants overlap the tessellation capture addresses"); const auto header = state.tessellationCapture->header->DeviceAddress(); const std::array words{static_cast(capturedItems), static_cast(capturedItems >> 32u), static_cast(header), static_cast(header >> 32u)}; static_assert(ShaderRecompiler::MeshDrawPushOffsetBytes + sizeof(std::uint32_t) * 4 <= ShaderRecompiler::TessellationLevelPushOffsetBytes); std::memcpy(block.data() + ShaderRecompiler::MeshDrawPushOffsetBytes, words.data(), sizeof(words)); stages |= VK_SHADER_STAGE_GEOMETRY_BIT; } pipeline.PushConstants(commands, stages, block); return; } const auto firstVertex = draw.indirect ? draw.indirect->vertexConstant : draw.firstVertex; const auto firstInstance = draw.indirect ? draw.indirect->instanceConstant : draw.firstInstance; std::array words{draw.indexCount, firstVertex, firstInstance, (draw.indexed ? draw.indexSize | (restartTable ? ShaderRecompiler::MeshIndexRestartTable : 0u) : 0u) | meshLayerStride << ShaderRecompiler::MeshLayerStrideShift, static_cast(meshArguments), static_cast(meshArguments >> 32u)}; if (state.tessellationCapture != nullptr) words = {static_cast(capturedItems), static_cast(capturedItems >> 32u), 0u, 0u, static_cast(meshArguments), static_cast(meshArguments >> 32u)}; static_assert(ShaderRecompiler::MeshDrawPushOffsetBytes + ShaderRecompiler::MeshDrawPushBytes == PipelinePushSlotBytes); std::memcpy(block.data() + ShaderRecompiler::MeshDrawPushOffsetBytes, words.data(), sizeof(words)); pipeline.PushConstants(commands, stages | VK_SHADER_STAGE_MESH_BIT_EXT, block); } // The record of a draw whose targets are all resident (`lean`: recorded into the device's open // batch, rendering in the general layout): one memory barrier before the pass (earlier writes to // the attachments and the draw's inputs visible to it) and one after it, recorded by the recorder // when the pass ends (Recorder::LeaveRenderPassOpen), so consecutive draws into the same // attachments with nothing recorded between them share one pass; the host-write and host-read // barriers are implicit in the submission and the fence. Then the kept objects, the completion // work and, for a waited-for draw, the recorder sync. bool CaptureInputsEnabled() { static const bool enabled = std::getenv("APS5_CAPTURE_INPUTS") != nullptr; Require(!enabled || CaptureTrace::Enabled(), "APS5_CAPTURE_INPUTS requires APS5_CAPTURE_TRACE"); return enabled; } void captureInputs(const Context& context, Recorder& recorder, VkCommandBuffer commands, const ShaderResources& resources, const std::shared_ptr& bindings, std::uint64_t target) { struct Sample { std::uint64_t address; std::size_t offset; std::vector expected; VkBuffer source; VkDeviceSize sourceOffset; }; static unsigned long long nextDraw = 0; const auto draw = ++nextDraw; const auto batch = static_cast(recorder.Submissions() + 1); std::vector samples; std::size_t total = 0; const auto addSample = [&](std::uint64_t address, std::size_t bytes, VkBuffer source, VkDeviceSize offset, const std::byte* expected) { if (bytes == 0 || bytes > 512) return; Require(offset % 4 == 0 && bytes % 4 == 0, "capture input is not aligned for a Vulkan buffer copy"); Require(total + bytes <= 65536, "capture inputs exceed 64 KiB per draw"); Sample sample{address, total, std::vector(bytes), source, offset}; std::memcpy(sample.expected.data(), expected, bytes); total += bytes; samples.push_back(std::move(sample)); }; if (bindings != nullptr) { for (const auto& snapshot : bindings->snapshots) { if (snapshot.buffer == nullptr) continue; const auto bytes = snapshot.Bytes(); addSample(snapshot.address, bytes.size(), snapshot.buffer->Handle(), snapshot.offset, bytes.data()); } } for (const auto& [begin, end] : resources.InPlaceReads()) { Require(end >= begin, "invalid capture input range"); const auto bytes = static_cast(end - begin); if (bytes == 0 || bytes > 512) continue; if (bindings != nullptr && std::any_of(bindings->snapshots.begin(), bindings->snapshots.end(), [&](const auto& snapshot) { return snapshot.address < end && begin < snapshot.address + snapshot.bytes; })) continue; if (resources.WritesOverlap(begin, bytes) || recorder.PendingWriteOverlaps(begin, bytes)) { CaptureTrace::Log("input-skip draw=%llu batch=%llu address=%llx bytes=%zu reason=gpu-writer", draw, batch, static_cast(begin), bytes); continue; } const auto* imported = HostImportFor(context, begin, bytes); Require(imported != nullptr, "capture input has no host import"); addSample(begin, bytes, imported->buffer, HostImportOffset(*imported, begin), reinterpret_cast(begin)); } CaptureTrace::Log("input-capture draw=%llu batch=%llu target=%llx ranges=%zu bytes=%zu", draw, batch, static_cast(target), samples.size(), total); if (samples.empty()) return; auto readback = std::make_shared(context, total, VK_BUFFER_USAGE_TRANSFER_DST_BIT); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); const auto copy = context.Function("vkCmdCopyBuffer"); for (const auto& sample : samples) { const VkBufferCopy region{sample.sourceOffset, sample.offset, sample.expected.size()}; copy(commands, sample.source, readback->Handle(), 1, ®ion); } RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT); recorder.OnComplete([draw, batch, target, readback, samples = std::move(samples)] { const auto actual = readback->Bytes(); std::size_t differences = 0; for (const auto& sample : samples) { std::size_t changed = 0; for (std::size_t index = 0; index < sample.expected.size(); ++index) { const auto gpu = actual[sample.offset + index]; if (sample.expected[index] == gpu) continue; if (changed < 16) CaptureTrace::Log("input-byte draw=%llu batch=%llu address=%llx offset=%zu cpu=%02x gpu=%02x", draw, batch, static_cast(sample.address), index, std::to_integer(sample.expected[index]), std::to_integer(gpu)); ++changed; } if (changed != 0) { ++differences; CaptureTrace::Log("input-mismatch draw=%llu batch=%llu target=%llx address=%llx bytes=%zu changed=%zu", draw, batch, static_cast(target), static_cast(sample.address), sample.expected.size(), changed); } } CaptureTrace::Log("input-result draw=%llu batch=%llu ranges=%zu mismatched=%zu", draw, batch, samples.size(), differences); }); } bool WriteOnlyPasses() { static const bool enabled = std::getenv("APS5_NO_WRITE_ONLY_PASSES") == nullptr; return enabled; } void recordDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, DrawInputs& inputs, BorrowedDraw& record, DrawOutcome& outcome, DrawTimer& timer, double& ownWaitedMs, const DrawTraceContext* trace = nullptr) { std::uint32_t subdraw = 0; auto* recorder = record.recorder; auto& resources = *record.resources; const auto* args = record.indirect != nullptr ? record.indirect->args : nullptr; const bool gpuIndirect = args != nullptr && record.indirect->path == IndirectDrawPath::Gpu; using CommandClass = Recorder::CommandClass; const auto countBarrier = [&](std::uint32_t count) { Recorder::CountBarriers(CommandClass::Draw, count); }; // The pass is named by its attachment views (stable while the kept targets live, so unique // within the open batch) and the extent. The previous draw's pass is continued only when this // draw neither reads its attachments (a barrier would be owed, which no pass allows) nor // records anything outside a pass (an indirect draw's argument barrier and scratch copies). const auto passKey = DrawRenderPassKey(context, state, record.targetViews); const bool readsTarget = std::any_of(record.targets.begin(), record.targets.end(), [&](const std::shared_ptr& target) { return resources.ReadsImage(target.get()); }); // A queued DCC key store over memory the draw writes or reads in place (unknown for an // address-based build), or over its GPU-side records, lands before it, as before a dispatch // (VulkanDevice::dispatch); the flush ends an open pass, so it comes before the decision. const auto touches = [&](std::uint64_t begin, std::uint64_t end) { const auto bytes = static_cast(end - begin); if (resources.WritesOverlap(begin, bytes) || resources.ReadsOverlap(begin, bytes)) return true; if (!gpuIndirect) return false; return (begin < args->arguments + args->RangeBytes() && args->arguments < end) || (args->countIndirect && begin < args->countAddress + 4 && args->countAddress < end); }; if (recorder->HasQueuedKeyStores() && (resources.HoldsLease() || recorder->AnyQueuedKeyStore(touches))) { recorder->FlushKeyStores(); outcome.keyStoresFlushed = true; } // A queued label store over such memory likewise (Recorder::RecordStore). if (recorder->HasQueuedStores() && (resources.HoldsLease() || recorder->AnyQueuedStore(touches))) { recorder->FlushStores(); outcome.storesFlushed = true; } const bool capture = CaptureInputsEnabled(); const bool meshIndirect = state.stages.mesh && args != nullptr; const bool captured = state.stages.mesh && state.tessellationCapture != nullptr; const bool addressBased = resources.HoldsLease(); thread_local std::vector>* passReadsSlot = nullptr; auto& passReads = ShaderRecompiler::ThreadOwned(passReadsSlot); passReads.clear(); if (!addressBased) resources.DeviceReads(passReads); const auto deviceReads = passReads.size(); if (gpuIndirect) { passReads.emplace_back(args->arguments, args->arguments + args->RangeBytes()); if (args->countIndirect) passReads.emplace_back(args->countAddress, args->countAddress + 4); } passReads.insert(passReads.end(), inputs.inPlaceReads.begin(), inputs.inPlaceReads.end()); for (const auto& entry : record.moved) { if (entry.inPlace == VK_NULL_HANDLE) continue; const auto begin = entry.address - entry.adjustment; passReads.emplace_back(begin, begin + GuestBufferMemory::ViewBytes(entry.size, entry.adjustment)); } thread_local std::vector>* passImagesSlot = nullptr; auto& passImages = ShaderRecompiler::ThreadOwned(passImagesSlot); resources.StorageImages(passImages); InlineList passAttachments; for (std::size_t index = 0; index < record.targets.size(); ++index) { const auto& target = record.targets[index]; if (target == nullptr) continue; if (index < state.colors.size()) { const auto& color = state.colors[index]; const std::uint32_t firstSlice = target->ImageDepth() > 1u ? color.depthSlice : color.arraySlice; const std::uint32_t sliceCount = target->ImageDepth() > 1u || color.arrayLastSlice != 0u ? color.layers : 1u; passAttachments.EmplaceBack(PassAttachment{target->Image(), true, color.mip, firstSlice, sliceCount}); } else { passAttachments.EmplaceBack(PassAttachment{target->Image(), true, 0u, 0u, 0u}); } } for (const auto image : record.multisampleImages) passAttachments.EmplaceBack(PassAttachment{image, true, 0u, 0u, 0u}); const bool unknownMemory = addressBased || resources.UsesAddressTable() || resources.HasCopiedWrites(); static_cast(StorageTexture::StoreDrawnLinearTouching("draw access", [&](std::uint64_t begin, std::uint64_t end) { return std::any_of(passReads.begin(), passReads.end(), [&](const auto& read) { return read.first < end && begin < read.second; }) || resources.WritesOverlap(begin, static_cast(end - begin)); }, unknownMemory)); const auto drawUse = resources.BeginDrawUse(*recorder); const auto drawBindings = resources.PrepareDrawBindings(*recorder, record.moved, false, drawUse != nullptr ? drawUse->record.get() : nullptr); static const bool addressReadPasses = std::getenv("APS5_NO_ADDRESS_READ_PASSES") == nullptr; const bool readOnlyBda = addressReadPasses && resources.BdaReadOnly(); outcome.addressDraw = addressBased; const bool unknownWrites = ((addressBased || resources.UsesAddressTable()) && !readOnlyBda) || resources.HasCopiedWrites(); GuestRangeList passWrites = resources.GpuWrites(); GuestRangeList passWriteOnly{}; thread_local std::vector>* hazardWritesSlot = nullptr; if (const auto& writeOnly = resources.WriteOnlyRanges(); !writeOnly.empty() && !unknownMemory && WriteOnlyPasses()) { const auto listed = [&](const std::pair& range, bool aligned) { return std::any_of(writeOnly.begin(), writeOnly.end(), [&](const auto& only) { if (!aligned) return only == range; const auto begin = only.first & ~std::uint64_t{3}; const auto end = begin == only.first ? only.second : (only.second + 3) & ~std::uint64_t{3}; return range.first == begin && range.second == end; }); }; const auto ownReads = passReads.begin() + static_cast(deviceReads); passReads.erase(std::remove_if(passReads.begin(), ownReads, [&](const auto& range) { return listed(range, true); }), ownReads); auto& hazardWrites = ShaderRecompiler::ThreadOwned(hazardWritesSlot); hazardWrites.clear(); for (const auto& range : resources.GpuWrites()) { if (!listed(range, false)) hazardWrites.push_back(range); } passWrites = hazardWrites; passWriteOnly = writeOnly; } const PassAccess passAccess{passReads, passWrites, passImages, passAttachments.Span(), unknownMemory, unknownWrites, passWriteOnly}; const bool fenced = state.depth.has_value() || !record.proxies.empty(); resources.RequireGuestBuffers(); if (UsesMeshWindow(shaders)) PrepareMeshWindow(context); const auto start = recorder->StartDrawPass(passKey, inputs.indexInputBehindGpuWrite || capture || readsTarget || gpuIndirect || meshIndirect || captured || !record.staged.empty() || PixelFunctionLdsSubgroup(shaders) != 0u, fenced, passAccess); if (record.spaceKeep != nullptr) *record.spaceKeep = reserveSpaceKeep(*recorder, resources); for (const auto& target : record.multisampleTargets) KeepMultisampleTarget_nid_no_patch(target); const bool continued = start.continued; outcome.passContinued = continued; outcome.passBegun = !continued; outcome.passBreak = start.reason; const auto commands = start.commands; auto& recording = recorder->GraphicsState(); if (!continued) { recorder->PrepareSampleSlot(); PerformanceTrace::Amount(PerformanceTrace::RenderPassScope, 1); } if (capture) captureInputs(context, *recorder, commands, resources, drawBindings, record.targets.empty() || record.targets.front() == nullptr ? 0 : record.targets.front()->Descriptor().baseAddress); // The draw's [gputime] class range: from its first barrier to the pass's trailing barrier (a // continued draw lies inside its pass's range). const auto drawTiming = !continued ? recorder->BeginGpuTiming(CommandClass::Draw) : Recorder::NoTiming; if (!continued && Recorder::BarrierValidate()) { auto reads = resources.InPlaceReads(); reads.insert(reads.end(), inputs.inPlaceReads.begin(), inputs.inPlaceReads.end()); if (gpuIndirect) { reads.emplace_back(args->arguments, args->arguments + args->RangeBytes()); if (args->countIndirect) reads.emplace_back(args->countAddress, args->countAddress + 4); } auto images = resources.StorageImages(); for (const auto& target : record.targets) { if (target != nullptr) images.emplace_back(target->Image(), true); } recorder->NoteAccess(CommandClass::Draw, Recorder::Access{reads, resources.GpuWrites(), images, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | inputs.shaderStages, resources.HoldsLease()}); } std::unique_ptr scratch; std::shared_ptr argumentSnapshot; std::shared_ptr meshArguments; VkBuffer argumentBuffer = VK_NULL_HANDLE; VkDeviceSize argumentOffset = 0; bool rewritten = false; if (!meshIndirect && !inputs.restartTable.empty()) meshArguments = directMeshArguments(context, draw, inputs.restartTable); if (continued) { record.pipeline->Continue(recording, state, record.masked); } else { for (const auto& proxy : record.proxies) { proxy->RecordAttachmentProxyLoad(commands, VK_IMAGE_LAYOUT_GENERAL); countBarrier(2); } if (start.barrier) { const VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT}; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, 1, &before, 0, nullptr, 0, nullptr); countBarrier(1); } APS5_LOG_CHARS_OUT_DEBUG("Upload barrier recorded"); if (inputs.vertexInputBehindGpuWrite || inputs.indexInputBehindGpuWrite) { RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, (inputs.vertexInputBehindGpuWrite ? VkAccessFlags{VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT} : VkAccessFlags{0}) | (inputs.indexInputBehindGpuWrite ? VkAccessFlags{VK_ACCESS_INDEX_READ_BIT} : VkAccessFlags{0})); countBarrier(1); } const auto pixelLdsSubgroup = PixelFunctionLdsSubgroup(shaders); if (pixelLdsSubgroup != 0u) PreparePixelFunctionLds(context, commands, pixelLdsSubgroup); if (captured) { recordCaptureBarrier(context, commands); countBarrier(1); meshArguments = state.tessellationCapture->header; argumentBuffer = meshArguments->Handle(); } else if (meshIndirect) { meshArguments = recordMeshArguments(context, commands, recorder, true, state, draw, *record.indirect, countBarrier, inputs.restartTable); argumentBuffer = meshArguments->Handle(); } else if (gpuIndirect) { rewritten = recordIndirectArguments(context, commands, recorder, true, *record.indirect, scratch, argumentSnapshot, argumentBuffer, argumentOffset, countBarrier); } // Earlier recorded work (dispatches, the previous draw) wrote the images in the general // layout, which a lean draw renders in: no transitions. if (!record.reordered.empty()) { std::vector> kept; RecordSampleOrder(context, recording, record.reorderPass, record.reordered, true, kept); for (auto& object : kept) recorder->Keep(std::move(object)); } for (const auto& write : record.staged) RecordStagedClear(context, commands, *write.temporary); APS5_LOG_OUT_DEBUG("Beginning pipeline renderExtent=%ux%u", state.renderExtent.width, state.renderExtent.height); record.pipeline->Begin(recording, *record.framebuffer, state.renderExtent, state, record.masked); } APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); if (drawBindings != nullptr) { const auto set = drawBindings->allocation.set; const auto fragmentSet = drawBindings->fragmentAllocation.set; if (set != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), 0, 1, &set, 0, nullptr); if (fragmentSet != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, 0, nullptr); } else { resources.BindDrawUse(commands, record.pipeline->Layout(), drawUse.get()); } if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; })) BindPixelFunctionLds(context, commands, record.pipeline->Layout()); if (UsesMeshWindow(shaders)) BindMeshWindow(context, commands, record.pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); std::array movedPush; const std::array* pushBytes = record.pushBytes; VkShaderStageFlags pushStages = record.pushStages; if (ShaderResources::MovedPushPatches(record.moved)) { movedPush = pushBytes != nullptr ? *pushBytes : AssemblePushConstants(shaders); if (pushBytes == nullptr) resources.PatchPushConstants(movedPush); if (resources.PatchMovedPushConstants(movedPush, record.moved)) { if (pushBytes == nullptr) pushStages = PushConstantStages(shaders); pushBytes = &movedPush; } } pushDrawConstants(*record.pipeline, commands, state, draw, shaders, resources, pushBytes, pushStages, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty(), inputs.meshLayerStride); APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded"); static const bool timeEachDraw = std::getenv("APS5_PROFILE_GPU_DRAWS") != nullptr; auto eachDrawTiming = Recorder::NoTiming; if (timeEachDraw && Recorder::GpuTimingEnabled()) { if (Recorder::DrawStageTimingEnabled()) { std::vector> stages; for (const auto& shader : shaders) { if (shader.program != nullptr) stages.emplace_back(static_cast(shader.stage), shader.program->variantId); } eachDrawTiming = recorder->BeginInPassGpuTiming(Recorder::DrawStageTimingKey(stages)); } else { std::uint64_t key = 0; for (const auto& shader : shaders) { if (shader.program != nullptr && (key == 0 || shader.stage == ShaderRecompiler::ShaderStage::Fragment)) key = shader.program->variantId; } eachDrawTiming = recorder->BeginInPassGpuTiming(Recorder::DrawTimingKey(key)); } } noteDrawFaultToken(context, *recorder, commands, shaders, draw, static_cast(state.stages.mesh.has_value() ? AgcDriver::FaultStage::mesh : AgcDriver::FaultStage::graphics), record.indirect != nullptr ? record.indirect->args : nullptr); if (record.stencilReplay.empty()) recordDrawCommands(context, commands, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); else { recordStencilReplay(context, recording, state, record.masked, draw, inputs, record.stencilReplay, shaders, resources, pushBytes, pushStages); for (const auto& [reference, pipeline] : record.stencilReplay) recorder->Keep(pipeline); } if (record.pipeline->SplitsFaces()) { record.pipeline->ContinueBackFaces(recording, state, record.masked); recordDrawCommands(context, commands, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); } if (record.pipeline->SplitsSecondChannel()) { record.pipeline->ContinueSecondChannel(recording, state, record.masked); recordDrawCommands(context, commands, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); } recorder->EndGpuTiming(eachDrawTiming); if (meshArguments != nullptr) recorder->Keep(meshArguments); if (argumentSnapshot != nullptr) recorder->Keep(argumentSnapshot); if (state.tessellationCapture != nullptr) { recorder->Keep(state.tessellationCapture->header); recorder->Keep(state.tessellationCapture->items); } if (args != nullptr) CountIndirectDraw(record.indirect->path, record.indirect->readMs, rewritten); auto checkRecords = indirectRecordCheck(record.indirect); APS5_LOG_CHARS_OUT_DEBUG("Draw recorded"); std::function storeProxies; if (!continued && (!record.proxies.empty() || !record.reordered.empty() || record.depthLocations)) { storeProxies = [proxies = record.proxies, reordered = record.reordered, reorderPass = record.reorderPass, depthLocations = record.depthLocations, context, recorder](CommandState& passRecording) { const auto passCommands = passRecording.Commands(); for (const auto& proxy : proxies) { proxy->RecordAttachmentProxyStore(passCommands, VK_IMAGE_LAYOUT_GENERAL); Recorder::CountBarriers(Recorder::CommandClass::Draw, 2); } if (!reordered.empty()) { std::vector> kept; RecordSampleOrder(context, passRecording, reorderPass, reordered, false, kept); for (auto& object : kept) recorder->Keep(std::move(object)); } if (depthLocations) { RecordDepthSampleLocations(context, passCommands, *depthLocations); Recorder::CountBarriers(Recorder::CommandClass::Draw, 2); recorder->Keep(depthLocations->keep); } }; } recorder->LeaveRenderPassOpen(passKey, drawTiming, fenced, passAccess, std::move(storeProxies)); timer.phase(PhaseRecord); keepRecordedDraw(*recorder, record.resources, record.pipeline, record.framebuffer, inputs, record.targets, record.targetSlices, state.scissor, std::move(scratch), std::move(checkRecords), record.listed, record.completion, outcome, drawUse, record.spaceKeep != nullptr && *record.spaceKeep != nullptr ? record.spaceKeep->get() : nullptr); timer.phase(PhaseKeep); if (!record.staged.empty()) { const auto merged = recorder->Commands(); for (auto& write : record.staged) { RecordStagedMerge(context, merged, *write.temporary, write.target, write.mask, write.samples, write.area); recorder->Keep(write.temporary); } } if (record.waited) { // The wait the dispatch path makes for such work (source 3, "address-based"): the // write-back runs before the next packet, so the CPU never reads copied results or // touches a leased allocation before they landed. Recorder::CountSync(3); const auto ownBefore = timer.profile ? Recorder::ThreadWaitedMs() : 0.0; recorder->Sync(); if (timer.profile) ownWaitedMs += Recorder::ThreadWaitedMs() - ownBefore; timer.phase(PhaseSync); } } // The state with the outputs the pixel shader lacks masked: Vulkan leaves attachments a pixel // shader has no output for undefined, so their writes are masked (shaders that only store to // images or buffers keep their targets as they were). Empty when no mask must change. std::optional maskedState(const State& state, std::uint32_t fragmentOutputs) { std::optional masked; for (std::size_t index = 0; index < state.blends.size(); ++index) { if ((index < 32 && ((fragmentOutputs >> index) & 1u) != 0) || state.blends[index].colorWriteMask == 0) continue; if (!masked.has_value()) masked = state; masked->blends[index].colorWriteMask = 0; } return masked; } std::optional passDepthLocations(const Context& context, const State& state, const Pipeline& pipeline) { if (!state.depth || state.depth->samples <= 1u || !state.customSampleLocations || !pipeline.SampleLocationsEnabled()) return std::nullopt; auto locations = DepthSurfaceSampleLocations(context, *state.depth); locations.grid = pipeline.HostSampleLocationGrid(); locations.locations = SampleLocations(state); return locations; } // Debug aid: APS5_DUMP_TARGETS= saves the first n renders of every color target as a raw file // (u32 width, u32 height, u32 VkFormat, then tightly packed rows). int DumpTargetLimit() { static const int dumpLimit = [] { const char* text = std::getenv("APS5_DUMP_TARGETS"); return text ? std::atoi(text) : 0; }(); return dumpLimit; } // A draw whose targets are all resident is recorded into the device's open batch like a dispatch: // the CPU does not wait for it, and the drain before it goes away (queue order and the barriers // keep it behind earlier recorded work); see `recorded` in Draw for the buffers that still need a // synchronous draw. Other draws keep their own synchronous batch. Debug aid: APS5_SYNC_DRAWS=1 // makes every draw synchronous. bool RecordDraws() { static const bool recordDraws = std::getenv("APS5_SYNC_DRAWS") == nullptr; return recordDraws; } } std::optional KnownValidationFailure(const Context& context, std::span shaders, const State& state) { auto& key = validationKeyScratch(); if (!ValidationKey(context, shaders, state, key)) return std::nullopt; std::lock_guard lock(validationMutex()); const auto& failures = validationFailures(); if (const auto found = failures.find(key); found != failures.end()) return found->second; return std::nullopt; } namespace { struct TargetBinding { ColorTarget color; bool gpuTiling = false; std::shared_ptr resident; bool proxied = false; std::unique_ptr transfer; bool banded = false; VkRect2D band{}; std::size_t bandOffset = 0; std::uint32_t bandPitch = 0; std::unique_ptr tiled; std::unique_ptr tiledDevice; std::unique_ptr linearDevice; std::vector original; TileMipLayout mip{}; std::unique_ptr target; bool multisampled = false; VkImage multisampleImage = VK_NULL_HANDLE; std::shared_ptr multisampleOwner; std::shared_ptr stagedTemporary; VkImageView stagedTarget = VK_NULL_HANDLE; std::unique_ptr dump; }; struct PreparedDraw { explicit PreparedDraw(bool profile) : timer(profile) {} PreparedDraw(const PreparedDraw&) = delete; PreparedDraw& operator=(const PreparedDraw&) = delete; std::shared_ptr* recipeOut = nullptr; const DrawTraceContext* trace = nullptr; std::uint64_t shape = 0; const std::vector* contentKey = nullptr; bool passAttachments = false; bool attachmentsFromMemo = false; std::vector stencilReferences; std::optional timing; DrawTimer timer; DrawOutcome outcome; const ShaderResources::BuildTiming* built = nullptr; double waitedBefore = 0; double ownWaitedMs = 0; DrawInputs inputs; const Pm4::DrawParameters::IndirectDraw* args = nullptr; int dumpLimit = 0; std::vector targets; std::vector targetViews; Recorder* recorder = nullptr; ResolvedResources resolved; IndirectRecord indirect; std::vector records; bool completion = false; bool listed = false; bool recorded = false; bool lean = false; bool multisampled = false; std::optional masked; std::vector>> stencilReplay; std::shared_ptr pipeline; std::vector> owners; std::vector> framebufferOwners; std::shared_ptr framebuffer; std::vector reordered; SampleOrderPass reorderPass; std::optional depthLocations; std::shared_ptr> spaceKeep; }; void keepHeldSpace(PreparedDraw& prepared) { const auto& resources = prepared.resolved.resources; if (prepared.spaceKeep != nullptr || prepared.recorder == nullptr || resources == nullptr || !resources->SpaceReuse() || !resources->SpaceHeld()) return; prepared.spaceKeep = reserveSpaceKeep(*prepared.recorder, *resources); } bool ShapeMemoEnabled() { static const bool enabled = std::getenv("APS5_NO_SHAPE_MEMO") == nullptr; return enabled; } bool VerifyShapeMemo() { static const bool verify = std::getenv("APS5_VERIFY_SHAPE_MEMO") != nullptr; return verify; } void noteShapeMemoVerified(bool pipeline) { static std::atomic targets{0}; static std::atomic pipelines{0}; static std::atomic last{0}; (pipeline ? pipelines : targets).fetch_add(1, std::memory_order_relaxed); const auto now = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); auto previous = last.load(std::memory_order_relaxed); if (now - previous < 10 || !last.compare_exchange_strong(previous, now)) return; std::fprintf(stderr, "[shape-memo] verified %llu targets and %llu pipelines\n", static_cast(targets.load()), static_cast(pipelines.load())); } struct ShapeChoice { VkImageLayout attachmentLayout = VK_IMAGE_LAYOUT_UNDEFINED; std::uint32_t fragmentOutputs = 0; std::vector stages; std::vector bindings; std::vector attributes; std::vector mainKey; std::vector fragmentKey; std::uint64_t hash = 0; std::weak_ptr pipeline; }; struct ShapeEntry { VkDevice device = VK_NULL_HANDLE; std::vector> targets; std::vector choices; }; struct ShapeMemoStorage {}; constexpr std::size_t ShapeMemoEntries = 4096; constexpr std::size_t ShapeMemoChoices = 4; std::unordered_map& shapeMemo() { return HostThreadLocal, ShapeMemoStorage>(); } const ShapeEntry* findShape(const Context& context, std::uint64_t shape) { if (shape == 0 || !ShapeMemoEnabled()) return nullptr; const auto& entries = shapeMemo(); const auto found = entries.find(shape); return found == entries.end() || found->second.device != context.device ? nullptr : &found->second; } std::shared_ptr shapeTarget(const Context& context, std::uint64_t shape, std::size_t index) { const auto* entry = findShape(context, shape); return entry == nullptr || index >= entry->targets.size() ? nullptr : entry->targets[index].lock(); } bool sameStages(std::span kept, std::span shaders) { if (kept.size() != shaders.size() * 4u + 1u) return false; std::size_t at = 0; for (const auto& shader : shaders) { const auto identity = shader.program->Identity(); if (identity.Empty() || kept[at] != static_cast(shader.stage) || kept[at + 1] != identity.low || kept[at + 2] != identity.high || kept[at + 3] != KeyedPushOffset(shader)) return false; at += 4; } return kept[at] == PushConstantStages(shaders); } bool sameChoice(const ShapeChoice& choice, const VertexInputLayout& input, const PipelineSetLayouts& layouts, std::span shaders, VkImageLayout attachmentLayout, std::uint32_t fragmentOutputs) { const auto sameBinding = [](const VkVertexInputBindingDescription& a, const VkVertexInputBindingDescription& b) { return a.binding == b.binding && a.stride == b.stride && a.inputRate == b.inputRate; }; const auto sameAttribute = [](const VkVertexInputAttributeDescription& a, const VkVertexInputAttributeDescription& b) { return a.location == b.location && a.binding == b.binding && a.format == b.format && a.offset == b.offset; }; return choice.attachmentLayout == attachmentLayout && choice.fragmentOutputs == fragmentOutputs && std::ranges::equal(choice.bindings, input.bindings, sameBinding) && std::ranges::equal(choice.attributes, input.attributes, sameAttribute) && std::ranges::equal(choice.mainKey, layouts.mainKey) && std::ranges::equal(choice.fragmentKey, layouts.fragmentKey) && sameStages(choice.stages, shaders); } std::shared_ptr shapePipeline(const Context& context, std::uint64_t shape, const VertexInputLayout& input, const PipelineSetLayouts& layouts, std::span shaders, VkImageLayout attachmentLayout, std::uint32_t fragmentOutputs) { const auto* entry = findShape(context, shape); if (entry == nullptr) return nullptr; for (const auto& choice : entry->choices) { if (!sameChoice(choice, input, layouts, shaders, attachmentLayout, fragmentOutputs)) continue; const auto hash = choice.hash; const auto& expected = choice.pipeline; return TouchCachedPipeline(context, hash, expected); } return nullptr; } void rememberShape(const Context& context, std::uint64_t shape, std::span targets, const std::shared_ptr* pipeline, std::uint64_t hash, const VertexInputLayout& input, const PipelineSetLayouts& layouts, std::span shaders, VkImageLayout attachmentLayout, std::uint32_t fragmentOutputs) { if (shape == 0 || !ShapeMemoEnabled()) return; auto& entries = shapeMemo(); if (entries.size() >= ShapeMemoEntries && !entries.contains(shape)) entries.clear(); auto& entry = entries[shape]; if (entry.device != context.device) { entry = {}; entry.device = context.device; } entry.targets.resize(targets.size()); for (std::size_t index = 0; index < targets.size(); ++index) { const auto& resident = targets[index].resident; if (resident == nullptr || targets[index].color.arrayLastSlice != 0) entry.targets[index].reset(); else if (entry.targets[index].owner_before(resident) || resident.owner_before(entry.targets[index])) entry.targets[index] = resident; } if (pipeline == nullptr || hash == 0) return; auto& choices = entry.choices; const auto kept = std::ranges::find_if(choices, [&](const ShapeChoice& choice) { return sameChoice(choice, input, layouts, shaders, attachmentLayout, fragmentOutputs); }); if (kept != choices.end()) { kept->hash = hash; kept->pipeline = *pipeline; std::rotate(choices.begin(), kept, std::next(kept)); return; } ShapeChoice choice; choice.attachmentLayout = attachmentLayout; choice.fragmentOutputs = fragmentOutputs; for (const auto& shader : shaders) { const auto identity = shader.program->Identity(); if (identity.Empty()) return; choice.stages.insert(choice.stages.end(), {static_cast(shader.stage), identity.low, identity.high, KeyedPushOffset(shader)}); } choice.stages.push_back(PushConstantStages(shaders)); choice.bindings = input.bindings; choice.attributes = input.attributes; choice.mainKey.assign(layouts.mainKey.begin(), layouts.mainKey.end()); choice.fragmentKey.assign(layouts.fragmentKey.begin(), layouts.fragmentKey.end()); choice.hash = hash; choice.pipeline = *pipeline; if (choices.size() >= ShapeMemoChoices) choices.pop_back(); choices.insert(choices.begin(), std::move(choice)); } bool sameColorTarget(const ColorTarget& a, const ColorTarget& b) { return a.address == b.address && a.extent.width == b.extent.width && a.extent.height == b.extent.height && a.format == b.format && a.bytes == b.bytes && a.componentMapping == b.componentMapping && a.tileMode == b.tileMode && a.elementBytes == b.elementBytes && a.packing == b.packing && a.dccAddress == b.dccAddress && a.chainDccAddress == b.chainDccAddress && a.dccAlphaOnMsb == b.dccAlphaOnMsb && a.dccPipeAligned == b.dccPipeAligned && a.cmaskAddress == b.cmaskAddress && a.cmaskBytes == b.cmaskBytes && a.cmaskFastClear == b.cmaskFastClear && a.eqaaFragments == b.eqaaFragments && a.surfaceAddress == b.surfaceAddress && a.surfaceExtent.width == b.surfaceExtent.width && a.surfaceExtent.height == b.surfaceExtent.height && a.mipCount == b.mipCount && a.mip == b.mip && a.mipTail == b.mipTail && a.clearWords == b.clearWords && a.slot == b.slot && a.depth == b.depth && a.depthSlice == b.depthSlice && a.arrayAddress == b.arrayAddress && a.arrayLastSlice == b.arrayLastSlice && a.arraySlice == b.arraySlice && a.layers == b.layers && a.exportIndex == b.exportIndex && a.uintExport == b.uintExport && a.volume == b.volume && a.pipeBankXor == b.pipeBankXor && a.samples == b.samples && a.coverageSamples == b.coverageSamples && a.dccControl == b.dccControl && a.fmaskAddress == b.fmaskAddress && a.fmaskPipeBankXor == b.fmaskPipeBankXor && a.partialWriteMask == b.partialWriteMask && a.staged == b.staged && a.stagedMask == b.stagedMask && a.stagedFormat == b.stagedFormat; } bool sameDepthTarget(const DepthTarget& a, const DepthTarget& b) { return a.address == b.address && a.stencilAddress == b.stencilAddress && a.extent.width == b.extent.width && a.extent.height == b.extent.height && a.format == b.format && std::bit_cast(a.clearDepth) == std::bit_cast(b.clearDepth) && a.clearStencil == b.clearStencil && a.htileAddress == b.htileAddress && a.htileStencil == b.htileStencil && a.samples == b.samples && a.depthSwizzle == b.depthSwizzle && a.pipeBankXor == b.pipeBankXor && a.firstSlice == b.firstSlice && a.lastSlice == b.lastSlice && a.iterate256 == b.iterate256 && a.htilePipeAligned == b.htilePipeAligned && a.htileVrsEncoding == b.htileVrsEncoding && a.htileDepthOnly == b.htileDepthOnly && a.gcn == b.gcn; } struct AttachmentMemo { bool valid = false; VkDevice device = VK_NULL_HANDLE; std::uint64_t recorder = 0; std::uint64_t generation = 0; std::uint64_t epoch = 0; std::uint64_t proof = 0; std::uint64_t pending = 0; std::uint64_t depthSerial = 0; std::uint64_t depthReleased = 0; std::vector colors; std::vector> residents; std::vector versions; std::vector gpuTiling; std::vector proxied; std::vector views; std::optional depth; bool depthWrite = false; bool stencilTest = false; bool stencilWritten = false; VkImageView depthView = VK_NULL_HANDLE; }; struct AttachmentMemoStorage {}; AttachmentMemo& attachmentMemo() { return HostThreadLocal(); } bool PassAttachmentMemoEnabled() { return !RuntimeSwitches::Set(RuntimeSwitch::NoPassAttachmentMemo) && ShaderResources::EpochProofs(); } bool VerifyPassAttachments() { static const bool verify = std::getenv("APS5_VERIFY_PASS_ATTACHMENTS") != nullptr; return verify; } enum class AttachmentEvent : std::size_t { Hit, NoMemo, Pass, Serials, Targets, Images, Depth, Stored, Ineligible, Verified, Mismatch, Count }; void noteAttachments(AttachmentEvent event) { static const bool stats = std::getenv("APS5_PIPELINE_STATS") != nullptr || std::getenv("APS5_PROFILE_DRAW") != nullptr; if (!stats) return; static std::array, static_cast(AttachmentEvent::Count)> counts{}; static std::atomic reportedAt{0}; counts[static_cast(event)].fetch_add(1, std::memory_order_relaxed); const auto tenSeconds = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count() / 10; if (reportedAt.exchange(tenSeconds, std::memory_order_relaxed) == tenSeconds) return; std::array(AttachmentEvent::Count)> taken{}; for (std::size_t index = 0; index < taken.size(); ++index) taken[index] = counts[index].exchange(0, std::memory_order_relaxed); AgcDriver::ProfilePrint_nid_no_patch("[pass-attachments] 10 s: %llu hits; misses: %llu no memo, %llu pass, %llu serials, %llu targets, %llu images, %llu depth; %llu stored, %llu ineligible; verify %llu checked, %llu differed\n", taken[0], taken[1], taken[2], taken[3], taken[4], taken[5], taken[6], taken[7], taken[8], taken[9], taken[10]); } bool matchAttachmentMemo(const Context& context, const State& state, InlineList, 8>& residents, std::span expectedViews) { const auto& memo = attachmentMemo(); const auto miss = [](AttachmentEvent why) { noteAttachments(why); return false; }; if (!memo.valid || memo.device != context.device) return miss(AttachmentEvent::NoMemo); const auto* recorder = Recorder::Active(); if (recorder == nullptr || recorder->Id() != memo.recorder || !recorder->RenderPassOpen() || recorder->RenderPassGeneration() != memo.generation) return miss(AttachmentEvent::Pass); if (GuestMemory::CollectEpoch() != memo.epoch || GuestMemory::ProofSerial() != memo.proof || StorageTexture::PendingSerial() != memo.pending) return miss(AttachmentEvent::Serials); if (state.colors.size() != memo.colors.size()) return miss(AttachmentEvent::Targets); for (std::size_t index = 0; index < state.colors.size(); ++index) { if (!sameColorTarget(state.colors[index], memo.colors[index])) return miss(AttachmentEvent::Targets); } if (state.depth.has_value() != memo.depth.has_value()) return miss(AttachmentEvent::Depth); if (state.depth && overwrittenStencil(state)) return miss(AttachmentEvent::Depth); if (state.depth) { if (!sameDepthTarget(*state.depth, *memo.depth) || state.depthWrite != memo.depthWrite || state.stencilTest != memo.stencilTest || writesStencilTarget(state) != memo.stencilWritten || DepthSurfacesSerial() != memo.depthSerial || DepthSurfacesReleased() != memo.depthReleased) return miss(AttachmentEvent::Depth); } if (!expectedViews.empty()) { if (expectedViews.size() != memo.views.size() + (state.depth ? 1u : 0u)) return miss(AttachmentEvent::Targets); for (std::size_t index = 0; index < memo.views.size(); ++index) { if (expectedViews[index] != memo.views[index]) return miss(AttachmentEvent::Targets); } if (state.depth && expectedViews.back() != memo.depthView) return miss(AttachmentEvent::Depth); } for (std::size_t index = 0; index < memo.residents.size(); ++index) { auto resident = memo.residents[index].lock(); if (resident == nullptr || resident->Version() != memo.versions[index] || !StorageImageCached(context, resident.get()) || !StorageImageServesKeys(*resident, SurfaceForTarget(state.colors[index]).dccAddress)) return miss(AttachmentEvent::Images); residents.EmplaceBack(std::move(resident)); } return true; } bool memoAttachments(const Context& context, const State& state, PreparedDraw& prepared, bool fill) { InlineList, 8> residents; if (!matchAttachmentMemo(context, state, residents, {})) return false; if (!fill) return true; const auto& memo = attachmentMemo(); noteAttachments(AttachmentEvent::Hit); auto& targets = prepared.targets; auto& targetViews = prepared.targetViews; auto matched = residents.Span(); for (std::size_t index = 0; index < state.colors.size(); ++index) { auto& binding = targets[index]; binding.resident = std::move(matched[index]); binding.color = state.colors[index]; binding.gpuTiling = memo.gpuTiling[index]; binding.proxied = memo.proxied[index]; targetViews.push_back(memo.views[index]); } if (state.depth) targetViews.push_back(memo.depthView); return true; } void checkAttachmentViews(const State& state, std::span views, const auto& residentAt) { const auto& memo = attachmentMemo(); bool same = views.size() == memo.views.size() + (memo.depth ? 1u : 0u); for (std::size_t index = 0; same && index < memo.views.size(); ++index) same = residentAt(index) == memo.residents[index].lock() && views[index] == memo.views[index]; if (same && state.depth) same = views.back() == memo.depthView; noteAttachments(same ? AttachmentEvent::Verified : AttachmentEvent::Mismatch); if (!same) { static std::atomic reports{0}; if (reports.fetch_add(1, std::memory_order_relaxed) < 20) std::fprintf(stderr, "[pass-attachments] verify: the memo's attachments differ from the full lookup (target 0x%llx, depth 0x%llx)\n", static_cast(state.hasColorTarget ? state.color.address : 0), static_cast(state.depth ? state.depth->address : 0)); } } void checkAttachments(const State& state, const PreparedDraw& prepared) { checkAttachmentViews(state, prepared.targetViews, [&](std::size_t index) { return prepared.targets[index].resident; }); } void storeAttachmentMemoHeader(AttachmentMemo& memo, const Context& context, const State& state, const Recorder& recorder, std::uint64_t epoch, std::span views) { memo.valid = true; memo.device = context.device; memo.recorder = recorder.Id(); memo.generation = recorder.RenderPassGeneration(); memo.epoch = epoch; memo.proof = GuestMemory::ProofSerial(); memo.pending = StorageTexture::PendingSerial(); memo.depthSerial = DepthSurfacesSerial(); memo.depthReleased = DepthSurfacesReleased(); memo.colors.assign(state.colors.begin(), state.colors.end()); memo.residents.clear(); memo.versions.clear(); memo.gpuTiling.clear(); memo.proxied.clear(); memo.views.clear(); memo.depth = state.depth; memo.depthWrite = state.depthWrite; memo.stencilTest = state.stencilTest; memo.stencilWritten = state.depth ? writesStencilTarget(state) : false; memo.depthView = state.depth ? views.back() : VK_NULL_HANDLE; } void rememberAttachments(const Context& context, const State& state, const PreparedDraw& prepared) { auto& memo = attachmentMemo(); const auto* recorder = prepared.recorder; const auto epoch = GuestMemory::CollectEpoch(); const bool eligible = epoch != 0 && recorder != nullptr && recorder->RenderPassOpen() && prepared.dumpLimit == 0 && (!state.depth || state.depth->samples == 1u) && prepared.targetViews.size() == prepared.targets.size() + (state.depth ? 1u : 0u) && std::ranges::all_of(prepared.targets, [](const TargetBinding& binding) { return !binding.multisampled && binding.resident != nullptr && binding.target == nullptr && binding.stagedTemporary == nullptr && binding.dump == nullptr && !binding.color.staged && binding.color.partialWriteMask == 0; }); if (!eligible) { memo.valid = false; noteAttachments(AttachmentEvent::Ineligible); return; } storeAttachmentMemoHeader(memo, context, state, *recorder, epoch, prepared.targetViews); for (std::size_t index = 0; index < prepared.targets.size(); ++index) { const auto& binding = prepared.targets[index]; memo.residents.emplace_back(binding.resident); memo.versions.push_back(binding.resident->Version()); memo.gpuTiling.push_back(binding.gpuTiling); memo.proxied.push_back(binding.proxied); memo.views.push_back(prepared.targetViews[index]); } noteAttachments(AttachmentEvent::Stored); } void rememberRecipeAttachments(const Context& context, const State& state, const Recorder* recorder, std::span> residents, std::span views) { auto& memo = attachmentMemo(); const auto epoch = GuestMemory::CollectEpoch(); const bool eligible = epoch != 0 && recorder != nullptr && recorder->RenderPassOpen() && (!state.depth || state.depth->samples == 1u) && views.size() == residents.size() + (state.depth ? 1u : 0u) && std::ranges::all_of(residents, [](const std::shared_ptr& resident) { return resident != nullptr; }) && std::ranges::all_of(state.colors, [](const ColorTarget& color) { return color.samples == 1u && !color.staged && color.partialWriteMask == 0; }); if (!eligible) { memo.valid = false; noteAttachments(AttachmentEvent::Ineligible); return; } storeAttachmentMemoHeader(memo, context, state, *recorder, epoch, views); for (std::size_t index = 0; index < residents.size(); ++index) { memo.residents.emplace_back(residents[index]); memo.versions.push_back(residents[index]->Version()); memo.gpuTiling.push_back(state.colors[index].tileMode == ColorTileMode::RenderTarget && context.detiler != nullptr); memo.proxied.push_back(false); memo.views.push_back(views[index]); } noteAttachments(AttachmentEvent::Stored); } bool storesIntoResident(const ShaderResources& resources, const StorageTexture& resident) { return std::ranges::any_of(resources.StorageImages(), [&](const std::pair& image) { return image.first == resident.Image() && image.second; }); } bool VerifyTargetMemo() { static const bool verify = std::getenv("APS5_VERIFY_TARGET_MEMO") != nullptr; return verify; } bool TargetMemoEnabled() { static const bool cached = std::getenv("APS5_NO_TEXTURE_CACHE") == nullptr; return cached && !RuntimeSwitches::Set(RuntimeSwitch::NoTargetMemo) && ShaderResources::EpochProofs(); } struct TargetProof { std::uint64_t epoch = 0; std::uint64_t proofs = 0; std::uint64_t pending = 0; std::uint64_t unwatch = 0; std::uint64_t allocations = 0; std::uint64_t surfaces = 0; std::uint64_t released = 0; std::uint64_t claims = 0; const Recorder* recorder = nullptr; VkDevice device = VK_NULL_HANDLE; bool operator==(const TargetProof&) const = default; const char* MovedBefore(const TargetProof& after) const { if (epoch != after.epoch) return "epoch"; if (surfaces != after.surfaces) return "surfaces"; return released != after.released ? "released" : nullptr; } }; TargetProof currentTargetProof(const Context& context) { return {GuestMemory::CollectEpoch(), GuestMemory::ProofSerial(), StorageTexture::PendingSerial(), GuestMemory::UnwatchSerial(), GuestAllocations::GuestAllocationsGeneration_nid_postfix(), DepthSurfacesSerial(), DepthSurfacesReleased(), MultisampleClaimSerial(), Recorder::Active(), context.device}; } struct DepthFootprint { std::uint64_t address = 0; std::uint64_t stencilAddress = 0; std::uint64_t htileAddress = 0; std::uint32_t width = 0; std::uint32_t height = 0; std::uint32_t samples = 0; bool d16 = false; bool sliced = false; bool operator==(const DepthFootprint&) const = default; }; std::optional depthFootprint(const std::optional& depth) { if (!depth) return std::nullopt; return DepthFootprint{depth->address, depth->stencilAddress, depth->htileAddress, depth->extent.width, depth->extent.height, depth->samples, depth->format == VK_FORMAT_D16_UNORM || depth->format == VK_FORMAT_D16_UNORM_S8_UINT, depth->firstSlice != 0u || depth->lastSlice != 0u}; } struct ColorMemo { struct Attachment { std::weak_ptr resident; bool proxied = false; VkImageView view = VK_NULL_HANDLE; }; bool valid = false; TargetProof proof; std::vector descriptors; std::vector attachments; std::optional clearOfDepth; }; struct DepthMemo { bool valid = false; TargetProof proof; std::optional descriptor; }; struct TargetMemo { ColorMemo colors; DepthMemo depth; void Invalidate() { colors.valid = false; depth.valid = false; } }; struct TargetMemoStorage {}; TargetMemo& ThreadTargetMemo() { return HostThreadLocal(); } thread_local std::uint64_t targetMemoBuilds = 0; std::atomic targetMemoOwner{nullptr}; constexpr std::array(TargetMemoEvent::Count)> TargetMemoEventNames{ "lookup", "hit", "overlap cached", "overlap computed", "accept", "accept without depth", "depth hit", "avoided refresh lookups", "invalid", "thread changed", "descriptor", "resident gone", "resident evicted", "depth overlap", "metadata", "epoch", "proofs", "pending", "unwatch", "allocations", "surfaces", "released", "claims", "recorder", "device", "post-depth invalidated", "depth fallback", "admission", "recipe invalidated", "build", "verify checked" }; std::array(TargetMemoEvent::Count)>& targetMemoEvents() { static std::array(TargetMemoEvent::Count)> events; return events; } const bool targetMemoProfiled = std::getenv("APS5_PROFILE_TARGET_MEMO") != nullptr || std::getenv("APS5_PROFILE_DRAW") != nullptr; void noteTargetMemo(TargetMemoEvent event, std::uint64_t count = 1) { if (targetMemoProfiled) targetMemoEvents()[static_cast(event)].Add(count); #ifdef TRACY_ENABLE static std::array, static_cast(TargetMemoEvent::Count)> counts{}; const auto index = static_cast(event); TracyCPlotI(TargetMemoEventNames[index], static_cast(counts[index].fetch_add(count, std::memory_order_relaxed) + count)); #endif } void reportTargetMemo() { using Clock = std::chrono::steady_clock; static std::atomic reported{Clock::now().time_since_epoch().count()}; static std::array(TargetMemoEvent::Count)> previous{}; const auto now = Clock::now().time_since_epoch().count(); auto last = reported.load(std::memory_order_relaxed); if (Clock::duration(now - last) < std::chrono::seconds(10) || !reported.compare_exchange_strong(last, now, std::memory_order_relaxed)) return; std::string line; for (std::size_t index = 0; index < previous.size(); ++index) { const auto total = targetMemoEvents()[index].Sum(); const auto count = total - previous[index]; previous[index] = total; if (count == 0) continue; line += (line.empty() ? " " : ", ") + std::string(TargetMemoEventNames[index]) + " " + std::to_string(count); } AgcDriver::ProfilePrint_nid_no_patch("[target-memo] (10 s, all threads):%s\n", line.empty() ? " none" : line.c_str()); } bool colorProofMatches(const TargetProof& before, const TargetProof& after) { if (before == after) return true; const auto note = [&](bool changed, TargetMemoEvent event) { if (changed) noteTargetMemo(event); }; note(before.epoch != after.epoch, TargetMemoEvent::Epoch); note(before.proofs != after.proofs, TargetMemoEvent::Proofs); note(before.pending != after.pending, TargetMemoEvent::Pending); note(before.unwatch != after.unwatch, TargetMemoEvent::Unwatch); note(before.allocations != after.allocations, TargetMemoEvent::Allocations); note(before.surfaces != after.surfaces, TargetMemoEvent::Surfaces); note(before.released != after.released, TargetMemoEvent::Released); note(before.claims != after.claims, TargetMemoEvent::Claims); note(before.recorder != after.recorder, TargetMemoEvent::Recorder); note(before.device != after.device, TargetMemoEvent::Device); return false; } bool ownsTargetMemo(TargetMemo& memo) { if (targetMemoOwner.load(std::memory_order_relaxed) == &memo) return true; targetMemoOwner.store(&memo, std::memory_order_relaxed); if (memo.colors.valid || memo.depth.valid) noteTargetMemo(TargetMemoEvent::ThreadChanged); memo.Invalidate(); return false; } void dropTargetMemo() { if (targetMemoOwner.load(std::memory_order_relaxed) == nullptr) return; ThreadTargetMemo().Invalidate(); targetMemoOwner.store(nullptr, std::memory_order_relaxed); } bool colorOverlapsDepth(const State& state, const TargetBinding& binding) { if (!state.depth) return false; const auto& color = binding.color; const auto& resident = *binding.resident; const auto& descriptor = resident.Descriptor(); return DepthTargetOverlaps(*state.depth, resident.Descriptor().baseAddress, resident.GuestBytes()) || (descriptor.dccAddress != 0 && DepthTargetOverlaps(*state.depth, descriptor.dccAddress, std::max(resident.GuestBytes() / 256u, 1u))) || (color.dccAddress != 0 && DepthTargetOverlaps(*state.depth, color.dccAddress, std::max(colorKeyCount(color, color.bytes), 1u))) || (color.chainDccAddress != 0 && DepthTargetOverlaps(*state.depth, color.chainDccAddress, std::max(colorKeyCount(color, color.bytes), 1u))) || (color.cmaskAddress != 0 && DepthTargetOverlaps(*state.depth, color.cmaskAddress, color.cmaskBytes)); } bool metadataProved(const ColorTarget& color) { const auto keys = std::max(colorKeyCount(color, color.bytes), 1u); const bool proved = (color.dccAddress == 0 || GuestMemory::CollectWrites(color.dccAddress, keys) != 0) && (color.chainDccAddress == 0 || GuestMemory::CollectWrites(color.chainDccAddress, keys) != 0) && (color.cmaskAddress == 0 || cmaskProved(color.cmaskAddress, color.cmaskBytes)); if (!proved) noteTargetMemo(TargetMemoEvent::Metadata); return proved; } void rememberTargets(const State& state, std::span targets, std::span views, const TargetProof& proof) { ++targetMemoBuilds; noteTargetMemo(TargetMemoEvent::Build); auto& colors = ThreadTargetMemo().colors; auto& depth = ThreadTargetMemo().depth; const bool enabled = TargetMemoEnabled() && proof.epoch != 0; colors.valid = enabled && !targets.empty() && std::ranges::all_of(targets, [&](const TargetBinding& binding) { return binding.resident != nullptr && binding.resident->Cached() && !binding.multisampled && binding.color.fmaskAddress == 0 && !binding.resident->OtherPendingOverlaps() && !colorOverlapsDepth(state, binding) && metadataProved(binding.color); }); if (colors.valid) { colors.proof = proof; colors.clearOfDepth = depthFootprint(state.depth); colors.descriptors.assign(state.colors.begin(), state.colors.end()); colors.attachments.resize(targets.size()); for (std::size_t index = 0; index < targets.size(); ++index) colors.attachments[index] = {targets[index].resident, targets[index].proxied, views[index]}; } depth.valid = enabled && (!state.depth || state.depth->samples == 1u); if (depth.valid) { depth.proof = proof; depth.descriptor = state.depth; } } bool sameColorTargetSurface(const ColorTarget& a, const ColorTarget& b) { if (a == b) return true; if (a.arrayLastSlice != 0 || b.arrayLastSlice != 0 || !(a.volume || a.depth > 1) || !(b.volume || b.depth > 1)) return false; auto adjusted = b; adjusted.depthSlice = a.depthSlice; adjusted.layers = a.layers; return a == adjusted; } bool repeatColors(const Context& context, const State& state, const TargetProof& proof, std::vector& targets, std::vector& views) { auto& memo = ThreadTargetMemo().colors; thread_local std::uint32_t lookups = 0; if (targetMemoProfiled && (++lookups & 4095u) == 0u) reportTargetMemo(); if (state.colors.empty()) return false; noteTargetMemo(TargetMemoEvent::Lookup); if (!memo.valid || !TargetMemoEnabled()) { noteTargetMemo(TargetMemoEvent::Invalid); return false; } if (!colorProofMatches(memo.proof, proof)) return false; if (memo.descriptors.size() != state.colors.size()) { noteTargetMemo(TargetMemoEvent::Descriptor); return false; } for (std::size_t index = 0; index < state.colors.size(); ++index) { if (!sameColorTargetSurface(memo.descriptors[index], state.colors[index]) || (memo.descriptors[index] != state.colors[index] && memo.attachments[index].proxied)) { noteTargetMemo(TargetMemoEvent::Descriptor); return false; } } const auto footprint = depthFootprint(state.depth); const bool overlapKnown = footprint == memo.clearOfDepth && !RuntimeSwitches::Set(RuntimeSwitch::NoTargetMemoOverlapCache); for (std::size_t index = 0; index < targets.size(); ++index) { auto& binding = targets[index]; binding.resident = memo.attachments[index].resident.lock(); if (binding.resident == nullptr || !binding.resident->Cached()) { noteTargetMemo(binding.resident == nullptr ? TargetMemoEvent::ResidentGone : TargetMemoEvent::ResidentEvicted); return false; } binding.color = state.colors[index]; if (VerifyTargetMemo()) Require(overlapKnown ? !colorOverlapsDepth(state, binding) : true, "APS5_VERIFY_TARGET_MEMO: a cached depth overlap differs from its computation"); if (!overlapKnown && colorOverlapsDepth(state, binding)) { noteTargetMemo(TargetMemoEvent::DepthOverlap); return false; } binding.gpuTiling = binding.color.tileMode == ColorTileMode::RenderTarget && context.detiler != nullptr; binding.proxied = memo.attachments[index].proxied; const bool exact = memo.descriptors[index] == binding.color; views.push_back(exact ? memo.attachments[index].view : binding.resident->AttachmentView(binding.color.format, binding.color.mip, binding.color.depthSlice, binding.color.layers, binding.color.arraySlice)); } noteTargetMemo(TargetMemoEvent::Hit); noteTargetMemo(overlapKnown ? TargetMemoEvent::OverlapCached : TargetMemoEvent::OverlapComputed); if (!overlapKnown) memo.clearOfDepth = footprint; return true; } VkImageView repeatDepth(const Context& context, const State& state, const TargetProof* proof) { const auto& memo = ThreadTargetMemo().depth; if (!state.depth || !memo.valid || !TargetMemoEnabled() || targetMemoOwner.load(std::memory_order_relaxed) != &ThreadTargetMemo() || memo.proof != (proof != nullptr ? *proof : currentTargetProof(context)) || !memo.descriptor) return VK_NULL_HANDLE; if (*memo.descriptor != *state.depth) return VK_NULL_HANDLE; return RepeatDepthSurfaceView(context, *state.depth, state.depthWrite, writesStencilTarget(state)); } const char* targetObligation(const Context& context, const State& state, std::span targets, bool repeatedDepth) { for (const auto& binding : targets) { const auto& color = binding.color; const auto layers = color.arrayLastSlice != 0 ? color.layers : 0u; if (const auto* owed = binding.resident->RefreshObligation(layers != 0 ? color.arraySlice : 0u, layers)) return owed; if (const auto* owed = DepthPlanesObligation(context.device, color.MemoryAddress(), color.bytes)) return owed; if (color.cmaskAddress == 0 || cmaskProved(color.cmaskAddress, color.cmaskBytes)) continue; std::vector cleared; if (readCmask(color, CmaskLayout(color.extent.width, color.extent.height), cleared) != CmaskState::Expanded) return "a CMASK clear"; } return repeatedDepth ? DepthTargetObligation(context, *state.depth, state.depthWrite) : nullptr; } bool prepareDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, PreparedDraw& prepared) { auto*& recipeOut = prepared.recipeOut; auto& stencilReferences = prepared.stencilReferences; for (const auto& shader : shaders) { if (shader.program != nullptr && !shader.program->stencilReferences.empty()) { Require(shader.stage == ShaderRecompiler::ShaderStage::Fragment && stencilReferences.empty(), "stencil replay requires exactly one fragment stage"); stencilReferences = shader.program->stencilReferences; } } if (!stencilReferences.empty()) { Require(!draw.indirect && !state.primitiveRestart && !state.rectList && !state.quadList && !state.stages.mesh && !state.stages.tessellation && (state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || StencilReplayStrip(context, state, shaders)), "stencil replay supports direct triangle lists, and triangle strips whose triangles share one face state and have no flat parameters, without restart, mesh or tessellation"); Require(!state.depthBiasPerFace && !ShadersWriteMemory(shaders), "stencil replay refuses face splits and shader memory writes"); Require(std::ranges::all_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->stencilReplaySafe && (shader.stage == ShaderRecompiler::ShaderStage::Vertex || shader.stage == ShaderRecompiler::ShaderStage::Fragment); }), "stencil replay refuses stages with side effects, clocks, subgroup dependencies or primitive ID inputs"); if (stencilReferences.size() == 256u) { static std::once_flag unbounded; std::call_once(unbounded, [] { APS5_LOG_CHARS_OUT("Stencil replay: a draw replays all 256 stencil reference values because its pixel shader's export is not bounded"); }); } 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"); } 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"); recipeOut = nullptr; } if (state.quadList || StripPatches(state, shaders)) recipeOut = nullptr; if (context.recorder != nullptr) context.recorder->BoundKeptBytes(); auto& timing = prepared.timing.emplace("Graphics.Draw"); // APS5_PROFILE_DRAW prints the time of each phase of the draw (microseconds) and the [draws] totals. static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; auto& timer = prepared.timer; timer = DrawTimer(profile); // APS5_TRACE_DRAWS (together with APS5_PROFILE_DRAW; alone it only enables Driver.cpp's own // [draw] lines) additionally prints one line per draw with its phases and, for synchronous // draws, their inputs: per-draw string building at ~1400 draws per 10 s is itself a cost the // totals must not carry. static const bool traceDraws = std::getenv("APS5_TRACE_DRAWS") != nullptr; auto& outcome = prepared.outcome; auto& built = prepared.built; // The thread's GPU waits so far: the difference at the report, less the draw's own syncs // (`ownWaitedMs`, sampled around them), is what this draw waited for through the flush hook // (nested in the draw's hold, see DrawOutcome::hookWaitUs). const auto waitedBefore = prepared.waitedBefore = profile ? Recorder::ThreadWaitedMs() : 0.0; auto& ownWaitedMs = prepared.ownWaitedMs; const auto report = [&](const char* suffix) { reportDrawEnd(state, timer, built, outcome, waitedBefore, ownWaitedMs, suffix); }; auto& inputs = prepared.inputs; const auto plan = planDraw(context, state, draw, shaders, nullptr, outcome, timer, prepared.contentKey); if (plan.nothing) return false; inputs = prepareDrawInputs(context, state, draw, shaders, plan, timer, timing); if (inputs.result == DrawResult::NeedsIndividualRecords) return false; if (inputs.nothing) { if (VerifyDrawPlan()) requireDrawPlanRepeats(context, state, draw, shaders, plan); return false; } const auto* args = prepared.args = draw.indirect ? &*draw.indirect : nullptr; const auto indexBytes = inputs.indexBytes; const int dumpLimit = prepared.dumpLimit = DumpTargetLimit(); auto& targets = prepared.targets; targets.resize(state.colors.size()); auto& targetViews = prepared.targetViews; const bool verifyAttachments = prepared.passAttachments && VerifyPassAttachments() && memoAttachments(context, state, prepared, false); prepared.attachmentsFromMemo = prepared.passAttachments && !VerifyPassAttachments() && memoAttachments(context, state, prepared, true); const bool memoActive = TargetMemoEnabled(); if (!memoActive) dropTargetMemo(); const bool memoConsulted = memoActive && !prepared.attachmentsFromMemo; const bool memoServes = memoConsulted && (!verifyAttachments || VerifyTargetMemo()); bool targetsUsed = false; TargetProof targetProof; TargetProof admissionProof; bool repeatedColors = false; if (memoConsulted) { static_cast(ownsTargetMemo(ThreadTargetMemo())); targetProof = currentTargetProof(context); admissionProof = targetProof; } if (memoServes) { targetsUsed = true; repeatedColors = repeatColors(context, state, targetProof, targets, targetViews); } const auto prepareColors = [&] { if (targetsUsed) { targets.clear(); targets.resize(state.colors.size()); } targetsUsed = true; targetViews.clear(); for (std::size_t index = 0; index < state.colors.size(); ++index) { auto& binding = targets[index]; binding.color = state.colors[index]; const auto& color = binding.color; binding.gpuTiling = color.tileMode == ColorTileMode::RenderTarget && context.detiler != nullptr; if (color.samples > 1) { binding.multisampled = true; timer.phase(PhaseSetup); if (color.staged) { const auto packed = StagedMergeTarget(color); binding.stagedTemporary = AcquireStagedTemporary(context, color.extent, color.samples); PrepareMultisampleTargetForDraw_nid_no_patch(context, packed); static_cast(MultisampleTargetView(context, packed, binding.multisampleOwner, &binding.multisampleImage)); binding.stagedTarget = MultisampleTargetStorageView(context, TargetMergeSurface(packed)); Require(MultisampleTargetStorable(context, packed), "a partial write of a multisampled packed color target needs a multisample image of this form to allow storage"); targetViews.push_back(binding.stagedTemporary->View()); timer.phase(PhaseReadTarget); continue; } PrepareMultisampleTargetForDraw_nid_no_patch(context, color); targetViews.push_back(MultisampleTargetView(context, color, binding.multisampleOwner, &binding.multisampleImage)); timer.phase(PhaseReadTarget); continue; } APS5_LOG_OUT_DEBUG("Creating color target %zu address=0x%llx bytes=%llu extent=%ux%u", index, static_cast(color.address), static_cast(color.bytes), color.extent.width, color.extent.height); const ColorTargetLayout colorLayout(color.extent.width, color.extent.height, color.tileMode, color.elementBytes); static_cast(FlushDepthPlanes(color.address, colorLayout.Bytes(), DepthPlaneScope::Whole)); RetireDepthSurfaces(context.device, color.address, colorLayout.Bytes()); ClaimMultisampleTargetMemory(color.address, colorLayout.Bytes()); if (color.fmaskAddress != 0) GuardOneFragmentFmask(context, color); constexpr VkBufferUsageFlags copies = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; timer.phase(PhaseSetup); // Debug aid: APS5_NO_RESIDENT_TARGETS=1 copies every target in and out again. static const bool residentTargets = std::getenv("APS5_NO_RESIDENT_TARGETS") == nullptr; static const bool residentLinear = std::getenv("APS5_NO_RESIDENT_LINEAR") == nullptr; const bool linearResident = residentLinear && residentTargets && context.detiler != nullptr && color.tileMode == ColorTileMode::Linear && (ExistingHostImportFor(context, color.address, colorLayout.Bytes()) != nullptr || (GuestMemory::Watched(color.address, colorLayout.Bytes()) && HostImportFor(context, color.address, colorLayout.Bytes(), ImportRequester::ColorTarget) != nullptr)); if ((binding.gpuTiling || ((!ColorTileModeIsLinear(color.tileMode) || linearResident) && context.detiler != nullptr)) && residentTargets) { // The lookup refreshes the image on every draw (StorageTexture::Refresh: FlushPending, // CollectWrites over the target's pages, the DCC key scan of TextureClearKeys, then // UnchangedSince). The page walk is skipped while the worker's collect epoch lasts // (GuestMemory::BumpCollectEpoch: ordering points of the queue, or every packet under // APS5_PACKET_EPOCH=1); the key scan runs on every lookup regardless. Lookups of a // millisecond or more are counted apart; the [texture] line says how many uploaded. binding.resident = refreshResidentTarget(context, state, color, outcome, profile, [&] { if (color.arrayLastSlice != 0) { Require(color.dccAddress == 0 && color.cmaskAddress == 0 && AttachmentProxyFormat(context, color.format) == VK_FORMAT_UNDEFINED, "a slice of a 2D array color target with DCC, CMASK or an attachment proxy has no resident array image"); const auto array = ArraySurfaceForTarget(color); // DecodeColorBuffer offsets slice s by s times this size; every slice the image stores must agree. const auto sliceBytes = ComputeSurfaceSize(ComputeElementMipLayout(ColorTextureTileMode(color.tileMode), color.elementBytes, color.surfaceExtent.width, color.surfaceExtent.height, color.mipCount), 1); const auto geometry = DescribeSurface(array); for (std::uint32_t slice = 0; slice <= color.arrayLastSlice; ++slice) Require(geometry.GuestLayerOffset(slice) == slice * sliceBytes, "the array image's layer pitch differs from the color view's slice offset"); Require(color.surfaceAddress == color.arrayAddress + color.arraySlice * sliceBytes, "the array image's layer pitch differs from the color view's slice offset"); auto resident = CachedStorageLayers(context, array, color.arraySlice, color.layers); Require(resident->Attachable(), "storage format cannot be a color attachment"); return resident; } const auto surface = SurfaceForTarget(color); auto resident = RepeatStorageSurface(context, surface, shapeTarget(context, prepared.shape, index)); if (resident != nullptr && VerifyShapeMemo()) { Require(CachedStorageSurface(context, surface) == resident, "APS5_VERIFY_SHAPE_MEMO: the shape memo's resident target differs from the storage cache's"); noteShapeMemoVerified(false); } if (resident == nullptr) resident = CachedStorageSurface(context, surface); Require(resident->Attachable(), "storage format cannot be a color attachment"); Require(color.volume || color.mipCount > 1 || color.depth > 1 || resident->GuestBytes() == colorLayout.Bytes(), "resident image layout differs from the color layout"); return resident; }); } if (binding.resident != nullptr) { timer.phase(PhaseReadTarget); binding.proxied = AttachmentProxyFormat(context, color.format) != VK_FORMAT_UNDEFINED; targetViews.push_back(binding.proxied ? binding.resident->AttachmentProxyView() : binding.resident->AttachmentView(color.format, color.mip, color.depthSlice, color.layers, color.arraySlice)); continue; } materializeCmaskClear(context, color, nullptr); Require(!color.mipTail || binding.gpuTiling, "rendering into a packed mip tail requires the GPU tiled fallback"); Require(color.depth == 1 && (!color.volume || (color.mipCount == 1 && color.tileMode == ColorTileMode::Linear)), "rendering into a 3D color target needs the resident image of its surface"); Require(color.layers == 1, "layered rendering into a 2D array color target needs the resident image of its array"); Require(color.arraySlice == 0 || !ColorTileModeIsXor(color.tileMode), "rendering into a slice of a 2D array color target with an XOR tile mode needs the resident image of its array"); if (binding.gpuTiling) { binding.mip = color.mipTail ? ComputeColorTargetMipLayout(color.tileMode, color.elementBytes, color.surfaceExtent.width, color.surfaceExtent.height, color.mipCount, color.mip) : ColorTargetMip(color, colorLayout); binding.tiled = std::make_unique(context, colorLayout.Bytes(), copies); binding.tiledDevice = std::make_unique(context, colorLayout.Bytes(), copies | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); binding.linearDevice = std::make_unique(context, colorLayout.LinearBytes(), copies | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); binding.original.resize(colorLayout.Bytes()); GuestMemory::Read(color.address, binding.original, colorLayout.Alignment()); std::memcpy(binding.tiled->Bytes().data(), binding.original.data(), binding.original.size()); } else { const auto x0 = static_cast(std::max(state.scissor.offset.x, 0)); const auto y0 = static_cast(std::max(state.scissor.offset.y, 0)); const auto x1 = std::min(x0 + state.scissor.extent.width, color.extent.width); const auto y1 = std::min(y0 + state.scissor.extent.height, color.extent.height); binding.banded = color.tileMode == ColorTileMode::Linear && color.dccAddress == 0 && x0 < x1 && y0 < y1 && (x1 - x0 < color.extent.width || y1 - y0 < color.extent.height); if (binding.banded) { binding.band = {{static_cast(x0), static_cast(y0)}, {x1 - x0, y1 - y0}}; binding.bandOffset = colorLayout.Offset(x0, y0); binding.bandPitch = static_cast(colorLayout.Bytes() / (std::size_t{color.extent.height} * color.elementBytes)); const auto bandBytes = colorLayout.Offset(x1 - 1, y1 - 1) + color.elementBytes - binding.bandOffset; binding.transfer = std::make_unique(context, bandBytes, copies); binding.original.resize(bandBytes); GuestMemory::Read(color.address + binding.bandOffset, binding.original, color.elementBytes); std::memcpy(binding.transfer->Bytes().data(), binding.original.data(), bandBytes); } else { binding.transfer = std::make_unique(context, colorLayout.LinearBytes(), copies); ReadColorTarget(color, binding.transfer->Bytes()); } } // A fast-cleared DCC target holds its clear value wherever the draw does not write. if (color.dccAddress != 0) { const auto keys = CurrentDccKeys(color.dccAddress, colorLayout.Bytes()); if (IsDccClear(keys)) { const auto pixels = binding.gpuTiling ? binding.tiled->Bytes() : binding.transfer->Bytes(); if (keys == DccKeys::ClearRegister) { const auto texel = clearTexel(color, keys); for (std::size_t offset = 0; offset + color.elementBytes <= pixels.size(); offset += color.elementBytes) std::memcpy(pixels.data() + offset, texel.data(), color.elementBytes); } else if (!FillDccClear(color.format, keys, color.dccAlphaOnMsb, pixels)) { static std::set> reported; if (reported.size() < 32 && reported.insert({color.address, static_cast(keys)}).second) std::fprintf(stderr, "[gpu] color target 0x%llx (VkFormat %d) has %s DCC keys; its stored texels are used\n", static_cast(color.address), static_cast(color.format), DccKeysName(keys)); if (binding.gpuTiling) std::memcpy(pixels.data(), binding.original.data(), binding.original.size()); else ReadColorTarget(color, pixels); } } } timer.phase(PhaseReadTarget); binding.target = std::make_unique(context, color, state.blends.at(color.exportIndex).blendEnable != 0); targetViews.push_back(binding.target->View()); } }; if (!repeatedColors && !prepared.attachmentsFromMemo) prepareColors(); const auto prepareDepth = [&] { noteTargetMemo(TargetMemoEvent::DepthFallback); return DepthSurfaceViewWithStencilWriteIntent(context, *state.depth, state.depthWrite, state.stencilTest, writesStencilTarget(state), overwrittenStencil(state)); }; auto depthView = memoServes ? repeatDepth(context, state, repeatedColors ? &targetProof : nullptr) : VkImageView{VK_NULL_HANDLE}; bool repeatedDepth = state.depth && depthView != VK_NULL_HANDLE; if (repeatedDepth) noteTargetMemo(TargetMemoEvent::DepthHit); if (state.depth && !repeatedDepth && !prepared.attachmentsFromMemo) depthView = prepareDepth(); if (repeatedColors && (targetMemoOwner.load(std::memory_order_relaxed) != &ThreadTargetMemo() || !colorProofMatches(targetProof, currentTargetProof(context)) || !std::ranges::all_of(targets, [](const TargetBinding& binding) { return binding.resident->Cached(); }))) { noteTargetMemo(TargetMemoEvent::PostDepthInvalidated); repeatedColors = false; admissionProof = currentTargetProof(context); prepareColors(); if (state.depth) depthView = prepareDepth(); repeatedDepth = false; } if (repeatedColors) { for (const auto& binding : targets) { binding.resident->NoteProved(); binding.resident->NoteUsed(); } noteTargetMemo(TargetMemoEvent::Accept); if (state.depth && !repeatedDepth) noteTargetMemo(TargetMemoEvent::AcceptWithDepthMiss); if (!VerifyTargetMemo()) noteTargetMemo(TargetMemoEvent::AvoidedRefreshLookups, targets.size()); } if ((repeatedColors || repeatedDepth) && VerifyTargetMemo()) { noteTargetMemo(TargetMemoEvent::VerifyChecked); const auto verifyProof = currentTargetProof(context); const auto ownProofBreaks = GuestMemory::OwnProofBreaks(); const auto ownPendingMoves = StorageTexture::OwnPendingMoves(); const auto ownRefreshWork = StorageTexture::OwnRefreshWork(); const auto* owed = targetObligation(context, state, repeatedColors ? std::span(targets) : std::span{}, repeatedDepth); Require(owed == nullptr, std::string("APS5_VERIFY_TARGET_MEMO: a repeated target skipped ") + (owed != nullptr ? owed : "")); if (repeatedColors) { const auto repeatedViews = targetViews; std::vector> repeatedResidents; for (const auto& binding : targets) repeatedResidents.push_back(binding.resident); prepareColors(); Require(repeatedViews == targetViews && std::ranges::equal(repeatedResidents, targets, {}, {}, &TargetBinding::resident), "APS5_VERIFY_TARGET_MEMO: a repeated color differs from its lookup"); } if (repeatedDepth) { const auto fullDepth = prepareDepth(); Require(fullDepth == depthView, "APS5_VERIFY_TARGET_MEMO: a repeated depth differs from its lookup"); } const auto* moved = StorageTexture::OwnRefreshWork() != ownRefreshWork ? "image content" : GuestMemory::OwnProofBreaks() != ownProofBreaks ? "proofs" : StorageTexture::OwnPendingMoves() != ownPendingMoves ? "pending" : verifyProof.MovedBefore(currentTargetProof(context)); Require(moved == nullptr, std::string("APS5_VERIFY_TARGET_MEMO: a repeated target's lookup moved ") + (moved != nullptr ? moved : "")); } if (state.depth && !prepared.attachmentsFromMemo) targetViews.push_back(depthView); if (memoConsulted) { const bool retainedOwner = ownsTargetMemo(ThreadTargetMemo()); const auto preparedProof = currentTargetProof(context); const bool unchangedDepth = (ThreadTargetMemo().depth.valid && ThreadTargetMemo().depth.proof == preparedProof && (repeatedDepth || (!state.depth && !ThreadTargetMemo().depth.descriptor))) || (state.depth && state.depth->samples != 1u && !ThreadTargetMemo().depth.valid); const bool unchanged = retainedOwner && repeatedColors && ThreadTargetMemo().colors.valid && ThreadTargetMemo().colors.proof == preparedProof && unchangedDepth; if (admissionProof == preparedProof) { if (!unchanged) rememberTargets(state, targets, targetViews, preparedProof); } else { noteTargetMemo(TargetMemoEvent::Admission); ThreadTargetMemo().Invalidate(); } } if (verifyAttachments) checkAttachments(state, prepared); timer.phase(PhasePrepare); const bool recordDraws = RecordDraws(); auto* recorder = prepared.recorder = Recorder::Active(); bool recordable = recordDraws && recorder != nullptr && dumpLimit == 0 && std::all_of(targets.begin(), targets.end(), [](const TargetBinding& binding) { return binding.resident != nullptr || binding.multisampled; }); auto& resolved = prepared.resolved; resolved = resolveDrawResources(context, state, draw, shaders, snapshots, indexBytes, recordable, plan, outcome, timer); if (stopAfterResolve.load(std::memory_order_relaxed) != 0) { const auto stop = stopAfterResolve.exchange(0, std::memory_order_relaxed); if (stop == 1) return false; if (stop == 2) throw std::runtime_error("injected failure after the draw's resources were resolved"); } if (state.depth && writesDepthTarget(state)) NoteDepthSurfaceWrite(context, *state.depth); auto& resources = resolved.resources; for (std::size_t index = 0; index < targets.size(); ++index) { auto& binding = targets[index]; if (binding.color.partialWriteMask == 0 || binding.multisampled || binding.resident == nullptr || binding.proxied || storesIntoResident(*resources, *binding.resident)) continue; const auto& color = binding.color; binding.resident = refreshResidentTarget(context, state, color, outcome, profile, [&] { return color.arrayLastSlice != 0 ? CachedStorageLayers(context, ArraySurfaceForTarget(color), color.arraySlice, color.layers) : CachedStorageSurface(context, SurfaceForTarget(color)); }); if (binding.resident != nullptr) targetViews[index] = binding.resident->AttachmentView(color.format, color.mip, color.depthSlice, color.layers, color.arraySlice); } if (args != nullptr && args->capturedRecords && std::ranges::any_of(targets, [&](const TargetBinding& binding) { if (resources->ReadsImage(binding.resident.get()) || resources->ReadsImageRange(binding.color.MemoryAddress(), binding.color.bytes)) return true; return (binding.proxied || binding.multisampled) && (!resources->SampledTextures().empty() || !resources->StorageImages().empty()); })) { inputs.result = DrawResult::NeedsIndividualRecords; return false; } if (!stencilReferences.empty() && resources->ChecksFaults()) recordable = false; if (!stencilReferences.empty()) { const auto readImages = resources->StorageImages(); const auto inputOverlaps = [&](std::uint64_t address, std::uint64_t bytes) { return std::ranges::any_of(inputs.inPlaceReads, [&](const auto& range) { return address < range.second && range.first < address + bytes; }); }; for (const auto& target : targets) { const bool imageRead = target.resident != nullptr && std::ranges::any_of(readImages, [&](const auto& image) { return image.first == target.resident->Image(); }); Require(!imageRead && !resources->ReadsImage(target.resident.get()) && !resources->ReadsOverlap(target.color.MemoryAddress(), static_cast(target.color.bytes)) && !inputOverlaps(target.color.MemoryAddress(), target.color.bytes), "stencil replay refuses attachment feedback reads"); } if (state.depth) { const auto bytes = static_cast(state.depth->extent.width) * state.depth->extent.height * 4u * std::max(state.depth->samples, 1u); Require(!resources->ReadsOverlap(state.depth->address, bytes) && !resources->ReadsOverlap(state.depth->stencilAddress, bytes) && !inputOverlaps(state.depth->address, bytes) && !inputOverlaps(state.depth->stencilAddress, bytes), "stencil replay refuses depth or stencil feedback reads"); const auto boundPlane = [&](std::uint64_t address, std::uint64_t length) { const auto overlaps = [&](std::uint64_t plane) { return plane != 0u && address < plane + bytes && plane < address + length; }; return overlaps(state.depth->address) || overlaps(state.depth->stencilAddress); }; for (const auto& shader : shaders) { for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages && binding.role != ShaderRecompiler::DescriptorRole::ImageTable) continue; for (std::size_t offset = 0; offset + 8u <= binding.guestDescriptor.size(); offset += 8u) { const auto words = std::span(binding.guestDescriptor).subspan(offset, 8u); if (words[0] == 0u && (words[1] & 0xffu) == 0u) continue; const auto texture = DecodeTextureResource(words); if (!DepthSurfaceAt(context, words, texture)) continue; const auto sampledBytes = static_cast(texture.width) * texture.height * 4u * std::max(texture.samples, 1u) * (static_cast(texture.depthOrLastArray) + 1u); Require(!boundPlane(texture.baseAddress, sampledBytes), "stencil replay refuses sampled depth-surface feedback"); } } } } } const auto& contentKey = resolved.contentKey; const bool cacheable = resolved.cacheable; built = resolved.built; // The memory-state decision of an indirect draw, made here after the resource build (which may // retire imports and wait for recorded work) and before anything is recorded, exactly as // VulkanDevice::dispatch decides for DISPATCH_INDIRECT: the GPU reads the records in place from // the host import unless storage-image results are pending over them (flushed, then synced), a // label or a copied buffer's write-back still has to land on them, or they are not imported; in // those cases (and with APS5_NO_GPU_INDIRECT_DRAW=1) the CPU reads them through the flush hook // and records plain draws with the same per-dimension rules. The import pointer stays valid: // refreshImports runs only under GuestMemory::GpuMutex, held here, and a retired import's // buffer is kept while the recorder is busy. auto& indirect = prepared.indirect; indirect.args = args; auto& records = prepared.records; if (args != nullptr && args->capturedRecords) { indirect.path.reset(); indirect.records = *args->capturedRecords; } else if (args != nullptr) { static const bool gpuIndirectDraws = std::getenv("APS5_NO_GPU_INDIRECT_DRAW") == nullptr; const auto decide = [&](std::uint64_t address, std::size_t bytes, const HostImport*& import) { if (StorageTexture::FlushPending(address, bytes, nullptr, "indirect draw arguments")) { if (recorder != nullptr) { Recorder::CountSync(2); recorder->Sync(); } return IndirectDrawPath::PendingImage; } if (recorder != nullptr && recorder->PendingLabelIn(address, bytes)) return IndirectDrawPath::PendingLabelOrCopy; const auto overlaps = [&](const auto& writer) { return writer->CopiedWritesOverlap(address, bytes); }; if (context.copiedWriters != nullptr && std::any_of(context.copiedWriters->begin(), context.copiedWriters->end(), overlaps)) return IndirectDrawPath::PendingLabelOrCopy; if (std::any_of(DrawCopiedWriters()->begin(), DrawCopiedWriters()->end(), overlaps)) return IndirectDrawPath::PendingLabelOrCopy; if ((import = HostImportFor(context, address, bytes)) == nullptr) return IndirectDrawPath::NotImported; static const bool settledReads = std::getenv("APS5_NO_SETTLED_INDIRECT_READ") == nullptr; if (settledReads && recorder != nullptr && recorder->PendingWriteSettled(address, bytes)) return IndirectDrawPath::Settled; return IndirectDrawPath::Gpu; }; const auto rangeBytes = args->RangeBytes(); if (rangeBytes == 0) { report(" indirect draw without records"); return false; } Require(rangeBytes <= std::numeric_limits::max(), "indirect draw record range overflow"); if (!gpuIndirectDraws) indirect.path = IndirectDrawPath::Disabled; else if (inputs.listRestartPrimitive != 0) indirect.path = IndirectDrawPath::FeatureGap; else indirect.path = decide(args->arguments, static_cast(rangeBytes), indirect.argumentImport); if (indirect.path == IndirectDrawPath::Gpu && args->countIndirect) { Require(context.drawIndirectCount, "indirect draw count without VK_KHR_draw_indirect_count must be resolved by the driver"); const auto countPath = decide(args->countAddress, 4, indirect.countImport); if (countPath != IndirectDrawPath::Settled) indirect.path = countPath; } if (indirect.path != IndirectDrawPath::Gpu) { // The reads wait for the producing batch through the flush hook, as the driver's // resolve did for every indirect dispatch before its GPU path. const auto readStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; FinishLeaseWrites(); const auto count = std::min(args->countIndirect ? Pm4::ReadDrawCount(*args) : args->count, args->count); records.reserve(count); for (std::uint32_t record = 0; record < count; ++record) records.push_back(Pm4::ReadDrawArguments(*args, record)); if (profile) indirect.readMs = std::chrono::duration(std::chrono::steady_clock::now() - readStart).count(); if (inputs.listRestartPrimitive != 0) CompactIndirectListRestart(context, draw, inputs, records); indirect.records = records; if (std::none_of(records.begin(), records.end(), [](const Pm4::DrawArguments& record) { return record.count != 0 && record.instances != 0; })) { CountIndirectDraw(indirect.path, indirect.readMs); report(" indirect draw with empty records"); return false; } } } // A draw whose only completion work is a BDA fault check (the rect-list stages carry a fault // buffer, so every rect-list draw needed one) is recorded too, with the check as a completion // action like a dispatch's write-back: its own batch would first wait for everything recorded // before it. A draw that writes a copied buffer (at the menu stage: 0x48-byte constant buffers // inside an import but not at its storage offset alignment, so GuestBufferMemory copies them // and every guest buffer counts as writable) is recorded and then waited for at once: the // write-back runs before the next packet, without the separate command batch and fence a // synchronous draw takes. The copied write-back is listed in DrawCopiedWriters, which lets such // draws run without the wait; both consumers of the device's list in VulkanDevice.cpp // (DispatchIndirect's argument check and the fill HLE's range check, see Draw.hpp) consult this // list too. A draw holding an address-based build's lease (which pins guest allocations until // the write-back releases it) runs free like the dispatch path's: the completion releases the // lease, and a guest thread that needs a leased allocation syncs the recorder through the // registry's pin waiter (see SyncLeaseWork); APS5_SYNC_LEASE_DISPATCH=1 waits for such draws // at once as before. Debug aids: // APS5_SYNC_COMPLETION_DRAWS=1 keeps every draw with completion work synchronous; // APS5_NO_RECORDER_SYNC_DRAWS=1 gives the waited-for draws their own batch as before; // APS5_NO_RECORD_COPIED_DRAWS=1 waits for copied-write draws at once instead of listing them. static const bool syncCompletionDraws = std::getenv("APS5_SYNC_COMPLETION_DRAWS") != nullptr; static const bool recorderSyncDraws = std::getenv("APS5_NO_RECORDER_SYNC_DRAWS") == nullptr; static const bool recordCopiedDraws = std::getenv("APS5_NO_RECORD_COPIED_DRAWS") == nullptr; const bool completion = prepared.completion = resources->NeedsCompletion(); const bool copiedWrites = completion && resources->HasCopiedWrites(); // A lease only forces the wait when deferred release is off. const bool lease = resources->HoldsLease() && SyncLeaseWork(); outcome.completion = completion; outcome.recorded = recordable; // Whether the copied write-back is listed in DrawCopiedWriters instead of waited for. auto& listed = prepared.listed; if (!recordable) { outcome.reason = !recordDraws || dumpLimit != 0 ? SyncDisabled : recorder == nullptr ? SyncNoRecorder : SyncNotResident; } else if (completion && (syncCompletionDraws || copiedWrites || lease)) { outcome.reason = syncCompletionDraws ? SyncDisabled : lease ? SyncLease : SyncCopiedWrites; if (syncCompletionDraws) outcome.recorded = false; else if (copiedWrites && !lease && recordCopiedDraws) listed = true; else if (recorderSyncDraws) outcome.waited = true; else outcome.recorded = false; } const bool recorded = prepared.recorded = outcome.recorded; // A build this recorded draw can share with later identical ones goes into the cache (a cache // hit is reusable by construction, so `recorded` holds for it; one with completion work is // never reusable). if (cacheable && built != nullptr && recorded && resources->Reusable()) SharedResourceCache().Insert(contentKey, resources); // A recorded draw renders into its resident targets in the general layout (recordDraw). Debug // aid: APS5_DRAW_TRANSITIONS=1 keeps the per-draw upload and download barriers, the layout // transitions of every target and one pass per draw, as before. static const bool drawTransitions = std::getenv("APS5_DRAW_TRANSITIONS") != nullptr; const bool lean = prepared.lean = recorded && !drawTransitions; const bool multisampled = prepared.multisampled = std::any_of(targets.begin(), targets.end(), [](const TargetBinding& binding) { return binding.multisampled; }); Require(lean || !multisampled, "multisampled draws are only rendered as recorded draws"); for (const auto& binding : targets) { if (!binding.multisampled) continue; const auto& sources = resources->MultisampleSources(); const auto reads = std::count(sources.begin(), sources.end(), binding.color.surfaceAddress); Require(reads == 0, "sampling a multisampled color target the draw renders to is not implemented"); } for (const auto& binding : targets) { if (binding.color.partialWriteMask == 0 || binding.multisampled) continue; Require(lean && binding.resident != nullptr && !binding.proxied, "a partial write of a packed color target is merged into its resident image by a recorded draw only"); Require(storesIntoResident(*resources, *binding.resident), "the partial write of a packed color target does not store into the target's resident image"); } if (!lean && (!resolved.moved.empty() || resolved.resources->HasStagedCopies())) { if (resolved.resources->SpaceReuse()) static_cast(resolved.resources->ReleaseSpace()); resolved.resources = std::make_shared(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, static_cast(indexBytes), snapshots); resolved.moved.clear(); } if (state.depth) RequireNoNativeDepthFeedback_nid_no_patch(context, *state.depth, resources->SampledTextures()); APS5_LOG_CHARS_OUT_DEBUG("Creating Pipeline"); // The state is copied only when a mask must change. auto& masked = prepared.masked; masked = maskedState(state, inputs.fragmentOutputs); if (std::any_of(targets.begin(), targets.end(), [](const TargetBinding& binding) { return binding.proxied || binding.stagedTemporary != nullptr || binding.dump != nullptr; })) recipeOut = nullptr; for (std::size_t index = 0; index < targets.size(); ++index) { if (!targets[index].proxied) continue; if (!masked.has_value()) masked = state; masked->colors[index].format = AttachmentProxyFormat(context, state.colors[index].format); masked->blends.at(state.colors[index].exportIndex).colorWriteMask &= VK_COLOR_COMPONENT_R_BIT; } const State& pipelineState = masked.has_value() ? *masked : state; static const bool verifySetLayouts = std::getenv("APS5_VERIFY_SET_LAYOUTS") != nullptr; if (verifySetLayouts && context.descriptorCache != nullptr) { const auto described = DescribeSetLayouts(context, shaders); const auto built = resources->SetLayouts(); Require(described.layouts.main == built.main && described.layouts.fragment == built.fragment && described.layouts.split == built.split && std::ranges::equal(described.mainKey, built.mainKey) && std::ranges::equal(described.fragmentKey, built.fragmentKey), "set layouts described from the shaders differ from the draw's"); } auto& stencilReplay = prepared.stencilReplay; for (const auto reference : stencilReferences) { auto selected = pipelineState; selected.stencilReplayReference = reference; selected.stencilFront.reference = reference; selected.stencilBack.reference = reference; auto selectedPipeline = stencilReplay.empty() ? CachedPipeline(context, selected, inputs.VertexLayout(), *resources, shaders, lean ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) : stencilReplay.front().second; Require(!selectedPipeline->SplitsFaces() && !selectedPipeline->SplitsSecondChannel(), "stencil replay refuses pipeline face or channel splits"); stencilReplay.emplace_back(reference, std::move(selectedPipeline)); } auto& pipeline = prepared.pipeline; const auto attachmentLayout = lean ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; if (!stencilReplay.empty()) { pipeline = stencilReplay.front().second; } else { const bool memoized = stencilReferences.empty() && std::none_of(targets.begin(), targets.end(), [](const TargetBinding& binding) { return binding.proxied || binding.multisampled; }); const auto layouts = resources->SetLayouts(); std::uint64_t storeHash = 0; if (memoized) pipeline = shapePipeline(context, prepared.shape, inputs.VertexLayout(), layouts, shaders, attachmentLayout, inputs.fragmentOutputs); if (pipeline != nullptr && VerifyShapeMemo()) { Require(CachedPipeline(context, pipelineState, inputs.VertexLayout(), layouts, shaders, attachmentLayout) == pipeline, "APS5_VERIFY_SHAPE_MEMO: the shape memo's pipeline differs from the pipeline store's"); noteShapeMemoVerified(true); } const bool repeated = pipeline != nullptr; if (!repeated && DefersPipelineBuild(shaders)) { pipeline = ResidentPipelineOrDeferredBuild(context, pipelineState, inputs.VertexLayout(), layouts, shaders, attachmentLayout, &storeHash); if (pipeline == nullptr) { report(" pipeline building in the background"); return false; } } if (!repeated && pipeline == nullptr) pipeline = CachedPipeline(context, pipelineState, inputs.VertexLayout(), layouts, shaders, attachmentLayout, nullptr, &storeHash); if (memoized) rememberShape(context, prepared.shape, targets, repeated ? nullptr : &pipeline, storeHash, inputs.VertexLayout(), layouts, shaders, attachmentLayout, inputs.fragmentOutputs); } // Resident targets' views are stable while their storage image lives, so the framebuffer is // reused with the pipeline; a per-draw RenderTarget gets a framebuffer of its own. auto& owners = prepared.owners; owners.reserve(targets.size()); auto& framebufferOwners = prepared.framebufferOwners; framebufferOwners.reserve(targets.size()); for (const auto& binding : targets) { owners.push_back(binding.resident); framebufferOwners.push_back(binding.multisampled ? binding.multisampleOwner : binding.resident); } Require(!pipeline->ReordersSamples() || std::ranges::none_of(state.colors, [](const ColorTarget& color) { return color.staged; }), "a partial write of a multisampled packed color target on a device that puts the guest's samples in order is not implemented"); auto& framebuffer = prepared.framebuffer; framebuffer = pipeline->AcquireFramebuffer(targetViews, framebufferOwners, state.renderExtent, state.renderLayers); auto& reordered = prepared.reordered; auto& reorderPass = prepared.reorderPass; if (pipeline->ReordersSamples()) { reorderPass = SampleOrderPassFor(context, pipelineState, pipeline->HostSampleOrder()); for (const auto& step : PlanSampleOrder(context, state, pipeline->HostSampleOrder())) { if (step.attachment < targets.size()) reordered.push_back(MultisampleTargetOrderTarget(context, targets[step.attachment].color)); else reordered.push_back(DepthSurfaceOrderTarget(context, *state.depth)); Require(reordered.back().method == step.method, "a reordered attachment's surface disagrees with the planned way of putting its samples in order"); } } prepared.depthLocations = passDepthLocations(context, pipelineState, *pipeline); timer.phase(PhasePipeline); APS5_LOG_CHARS_OUT_DEBUG("Pipeline created"); if (VerifyDrawPlan()) requireDrawPlanRepeats(context, state, draw, shaders, plan); return true; } void recordPreparedDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, PreparedDraw& prepared) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; static const bool traceDraws = std::getenv("APS5_TRACE_DRAWS") != nullptr; static AgcDriver::Mutex dumpMutex; static std::map dumped; auto& timing = *prepared.timing; auto& timer = prepared.timer; auto& outcome = prepared.outcome; const auto* built = prepared.built; const auto waitedBefore = prepared.waitedBefore; auto& ownWaitedMs = prepared.ownWaitedMs; const auto report = [&](const char* suffix) { reportDrawEnd(state, timer, built, outcome, waitedBefore, ownWaitedMs, suffix); }; auto* recipeOut = prepared.recipeOut; const auto& stencilReferences = prepared.stencilReferences; auto& inputs = prepared.inputs; const auto* args = prepared.args; const int dumpLimit = prepared.dumpLimit; auto& targets = prepared.targets; const auto& targetViews = prepared.targetViews; auto* recorder = prepared.recorder; auto& resolved = prepared.resolved; auto& resources = resolved.resources; const auto& contentKey = resolved.contentKey; const bool cacheable = resolved.cacheable; auto& indirect = prepared.indirect; const bool completion = prepared.completion; const bool listed = prepared.listed; const bool recorded = prepared.recorded; const bool lean = prepared.lean; const bool multisampled = prepared.multisampled; const auto& masked = prepared.masked; const auto& stencilReplay = prepared.stencilReplay; const auto& pipeline = prepared.pipeline; const auto& owners = prepared.owners; const auto& framebuffer = prepared.framebuffer; const auto& reordered = prepared.reordered; const auto& reorderPass = prepared.reorderPass; const auto& depthLocations = prepared.depthLocations; InlineList, 8> slices; for (const auto& binding : targets) slices.EmplaceBack(binding.color.arraySlice, binding.color.arrayLastSlice != 0 ? binding.color.layers : 1u); if (lean) { BorrowedDraw record{resources, pipeline, framebuffer}; record.recorder = recorder; record.moved = resolved.moved; record.targetViews = targetViews; record.targets = owners; record.targetSlices = slices.Span(); for (const auto& binding : targets) { if (binding.proxied) record.proxies.push_back(binding.resident); if (binding.multisampled) { record.multisampleImages.push_back(binding.multisampleImage); record.multisampleTargets.push_back(binding.multisampleOwner); } if (binding.stagedTemporary != nullptr) { record.multisampleImages.push_back(binding.stagedTemporary->Image()); const auto& color = binding.color; const auto bounds = VkRect2D{{0, 0}, color.extent}; auto area = state.scissor; area.offset.x = std::max(area.offset.x, bounds.offset.x); area.offset.y = std::max(area.offset.y, bounds.offset.y); const auto right = std::min(static_cast(state.scissor.offset.x) + state.scissor.extent.width, color.extent.width); const auto bottom = std::min(static_cast(state.scissor.offset.y) + state.scissor.extent.height, color.extent.height); area.extent = {static_cast(std::max(right - area.offset.x, 0)), static_cast(std::max(bottom - area.offset.y, 0))}; record.staged.push_back({binding.stagedTemporary, binding.stagedTarget, color.stagedMask, color.samples, area}); } } record.indirect = args != nullptr ? &indirect : nullptr; record.listed = listed; record.completion = completion; record.waited = outcome.waited; record.stencilReplay = stencilReplay; record.reordered = reordered; record.reorderPass = reorderPass; record.depthLocations = depthLocations; record.spaceKeep = &prepared.spaceKeep; record.masked = prepared.masked.has_value() ? &*prepared.masked : nullptr; recordDraw(context, state, draw, shaders, inputs, record, outcome, timer, ownWaitedMs, prepared.trace); if (prepared.passAttachments) rememberAttachments(context, state, prepared); // The recipe for the caller's draw-cache entry (design_cpu_final M8, rule R3 for draws): // only a template the resource cache serves under this content key (reusable: no lease, // no copied writes, every direct region import- or mirror-served) of a direct draw, so a // hit's proof is the template's ProveCurrent and nothing needs completion work. if (recipeOut != nullptr && DrawRecipes() && cacheable && !outcome.waited && args == nullptr && resources->Reusable() && !resources->SpaceReuse() && !multisampled && !pipeline->ReordersSamples()) { auto recipe = std::make_shared(); recipe->device = context.device; recipe->templateRef = resources; recipe->key = contentKey; recipe->pipeline = pipeline; recipe->framebuffer = framebuffer; for (const auto& owner : owners) recipe->targets.emplace_back(owner); recipe->targetViews = targetViews; recipe->passKey = DrawRenderPassKey(context, state, targetViews); recipe->vertexInput = inputs.VertexLayout(); recipe->pushStages = PushConstantStages(shaders); if (recipe->pushStages != 0) { recipe->pushBytes = AssemblePushConstants(shaders); resources->PatchPushConstants(recipe->pushBytes); } recipe->masked = masked; recipe->fragmentOutputs = inputs.fragmentOutputs; recipe->shaderStages = inputs.shaderStages; recipe->hasDepth = state.depth.has_value(); *recipeOut = std::move(recipe); } timing.Mark("draw_and_resource_release"); report(outcome.waited ? (outcome.reason == SyncLease ? " recorded then waited (lease)" : " recorded then waited (copied writes)") : completion ? " recorded with completion" : " recorded"); return; } if (prepared.passAttachments) attachmentMemo().valid = false; const bool gpuIndirect = args != nullptr && indirect.path == IndirectDrawPath::Gpu; const auto touches = [&](std::uint64_t begin, std::uint64_t end) { const auto bytes = static_cast(end - begin); if (resources->WritesOverlap(begin, bytes) || resources->ReadsOverlap(begin, bytes)) return true; if (!gpuIndirect) return false; return (begin < args->arguments + args->RangeBytes() && args->arguments < end) || (args->countIndirect && begin < args->countAddress + 4 && args->countAddress < end); }; static_cast(StorageTexture::StoreDrawnLinearTouching("draw access", [&](std::uint64_t begin, std::uint64_t end) { return touches(begin, end) || std::any_of(inputs.inPlaceReads.begin(), inputs.inPlaceReads.end(), [&](const auto& read) { return read.first < end && begin < read.second; }); }, resources->HoldsLease() || resources->UsesAddressTable() || resources->HasCopiedWrites())); if (UsesMeshWindow(shaders)) PrepareMeshWindow(context); APS5_LOG_CHARS_OUT_DEBUG("Creating CommandBatch"); std::optional batch; if (!recorded) { // The color-target detiles below take their descriptor sets from a fresh batch. if (context.detiler != nullptr) context.detiler->BeginBatch(); batch.emplace(context); } using CommandClass = Recorder::CommandClass; const auto countBarrier = [&](std::uint32_t count = 1) { if (recorded) Recorder::CountBarriers(CommandClass::Draw, count); }; // A queued DCC key store over memory the draw writes or reads in place (unknown for an // address-based build), or over its GPU-side records, lands before it, as before a dispatch // (VulkanDevice::dispatch). if (recorded && recorder->HasQueuedKeyStores() && (resources->HoldsLease() || recorder->AnyQueuedKeyStore(touches))) recorder->FlushKeyStores(); // A queued label store over such memory likewise (Recorder::RecordStore). if (recorded && recorder->HasQueuedStores() && (resources->HoldsLease() || recorder->AnyQueuedStore(touches))) recorder->FlushStores(); const auto commands = recorded ? recorder->Commands() : batch->Handle(); if (recorded) prepared.spaceKeep = reserveSpaceKeep(*recorder, *resources); std::optional batchRecording; if (!recorded) batchRecording.emplace().Begin(commands, false); auto& recording = recorded ? recorder->GraphicsState() : *batchRecording; if (recorded) recorder->PrepareSampleSlot(); APS5_LOG_CHARS_OUT_DEBUG("CommandBatch created"); // The draw's [gputime] class range: from its first barrier to the download barrier. const auto drawTiming = recorded ? recorder->BeginGpuTiming(CommandClass::Draw) : Recorder::NoTiming; if (recorded && Recorder::BarrierValidate()) { auto reads = resources->InPlaceReads(); reads.insert(reads.end(), inputs.inPlaceReads.begin(), inputs.inPlaceReads.end()); if (gpuIndirect) { reads.emplace_back(args->arguments, args->arguments + args->RangeBytes()); if (args->countIndirect) reads.emplace_back(args->countAddress, args->countAddress + 4); } auto images = resources->StorageImages(); for (const auto& binding : targets) { if (binding.resident != nullptr) images.emplace_back(binding.resident->Image(), true); } recorder->NoteAccess(CommandClass::Draw, Recorder::Access{reads, resources->GpuWrites(), images, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | inputs.shaderStages, resources->HoldsLease()}); } std::unique_ptr scratch; std::shared_ptr argumentSnapshot; VkBuffer argumentBuffer = VK_NULL_HANDLE; VkDeviceSize argumentOffset = 0; bool rewritten = false; VkMemoryBarrier upload{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; upload.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; upload.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | inputs.shaderStages, 0, 1, &upload, 0, nullptr, 0, nullptr); countBarrier(); if (state.depth) { RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT); countBarrier(); } APS5_LOG_CHARS_OUT_DEBUG("Upload barrier recorded"); if (inputs.vertexInputBehindGpuWrite || inputs.indexInputBehindGpuWrite) { RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, (inputs.vertexInputBehindGpuWrite ? VkAccessFlags{VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT} : VkAccessFlags{0}) | (inputs.indexInputBehindGpuWrite ? VkAccessFlags{VK_ACCESS_INDEX_READ_BIT} : VkAccessFlags{0})); countBarrier(); } const auto pixelLdsSubgroup = PixelFunctionLdsSubgroup(shaders); if (pixelLdsSubgroup != 0u) PreparePixelFunctionLds(context, commands, pixelLdsSubgroup); std::shared_ptr meshArguments; if (state.stages.mesh && state.tessellationCapture != nullptr) { recordCaptureBarrier(context, commands); countBarrier(); meshArguments = state.tessellationCapture->header; argumentBuffer = meshArguments->Handle(); } else if (state.stages.mesh && args != nullptr) { meshArguments = recordMeshArguments(context, commands, recorder, recorded, state, draw, indirect, countBarrier, inputs.restartTable); argumentBuffer = meshArguments->Handle(); } else if (!inputs.restartTable.empty()) { meshArguments = directMeshArguments(context, draw, inputs.restartTable); } else if (gpuIndirect) { rewritten = recordIndirectArguments(context, commands, recorder, recorded, indirect, scratch, argumentSnapshot, argumentBuffer, argumentOffset, countBarrier); } for (auto& binding : targets) { if (binding.proxied) { binding.resident->RecordAttachmentProxyLoad(commands, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); countBarrier(2); continue; } if (binding.resident != nullptr) { imageBarrier(context, commands, binding.resident->Image(), VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, binding.color.mip, 1, binding.resident->ImageDepth() == 1 ? binding.color.arraySlice : 0, binding.resident->ImageDepth() == 1 ? binding.color.layers : 1}); countBarrier(); continue; } VkBufferImageCopy copy{}; copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; copy.imageExtent = {binding.color.extent.width, binding.color.extent.height, 1}; if (binding.banded) { copy.bufferRowLength = binding.bandPitch; copy.imageOffset = {binding.band.offset.x, binding.band.offset.y, 0}; copy.imageExtent = {binding.band.extent.width, binding.band.extent.height, 1}; } const VkBuffer linear = binding.gpuTiling ? binding.linearDevice->Handle() : binding.transfer->Handle(); countBarrier(binding.gpuTiling ? 4 : 2); if (binding.gpuTiling) { CopyBuffer(context, commands, binding.tiled->Handle(), 0, binding.tiledDevice->Handle(), 0, binding.original.size()); memoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); context.detiler->Dispatch(commands, TextureTileMode::kR64KBX, binding.color.elementBytes, binding.tiledDevice->Handle(), 0, binding.linearDevice->Handle(), 0, binding.mip, false, 0, false, {.pipeBankXor = binding.color.pipeBankXor}); memoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); } imageBarrier(context, commands, binding.target->Image(), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, VK_ACCESS_TRANSFER_WRITE_BIT); context.Resolved(&DeviceFunctions::cmdCopyBufferToImage, "vkCmdCopyBufferToImage")(commands, linear, binding.target->Image(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©); PerformanceTrace::Amount("Graphics.Copy", 1); PerformanceTrace::Amount("Graphics.Copy.bytes", binding.original.size()); imageBarrier(context, commands, binding.target->Image(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT); } std::vector> reorderKept; RecordSampleOrder(context, recording, reorderPass, reordered, true, reorderKept); APS5_LOG_OUT_DEBUG("Beginning pipeline renderExtent=%ux%u", state.renderExtent.width, state.renderExtent.height); pipeline->Begin(recording, *framebuffer, state.renderExtent, state, masked.has_value() ? &*masked : nullptr); APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); const auto drawUse = recorded ? resources->BeginDrawUse(*recorder) : nullptr; resources->BindDrawUse(commands, pipeline->Layout(), drawUse.get()); if (pixelLdsSubgroup != 0u) BindPixelFunctionLds(context, commands, pipeline->Layout()); if (UsesMeshWindow(shaders)) BindMeshWindow(context, commands, pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); pushDrawConstants(*pipeline, commands, state, draw, shaders, *resources, nullptr, 0, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty(), inputs.meshLayerStride); APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded"); std::uint32_t subdraw = 0; if (recorded) noteDrawFaultToken(context, *recorder, commands, shaders, draw, static_cast(state.stages.mesh.has_value() ? AgcDriver::FaultStage::mesh : AgcDriver::FaultStage::graphics), args); if (stencilReplay.empty()) recordDrawCommands(context, commands, state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw); else { recordStencilReplay(context, recording, state, masked.has_value() ? &*masked : nullptr, draw, inputs, stencilReplay, shaders, *resources); if (recorded) for (const auto& [reference, selectedPipeline] : stencilReplay) recorder->Keep(selectedPipeline); } if (pipeline->SplitsFaces()) { pipeline->ContinueBackFaces(recording, state, masked.has_value() ? &*masked : nullptr); recordDrawCommands(context, commands, state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw); } if (pipeline->SplitsSecondChannel()) { pipeline->ContinueSecondChannel(recording, state, masked.has_value() ? &*masked : nullptr); recordDrawCommands(context, commands, state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw); } if (meshArguments != nullptr && recorded) recorder->Keep(meshArguments); if (argumentSnapshot != nullptr && recorded) recorder->Keep(argumentSnapshot); if (state.tessellationCapture != nullptr && recorded) { recorder->Keep(state.tessellationCapture->header); recorder->Keep(state.tessellationCapture->items); } if (args != nullptr) CountIndirectDraw(indirect.path, indirect.readMs, rewritten); auto checkRecords = indirectRecordCheck(args != nullptr ? &indirect : nullptr); APS5_LOG_CHARS_OUT_DEBUG("Draw recorded"); if (recorded) recorder->EndPassSamples(); EndRenderPass(context, commands); RecordSampleOrder(context, recording, reorderPass, reordered, false, reorderKept); if (depthLocations) { RecordDepthSampleLocations(context, commands, *depthLocations); countBarrier(2); reorderKept.push_back(depthLocations->keep); } if (recorded) { for (auto& object : reorderKept) recorder->Keep(std::move(object)); } APS5_LOG_CHARS_OUT_DEBUG("Render pass ended"); for (auto& binding : targets) { if (binding.proxied) { binding.resident->RecordAttachmentProxyStore(commands, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); countBarrier(2); continue; } if (binding.resident != nullptr) { imageBarrier(context, commands, binding.resident->Image(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, binding.color.mip, 1, binding.resident->ImageDepth() == 1 ? binding.color.arraySlice : 0, binding.resident->ImageDepth() == 1 ? binding.color.layers : 1}); countBarrier(); continue; } VkBufferImageCopy copy{}; copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; copy.imageExtent = {binding.color.extent.width, binding.color.extent.height, 1}; if (binding.banded) { copy.bufferRowLength = binding.bandPitch; copy.imageOffset = {binding.band.offset.x, binding.band.offset.y, 0}; copy.imageExtent = {binding.band.extent.width, binding.band.extent.height, 1}; } countBarrier(binding.gpuTiling ? 4 : 2); imageBarrier(context, commands, binding.target->Image(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); const VkBuffer linear = binding.gpuTiling ? binding.linearDevice->Handle() : binding.transfer->Handle(); VkBufferMemoryBarrier reuse{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; reuse.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; reuse.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; reuse.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; reuse.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; reuse.buffer = linear; reuse.size = VK_WHOLE_SIZE; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, &reuse, 0, nullptr); context.Resolved(&DeviceFunctions::cmdCopyImageToBuffer, "vkCmdCopyImageToBuffer")(commands, binding.target->Image(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, linear, 1, ©); PerformanceTrace::Amount("Graphics.Copy", 1); PerformanceTrace::Amount("Graphics.Copy.bytes", binding.original.size()); if (binding.gpuTiling) { memoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT); if (dumpLimit > 0) { std::lock_guard lock(dumpMutex); if (dumped[binding.color.address] < dumpLimit) { binding.dump = std::make_unique(context, binding.linearDevice->Size(), VK_BUFFER_USAGE_TRANSFER_DST_BIT); CopyBuffer(context, commands, binding.linearDevice->Handle(), 0, binding.dump->Handle(), 0, binding.linearDevice->Size()); } } context.detiler->Dispatch(commands, TextureTileMode::kR64KBX, binding.color.elementBytes, binding.linearDevice->Handle(), 0, binding.tiledDevice->Handle(), 0, binding.mip, true, 0, false, {.pipeBankXor = binding.color.pipeBankXor}); memoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); CopyBuffer(context, commands, binding.tiledDevice->Handle(), 0, binding.tiled->Handle(), 0, binding.original.size()); } } VkMemoryBarrier download{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; download.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT; download.dstAccessMask = VK_ACCESS_HOST_READ_BIT; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | inputs.shaderStages, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &download, 0, nullptr, 0, nullptr); countBarrier(); if (recorded) recorder->EndGpuTiming(drawTiming); APS5_LOG_CHARS_OUT_DEBUG("Download barrier recorded"); APS5_LOG_CHARS_OUT_DEBUG("SubmitAndWait"); timer.phase(PhaseRecord); if (recorded) { keepRecordedDraw(*recorder, resources, pipeline, framebuffer, inputs, owners, slices.Span(), state.scissor, std::move(scratch), std::move(checkRecords), listed, completion, outcome, drawUse, prepared.spaceKeep != nullptr ? prepared.spaceKeep.get() : nullptr); timer.phase(PhaseKeep); if (outcome.waited) { // The wait the dispatch path makes for such work (source 3, "address-based"): the // write-back runs before the next packet, so the CPU never reads copied results or // touches a leased allocation before they landed. Recorder::CountSync(3); const auto ownBefore = profile ? Recorder::ThreadWaitedMs() : 0.0; recorder->Sync(); if (profile) ownWaitedMs += Recorder::ThreadWaitedMs() - ownBefore; timer.phase(PhaseSync); } report(outcome.waited ? (outcome.reason == SyncLease ? " recorded then waited (lease)" : " recorded then waited (copied writes)") : completion ? " recorded with completion" : " recorded"); return; } { // The recorder sync SubmitAndWait makes is the draw's own wait, not a nested hook wait. const auto ownBefore = profile ? Recorder::ThreadWaitedMs() : 0.0; batch->SubmitAndWait(); if (!stencilReferences.empty()) resources->CheckFaults(); if (profile) ownWaitedMs += Recorder::ThreadWaitedMs() - ownBefore; } if (checkRecords) checkRecords(); timer.phase(PhaseSync); APS5_LOG_CHARS_OUT_DEBUG("SubmitAndWait OK"); for (const auto& binding : targets) GuestMemory::CheckRange(reinterpret_cast(binding.color.MemoryAddress()), binding.color.bytes, 256, true); for (auto& binding : targets) { if (!binding.dump) continue; std::lock_guard lock(dumpMutex); char name[64]; std::snprintf(name, sizeof(name), "target_%llx_%d.raw", static_cast(binding.color.address), dumped[binding.color.address]++); if (std::FILE* file = std::fopen(name, "wb")) { const std::uint32_t header[3] = {binding.color.extent.width, binding.color.extent.height, static_cast(binding.color.format)}; std::fwrite(header, sizeof(header), 1, file); std::fwrite(binding.dump->Bytes().data(), 1, binding.dump->Bytes().size(), file); std::fclose(file); } } APS5_LOG_CHARS_OUT_DEBUG("Shader resources WriteBack"); resources->WriteBack(); APS5_LOG_CHARS_OUT_DEBUG("Shader resources WriteBack OK"); static const bool skipTargetWrite = std::getenv("APS5_NO_TARGET_WRITEBACK") != nullptr; for (const auto& binding : targets) { if (skipTargetWrite) break; if (binding.resident != nullptr) { // The results stay on the GPU until something reads the target's memory. binding.resident->MarkSliceDirty(binding.color.arraySlice, binding.color.arrayLastSlice != 0 ? binding.color.layers : 1u); continue; } if (binding.gpuTiling) GuestMemory::WriteChanged(binding.color.address, binding.tiled->Bytes(), binding.original); else if (binding.banded) GuestMemory::WriteChanged(binding.color.address + binding.bandOffset, binding.transfer->Bytes(), binding.original); else WriteColorTarget(binding.color, binding.transfer->Bytes()); // The stored texels are the whole target now, so later reads must see them rather than a fast clear. const auto targetBytes = ColorTargetLayout(binding.color.extent.width, binding.color.extent.height, binding.color.tileMode, binding.color.elementBytes).Bytes(); MarkDccUncompressed(binding.color.dccAddress, targetBytes, colorKeyCount(binding.color, targetBytes)); } timer.phase(PhaseWriteBack); if (profile && traceDraws) { // A synchronous draw's inputs and target sample are described as a rendering debug aid; // the ~0.5 ms that takes (Describe samples every bound range and reads its DCC keys) is // shown as its own phase and kept out of the plain profile. std::size_t nonzero = 0; std::size_t sampled = 0; if (!targets.empty() && targets.front().resident == nullptr) { const auto bytes = targets.front().gpuTiling ? targets.front().tiled->Bytes() : targets.front().transfer->Bytes(); sampled = bytes.size() / 64; for (std::size_t i = 0; i < bytes.size(); i += 64) nonzero += bytes[i] != std::byte{0}; } std::fprintf(stderr, "[draw] inputs:%s\n", resources->Describe().c_str()); if (targets.size() > 1) { std::string list; for (const auto& binding : targets) { char entry[64]; std::snprintf(entry, sizeof(entry), " 0x%llx(%d,%ux%u)", static_cast(binding.color.address), static_cast(binding.color.format), binding.color.extent.width, binding.color.extent.height); list += entry; } std::fprintf(stderr, "[draw] targets:%s\n", list.c_str()); } timer.phase(PhaseDescribe); char suffix[160]; std::snprintf(suffix, sizeof(suffix), " synchronous (%s), first 0x%llx format %d (%zu of %zu sampled bytes nonzero)", SyncReasonNames[outcome.reason], static_cast(state.color.address), static_cast(state.color.format), nonzero, sampled); report(suffix); } else { report(" synchronous"); } APS5_LOG_CHARS_OUT_DEBUG("Draw finished"); } } constexpr std::uint64_t MaxCapturedTriangles = 1ull << 20u; void drawTessellationGeometry(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, const DrawTraceContext* trace) { using Stage = ShaderRecompiler::ShaderStage; Require(context.meshShader && context.geometryShader, "tessellation followed by a geometry stage needs mesh and geometry shaders"); Require(!draw.indirect, "an indirect draw with tessellation and a geometry stage must be resolved by the driver"); Require(draw.instanceCount <= 1u, "tessellation followed by a geometry stage is drawn for one instance only"); if (draw.indexCount == 0 || draw.instanceCount == 0) return; const auto& tessellation = *state.stages.tessellation; const auto& geometry = *state.stages.tessellationGeometry; std::vector first; std::vector second; for (const auto& shader : shaders) { if (shader.stage != Stage::Mesh && shader.stage != Stage::Fragment) first.push_back(shader); if (shader.stage == Stage::Mesh || shader.stage == Stage::Fragment) second.push_back(shader); } Require(second.size() == 2u && second.front().stage == Stage::Mesh && std::ranges::count_if(first, [](const CompiledShader& shader) { return shader.stage == Stage::Geometry; }) == 1, "tessellation followed by a geometry stage needs its capture and mesh stages"); const auto patches = static_cast(draw.indexCount / tessellation.inputControlPoints); const auto level = static_cast(std::ceil(std::clamp(state.stages.maxTessellationLevel, 1.0f, 64.0f))) + 1u; const auto perPatch = 2u * level * level; const auto capacity = static_cast(std::min(perPatch * patches, MaxCapturedTriangles)); auto capture = std::make_shared(); capture->header = std::make_shared(context, ShaderRecompiler::MeshCapturedHeaderBytes, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); std::array header{}; header[1] = 1u; header[2] = 1u; header[ShaderRecompiler::MeshCapturedCapacityDword] = capacity; std::memcpy(capture->header->Bytes().data(), header.data(), sizeof(header)); capture->items = std::make_shared(context, static_cast(capacity) * 3u * geometry.esgsItemSize * sizeof(std::uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); auto tessellated = state; tessellated.stages.path = ShaderPath::Tessellation; tessellated.stages.tessellationGeometry.reset(); tessellated.rasterizerDiscard = true; tessellated.tessellationCapture = capture; Draw(context, tessellated, draw, first, snapshots, nullptr, trace); auto meshed = state; meshed.stages.path = ShaderPath::Geometry; meshed.stages.mesh = geometry; meshed.stages.tessellation.reset(); meshed.stages.tessellationGeometry.reset(); meshed.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; meshed.tessellationCapture = capture; const Pm4::DrawParameters captured{0, 3u, 0, 1u, 0, false, 0, 0}; Draw(context, meshed, captured, second, snapshots, nullptr, trace); } std::vector DrawResourceContentKey(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders) { if (!EarlyDrawKeys() || shaders.empty() || std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program == nullptr; })) return {}; static const bool trimKey = std::getenv("APS5_NO_DRAW_KEY_TRIM") == nullptr; const auto indexBytes = static_cast(draw.indexCount) * draw.indexSize; return DrawResourceKey(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, indexBytes, !trimKey); } DrawResult Draw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, std::shared_ptr* recipeOut, const DrawTraceContext* trace, std::uint64_t shape, const std::vector* contentKey) { const DepthCopySourceScope depthCopySource(state.depthCopySource); if (draw.indirect && draw.indirect->capturedRecords) { const auto& args = *draw.indirect; if (indexAliasesColor(state, draw, static_cast(draw.indexCount) * draw.indexSize)) return DrawResult::NeedsIndividualRecords; if (!draw.indexed && std::ranges::any_of(*args.capturedRecords, [&](const Pm4::DrawArguments& record) { return record.count != 0 && record.instances != 0 && (!autoRangeFits(args.vertexConstant, record.count) || !autoRangeFits(args.instanceConstant, record.instances)); })) return DrawResult::NeedsIndividualRecords; } if (state.stages.tessellationGeometry) { drawTessellationGeometry(context, state, draw, shaders, snapshots, trace); return DrawResult::Handled; } if (state.stages.mesh && state.layerExports != 0u && state.renderLayers > context.meshLimits.maxMeshOutputLayers && (draw.indirect || (draw.indexCount != 0u && draw.instanceCount != 0u))) { const auto limit = context.meshLimits.maxMeshOutputLayers; Require(limit != 0u && !state.depth, "mesh layer windows require a nonzero output limit and color-only layered rendering"); Require(std::ranges::all_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->layerReplaySafe; }), "mesh layer windows refuse shaders with guest memory writes, clocks or unproven side effects"); if (recipeOut != nullptr) recipeOut->reset(); const auto makeWindow = [&](std::uint32_t base) { auto window = state; window.renderLayers = std::min(limit, state.renderLayers - base); window.meshLayerBase = base; window.meshLayerCount = window.renderLayers; for (auto& color : window.colors) { Require(color.layers == state.renderLayers, "mesh layer window targets have different layer counts"); if (color.depth > 1u) color.depthSlice += base; else color.arraySlice += base; color.layers = window.renderLayers; } if (!window.colors.empty()) window.color = window.colors.front(); return window; }; auto firstWindow = makeWindow(0u); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; PreparedDraw prepared(profile); prepared.trace = trace; prepared.contentKey = contentKey; prepared.passAttachments = PassAttachmentMemoEnabled(); const struct HeldSpace { PreparedDraw& prepared; ~HeldSpace() { const auto& resources = prepared.resolved.resources; if (resources == nullptr || !resources->SpaceReuse() || !resources->SpaceHeld()) return; if (prepared.spaceKeep != nullptr) *prepared.spaceKeep = resources->ReleaseSpace(); else if (prepared.recorder != nullptr) resources->HoldSpaceThrough(prepared.recorder->Id(), prepared.recorder->OpenSerial()); else static_cast(resources->ReleaseSpace()); } } heldSpace{prepared}; bool sharePrepared = false; try { if (!prepareDraw(context, firstWindow, draw, shaders, snapshots, prepared)) { keepHeldSpace(prepared); return DrawResult::Handled; } sharePrepared = !draw.indirect && prepared.lean && !prepared.multisampled && prepared.stencilReplay.empty() && prepared.resolved.resources != nullptr && !prepared.resolved.resources->SpaceReuse() && !prepared.targets.empty() && std::none_of(prepared.targets.begin(), prepared.targets.end(), [](const TargetBinding& binding) { return binding.resident == nullptr || binding.proxied || binding.stagedTemporary != nullptr || binding.dump != nullptr; }); const bool finalCompletion = prepared.completion; const bool finalWaited = prepared.outcome.waited; if (sharePrepared) { prepared.completion = false; prepared.outcome.waited = false; } recordPreparedDraw(context, firstWindow, draw, shaders, prepared); if (sharePrepared) { for (std::uint32_t base = firstWindow.renderLayers; base < state.renderLayers;) { auto window = makeWindow(base); if (base + window.renderLayers >= state.renderLayers) { prepared.completion = finalCompletion; prepared.outcome.waited = finalWaited; } for (std::size_t index = 0; index < window.colors.size(); ++index) { const auto& color = window.colors[index]; prepared.targets[index].color = color; prepared.targetViews[index] = prepared.targets[index].resident->AttachmentView(color.format, color.mip, color.depthSlice, color.layers, color.arraySlice); } if (prepared.masked.has_value()) { prepared.masked->renderLayers = window.renderLayers; prepared.masked->meshLayerBase = window.meshLayerBase; prepared.masked->meshLayerCount = window.meshLayerCount; prepared.masked->colors = window.colors; prepared.masked->color = window.color; } const auto& pipelineState = prepared.masked.has_value() ? *prepared.masked : window; prepared.pipeline = CachedPipeline(context, pipelineState, prepared.inputs.VertexLayout(), prepared.resolved.resources->SetLayouts(), shaders, VK_IMAGE_LAYOUT_GENERAL); prepared.framebuffer = prepared.pipeline->AcquireFramebuffer(prepared.targetViews, prepared.framebufferOwners, window.renderExtent, window.renderLayers); recordPreparedDraw(context, window, draw, shaders, prepared); base += window.renderLayers; } } } catch (...) { ThreadTargetMemo().Invalidate(); keepHeldSpace(prepared); throw; } keepHeldSpace(prepared); if (!sharePrepared) { for (std::uint32_t base = firstWindow.renderLayers; base < state.renderLayers;) { auto window = makeWindow(base); Draw(context, window, draw, shaders, snapshots, nullptr, trace); base += window.renderLayers; } } return DrawResult::Handled; } static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; PreparedDraw prepared(profile); prepared.recipeOut = recipeOut; prepared.trace = trace; prepared.shape = shape; prepared.contentKey = contentKey; prepared.passAttachments = PassAttachmentMemoEnabled(); const struct HeldSpace { PreparedDraw& prepared; ~HeldSpace() { const auto& resources = prepared.resolved.resources; if (resources == nullptr || !resources->SpaceReuse() || !resources->SpaceHeld()) return; if (prepared.spaceKeep != nullptr) *prepared.spaceKeep = resources->ReleaseSpace(); else if (prepared.recorder != nullptr) resources->HoldSpaceThrough(prepared.recorder->Id(), prepared.recorder->OpenSerial()); else static_cast(resources->ReleaseSpace()); } } heldSpace{prepared}; try { if (prepareDraw(context, state, draw, shaders, snapshots, prepared)) recordPreparedDraw(context, state, draw, shaders, prepared); } catch (...) { ThreadTargetMemo().Invalidate(); keepHeldSpace(prepared); throw; } keepHeldSpace(prepared); return prepared.inputs.result; } DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, const DrawRecipe& recipe, const DrawTraceContext* trace) { const DepthCopySourceScope depthCopySource(state.depthCopySource); if (context.recorder != nullptr) context.recorder->BoundKeptBytes(); static_cast(snapshots); PerformanceTimer timing("Graphics.DrawWithRecipe"); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; DrawTimer timer(profile); DrawRecipeOutcome result; DrawOutcome outcome; outcome.kind = KindRecipeHit; const auto waitedBefore = profile ? Recorder::ThreadWaitedMs() : 0.0; double ownWaitedMs = 0; const auto miss = [&](DrawRecipeMiss reason) { result.miss = reason; if (profile) { auto& stats = Profile(); std::lock_guard lock(stats.mutex); ++stats.recipeMisses[static_cast(reason)]; } return result; }; Require(!draw.indirect, "a draw recipe covers direct draws only"); auto* recorder = Recorder::Active(); if (state.quadList || StripPatches(state, shaders) || !RecordDraws() || recorder == nullptr || DumpTargetLimit() != 0) return miss(DrawRecipeMiss::NotRecordable); if (recipe.hasDepth != state.depth.has_value()) return miss(DrawRecipeMiss::TargetGone); if (!ZeroVertexLayoutMatches(recipe.vertexInput, shaders.front().program->vertexAttributes)) return miss(DrawRecipeMiss::Proof); const std::size_t expectedViews = state.colors.size() + (recipe.hasDepth ? 1u : 0u); Require(recipe.targets.size() == state.colors.size() && recipe.targetViews.size() == expectedViews, "draw recipe targets do not match the state"); const auto plan = planDraw(context, state, draw, shaders, &recipe, outcome, timer); DrawInputs inputs; if (plan.nothing) inputs.nothing = true; else inputs = prepareDrawInputs(context, state, draw, shaders, plan, timer, timing); if (inputs.nothing) { result.recorded = true; return result; } // The resident-target proof on the stored images (design_cpu_final 3.7): while an image is // still the storage cache's for its surface (StorageImageCached: the cache entry, removed under // the cache mutex before an eviction's flush, and the LRU touch a lookup would make), it is // what the lookup would return, and Refresh brings it up to date exactly as the lookup's does // (FlushPending, the whole-surface collect and UnchangedSince, the key scan). An image gone // from the cache is a miss: the ordinary path looks up anew. auto& memo = ThreadTargetMemo(); if (ownsTargetMemo(memo) && (memo.colors.valid || memo.depth.valid)) noteTargetMemo(TargetMemoEvent::RecipeInvalidated); memo.Invalidate(); const bool passAttachments = PassAttachmentMemoEnabled(); const bool verifyAttachments = passAttachments && VerifyPassAttachments() && [&] { InlineList, 8> ignored; return matchAttachmentMemo(context, state, ignored, recipe.targetViews); }(); InlineList, 8> targets; const bool attachmentsFromMemo = passAttachments && !VerifyPassAttachments() && matchAttachmentMemo(context, state, targets, recipe.targetViews); if (attachmentsFromMemo) { noteAttachments(AttachmentEvent::Hit); for (std::size_t index = 0; index < state.colors.size(); ++index) { if (state.colors[index].fmaskAddress != 0) GuardOneFragmentFmask(context, state.colors[index]); } } else { for (std::size_t index = 0; index < recipe.targets.size(); ++index) { timer.phase(PhaseSetup); if (state.colors[index].fmaskAddress != 0) GuardOneFragmentFmask(context, state.colors[index]); auto stored = recipe.targets[index].lock(); if (stored == nullptr || !StorageImageCached(context, stored.get()) || !StorageImageServesKeys(*stored, SurfaceForTarget(state.colors[index]).dccAddress)) return miss(DrawRecipeMiss::TargetGone); auto resident = refreshResidentTarget(context, state, state.colors[index], outcome, profile, [&] { if (state.colors[index].arrayLastSlice != 0) stored->RefreshLayers(state.colors[index].arraySlice, state.colors[index].layers); else stored->Refresh(); return stored; }); timer.phase(PhaseReadTarget); if (resident == nullptr) return miss(DrawRecipeMiss::TargetGone); targets.EmplaceBack(std::move(resident)); } if (recipe.hasDepth) { timer.phase(PhaseSetup); const auto depthView = DepthSurfaceViewWithStencilWriteIntent(context, *state.depth, state.depthWrite, state.stencilTest, writesStencilTarget(state), overwrittenStencil(state)); timer.phase(PhaseReadTarget); if (recipe.targetViews.back() != depthView) return miss(DrawRecipeMiss::TargetGone); } if (verifyAttachments) { const auto matchedTargets = targets.Span(); checkAttachmentViews(state, recipe.targetViews, [&](std::size_t index) { return matchedTargets[index]; }); } } timer.phase(PhasePrepare); // The template's proof (rules R6/R7): ProveCurrent, T1 included, the alias checks the trimmed // key leaves to a hit repeated; a failure removes the template from the cache (the batch keeps // it) and the caller rebuilds. auto resources = recipe.templateRef.lock(); if (resources == nullptr) return miss(DrawRecipeMiss::TemplateGone); Require(resources->Reusable(), "draw recipe over a non-reusable template"); const auto proofStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const bool proved = resources->ProveCurrent(shaders, &result.proof); if (profile) result.proofUs = std::chrono::duration(std::chrono::steady_clock::now() - proofStart).count(); if (!proved) { SharedResourceCache().Remove(recipe.key, resources.get()); countCache(&DrawProfile::cacheInvalidated); resources->KeepStorageImageBytes(*recorder); recorder->Keep(std::move(resources)); timer.phase(PhaseLookup); return miss(DrawRecipeMiss::Proof); } const auto moved = resources->MovedReadOnlyBuffers(shaders, *recorder, &state.color); if (!moved.has_value()) return miss(DrawRecipeMiss::Buffers); CheckBufferAliases(shaders, state.color, draw.indexAddress, inputs.indexBytes); if (recipe.hasDepth && writesDepthTarget(state)) NoteDepthSurfaceWrite(context, *state.depth); SharedResourceCache().Touch(recipe.key); countCache(&DrawProfile::cacheHits); timer.phase(PhaseLookup); outcome.completion = resources->ChecksFaults(); outcome.recorded = true; // The pipeline is the recipe's while the pipeline store still holds it (its device's teardown // or its eviction bound drops it: a miss). The framebuffer is the recipe's while the pipeline's // list holds it: the views are the stored targets' (stable while they live, and they are the // same objects), so AcquireFramebuffer only runs when the list evicted it. auto pipeline = recipe.pipeline.lock(); if (pipeline == nullptr) return miss(DrawRecipeMiss::ObjectsGone); auto framebuffer = recipe.framebuffer.lock(); if (framebuffer == nullptr) { const auto stored = targets.Span(); const std::vector> framebufferOwners(stored.begin(), stored.end()); framebuffer = pipeline->AcquireFramebuffer(recipe.targetViews, framebufferOwners, state.renderExtent, state.renderLayers); } timer.phase(PhasePipeline); const auto recordStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; BorrowedDraw record{resources, pipeline, framebuffer}; record.recorder = recorder; record.masked = recipe.masked.has_value() ? &*recipe.masked : nullptr; record.completion = outcome.completion; record.moved = *moved; record.targetViews = recipe.targetViews; record.targets = targets.Span(); InlineList, 8> slices; for (const auto& color : state.colors) slices.EmplaceBack(color.arraySlice, color.arrayLastSlice != 0 ? color.layers : 1u); record.targetSlices = slices.Span(); auto pushBytes = recipe.pushBytes; if (recipe.pushStages != 0) { pushBytes = AssemblePushConstants(shaders); record.resources->PatchPushConstants(pushBytes); } record.pushBytes = &pushBytes; record.pushStages = recipe.pushStages; record.depthLocations = passDepthLocations(context, state, *record.pipeline); recordDraw(context, state, draw, shaders, inputs, record, outcome, timer, ownWaitedMs, trace); if (passAttachments) rememberRecipeAttachments(context, state, recorder, targets.Span(), recipe.targetViews); if (profile) { result.recordUs = std::chrono::duration(std::chrono::steady_clock::now() - recordStart).count(); auto& stats = Profile(); std::lock_guard lock(stats.mutex); ++stats.recipeHits; } timing.Mark("draw_and_resource_release"); reportDrawEnd(state, timer, nullptr, outcome, waitedBefore, ownWaitedMs, " recorded from recipe"); result.recorded = true; return result; } namespace { std::shared_ptr metadataPassResident(const Context& context, const ColorTarget& color) { if (ColorTileModeIsLinear(color.tileMode) || context.detiler == nullptr) return nullptr; const auto resident = CachedStorageSurface(context, SurfaceForTarget(color)); return resident != nullptr && resident->GuestBytes() == color.bytes ? resident : nullptr; } } std::vector> PipelinedColorMetadataPassWrites(const ColorMetadataPass& pass) { std::vector> writes; if (pass.mode == ColorMetadataPass::Mode::Resolve) { if (!pass.source.has_value() || pass.targets.size() != 1) return writes; const auto& destination = pass.targets.front(); if (destination.samples != 1u || destination.bytes == 0 || destination.cmaskAddress != 0) return writes; writes.emplace_back(destination.MemoryAddress(), destination.MemoryAddress() + destination.bytes); if (destination.dccAddress != 0) writes.emplace_back(destination.dccAddress, destination.dccAddress + std::max(colorKeyCount(destination, destination.bytes), 1u)); return writes; } if (pass.mode != ColorMetadataPass::Mode::EliminateFastClear && pass.mode != ColorMetadataPass::Mode::DccDecompress) return writes; for (const auto& color : pass.targets) { if (color.samples != 1u || color.bytes == 0) return {}; writes.emplace_back(color.MemoryAddress(), color.MemoryAddress() + color.bytes); if (color.cmaskAddress != 0) writes.emplace_back(color.cmaskAddress, color.cmaskAddress + std::max(color.cmaskBytes, 1u)); if (color.dccAddress != 0) writes.emplace_back(color.dccAddress, color.dccAddress + std::max(colorKeyCount(color, color.bytes), 1u)); } return writes; } void RunColorMetadataPass(const Context& context, const ColorMetadataPass& pass) { if (pass.mode == ColorMetadataPass::Mode::Resolve) { Require(pass.source.has_value() && pass.targets.size() == 1, "CB resolve without its source and destination"); const auto& destination = pass.targets.front(); Require(!ColorTileModeIsLinear(destination.tileMode) && context.detiler != nullptr, "CB resolve into a target without a resident image is not implemented"); const auto resident = CachedStorageSurface(context, SurfaceForTarget(destination)); Require(resident->Attachable(), "storage format cannot be a color attachment"); ResolveMultisampleTarget(context, *pass.source, *resident, resident->AttachmentView(destination.format, destination.mip)); return; } if (pass.mode == ColorMetadataPass::Mode::FmaskDecompress) { for (const auto& color : pass.targets) MaterializeMultisampleTargetClear(context, color); return; } for (const auto& color : pass.targets) { if (color.samples != 1u) { MaterializeMultisampleTargetClear(context, color); continue; } ClaimMultisampleTargetMemory(color.MemoryAddress(), color.bytes); if (color.cmaskAddress != 0) { const auto resident = metadataPassResident(context, color); if (materializeCmaskClear(context, color, resident) && resident != nullptr) resident->MarkDirty(); } if (color.dccAddress == 0) continue; auto keys = CurrentDccKeys(color.dccAddress, color.bytes); if (keys == DccKeys::Uncompressed) continue; if (keys == DccKeys::ClearSingle) { Require(pass.mode == ColorMetadataPass::Mode::DccDecompress, "CB fast-clear eliminate over comp-to-single DCC keys (whether it expands them is not modeled)"); storeSingleTexels(context, color); if (const auto resident = metadataPassResident(context, color)) resident->Refresh(); continue; } Require(IsDccClear(keys), std::string("CB metadata pass over DCC keys that are ") + DccKeysName(keys) + " (per-block metadata is not modeled)"); const auto texel = clearTexel(color, keys); const auto resident = metadataPassResident(context, color); if (resident != nullptr) { const char* refusal = nullptr; const bool current = keys == DccKeys::ClearRegister ? clearToTexel(*resident, texel, color.elementBytes, refusal, true) : StorageTexture::FindPending(color.address, color.bytes) == resident || resident->UploadedKeys() == keys; if (current) { resident->MarkDirty(); MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes)); continue; } } if (color.mipCount > 1 && resident == nullptr) { std::shared_ptr chain = CachedStorageSurface(context, SurfaceForTarget(color)); if (materializeMipClear(context, color, chain)) continue; } storeClearTexels(context, color, texel); } } AddressDrawReuseCounts AddressDrawReuseCounters() { AddressDrawReuseCounts counts{}; const auto& counters = addressDrawReuses(); for (std::size_t index = 0; index < counts.size(); ++index) counts[index] = counters[index].load(std::memory_order_relaxed); return counts; } const char* AddressDrawReuseName(AddressDrawReuse outcome) { return static_cast(outcome) < AddressDrawReuseNames.size() ? AddressDrawReuseNames[static_cast(outcome)] : "?"; } void SetSpaceKeepFailuresForTest(std::uint32_t count) { spaceKeepFailures.store(count, std::memory_order_relaxed); } void SetDrawStopAfterResolveForTest(DrawStopForTest stop) { stopAfterResolve.store(static_cast(stop), std::memory_order_relaxed); } std::uint64_t TargetMemoEvents(TargetMemoEvent event) { return targetMemoEvents()[static_cast(event)].Sum(); } const char* TargetMemoEventName(TargetMemoEvent event) { return static_cast(event) < TargetMemoEventNames.size() ? TargetMemoEventNames[static_cast(event)] : "?"; } std::uint64_t TargetMemoBuildsForTest() { return targetMemoBuilds; } std::uint64_t TargetMemoHitNanosecondsForTest(const Context& context, const State& state, std::size_t repeats, std::size_t& hits) { std::vector targets; std::vector views; const auto proof = currentTargetProof(context); hits = 0; const auto start = std::chrono::steady_clock::now(); for (std::size_t repeat = 0; repeat < repeats; ++repeat) { targets.clear(); targets.resize(state.colors.size()); views.clear(); if (repeatColors(context, state, proof, targets, views)) ++hits; } return static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()); } std::uint64_t AddressDrawReuseVerifications() { return addressDrawReuseVerifications().load(std::memory_order_relaxed); } VertexPlanScratchState ThreadVertexPlanScratch() { const auto& scratch = VertexPlanLease::Resting(); VertexPlanScratchState state; state.busy = VertexPlanLease::Busy(); state.resting = scratch.fetches.size() + scratch.fetchValid.size() + scratch.fetchOf.size() + scratch.zeroed.size() + scratch.isSolo.size() + scratch.plannedFetches.size() + scratch.plannedOf.size() + scratch.rangeHandles.size() + scratch.rangeOffsets.size(); state.capacity = scratch.fetches.capacity() + scratch.fetchValid.capacity() + scratch.fetchOf.capacity() + scratch.zeroed.capacity() + scratch.isSolo.capacity() + scratch.plannedFetches.capacity() + scratch.plannedOf.capacity() + scratch.rangeHandles.capacity() + scratch.rangeOffsets.capacity(); return state; } bool DrawPipelineEnabled() { static const bool enabled = std::getenv("APS5_DRAW_PIPELINE") != nullptr; return enabled; } bool CommitTrims() { return DrawPipelineEnabled(); } FragmentOutputLookups ThreadFragmentOutputLookups() { return ThreadScratch().lookups; } VkDrawCounts TakeVkDrawCounts() { VkDrawCounts counts; counts.direct = vkDrawCounts[static_cast(VkDrawKind::Direct)].exchange(0, std::memory_order_relaxed); counts.indexed = vkDrawCounts[static_cast(VkDrawKind::Indexed)].exchange(0, std::memory_order_relaxed); counts.indirect = vkDrawCounts[static_cast(VkDrawKind::Indirect)].exchange(0, std::memory_order_relaxed); counts.mesh = vkDrawCounts[static_cast(VkDrawKind::Mesh)].exchange(0, std::memory_order_relaxed); return counts; } }