Skip to content
Closed
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
10 changes: 9 additions & 1 deletion core/libs/prx/libSceAgcDriver/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,14 @@ target_link_libraries(agc_spirv_module_tests PRIVATE shader_recompiler_agc_drive
set_target_properties(agc_spirv_module_tests PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(agc_spirv_module_tests)

add_test_executable(agc_spirv_bvh_intersect_function_tests EXCLUDE_FROM_ALL tests/SpirvBvhIntersectFunction.cpp)
target_link_libraries(agc_spirv_bvh_intersect_function_tests PRIVATE shader_recompiler_agc_driver libc)
set_target_properties(agc_spirv_bvh_intersect_function_tests PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(agc_spirv_bvh_intersect_function_tests)
if(ANYPS5_ENABLE_SPIRV_TOOLS)
target_link_libraries(agc_spirv_bvh_intersect_function_tests PRIVATE SPIRV-Tools-static)
endif()

add_test_executable(agc_spirv_narrow_constant_store_tests EXCLUDE_FROM_ALL tests/SpirvNarrowConstantStore.cpp)
target_link_libraries(agc_spirv_narrow_constant_store_tests PRIVATE shader_recompiler_agc_driver libc)
set_target_properties(agc_spirv_narrow_constant_store_tests PROPERTIES CXX_EXTENSIONS OFF)
Expand Down Expand Up @@ -1217,7 +1225,7 @@ if(BUILD_TESTING)
if(WIN32)
set_tests_properties(agc_shader_bindless agc_shader_srt_read_patching agc_shader_frontend_pair agc_shader_frontend_pair_off PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
foreach(agcTest IN ITEMS agc_shared_write_tests agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_spirv_module_tests agc_dpp_write_tests agc_masked_select_tests agc_ir_reclaim_tests agc_vector_window_tests agc_constant_bit_test_tests agc_integer_narrowing_tests agc_scalar_select_mask_tests agc_vop1_control_decode_tests agc_validate_program_tests agc_pass_hazards_tests agc_shader_disk_cache_tests agc_shader_device_profile_tests agc_placeholder_images_tests agc_shader_control_flow_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests agc_driver_bda_device_tests agc_driver_mesh_tests agc_driver_cmask_fast_clear_tests agc_formatted_buffer_once_tests agc_formatted_buffer_byte_stores_tests ${agcExecutionTests})
foreach(agcTest IN ITEMS agc_shared_write_tests agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_spirv_module_tests agc_dpp_write_tests agc_masked_select_tests agc_ir_reclaim_tests agc_vector_window_tests agc_constant_bit_test_tests agc_integer_narrowing_tests agc_scalar_select_mask_tests agc_vop1_control_decode_tests agc_validate_program_tests agc_pass_hazards_tests agc_shader_disk_cache_tests agc_shader_device_profile_tests agc_placeholder_images_tests agc_shader_control_flow_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests agc_driver_bda_device_tests agc_driver_mesh_tests agc_driver_cmask_fast_clear_tests agc_formatted_buffer_once_tests agc_formatted_buffer_byte_stores_tests agc_spirv_bvh_intersect_function_tests ${agcExecutionTests})
if(agcTest STREQUAL "agc_driver_constant_store_tests" OR agcTest STREQUAL "agc_driver_flat_apertures_tests" OR agcTest STREQUAL "agc_driver_pipeline_optimized_readback_tests")
continue()
endif()
Expand Down
178 changes: 178 additions & 0 deletions core/libs/prx/libSceAgcDriver/tests/SpirvBvhIntersectFunction.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
#include "BdaAbi.hpp"
#include "Recompiler.hpp"
#include <array>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <set>
#include <span>
#include <spirv/unified1/spirv.hpp>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#if ANYPS5_ENABLE_SPIRV_TOOLS
#include <spirv-tools/libspirv.hpp>
#endif

namespace {

using namespace ShaderRecompiler;

constexpr std::uint32_t Threads = 64;
constexpr std::uint32_t Record = 16;
constexpr std::uint32_t Forms = 4;

void Check(bool condition, const std::string& message) {
if (!condition) throw std::runtime_error(message);
}

constexpr std::array<std::uint32_t, 82> MakeCode() {
std::array<std::uint32_t, 82> code{};
std::size_t at = 0;
code[at++] = 0x34020086u;
for (std::uint32_t dword = 0; dword < Record; ++dword) {
code[at++] = 0xe0301000u | (dword * 4u);
code[at++] = 0x80000001u | ((4u + dword) << 8u);
}
code[at++] = 0xbf8c3f70u;
code[at++] = 0xf19c9f01u;
code[at++] = 0x00031405u;
code[at++] = 0xf1989f07u;
code[at++] = 0x00021804u;
code[at++] = 0x0a090807u;
code[at++] = 0x0e0d0c0bu;
code[at++] = 0x0000100fu;
code[at++] = 0xf19c9f05u;
code[at++] = 0x40031c05u;
code[at++] = 0x09080706u;
code[at++] = 0x1312110au;
code[at++] = 0xf1989f05u;
code[at++] = 0x40022004u;
code[at++] = 0x0a090807u;
code[at++] = 0x00131211u;
for (std::uint32_t dword = 0; dword < Record; ++dword) {
code[at++] = 0xe0701000u | (dword * 4u);
code[at++] = 0x80010001u | ((20u + dword) << 8u);
}
code[at++] = 0xbf810000u;
return code;
}

alignas(256) constexpr std::array<std::uint32_t, 82> Code = MakeCode();
alignas(256) std::array<std::uint32_t, Threads * Record> Input{};
alignas(256) std::array<std::uint32_t, Threads * Record> Output{};

SpirvTarget Target(std::uint32_t subgroupSize) {
static constexpr std::array<std::uint32_t, 3> capabilities{spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess};
static constexpr std::array<std::string_view, 4> extensions{"SPV_EXT_descriptor_indexing", "SPV_KHR_8bit_storage", "SPV_KHR_float_controls", "SPV_KHR_physical_storage_buffer"};
return {0x00401000u, 0x00010300u, subgroupSize, BdaAbi::Version, capabilities, extensions, false, {1024, 1024, 64}, 1024, 32768, {}, {}};
}

std::array<std::uint32_t, 4> BufferDescriptor(const void* data, std::uint32_t bytes) {
const auto address = reinterpret_cast<std::uintptr_t>(data);
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu), bytes, 0x31016facu};
}

struct Module {
std::size_t words = 0;
std::set<std::uint32_t> functions;
std::size_t calls = 0;
bool dontInline = true;
};

std::string Name(const std::vector<std::uint32_t>& words, std::size_t offset, std::uint32_t count) {
std::string name;
for (std::uint32_t i = 2; i < count; ++i) {
for (std::uint32_t byte = 0; byte < 4u; ++byte) {
const char c = static_cast<char>((words[offset + i] >> (byte * 8u)) & 0xffu);
if (c == '\0') return name;
name.push_back(c);
}
}
return name;
}

Module Inspect(const RecompileResult& result, const std::string& label) {
const auto& words = result.spirv.Words();
Check(words.size() >= 5 && words[0] == spv::MagicNumber, label + ": missing SPIR-V module");
Module module;
module.words = words.size();
std::set<std::uint32_t> named;
for (std::size_t offset = 5; offset < words.size();) {
const auto count = words[offset] >> spv::WordCountShift;
const auto opcode = words[offset] & spv::OpCodeMask;
Check(count != 0 && count <= words.size() - offset, label + ": malformed SPIR-V instruction");
if (opcode == spv::OpName && count >= 3 && Name(words, offset, count) == "image_bvh_intersect_ray") named.insert(words[offset + 1]);
if (opcode == spv::OpFunction && count == 5 && named.contains(words[offset + 2])) {
module.functions.insert(words[offset + 2]);
module.dontInline = module.dontInline && (words[offset + 3] & spv::FunctionControlDontInlineMask) != 0u;
}
if (opcode == spv::OpFunctionCall && count >= 4 && named.contains(words[offset + 3])) ++module.calls;
offset += count;
}
#if ANYPS5_ENABLE_SPIRV_TOOLS
std::string diagnostics;
spvtools::SpirvTools validator(SPV_ENV_VULKAN_1_1);
validator.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&, const char* message) {
if (message != nullptr) diagnostics += std::string(message) + '\n';
});
Check(validator.Validate(words), label + ": emitted invalid SPIR-V:\n" + diagnostics);
#endif
return module;
}

Module Compile(std::uint32_t waveSize, std::uint32_t subgroupSize) {
std::vector<std::uint32_t> userData(16, 0u);
const auto input = BufferDescriptor(Input.data(), static_cast<std::uint32_t>(Input.size() * 4u));
const auto output = BufferDescriptor(Output.data(), static_cast<std::uint32_t>(Output.size() * 4u));
const std::array<std::uint32_t, 4> bvh{0x100u, 0x80000000u, 6u, 0u};
std::copy(input.begin(), input.end(), userData.begin());
std::copy(output.begin(), output.end(), userData.begin() + 4);
std::copy(bvh.begin(), bvh.end(), userData.begin() + 8);
std::copy(bvh.begin(), bvh.end(), userData.begin() + 12);
const std::span<const std::uint32_t> code(Code);
const std::array<MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(code)}}};
const ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1, {}};
RecompileRequest request{
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
{waveSize, 0, userData, compute, std::nullopt, std::nullopt, memory, std::nullopt},
Target(subgroupSize), {0, 0, 0, 128}, std::nullopt, false,
};
return Inspect(Recompile(request), "wave" + std::to_string(waveSize) + " on " + std::to_string(subgroupSize) + " lanes");
}

