Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 167 additions & 0 deletions core/libs/prx/libSceAgcDriver/tests/execution/BdaRangeCache.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
#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 <windows.h>
#endif
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <span>
#include <string>
#include <vector>

namespace {

using AgcDriver::Graphics::Require;
using ShaderRecompiler::ShaderStage;

constexpr std::uint32_t Threads = 64;
constexpr std::size_t BlockBytes = 65536;
constexpr std::uint32_t OutputBase = 0x8000;
constexpr std::uint32_t Blocks = 5;

struct Load {
std::uint32_t block;
std::uint32_t offset;
};

constexpr std::array<Load, 8> Loads{{{0u, 0u}, {0u, 4u}, {1u, 0u}, {2u, 0u}, {3u, 0u}, {4u, 0u}, {0u, 8u}, {1u, 4u}}};

alignas(256) std::array<std::array<std::uint32_t, 40>, 2> Programs{};

std::span<const std::uint32_t> Code(bool coherent) {
auto& program = Programs[coherent ? 1u : 0u];
std::vector<std::uint32_t> code{0x34040082};
for (std::uint32_t index = 0; index < Loads.size(); ++index) {
code.push_back(0xdc308000u | (coherent ? 0x10000u : 0u) | Loads[index].offset);
code.push_back(((4u + index) << 24u) | (Loads[index].block * 2u << 16u) | 2u);
}
code.insert(code.end(), {0xbf8c3f70, 0x34060085, 0x4a0606ff, OutputBase, 0xdc788000, 0x00000403, 0xdc788010, 0x00000803, 0xbf810000});
Require(code.size() <= program.size(), "BDA range cache: program does not fit");
std::copy(code.begin(), code.end(), program.begin());
return std::span<const std::uint32_t>(program.data(), code.size());
}

class GuestBlock {
public:
GuestBlock() {
#ifdef _WIN32
block = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, BlockBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
#else
block = static_cast<std::uint8_t*>(std::aligned_alloc(BlockBytes, BlockBytes));
#endif
Require(block != nullptr, "BDA range cache: cannot allocate a guest block");
GuestAllocations::Mutation().Add(block, BlockBytes, true, 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; }

std::uint64_t Address() const { return static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(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<std::uint32_t> Initial(std::uint32_t block) {
std::vector<std::uint32_t> memory(BlockBytes / 4u, 0xcdcdcdcdu);
for (std::uint32_t dword = 0; dword < OutputBase / 4u; ++dword) memory[dword] = 0x41000000u + block * 0x11000000u + dword * 0x00010203u;
return memory;
}

std::vector<std::uint32_t> Expected() {
std::array<std::vector<std::uint32_t>, Blocks> initial;
for (std::uint32_t block = 0; block < Blocks; ++block) initial[block] = Initial(block);
auto memory = initial[0];
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
for (std::uint32_t index = 0; index < Loads.size(); ++index) {
memory[OutputBase / 4u + tid * Loads.size() + index] = initial[Loads[index].block][tid + Loads[index].offset / 4u];
}
}
return memory;
}

ShaderRecompiler::RecompileResult Recompile(std::span<const std::uint32_t> code, std::uint32_t waveSize, std::span<const std::uint32_t> userData, const ShaderRecompiler::SpirvTarget& target) {
const std::array<ShaderRecompiler::MemoryRegion, 1> regions{{{reinterpret_cast<std::uintptr_t>(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<std::uintptr_t>(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, std::array<GuestBlock, Blocks>& blocks, bool coherent, std::uint32_t waveSize, const ShaderRecompiler::SpirvTarget& target, const std::string& name) {
const auto code = Code(coherent);
for (std::uint32_t block = 0; block < blocks.size(); ++block) {
const auto initial = Initial(block);
std::memcpy(blocks[block].Data(), initial.data(), BlockBytes);
}
std::vector<std::uint32_t> userData;
for (const auto& block : blocks) userData.insert(userData.end(), {static_cast<std::uint32_t>(block.Address()), static_cast<std::uint32_t>(block.Address() >> 32u)});
const auto result = Recompile(code, waveSize, userData, target);
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(code.data()));
device.WaitIdle();
std::vector<std::uint32_t> memory(BlockBytes / 4u);
std::memcpy(memory.data(), blocks[0].Data(), BlockBytes);
const auto expected = Expected();
for (std::size_t dword = 0; dword < memory.size(); ++dword) {
Require(memory[dword] == expected[dword], "BDA range cache: " + name + (coherent ? " glc" : "") + " byte " + std::to_string(dword * 4u) + " is " + Hex(memory[dword]) + ", expected " + Hex(expected[dword]));
}
for (std::uint32_t block = 1; block < Blocks; ++block) {
const auto other = Initial(block);
Require(std::memcmp(blocks[block].Data(), other.data(), BlockBytes) == 0, "BDA range cache: " + name + (coherent ? " glc" : "") + " changed block " + std::to_string(block));
}
}

}

int main() {
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
std::array<GuestBlock, Blocks> blocks;
const auto native = device->Target();
const auto split = device->ComputeTarget(32);
for (const bool coherent : {false, true}) {
Run(*device, blocks, coherent, 32, native, "wave32");
Run(*device, blocks, coherent, 64, native, "wave64");
if (split.subgroupSize != native.subgroupSize) Run(*device, blocks, coherent, 64, split, "wave64 split");
}
std::puts("BDA range cache tests passed");
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ struct SpirvEmitterState {
};
std::vector<BdaAnchor> bdaAnchors;
std::uint32_t bdaAnchorFunction = 0;
std::array<std::uint32_t, 5> bdaRangeCache {};
std::uint32_t bdaStopValue = 0;
std::uint32_t bdaPcOverride = 0;
// False for programs with workgroup barriers: faulting BDA accesses then continue (see BdaInvocationsMayStop).
Expand Down
66 changes: 64 additions & 2 deletions core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,56 @@ std::uint32_t DefineBdaSpanLoadFunction(SpirvEmitterState& state, bool coherent)
return function;
}

constexpr std::uint32_t BdaRangeCacheEntries = 4;

std::uint32_t BdaRangeType(SpirvEmitterState& state) {
return state.module.Type(spv::OpTypeVector, TypeScalarU64(state), 3u);
}

std::uint32_t EmitCachedBdaTranslation(SpirvEmitterState& state, std::uint32_t address, std::uint32_t bytes, std::uint32_t instruction) {
const auto u32 = TypeU32(state);
const auto u64 = TypeScalarU64(state);
const auto boolean = TypeBool(state);
const auto range = BdaRangeType(state);
const auto part = [&](std::uint32_t value, std::uint32_t index) {
const auto result = state.module.AllocateId();
state.module.AddFunction(spv::OpCompositeExtract, u64, result, value, index);
return result;
};
const auto choose = [&](std::uint32_t condition, std::uint32_t first, std::uint32_t second) {
const auto result = state.module.AllocateId();
state.module.AddFunction(spv::OpCompositeConstruct, range, result, Select(state, u64, condition, part(first, 0u), part(second, 0u)), Select(state, u64, condition, part(first, 1u), part(second, 1u)), Select(state, u64, condition, part(first, 2u), part(second, 2u)));
return result;
};
const auto translate = [&](std::uint32_t found) { return Binary(state, spv::OpIAdd, u64, part(found, 2u), Binary(state, spv::OpISub, u64, address, part(found, 0u))); };
const auto end = Binary(state, spv::OpIAdd, u64, address, Unary(state, spv::OpUConvert, u64, bytes));
std::array<std::uint32_t, BdaRangeCacheEntries> entries{};
auto chosen = state.module.Constant(spv::OpConstantNull, range);
auto hit = ConstantBool(state, false);
for (std::uint32_t index = 0; index < BdaRangeCacheEntries; ++index) {
entries[index] = state.module.AllocateId();
state.module.AddFunction(spv::OpLoad, range, entries[index], state.bdaRangeCache[index]);
const auto inside = Binary(state, spv::OpLogicalAnd, boolean, Binary(state, spv::OpUGreaterThanEqual, boolean, address, part(entries[index], 0u)), Binary(state, spv::OpULessThanEqual, boolean, end, part(entries[index], 1u)));
chosen = choose(inside, entries[index], chosen);
hit = Binary(state, spv::OpLogicalOr, boolean, hit, inside);
}
hit = Binary(state, spv::OpLogicalAnd, boolean, hit, Binary(state, spv::OpUGreaterThan, boolean, end, address));
return EmitValueIfElse(state, hit, u64, [&] { return translate(chosen); }, [&] {
const auto found = state.module.AllocateId();
state.module.AddFunction(spv::OpFunctionCall, range, found, state.bdaAnchorFunction, address, bytes, instruction);
const auto mapped = Binary(state, spv::OpINotEqual, boolean, part(found, 1u), BdaConstant(state, 0u));
EmitIfCondition(state, mapped, [&] {
const auto victim = state.module.AllocateId();
state.module.AddFunction(spv::OpLoad, u32, victim, state.bdaRangeCache[BdaRangeCacheEntries]);
for (std::uint32_t index = 0; index < BdaRangeCacheEntries; ++index) {
state.module.AddFunction(spv::OpStore, state.bdaRangeCache[index], choose(Binary(state, spv::OpIEqual, boolean, victim, ConstantU32(state, index)), found, entries[index]));
}
state.module.AddFunction(spv::OpStore, state.bdaRangeCache[BdaRangeCacheEntries], Binary(state, spv::OpBitwiseAnd, u32, Binary(state, spv::OpIAdd, u32, victim, ConstantU32(state, 1u)), ConstantU32(state, BdaRangeCacheEntries - 1u)));
});
return Select(state, u64, mapped, translate(found), BdaConstant(state, 0u));
});
}

std::uint32_t DefineBdaSpanReadFunction(SpirvEmitterState& state, bool coherent, std::uint32_t loader) {
const auto u32 = TypeU32(state);
const auto u64 = TypeScalarU64(state);
Expand All @@ -199,8 +249,13 @@ std::uint32_t DefineBdaSpanReadFunction(SpirvEmitterState& state, bool coherent,
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);
auto physical = 0u;
if (state.bdaRangeCache[0] != 0) {
physical = EmitCachedBdaTranslation(state, firstAddress, span, instruction);
} else {
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) {
Expand Down Expand Up @@ -335,6 +390,13 @@ void DefineBdaDwordReadFunctions(SpirvEmitterState& state) {

void DefineBdaSpanReadFunctions(SpirvEmitterState& state) {
if (state.bdaProbeFunction == 0) return;
static const bool rangeCache = std::getenv("APS5_NO_BDA_RANGE_CACHE") == nullptr;
if (rangeCache) {
DefineBdaAnchorFunction(state);
const auto range = BdaRangeType(state);
for (std::uint32_t index = 0; index < BdaRangeCacheEntries; ++index) state.bdaRangeCache[index] = state.module.DefineInitializedGlobalVariable(TypePointer(state, spv::StorageClassPrivate, range), spv::StorageClassPrivate, state.module.Constant(spv::OpConstantNull, range));
state.bdaRangeCache[BdaRangeCacheEntries] = state.module.DefineInitializedGlobalVariable(TypePointer(state, spv::StorageClassPrivate, TypeU32(state)), spv::StorageClassPrivate, ConstantU32(state, 0u));
}
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;
Expand Down
1 change: 1 addition & 0 deletions docs/dev/ENVIRONMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti
| `APS5_NO_ATOMIC_STAGING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | binds atomic shader elements in place instead of staging them through a device-local buffer |
| `APS5_NO_BARRIER_BATCH` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | records the staging, write-back and label-run leading barriers that a covering barrier already orders, instead of leaving them out; APS5_AB can toggle it |
| `APS5_NO_BARRIER_ELISION` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records every leading barrier instead of merging it into the following submission |
| `APS5_NO_BDA_RANGE_CACHE` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp` | | makes every span read walk the BDA table instead of first trying the last four ranges the invocation's span reads found |
| `APS5_NO_BDA_STAGING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | binds the written elements of address-based compute builds in place in the host imports instead of staging them device-local |
| `APS5_NO_BDA_TABLE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp` | | builds every BDA descriptor table instead of reusing the recent-table cache |
| `APS5_NO_BLOCK_TRACKING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | tracks array layers, or the whole surface, instead of 64 KiB blocks |
Expand Down
Loading