From 5623c0e93773bfc882a116da16b3b554ddd142dc Mon Sep 17 00:00:00 2001 From: Celegans12 <53881228+Celegans12@users.noreply.github.com> Date: Wed, 7 Oct 2026 17:18:59 +0200 Subject: [PATCH] perf(shader): share the BDA dword span read between read sites Every BDA dword read site still emitted in the entry function the add of its first dword address with the overflow fault, a probe_bda_pointer call, the wide loads, and one read_bda_dword_bytes call per extracted dword. NVIDIA's pipeline compile time grows with every call left in the entry function, so large compute programs with a few hundred such reads spend 47-77 s in vkCreateComputePipelines. A read site is now one call to a DontInline read_bda_span function, in a stop and a coherent variant, taking the address, the immediate offset, the mask of extracted dwords and the pc, which does the same steps in the same order. Fault reasons, addresses, pcs, Volatile, the stop behaviour and the APS5_BDA_BYTE_READS path are unchanged. --- .../libSceAgcDriver/tests/BdaExecution.cpp | 41 +++++ .../prx/libSceAgcDriver/tests/BdaShader.cpp | 20 ++- .../prx/libSceAgcDriver/tests/BdaShader.hpp | 1 + .../libSceAgcDriver/tests/ShaderMemory.cpp | 18 +- .../tests/execution/BdaSpanReads.cpp | 159 +++++++++++++++++ .../include/SpirvBackend/SpirvBda.hpp | 1 + .../SpirvBackend/SpirvEmitterState.hpp | 1 + .../SpirvBackend/src/SpirvBdaLookup.cpp | 1 + .../SpirvBackend/src/SpirvBdaRead.cpp | 164 ++++++++++++++---- 9 files changed, 369 insertions(+), 37 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/BdaSpanReads.cpp diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaExecution.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaExecution.cpp index faf2f911c..3361f7109 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaExecution.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaExecution.cpp @@ -163,6 +163,47 @@ void RunBdaExecutionTests(const Context& context) { read(guest + 1, 4, coherent, stops, 0x55443322, true); } } + Buffer wide(context, 32, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + for (std::uint32_t dword = 0; dword < 8u; ++dword) { + const std::uint32_t value = 0xa0b0c000u + dword; + std::memcpy(wide.Bytes().data() + dword * 4u, &value, sizeof(value)); + } + constexpr std::uint64_t spanGuest = 0x7fff56780000ULL; + const std::array spanRanges{{ranges[0], ranges[1], {spanGuest, spanGuest + 32, wide.DeviceAddress(), Abi::Read, 0}}}; + Buffer spanTable(context, sizeof(Abi::Header) + sizeof(spanRanges), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + const auto span = [&](std::uint64_t address, std::int32_t offset, std::uint32_t extracted, bool coherent, bool stops, std::array values, Abi::FaultReason reason = {}, std::uint64_t faultAddress = 0, std::uint32_t faultBytes = 0) { + const Abi::Header header{Abi::Version, 3, sizeof(Abi::Range), 0}; + std::memcpy(spanTable.Bytes().data(), &header, sizeof(header)); + std::memcpy(spanTable.Bytes().data() + sizeof(header), spanRanges.data(), sizeof(spanRanges)); + std::memset(fault.Bytes().data(), 0, fault.Bytes().size()); + const std::array sentinel{0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef}; + std::memcpy(words.Bytes().data(), sentinel.data(), sizeof(sentinel)); + Pipeline pipeline(context, MakeBdaSpanReadTestShader(address, static_cast(offset), extracted, coherent, stops), {&spanTable, &fault, &words}); + pipeline.Run(1); + Abi::Fault report{}; + std::array result{}; + std::memcpy(&report, fault.Bytes().data(), sizeof(report)); + std::memcpy(result.data(), words.Bytes().data(), sizeof(result)); + const bool faults = static_cast(reason) != 0u; + if (faults) { + Require(report.state == Abi::FaultState::Ready && report.reason == reason && report.address == faultAddress && report.bytes == faultBytes && report.instruction == 0x1234, "BDA span read did not publish its first fault"); + } else { + Require(report.state == Abi::FaultState::Empty, "mapped BDA span read published a fault"); + } + Require(result == (faults && stops ? sentinel : values), faults && stops ? "faulting BDA span read continued to output a substitute value" : "BDA span read produced incorrect data"); + }; + const auto at = [&](std::uint32_t dword) { return 0xa0b0c000u + dword; }; + for (const bool stops : {true, false}) { + for (const bool coherent : {false, true}) { + span(spanGuest + 16, -12, 0b1010u, coherent, stops, {0, at(2), 0, at(4)}); + span(spanGuest, 4, 0b0101u, coherent, stops, {at(1), 0, at(3), 0}); + span(spanGuest + 24, 0, 0b0011u, coherent, stops, {at(6), at(7), 0, 0}); + span(spanGuest + 20, 8, 0b0001u, coherent, stops, {at(7), 0, 0, 0}); + span(spanGuest + 28, 0, 0b0101u, coherent, stops, {at(7), 0, 0, 0}, Abi::FaultReason::Unmapped, spanGuest + 36, 1); + span(guest, 1, 0b1001u, coherent, stops, {0x55443322, 0, 0, 0}, Abi::FaultReason::Unmapped, guest + 13, 1); + span(4, -8, 0b0001u, coherent, stops, {0, 0, 0, 0}, Abi::FaultReason::Overflow, 4, 0); + } + } ranges[0].permissions = 0; run(guest, 8, 0, Abi::FaultReason::Permission); } diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaShader.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaShader.cpp index 9c4dd099d..4cbfffe4c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaShader.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaShader.cpp @@ -2,11 +2,12 @@ #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" +#include "IntermediateRepresentation/IrBuilder.hpp" namespace { template -std::vector MakeShader(std::uint64_t address, bool coherent, bool stops, const TEmit& emit) { +std::vector MakeShader(std::uint64_t address, bool coherent, bool stops, const TEmit& emit, std::uint32_t extracted = 0) { using namespace ShaderRecompiler; IrProgram program; program.Resources().stage = IrShaderStage::Compute; @@ -38,7 +39,14 @@ std::vector MakeShader(std::uint64_t address, bool coherent, bool state.module.AddFunction(spv::OpFunction, TypeVoid(state), main, spv::FunctionControlMaskNone, TypeFunction(state)); EmitLabel(state, state.module.AllocateId()); SpirvValueEmitContext ctx(state); - auto& instruction = program.CreateValue(IrOpcode::LoadAddressU32, IrType::U32); + auto& instruction = extracted != 0u ? program.CreateValue(IrOpcode::LoadAddressU32x4, IrType::U32x4) : program.CreateValue(IrOpcode::LoadAddressU32, IrType::U32); + IrBuilder ir(program); + for (std::uint32_t dword = 0; dword < 4u; ++dword) { + if ((extracted & (1u << dword)) == 0u) continue; + auto& extract = program.CreateValue(IrOpcode::CompositeExtractU32x4, IrType::U32); + extract.AddArgument(&instruction); + extract.AddArgument(&ir.Constant(dword)); + } MemoryFlags flags{}; flags.pc = 0x1234; instruction.SetFlags(flags); @@ -67,6 +75,14 @@ std::vector MakeBdaTestShader(std::uint64_t address, std::uint32_ }); } +std::vector MakeBdaSpanReadTestShader(std::uint64_t address, std::uint32_t offset, std::uint32_t extracted, bool coherent, bool stops) { + using namespace ShaderRecompiler; + return MakeShader(address, coherent, stops, [&](SpirvValueEmitContext& ctx, const IrValue& instruction, std::uint32_t base) { + const auto values = EmitBdaDwordReads(ctx, instruction, base, offset, 4u); + return std::vector(values.begin(), values.end()); + }, extracted); +} + std::vector MakeBdaDwordReadTestShader(std::uint64_t address, std::uint32_t dwords, bool coherent, bool stops) { using namespace ShaderRecompiler; return MakeShader(address, coherent, stops, [&](SpirvValueEmitContext& ctx, const IrValue& instruction, std::uint32_t base) { diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaShader.hpp b/core/libs/prx/libSceAgcDriver/tests/BdaShader.hpp index 2baa4468a..cd61a127e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaShader.hpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaShader.hpp @@ -7,6 +7,7 @@ std::vector MakeBdaTestShader(std::uint64_t address, std::uint32_t bits, std::int64_t offset = 0); std::vector MakeBdaDwordReadTestShader(std::uint64_t address, std::uint32_t dwords, bool coherent, bool stops); +std::vector MakeBdaSpanReadTestShader(std::uint64_t address, std::uint32_t offset, std::uint32_t extracted, bool coherent, bool stops); void RunBdaExecutionTests(const AgcDriver::Graphics::Context& context); void RunBdaContractTests(); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 0d8e318a3..be23a86fc 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -1640,9 +1640,12 @@ void verifyBdaReadFallbackFunctions() { std::map names; std::map definitions; const auto reader = std::string("read_bda_dword_bytes") + (barrier ? "" : "_stop") + (coherent ? "_coherent" : ""); + const auto span = std::string("read_bda_span") + (barrier ? "" : "_stop") + (coherent ? "_coherent" : ""); std::string function; std::size_t compareExchanges = 0; std::size_t mainLookups = 0; + std::size_t mainProbes = 0; + std::size_t spanCalls = 0; std::array readerLoads{}; for (std::size_t cursor = 5; cursor < five.size();) { const auto length = five[cursor] >> 16u; @@ -1651,22 +1654,29 @@ void verifyBdaReadFallbackFunctions() { if (op == spv::OpName) names[five[cursor + 1]] = reinterpret_cast(&five[cursor + 2]); if (op == spv::OpFunction) { function = names[five[cursor + 2]]; - if (function == "record_bda_fault" || function.starts_with("read_bda_dword_bytes")) { - require((five[cursor + 3] & spv::FunctionControlDontInlineMask) != 0u, "BDA read functions: a fault or byte read function may be inlined"); + if (function == "record_bda_fault" || function.starts_with("read_bda_dword_bytes") || function.starts_with("read_bda_span")) { + require((five[cursor + 3] & spv::FunctionControlDontInlineMask) != 0u, "BDA read functions: a fault, byte read or span read function may be inlined"); ++definitions[function]; } } if (op == spv::OpAtomicCompareExchange) ++compareExchanges; if (op == spv::OpFunctionCall && function == "main" && names[five[cursor + 3]] == "get_bda_pointer") ++mainLookups; + if (op == spv::OpFunctionCall && function == "main") { + const auto& callee = names[five[cursor + 3]]; + if (callee == "probe_bda_pointer" || callee.starts_with("read_bda_dword_bytes")) ++mainProbes; + if (callee == span) ++spanCalls; + } if (op == spv::OpLoad && function == reader) ++readerLoads[length > 4u && (five[cursor + 4] & spv::MemoryAccessVolatileMask) != 0u]; cursor += length; } - require(definitions["record_bda_fault"] == 1u && definitions[reader] == 1u, "BDA read functions: the fault and byte read functions are not defined"); + require(definitions["record_bda_fault"] == 1u && definitions[reader] == 1u && definitions[span] == 1u, "BDA read functions: the fault, byte read and span read functions are not defined"); for (const auto& [name, count] : definitions) require(count == 1u, "BDA read functions: a function is defined twice"); require(compareExchanges == 1u, "BDA read functions: a fault is recorded outside record_bda_fault"); require(mainLookups == 0u, "BDA read functions: a read site looks up its bytes inline"); require(readerLoads[coherent] == 4u && readerLoads[!coherent] == 0u, "BDA read functions: the byte loads do not keep the access's coherence"); - require(five.size() - one.size() < 4u * 300u, "BDA read functions: a read site takes 300 SPIR-V words or more"); + require(mainProbes == 0u, "BDA read functions: a read site probes or reads bytes outside its span read function"); + require(spanCalls == 5u, "BDA read functions: a read site does not call its span read function once"); + require(five.size() - one.size() < 4u * 150u, "BDA read functions: a read site takes 150 SPIR-V words or more"); } } } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/BdaSpanReads.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/BdaSpanReads.cpp new file mode 100644 index 000000000..ccc63037b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/BdaSpanReads.cpp @@ -0,0 +1,159 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Threads = 64; +constexpr std::size_t BlockBytes = 65536; +constexpr std::uint32_t InputDwords = 768; +constexpr std::uint32_t Fill = 0xcdcdcdcdu; +constexpr std::uint32_t LoadBase = 0x100; +constexpr std::uint32_t OutputBase = 0x8000; + +alignas(256) std::array, 4> Programs{}; + +std::span Code(bool coherent, bool barrier) { + auto& program = Programs[(coherent ? 2u : 0u) + (barrier ? 1u : 0u)]; + std::vector code{0x34040084, 0x4a0404ff, LoadBase, 0x34080081, 0x36080882, 0x4a040504, 0x34060083, 0x4a0606ff, OutputBase, 0xdc388ff8 | (coherent ? 0x10000u : 0u), 0x04000002, 0xbf8c3f70}; + if (barrier) code.push_back(0xbf8a0000); + code.insert(code.end(), {0xdc708000, 0x00000503, 0xdc708004, 0x00000703, 0xbf810000}); + std::copy(code.begin(), code.end(), program.begin()); + return std::span(program.data(), code.size()); +} + +class GuestBlock { +public: + GuestBlock() { +#ifdef _WIN32 + block = static_cast(VirtualAlloc(nullptr, BlockBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); +#else + block = static_cast(std::aligned_alloc(BlockBytes, BlockBytes)); +#endif + Require(block != nullptr, "BDA span reads: cannot allocate the guest block"); + GuestAllocations::Mutation().Add(block, BlockBytes, true, true); + } + + ~GuestBlock() { + GuestAllocations::Mutation().Remove(block); +#ifdef _WIN32 + VirtualFree(block, 0, MEM_RELEASE); +#else + std::free(block); +#endif + } + + GuestBlock(const GuestBlock&) = delete; + GuestBlock& operator=(const GuestBlock&) = delete; + + std::uint8_t* Data() { return block; } + +private: + std::uint8_t* block = nullptr; +}; + +std::string Hex(std::uint32_t value) { + char text[16]; + std::snprintf(text, sizeof(text), "0x%08x", value); + return text; +} + +std::vector Initial() { + std::vector memory(BlockBytes / 4u, Fill); + for (std::uint32_t dword = 0; dword < InputDwords; ++dword) memory[dword] = 0x52000000u + dword * 0x00010203u; + return memory; +} + +std::uint32_t Bytes(const std::vector& memory, std::uint32_t address) { + std::uint32_t value = 0; + for (std::uint32_t byte = 0; byte < 4u; ++byte) { + const std::uint32_t at = address + byte; + value |= ((memory[at / 4u] >> (at % 4u * 8u)) & 0xffu) << (byte * 8u); + } + return value; +} + +std::vector Expected() { + const auto initial = Initial(); + auto memory = initial; + for (std::uint32_t tid = 0; tid < Threads; ++tid) { + const std::uint32_t load = LoadBase + tid * 16u + (tid & 1u) * 2u - 8u; + memory[OutputBase / 4u + tid * 2u] = Bytes(initial, load + 4u); + memory[OutputBase / 4u + tid * 2u + 1u] = Bytes(initial, load + 12u); + } + return memory; +} + +ShaderRecompiler::RecompileResult Recompile(std::span code, std::uint32_t waveSize, std::span userData, const ShaderRecompiler::SpirvTarget& target) { + const std::array regions{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, + {waveSize, 0, userData, compute, std::nullopt, std::nullopt, regions}, + target, + {0, 0, 0, 128} + }; + request.useCache = false; + return ShaderRecompiler::Recompile(request); +} + +void Run(AgcDriver::VulkanDevice& device, GuestBlock& guest, bool coherent, bool barrier, std::uint32_t waveSize, const ShaderRecompiler::SpirvTarget& target, const std::string& name) { + const auto code = Code(coherent, barrier); + auto memory = Initial(); + std::memcpy(guest.Data(), memory.data(), BlockBytes); + const auto address = static_cast(reinterpret_cast(guest.Data())); + const std::vector userData{static_cast(address), static_cast(address >> 32u)}; + const auto result = Recompile(code, waveSize, userData, target); + device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); + device.WaitIdle(); + std::memcpy(memory.data(), guest.Data(), BlockBytes); + const auto expected = Expected(); + for (std::size_t dword = 0; dword < memory.size(); ++dword) { + Require(memory[dword] == expected[dword], "BDA span reads: " + name + (coherent ? " glc" : "") + (barrier ? " barrier" : "") + " byte " + std::to_string(dword * 4u) + " is " + Hex(memory[dword]) + ", expected " + Hex(expected[dword])); + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + GuestBlock guest; + const auto native = device->Target(); + const auto split = device->ComputeTarget(32); + for (const bool coherent : {false, true}) { + for (const bool barrier : {false, true}) { + Run(*device, guest, coherent, barrier, 32, native, "wave32"); + Run(*device, guest, coherent, barrier, 64, native, "wave64"); + if (split.subgroupSize != native.subgroupSize) Run(*device, guest, coherent, barrier, 64, split, "wave64 split"); + } + } + std::puts("BDA span read tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvBda.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvBda.hpp index 4b68725c7..9bff87d24 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvBda.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvBda.hpp @@ -15,6 +15,7 @@ std::uint32_t BdaLoadWord(SpirvEmitterState& state, std::uint32_t index); std::uint32_t BdaLoadAddress(SpirvEmitterState& state, std::uint32_t index); void DefineBdaFaultFunction(SpirvEmitterState& state); void DefineBdaDwordReadFunctions(SpirvEmitterState& state); +void DefineBdaSpanReadFunctions(SpirvEmitterState& state); void RecordBdaFault(SpirvEmitterState& state, std::uint32_t address, std::uint32_t bytes, std::uint32_t instruction, BdaAbi::FaultReason reason); void ReturnBdaFailureIf(SpirvEmitterState& state, std::uint32_t condition, std::uint32_t address, std::uint32_t bytes, std::uint32_t instruction, BdaAbi::FaultReason reason); void ValidateBdaTarget(const IrProgram& program, const SpirvTargetOptions& target); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index a2498d029..98aec7f8b 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -113,6 +113,7 @@ struct SpirvEmitterState { std::uint32_t bdaNoteWriteFunction = 0; std::uint32_t bdaFaultFunction = 0; std::array, 2> bdaDwordReadFunctions {}; + std::array, 2> bdaSpanReadFunctions {}; std::uint32_t bdaStopValue = 0; // False for programs with workgroup barriers: faulting BDA accesses then continue (see BdaInvocationsMayStop). bool bdaStopsInvocations = true; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp index e6d905db3..253a8d041 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp @@ -162,6 +162,7 @@ void DefineGetBdaPointer(SpirvEmitterState& state) { state.bdaPointerFunction = DefineBdaLookup(state, "get_bda_pointer", true); if (!BdaByteReadsForced()) state.bdaProbeFunction = DefineBdaLookup(state, "probe_bda_pointer", false); DefineBdaDwordReadFunctions(state); + DefineBdaSpanReadFunctions(state); if (state.program.Info().bdaWrites) { state.bdaWritePointerFunction = DefineBdaLookup(state, "get_bda_write_pointer", true, BdaAbi::Write); state.bdaAtomicPointerFunction = DefineBdaLookup(state, "get_bda_atomic_pointer", true, BdaAbi::Read | BdaAbi::Write); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp index 60df7b542..bd14a957b 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp @@ -1,6 +1,7 @@ #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" +#include #include #include #include @@ -107,6 +108,108 @@ std::uint32_t BdaAddressUnaligned(SpirvEmitterState& state, std::uint32_t addres return Binary(state, spv::OpINotEqual, TypeBool(state), Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, BdaConstant(state, 3u)), BdaConstant(state, 0u)); } +std::uint32_t AddBdaSignedOffset(SpirvEmitterState& state, std::uint32_t address, std::uint32_t offset, std::uint32_t instruction) { + const auto u32 = TypeU32(state); + const auto u64 = TypeScalarU64(state); + const auto boolean = TypeBool(state); + const auto negative = Binary(state, spv::OpSLessThan, boolean, offset, ConstantU32(state, 0u)); + const auto magnitude = Unary(state, spv::OpUConvert, u64, Select(state, u32, negative, Binary(state, spv::OpISub, u32, ConstantU32(state, 0u), offset), offset)); + const auto sum = Binary(state, spv::OpIAdd, u64, address, magnitude); + const auto result = Select(state, u64, negative, Binary(state, spv::OpISub, u64, address, magnitude), sum); + const auto overflow = Select(state, boolean, negative, Binary(state, spv::OpUGreaterThan, boolean, magnitude, address), Binary(state, spv::OpULessThan, boolean, sum, address)); + EmitIfCondition(state, overflow, [&] { RecordBdaFault(state, address, ConstantU32(state, 0u), instruction, BdaAbi::FaultReason::Overflow); }); + StopBdaInvocationIf(state, overflow); + return result; +} + +std::uint32_t BdaSpanReadResultType(SpirvEmitterState& state) { + const auto values = TypeU32Vector(state, 4); + return state.bdaStopsInvocations ? state.module.Type(spv::OpTypeStruct, values, TypeU32(state)) : values; +} + +std::uint32_t DefineBdaSpanReadFunction(SpirvEmitterState& state, bool coherent) { + const auto u32 = TypeU32(state); + const auto u64 = TypeScalarU64(state); + const auto boolean = TypeBool(state); + const auto values = TypeU32Vector(state, 4); + const auto zero = ConstantU32(state, 0u); + const bool stops = state.bdaStopsInvocations; + const auto result = BdaSpanReadResultType(state); + const auto reader = state.bdaDwordReadFunctions[stops][coherent]; + const auto function = state.module.AllocateId(); + state.module.AddName(function, std::string("read_bda_span") + (stops ? "_stop" : "") + (coherent ? "_coherent" : "")); + state.module.AddFunction(spv::OpFunction, result, function, spv::FunctionControlDontInlineMask, state.module.Type(spv::OpTypeFunction, result, u64, u32, u32, u32)); + const auto address = state.module.AllocateId(); + const auto offset = state.module.AllocateId(); + const auto used = state.module.AllocateId(); + const auto instruction = state.module.AllocateId(); + state.module.AddFunction(spv::OpFunctionParameter, u64, address); + state.module.AddFunction(spv::OpFunctionParameter, u32, offset); + state.module.AddFunction(spv::OpFunctionParameter, u32, used); + state.module.AddFunction(spv::OpFunctionParameter, u32, instruction); + EmitLabel(state, state.module.AllocateId()); + const auto first = EmitGlsl(state, used); + const auto last = EmitGlsl(state, used); + const auto firstBytes = Binary(state, spv::OpShiftLeftLogical, u32, first, ConstantU32(state, 2u)); + const auto firstAddress = AddBdaSignedOffset(state, address, Binary(state, spv::OpIAdd, u32, offset, firstBytes), instruction); + const auto span = Binary(state, spv::OpISub, u32, Binary(state, spv::OpShiftLeftLogical, u32, Binary(state, spv::OpIAdd, u32, last, ConstantU32(state, 1u)), ConstantU32(state, 2u)), firstBytes); + const auto physical = state.module.AllocateId(); + state.module.AddFunction(spv::OpFunctionCall, u64, physical, state.bdaProbeFunction, firstAddress, span, instruction); + const auto mapped = Binary(state, spv::OpINotEqual, boolean, physical, BdaConstant(state, 0u)); + const auto wide = Binary(state, spv::OpLogicalAnd, boolean, mapped, Unary(state, spv::OpLogicalNot, boolean, BdaAddressUnaligned(state, physical))); + const auto isUsed = [&](std::uint32_t dword) { + return Binary(state, spv::OpINotEqual, boolean, Binary(state, spv::OpBitwiseAnd, u32, used, ConstantU32(state, 1u << dword)), zero); + }; + const auto composite = [&](const std::array& parts) { + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeConstruct, values, value, parts[0], parts[1], parts[2], parts[3]); + return value; + }; + const auto read = EmitValueIfElse(state, wide, values, [&] { + std::array loaded{}; + for (std::uint32_t dword = 0; dword < 4u; ++dword) { + loaded[dword] = EmitValueOrZeroIfCondition(state, isUsed(dword), [&] { + const auto delta = Unary(state, spv::OpUConvert, u64, Binary(state, spv::OpISub, u32, ConstantU32(state, dword * 4u), firstBytes)); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, Binary(state, spv::OpIAdd, u64, physical, delta)); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, u32, value, pointer, BdaAccessMask(coherent), 4u); + return value; + }); + } + return composite(loaded); + }, [&] { + std::array bytes{}; + for (std::uint32_t dword = 0; dword < 4u; ++dword) { + bytes[dword] = EmitValueOrZeroIfCondition(state, isUsed(dword), [&] { + const auto isFirst = Binary(state, spv::OpIEqual, boolean, first, ConstantU32(state, dword)); + const auto dwordAddress = EmitValueIfElse(state, isFirst, u64, [&] { return firstAddress; }, [&] { + return AddBdaSignedOffset(state, address, Binary(state, spv::OpIAdd, u32, offset, ConstantU32(state, dword * 4u)), instruction); + }); + const auto pair = state.module.AllocateId(); + state.module.AddFunction(spv::OpFunctionCall, TypeU32Vector(state, 2), pair, reader, dwordAddress, instruction); + if (stops) { + const auto stopped = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, u32, stopped, pair, 1u); + StopBdaInvocationIf(state, Binary(state, spv::OpINotEqual, boolean, stopped, zero)); + } + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, u32, value, pair, 0u); + return value; + }); + } + return composite(bytes); + }); + auto returned = read; + if (stops) { + returned = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeConstruct, result, returned, read, zero); + } + state.module.AddFunction(spv::OpReturnValue, returned); + state.module.AddFunction(spv::OpFunctionEnd); + return function; +} + } void DefineBdaDwordReadFunctions(SpirvEmitterState& state) { @@ -143,6 +246,25 @@ void DefineBdaDwordReadFunctions(SpirvEmitterState& state) { state.bdaStopValue = 0; } +void DefineBdaSpanReadFunctions(SpirvEmitterState& state) { + if (state.bdaProbeFunction == 0) return; + const auto& memory = state.program.Resources().memoryInfo; + const bool coherentAccesses = std::any_of(memory.begin(), memory.end(), [](const MemoryInfo& info) { return info.coherent; }); + const bool stops = state.bdaStopsInvocations; + const auto zero = ConstantU32(state, 0u); + for (const bool stop : {false, true}) { + if (stop && !stops) continue; + state.bdaStopsInvocations = stop; + state.bdaStopValue = stop ? state.module.Constant(spv::OpConstantComposite, BdaSpanReadResultType(state), state.module.Constant(spv::OpConstantComposite, TypeU32Vector(state, 4), zero, zero, zero, zero), ConstantU32(state, 1u)) : 0u; + for (const bool coherent : {false, true}) { + if (coherent && !coherentAccesses) continue; + state.bdaSpanReadFunctions[stop][coherent] = DefineBdaSpanReadFunction(state, coherent); + } + } + state.bdaStopsInvocations = stops; + state.bdaStopValue = 0; +} + // APS5_BDA_BYTE_READS=1 restores one lookup and one byte load per byte for every read. bool BdaByteReadsForced() { static const bool forced = std::getenv("APS5_BDA_BYTE_READS") != nullptr; @@ -285,7 +407,6 @@ std::array EmitBdaDwordReads(SpirvValueEmitContext& ctx, const auto& state = ctx.state; if (dwords == 0u || dwords > 4u) ctx.Fail(inst, "unsupported BDA read width"); if (state.bdaPointerFunction == 0) ctx.Fail(inst, "BDA lookup function is missing"); - const auto u64 = TypeScalarU64(state); const auto instruction = ConstantU32(state, inst.Flags().pc); const auto used = everyDword ? (1u << dwords) - 1u : UsedBdaDwords(inst, dwords); const auto isUsed = [&](std::uint32_t dword) { return (used & (1u << dword)) != 0u; }; @@ -319,44 +440,25 @@ std::array EmitBdaDwordReads(SpirvValueEmitContext& ctx, const StopBdaInvocationIf(state, Binary(state, spv::OpINotEqual, TypeBool(state), stopped, ConstantU32(state, 0u))); } }; - addresses[first] = dwordAddress(first); if (state.bdaProbeFunction == 0) { + addresses[first] = dwordAddress(first); readBytes(values); return values; } - const auto physical = state.module.AllocateId(); - state.module.AddFunction(spv::OpFunctionCall, u64, physical, state.bdaProbeFunction, addresses[first], ConstantU32(state, (last - first + 1u) * 4u), instruction); - const auto mapped = Binary(state, spv::OpINotEqual, TypeBool(state), physical, BdaConstant(state, 0u)); - const auto aligned = Binary(state, spv::OpIEqual, TypeBool(state), Binary(state, spv::OpBitwiseAnd, u64, physical, BdaConstant(state, 3u)), BdaConstant(state, 0u)); - const auto wide = Binary(state, spv::OpLogicalAnd, TypeBool(state), mapped, aligned); - const auto wideLabel = state.module.AllocateId(); - const auto byteLabel = state.module.AllocateId(); - const auto byteExit = state.module.AllocateId(); - const auto merge = state.module.AllocateId(); - state.module.AddFunction(spv::OpSelectionMerge, merge, spv::SelectionControlMaskNone); - state.module.AddFunction(spv::OpBranchConditional, wide, wideLabel, byteLabel); - EmitLabel(state, wideLabel); - std::array wideValues{}; - for (std::uint32_t dword = first; dword <= last; ++dword) { - if (!isUsed(dword)) continue; - const auto element = dword == first ? physical : Binary(state, spv::OpIAdd, u64, physical, BdaConstant(state, (dword - first) * 4u)); - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, element); - wideValues[dword] = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), wideValues[dword], pointer, BdaAccessMask(state, inst), 4u); + const auto function = state.bdaSpanReadFunctions[state.bdaStopsInvocations][BdaCoherent(state, inst)]; + if (function == 0) ctx.Fail(inst, "BDA span read function is missing"); + const auto read = state.module.AllocateId(); + state.module.AddFunction(spv::OpFunctionCall, BdaSpanReadResultType(state), read, function, address, ConstantU32(state, offset), ConstantU32(state, used), instruction); + if (state.bdaStopsInvocations) { + const auto stopped = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), stopped, read, 1u); + StopBdaInvocationIf(state, Binary(state, spv::OpINotEqual, TypeBool(state), stopped, ConstantU32(state, 0u))); } - state.module.AddFunction(spv::OpBranch, merge); - EmitLabel(state, byteLabel); - std::array byteValues{}; - readBytes(byteValues); - state.module.AddFunction(spv::OpBranch, byteExit); - EmitLabel(state, byteExit); - state.module.AddFunction(spv::OpBranch, merge); - EmitLabel(state, merge); for (std::uint32_t dword = first; dword <= last; ++dword) { if (!isUsed(dword)) continue; values[dword] = state.module.AllocateId(); - state.module.AddFunction(spv::OpPhi, TypeU32(state), values[dword], wideValues[dword], wideLabel, byteValues[dword], byteExit); + if (state.bdaStopsInvocations) state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), values[dword], read, 0u, dword); + else state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), values[dword], read, dword); } return values; }