void SharedFunctions() {
const auto wave32 = Compile(32, 32);
Check(wave32.functions.size() == Forms, "wave32: expected one image_bvh_intersect_ray function per variant, found " + std::to_string(wave32.functions.size()));
Check(wave32.dontInline, "wave32: an image_bvh_intersect_ray function may be inlined");
Check(wave32.calls == Forms, "wave32: expected one call per instruction, found " + std::to_string(wave32.calls));
const auto wave64 = Compile(64, 32);
Check(wave64.functions.size() == Forms, "wave64 on 32 lanes: expected one image_bvh_intersect_ray function per variant, found " + std::to_string(wave64.functions.size()));
Check(wave64.dontInline, "wave64 on 32 lanes: an image_bvh_intersect_ray function may be inlined");
Check(wave64.calls == 2u * Forms, "wave64 on 32 lanes: expected one call per instruction and lane half, found " + std::to_string(wave64.calls));
Check(wave64.words < wave32.words + wave32.words / 2u, "wave64 on 32 lanes: the module is " + std::to_string(wave64.words) + " words against " + std::to_string(wave32.words) + " for wave32, so the query is still emitted per lane half");
std::printf("wave32 %zu words, wave64 on 32 lanes %zu words\n", wave32.words, wave64.words);
}

}

int main() {
try {
if (RayTracingStrict() || RayTracingMiss()) {
std::puts("skipped, APS5_RAYTRACING replaces the node test");
return 0;
}
if (std::getenv("APS5_BDA_BYTE_READS") != nullptr) {
std::puts("skipped, APS5_BDA_BYTE_READS keeps the query inline");
return 0;
}
SharedFunctions();
std::puts("image_bvh_intersect_ray shared function tests passed");
return 0;
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ std::uint32_t EmitF16BitsToF32Decoded(SpirvEmitterState& state, std::uint32_t bi
void EmitProgram(SpirvEmitterState& state);
void DefineGetBdaPointer(SpirvEmitterState& state);
void DefineDot2F32F16Function(SpirvEmitterState& state);
void DefineBvhIntersectFunctions(SpirvEmitterState& state);
void EmitLabel(SpirvEmitterState& state, std::uint32_t label);
std::uint32_t Unary(SpirvEmitterState& state, std::uint32_t opcode, std::uint32_t type, std::uint32_t value);
std::uint32_t Binary(SpirvEmitterState& state, std::uint32_t opcode, std::uint32_t type, std::uint32_t lhs, std::uint32_t rhs);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ struct SpirvEmitterState {
bool nativeF16ModesEmitted = false;
bool f16DenormPreserveEmitted = false;
std::uint32_t dot2F32F16Function = 0;
std::array<std::uint32_t, 4> bvhIntersectFunctions {};
std::array<std::array<std::uint32_t, 2>, 2> bdaDwordReadFunctions {};
std::array<std::array<std::uint32_t, 2>, 2> bdaSpanReadFunctions {};
std::uint32_t bdaStopValue = 0;
Expand Down
83 changes: 73 additions & 10 deletions core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1875,8 +1875,10 @@ void EmitImageAtomicCmpSwap64(SpirvValueEmitContext& ctx, const IrValue& inst) {
EmitImage(ctx, inst);
}

void EmitImageBvhIntersectRay(SpirvValueEmitContext& ctx, const IrValue& inst) {
auto& state = ctx.state;
namespace {

template <typename TComponent>
std::uint32_t EmitBvhQuery(SpirvEmitterState& state, SpirvValueEmitContext* inlineCtx, const IrValue* inlineInst, std::uint32_t descriptor, TComponent&& component, bool a16, bool node64, std::uint32_t pcValue) {
const auto u32 = TypeU32(state);
const auto u64 = TypeScalarU64(state);
const auto f32 = TypeF32(state);
Expand All @@ -1902,16 +1904,11 @@ void EmitImageBvhIntersectRay(SpirvValueEmitContext& ctx, const IrValue& inst) {
const auto pair = [&](std::uint32_t low, std::uint32_t high) { return op(spv::OpBitwiseOr, u64, widen(low), op(spv::OpShiftLeftLogical, u64, widen(high), BdaConstant(state, 32u))); };

const auto query = [&] {
const auto descriptor = ctx.Arg(inst, 0);
std::array<std::uint32_t, 4> word{};
for (std::uint32_t i = 0; i < 4u; ++i) {
word[i] = state.module.AllocateId();
state.module.AddFunction(spv::OpCompositeExtract, u32, word[i], descriptor, i);
}
const IrValue* address = ctx.ImageAddress(inst.Argument(1));
const auto component = [&](std::uint32_t index) { return ctx.Arg(*address, index); };
const bool a16 = (ctx.Memory(inst).imageSampleFlags & RdnaImageSampleFlagA16) != 0u;
const bool node64 = ctx.Memory(inst).addressIsFull;
const std::uint32_t ray = node64 ? 2u : 1u;

const auto nodeLow = component(0);
Expand Down Expand Up @@ -1956,12 +1953,12 @@ void EmitImageBvhIntersectRay(SpirvValueEmitContext& ctx, const IrValue& inst) {
std::vector<std::uint32_t> dwords;
if (state.bdaProbeFunction == 0) {
for (std::uint32_t first = 0; first < count; first += 4u) {
const auto read = EmitBdaDwordReads(ctx, inst, nodeAddress, first * 4u, 4u, true);
const auto read = EmitBdaDwordReads(*inlineCtx, *inlineInst, nodeAddress, first * 4u, 4u, true);
dwords.insert(dwords.end(), read.begin(), read.end());
}
return dwords;
}
const auto pc = uint(inst.Flags<MemoryFlags>().pc);
const auto pc = pcValue;
const auto bytes = uint(count * 4u);
const auto physical = state.module.AllocateId();
state.module.AddFunction(spv::OpFunctionCall, u64, physical, state.bdaProbeFunction, nodeAddress, bytes, pc);
Expand Down Expand Up @@ -2096,7 +2093,73 @@ void EmitImageBvhIntersectRay(SpirvValueEmitContext& ctx, const IrValue& inst) {
const auto box16 = EmitValueOrDefaultIfCondition(state, isBox16, result4, tested, [&] { return boxes(true); });
return EmitValueOrDefaultIfCondition(state, isBox32, result4, box16, [&] { return boxes(false); });
};
const auto inactive = compose({invalid, invalid, invalid, invalid});
return query();
}

std::uint32_t BvhVariant(bool a16, bool node64) {
return (a16 ? 1u : 0u) | (node64 ? 2u : 0u);
}

std::uint32_t BvhComponents(bool a16, bool node64) {
return (node64 ? 2u : 1u) + (a16 ? 7u : 10u);
}

}

void DefineBvhIntersectFunctions(SpirvEmitterState& state) {
if (state.bdaProbeFunction == 0) return;
std::array<bool, 4> used{};
for (const IrBlock* block : state.program.BlockOrder()) {
for (const IrValue* inst : block->Instructions()) {
if (inst->Opcode() != IrOpcode::ImageBvhIntersectRay) continue;
const auto& memory = state.program.Resources().memoryInfo.at(inst->Flags<MemoryFlags>().index);
used[BvhVariant((memory.imageSampleFlags & RdnaImageSampleFlagA16) != 0u, memory.addressIsFull)] = true;
}
}
const auto u32 = TypeU32(state);
const auto result4 = TypeU32Composite(state, 4u);
for (std::uint32_t variant = 0; variant < used.size(); ++variant) {
if (!used[variant]) continue;
const bool a16 = (variant & 1u) != 0u;
const bool node64 = (variant & 2u) != 0u;
std::vector<std::uint32_t> parameterTypes{result4};
parameterTypes.insert(parameterTypes.end(), BvhComponents(a16, node64) + 1u, u32);
const auto function = state.module.AllocateId();
state.module.AddName(function, "image_bvh_intersect_ray");
state.module.AddFunction(spv::OpFunction, result4, function, spv::FunctionControlDontInlineMask, state.module.Type(spv::OpTypeFunction, result4, std::span<const std::uint32_t>(parameterTypes)));
std::vector<std::uint32_t> parameters(parameterTypes.size());
for (std::size_t i = 0; i < parameters.size(); ++i) {
parameters[i] = state.module.AllocateId();
state.module.AddFunction(spv::OpFunctionParameter, parameterTypes[i], parameters[i]);
}
EmitLabel(state, state.module.AllocateId());
const auto value = EmitBvhQuery(state, nullptr, nullptr, parameters[0], [&](std::uint32_t index) { return parameters[1u + index]; }, a16, node64, parameters.back());
state.module.AddFunction(spv::OpReturnValue, value);
state.module.AddFunction(spv::OpFunctionEnd);
state.bvhIntersectFunctions[variant] = function;
}
}

void EmitImageBvhIntersectRay(SpirvValueEmitContext& ctx, const IrValue& inst) {
auto& state = ctx.state;
const auto result4 = TypeU32Composite(state, 4u);
const auto invalid = ConstantU32(state, 0xffffffffu);
const IrValue* address = ctx.ImageAddress(inst.Argument(1));
const bool a16 = (ctx.Memory(inst).imageSampleFlags & RdnaImageSampleFlagA16) != 0u;
const bool node64 = ctx.Memory(inst).addressIsFull;
const auto pc = ConstantU32(state, inst.Flags<MemoryFlags>().pc);
const auto function = state.bvhIntersectFunctions[BvhVariant(a16, node64)];
const auto query = [&] {
if (function == 0) return EmitBvhQuery(state, &ctx, &inst, ctx.Arg(inst, 0), [&](std::uint32_t index) { return ctx.Arg(*address, index); }, a16, node64, pc);
std::vector<std::uint32_t> arguments{ctx.Arg(inst, 0)};
for (std::uint32_t i = 0; i < BvhComponents(a16, node64); ++i) arguments.push_back(ctx.Arg(*address, i));
arguments.push_back(pc);
const auto value = state.module.AllocateId();
state.module.AddFunction(spv::OpFunctionCall, result4, value, function, std::span<const std::uint32_t>(arguments));
return value;
};
const auto inactive = state.module.AllocateId();
state.module.AddFunction(spv::OpCompositeConstruct, result4, inactive, invalid, invalid, invalid, invalid);
ctx.Define(inst, EmitValueOrDefaultIfCondition(state, ctx.Arg(inst, 2), result4, inactive, query));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,7 @@ void EmitProgram(SpirvEmitterState& state) {
}
DefineGetBdaPointer(state);
DefineDot2F32F16Function(state);
DefineBvhIntersectFunctions(state);
for (const IrBlock* block : program.BlockOrder()) {
const bool needsScratch = std::any_of(block->Instructions().begin(), block->Instructions().end(), [](const IrValue* inst) {
return inst->Opcode() == IrOpcode::SwizzleU32;
Expand Down
Loading