Merge pull request #1270 from Celegans12/fix/agc-unaligned-buffer-views

fix(agc): bind guest buffer views that start off a DWORD boundary
This commit is contained in:
Adrià
2026-10-08 14:34:45 +02:00
committed by GitHub
14 changed files with 370 additions and 23 deletions
@@ -204,6 +204,7 @@ public:
void UploadPrepare(bool addressable);
void UploadFinish(bool addressable);
VkDescriptorBufferInfo Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const;
static std::uint64_t ViewBytes(std::uint64_t bytes, std::uint32_t adjustment);
std::vector<ShaderRecompiler::BdaAbi::Range> AddressRanges() const;
// The BDA table of the cached address space when it serves this upload alone (an address-based
// build with no region outside it): its ranges, immutable while the space lives, and the
@@ -1628,7 +1628,9 @@ const GuestBufferMemory::Region* GuestBufferMemory::owner(std::uint64_t address)
void GuestBufferMemory::addDescriptorRegion(std::uint64_t address, std::size_t bytes, bool atomic) {
validate(address, bytes);
switch (baseOverlap(address, address + bytes, nullptr)) {
const auto begin = address & ~std::uint64_t{3};
const auto end = begin == address ? address + bytes : (address + bytes + 3) & ~std::uint64_t{3};
switch (baseOverlap(begin, end, nullptr)) {
case BaseOverlap::Inside:
return;
case BaseOverlap::Partial:
@@ -1640,9 +1642,9 @@ void GuestBufferMemory::addDescriptorRegion(std::uint64_t address, std::size_t b
}
// `writable` here means the bytes come from live guest memory (not a snapshot), whether or not
// the shader stores to them; what is written back is decided by Writes() alone.
Region region{address, address + bytes, true, {}, nullptr};
Region region{begin, end, true, {}, nullptr};
region.atomic = atomic;
auto committed = GuestMemory::DescribeCommitted(address, bytes);
auto committed = GuestMemory::DescribeCommitted(begin, static_cast<std::size_t>(end - begin));
if (!committed.whole) {
// A GPU heap bound whole while the guest commits its pages on demand, or a descriptor left
region.sparse = true;
@@ -2484,11 +2486,18 @@ VkDescriptorBufferInfo GuestBufferMemory::Descriptor(std::uint64_t address, std:
const auto base = region.direct != nullptr ? region.direct->base : region.mirror != nullptr ? region.mirror->base : region.begin;
const auto offset = address - base;
Require(context.limits.minStorageBufferOffsetAlignment != 0, "no storage buffer offset alignment");
adjustment = static_cast<std::uint32_t>(offset % context.limits.minStorageBufferOffsetAlignment);
Require(adjustment % 4 == 0, "guest buffer view off the storage buffer offset alignment is not DWORD aligned");
Require(bytes + adjustment <= context.limits.maxStorageBufferRange, "guest buffer view exceeds descriptor range limit");
Require(base % 4 == 0, "a guest buffer view in a GPU owner that does not start at a DWORD boundary is not implemented");
adjustment = static_cast<std::uint32_t>(offset % std::max<VkDeviceSize>(context.limits.minStorageBufferOffsetAlignment, 4));
const auto range = ViewBytes(bytes, adjustment);
const auto end = region.direct != nullptr ? region.direct->base + region.direct->bytes : region.end;
Require(address - adjustment + range <= end, "guest buffer view exceeds its GPU owner");
Require(range <= context.limits.maxStorageBufferRange, "guest buffer view exceeds descriptor range limit");
const auto handle = region.direct != nullptr ? region.direct->buffer : region.mirror != nullptr ? region.mirror->buffer->Handle() : region.buffer->Handle();
return {handle, offset - adjustment, bytes + adjustment};
return {handle, offset - adjustment, range};
}
std::uint64_t GuestBufferMemory::ViewBytes(std::uint64_t bytes, std::uint32_t adjustment) {
return adjustment % 4 == 0 ? bytes + adjustment : 4 * (adjustment / 4 + bytes / 4 + 1);
}
ShaderRecompiler::BdaAbi::Range GuestBufferMemory::addressRange(const Region& region) {
@@ -2762,7 +2762,7 @@ std::optional<std::vector<ShaderResources::MovedBuffer>> ShaderResources::MovedR
const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element];
if (written || empty || item.written || size > context.limits.maxStorageBufferRange) return std::nullopt;
const auto begin = address - item.adjustment;
const auto bytes = static_cast<std::size_t>(size) + item.adjustment;
const auto bytes = static_cast<std::size_t>(GuestBufferMemory::ViewBytes(size, item.adjustment));
if (!GuestMemory::Accessible(reinterpret_cast<const void*>(begin), bytes)) return std::nullopt;
if (guestMemory.WritesOverlap(begin, bytes) || recorder.PendingWriteOverlaps(begin, bytes) || PendingStorageOverlaps(begin, bytes, nullptr) || AnyShadowedOverlaps(begin, bytes)) return std::nullopt;
moved.push_back({index, address, static_cast<std::size_t>(size)});
@@ -2801,7 +2801,7 @@ std::shared_ptr<ShaderResources::DrawBindings> ShaderResources::PrepareDrawBindi
if (!direct || recorder.PendingWriteOverlaps(item.address, item.size)) continue;
}
const auto begin = address - item.adjustment;
const auto bytes = size + item.adjustment;
const auto bytes = static_cast<std::size_t>(GuestBufferMemory::ViewBytes(size, item.adjustment));
const auto registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
const auto generation = GuestMemory::CollectWrites(begin, bytes);
auto buffer = recorder.ReusableDrawSnapshot(begin, bytes);
@@ -325,6 +325,20 @@ void RunBdaResourceTests(const Context& context, const BdaTestAccess& access) {
const auto view = unaligned.Descriptor(address + 4, 4, adjustment);
Require(adjustment == 4 && view.offset == 0 && view.range == 8, "a view off the offset alignment binds from below it");
reject([&] { unaligned.Descriptor(address + sizeof(guest), 4, adjustment); }, "exceeds its GPU owner");
const auto odd = unaligned.Descriptor(address + 2, 6, adjustment);
Require(adjustment == 2 && odd.offset == 0 && odd.range == 8, "a view off a DWORD boundary does not bind the DWORDs around it");
const auto late = unaligned.Descriptor(address + 0x13, 8, adjustment);
Require(adjustment == 3 && late.offset == 16 && late.range == 12, "a view off a DWORD boundary does not bind from the offset alignment below it");
GuestBufferMemory lone(aligned);
lone.AddReadable(address + 6, 5);
lone.Upload(true);
const auto copied = lone.Descriptor(address + 6, 5, adjustment);
Require(adjustment == 2 && copied.offset == 0 && copied.range == 8, "a lone view off a DWORD boundary is not copied from the DWORD below it");
Require(std::memcmp(access.bytes(copied.buffer).data(), reinterpret_cast<const void*>(address + 4), 8) == 0, "a lone view off a DWORD boundary copied other bytes");
GuestBufferMemory tail(aligned);
tail.AddWritable(address, 62);
tail.Upload(true);
reject([&] { tail.Descriptor(address + 58, 4, adjustment); }, "exceeds its GPU owner");
}
{
// The cached address space: a second build in an unchanged registry takes the first one's
@@ -0,0 +1,260 @@
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "Recompiler.hpp"
#include "VulkanTestDevice.hpp"
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <span>
#include <string>
#include <vector>
namespace {
using AgcDriver::Graphics::Require;
using ShaderRecompiler::ShaderStage;
constexpr std::uint32_t Lanes = 32;
constexpr std::uint32_t Slots = 8;
constexpr std::uint32_t Checked = 8;
constexpr std::uint32_t InputBytes = 256;
constexpr std::uint32_t ViewBytes = 60;
constexpr std::uint32_t ResultBytes = Lanes * Slots * 4;
constexpr std::uint32_t StoredBytes = 8 * 28;
constexpr std::uint32_t Fill = 0xdeadbeefu;
alignas(256) std::array<std::uint8_t, InputBytes> Input{};
alignas(256) std::array<std::uint32_t, 384> Output{};
alignas(256) constexpr std::array<std::uint32_t, 56> Code{
0x34020082, 0x34040085, 0x34100081, 0x4a101082, 0x34140081, 0x4a141500, 0x4a141481, 0x34180083,
0x4a1a00ff, 0x5a5abe00, 0x4a1c00ff, 0x7f7f7f91, 0x4a1e00ff, 0xa1b2c300, 0x4a2000bc, 0xe0301000,
0x80000301, 0xe0301000, 0x80010401, 0xe0341004, 0x80010501, 0xe0281000, 0x80010708, 0xe0201000,
0x8001090a, 0xe8281002, 0x80011101, 0xf4200402, 0xfa000006, 0xbf8c0000, 0x7e160210, 0xe0701000,
0x80020302, 0xe0701004, 0x80020402, 0xe0701008, 0x80020502, 0xe070100c, 0x80020602, 0xe0701010,
0x80020702, 0xe0701014, 0x80020902, 0xe0701018, 0x80020b02, 0xe070101c, 0x80021102, 0xe0701000,
0x80030f0c, 0xe0601004, 0x80030e0c, 0xe0681006, 0x80030d0c, 0xe82c1005, 0x8003100c, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 11> PairCode{
0x34040083, 0x7e0a0281, 0x7e0c0280, 0xe0345000, 0x80010300, 0xe1480100, 0x80020500, 0xbf8c0000,
0xe0741000, 0x80020302, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 3> AtomicCode{0xe0c81000, 0x80000100, 0xbf810000};
constexpr std::array<std::uint32_t, 7> FormattedLoadCode(std::uint32_t format, std::uint32_t offset) {
return {0x34020082, 0xe8001000u | (format << 19u) | offset, 0x80000201, 0xbf8c0000, 0xe0701000, 0x80010201, 0xbf810000};
}
constexpr std::array<std::uint32_t, 6> FormattedStoreCode(std::uint32_t format, std::uint32_t offset) {
return {0x34020082, 0x4a0400ff, 0x0000c300, 0xe8041000u | (format << 19u) | offset, 0x80000201, 0xbf810000};
}
constexpr std::uint32_t Format16UInt = 11;
constexpr std::uint32_t Format32UInt = 20;
constexpr std::uint32_t Format16_16UInt = 27;
alignas(256) constexpr auto Load16Code = FormattedLoadCode(Format16UInt, 2);
alignas(256) constexpr auto Load32Code = FormattedLoadCode(Format32UInt, 0);
alignas(256) constexpr auto Load16_16Code = FormattedLoadCode(Format16_16UInt, 0);
alignas(256) constexpr auto Store16Code = FormattedStoreCode(Format16UInt, 0);
constexpr const char* Names[Checked] = {
"aligned dword", "dword", "dwordx2[0]", "dwordx2[1]", "ushort", "ubyte", "s_buffer_load_dword", "tbuffer_load_format_x 8_UINT",
};
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};
}
std::string Hex(std::uint32_t value) {
char text[16];
std::snprintf(text, sizeof(text), "0x%08x", value);
return text;
}
std::uint32_t ViewDword(const std::uint8_t* view, std::uint32_t dword) {
if (dword >= ViewBytes / 4) return 0;
std::uint32_t value = 0;
std::memcpy(&value, view + dword * 4u, sizeof(value));
return value;
}
std::uint32_t ViewField(const std::uint8_t* view, std::uint32_t byte, std::uint32_t mask) {
return (ViewDword(view, byte / 4u) >> ((byte % 4u) * 8u)) & mask;
}
std::uint8_t FillByte(std::size_t offset) {
return static_cast<std::uint8_t>(Fill >> ((offset % 4u) * 8u));
}
ShaderRecompiler::RecompileRequest Request(std::span<const std::uint32_t> code, const std::vector<std::uint32_t>& userData, const ShaderRecompiler::SpirvTarget& target, std::span<const ShaderRecompiler::MemoryRegion> memory) {
const ShaderRecompiler::ShaderComputeStageInfo compute{{Lanes, 1, 1}, 0u, {false, false, false}, false, 1};
ShaderRecompiler::RecompileRequest request{
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
{Lanes, 0, userData, compute, std::nullopt, std::nullopt, memory},
target,
{0, 0, 0, 128}
};
request.useCache = false;
return request;
}
void Run(AgcDriver::VulkanDevice& device, std::uint32_t viewOffset, std::uint32_t storeOffset) {
for (std::uint32_t index = 0; index < InputBytes; ++index) Input[index] = static_cast<std::uint8_t>(index * 37u + 11u + (index >> 3u));
Output.fill(Fill);
auto* output = reinterpret_cast<std::uint8_t*>(Output.data());
const auto* view = Input.data() + viewOffset;
std::vector<std::uint32_t> userData;
for (const auto& descriptor : {BufferDescriptor(Input.data(), InputBytes), BufferDescriptor(view, ViewBytes), BufferDescriptor(Output.data(), ResultBytes), BufferDescriptor(output + ResultBytes + storeOffset, StoredBytes)}) {
userData.insert(userData.end(), descriptor.begin(), descriptor.end());
}
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(Code.data()), std::as_bytes(std::span(Code))}}};
const auto result = ShaderRecompiler::Recompile(Request(Code, userData, device.Target(), memory));
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(Code.data()));
device.WaitIdle();
const auto run = "view +" + std::to_string(viewOffset) + ", stores +" + std::to_string(storeOffset);
for (std::uint32_t lane = 0; lane < Lanes; ++lane) {
std::uint32_t aligned = 0;
std::memcpy(&aligned, Input.data() + lane * 4u, sizeof(aligned));
std::uint32_t scalar = 0;
std::memcpy(&scalar, Input.data() + (viewOffset & ~3u) + 4u, sizeof(scalar));
const std::uint32_t expected[Checked] = {aligned, ViewDword(view, lane), ViewDword(view, lane + 1u), ViewDword(view, lane + 2u), ViewField(view, lane * 2u + 2u, 0xffffu), ViewField(view, lane * 3u + 1u, 0xffu), scalar, ViewField(view, lane * 4u + 2u, 0xffu)};
for (std::uint32_t slot = 0; slot < Checked; ++slot) {
const auto actual = Output[lane * Slots + slot];
Require(actual == expected[slot], "buffer unaligned base " + run + ": lane " + std::to_string(lane) + " " + Names[slot] + " is " + Hex(actual) + ", expected " + Hex(expected[slot]));
}
}
for (std::size_t offset = ResultBytes; offset < Output.size() * 4u; ++offset) {
const auto relative = static_cast<std::int64_t>(offset) - static_cast<std::int64_t>(ResultBytes + storeOffset);
auto expected = FillByte(offset);
if (relative >= 0 && relative < StoredBytes) {
const auto lane = static_cast<std::uint32_t>(relative / 8);
const auto byte = static_cast<std::uint32_t>(relative % 8);
if (byte < 4u) expected = static_cast<std::uint8_t>((0xa1b2c300u + lane) >> (byte * 8u));
else if (byte == 4u) expected = static_cast<std::uint8_t>(0x91u + lane);
else if (byte == 5u) expected = static_cast<std::uint8_t>(0x3cu + lane);
else if (byte >= 6u) expected = static_cast<std::uint8_t>((0xbe00u + lane) >> ((byte - 6u) * 8u));
}
Require(output[offset] == expected, "buffer unaligned base " + run + ": stored byte " + std::to_string(offset - ResultBytes) + " is " + Hex(output[offset]) + ", expected " + Hex(expected));
}
}
void RunPair(AgcDriver::VulkanDevice& device, std::uint32_t viewOffset) {
for (std::uint32_t index = 0; index < InputBytes; ++index) Input[index] = static_cast<std::uint8_t>(index * 53u + 7u + (index >> 2u));
Output.fill(Fill);
const auto* view = Input.data() + viewOffset;
std::vector<std::uint32_t> userData;
for (const auto& descriptor : {BufferDescriptor(Input.data(), InputBytes), BufferDescriptor(view, ViewBytes), BufferDescriptor(Output.data(), ResultBytes)}) {
userData.insert(userData.end(), descriptor.begin(), descriptor.end());
}
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(PairCode.data()), std::as_bytes(std::span(PairCode))}}};
const auto result = ShaderRecompiler::Recompile(Request(PairCode, userData, device.Target(), memory));
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(PairCode.data()));
device.WaitIdle();
const auto run = "buffer unaligned base glc dwordx2, view +" + std::to_string(viewOffset);
for (std::uint32_t lane = 0; lane < Lanes; ++lane) {
for (std::uint32_t half = 0; half < 2u; ++half) {
const auto actual = Output[lane * 2u + half];
const auto expected = ViewDword(view, lane / 4u + half);
Require(actual == expected, run + ": lane " + std::to_string(lane) + " dword " + std::to_string(half) + " is " + Hex(actual) + ", expected " + Hex(expected));
}
}
Require(Output[Lanes * 2u] == Fill + Lanes && Output[Lanes * 2u + 1u] == Fill, run + ": the 64-bit atomic is " + Hex(Output[Lanes * 2u + 1u]) + Hex(Output[Lanes * 2u]));
}
auto RecompileFormatted(AgcDriver::VulkanDevice& device, std::span<const std::uint32_t> code, const std::uint8_t* view, std::uint32_t viewBytes) {
std::vector<std::uint32_t> userData;
for (const auto& descriptor : {BufferDescriptor(view, viewBytes), BufferDescriptor(Output.data(), ResultBytes)}) {
userData.insert(userData.end(), descriptor.begin(), descriptor.end());
}
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(code)}}};
return ShaderRecompiler::Recompile(Request(code, userData, device.Target(), memory));
}
void RunFormattedFault(AgcDriver::VulkanDevice& device, const std::string& name, std::span<const std::uint32_t> code, std::uint32_t viewOffset) {
const auto run = "buffer unaligned base " + name + ", view +" + std::to_string(viewOffset);
try {
static_cast<void>(RecompileFormatted(device, code, Input.data() + viewOffset, ViewBytes));
} catch (const std::exception& error) {
Require(std::string(error.what()).find("is a formatted buffer access through a V# whose base is not aligned to its element") != std::string::npos, run + ": unexpected error: " + error.what());
return;
}
throw std::runtime_error(run + ": a formatted access the hardware faults on was recompiled");
}
void RunFormattedLoad(AgcDriver::VulkanDevice& device, std::uint32_t viewOffset) {
for (std::uint32_t index = 0; index < InputBytes; ++index) Input[index] = static_cast<std::uint8_t>(index * 29u + 5u + (index >> 4u));
Output.fill(Fill);
const auto* view = Input.data() + viewOffset;
const auto result = RecompileFormatted(device, Load16Code, view, ViewBytes);
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(Load16Code.data()));
device.WaitIdle();
for (std::uint32_t lane = 0; lane < Lanes; ++lane) {
const auto expected = ViewField(view, lane * 4u + 2u, 0xffffu);
Require(Output[lane] == expected, "buffer unaligned base tbuffer_load_format_x 16_UINT, view +" + std::to_string(viewOffset) + ": lane " + std::to_string(lane) + " is " + Hex(Output[lane]) + ", expected " + Hex(expected));
}
}
void RunFormattedStore(AgcDriver::VulkanDevice& device, std::uint32_t viewOffset) {
Output.fill(Fill);
auto* output = reinterpret_cast<std::uint8_t*>(Output.data());
const auto result = RecompileFormatted(device, Store16Code, output + viewOffset, Lanes * 4u);
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(Store16Code.data()));
device.WaitIdle();
for (std::size_t offset = 0; offset < Output.size() * 4u; ++offset) {
const auto relative = static_cast<std::int64_t>(offset) - static_cast<std::int64_t>(viewOffset);
auto expected = FillByte(offset);
if (relative >= 0 && relative < Lanes * 4 && relative % 4 < 2) expected = static_cast<std::uint8_t>((0xc300u + static_cast<std::uint32_t>(relative / 4)) >> ((relative % 4) * 8));
Require(output[offset] == expected, "buffer unaligned base tbuffer_store_format_x 16_UINT, view +" + std::to_string(viewOffset) + ": byte " + std::to_string(offset) + " is " + Hex(output[offset]) + ", expected " + Hex(expected));
}
}
void RunAtomic(AgcDriver::VulkanDevice& device) {
std::vector<std::uint32_t> userData;
const auto descriptor = BufferDescriptor(reinterpret_cast<std::uint8_t*>(Output.data()) + 2u, 64u);
userData.insert(userData.end(), descriptor.begin(), descriptor.end());
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(AtomicCode.data()), std::as_bytes(std::span(AtomicCode))}}};
try {
const auto result = ShaderRecompiler::Recompile(Request(AtomicCode, userData, device.Target(), memory));
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(AtomicCode.data()));
device.WaitIdle();
} catch (const std::exception& error) {
Require(std::string(error.what()).find("buffer atomic on a V# whose base is not DWORD aligned") != std::string::npos, std::string("buffer unaligned base atomic: unexpected error: ") + error.what());
return;
}
throw std::runtime_error("buffer unaligned base atomic: an atomic on a V# off a DWORD boundary ran");
}
}
int main() {
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
Run(*device, 2, 1);
Run(*device, 3, 3);
Run(*device, 1, 2);
RunPair(*device, 1);
RunPair(*device, 2);
RunPair(*device, 3);
RunAtomic(*device);
RunFormattedLoad(*device, 2);
RunFormattedStore(*device, 2);
for (const auto view : {1u, 3u}) {
RunFormattedFault(*device, "tbuffer_load_format_x 16_UINT", Load16Code, view);
RunFormattedFault(*device, "tbuffer_store_format_x 16_UINT", Store16Code, view);
}
for (const auto view : {1u, 2u, 3u}) {
RunFormattedFault(*device, "tbuffer_load_format_x 32_UINT", Load32Code, view);
RunFormattedFault(*device, "tbuffer_load_format_x 16_16_UINT", Load16_16Code, view);
}
std::puts("buffer unaligned base tests passed");
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -27,6 +27,7 @@ struct BufferResource {
bool formatted = false;
bool scalar = false;
bool empty = false;
std::uint8_t baseMisalignment = 0;
bool operator==(const BufferResource& other) const = default;
};
@@ -14,6 +14,7 @@ struct ResourceSpecialization {
IrBufferFormat descriptorFormat = IrBufferFormat::Invalid;
std::uint32_t descriptorSwizzle = ShaderImageIdentitySwizzle;
bool empty = false;
std::uint8_t baseMisalignment = 0;
bool operator==(const Buffer& other) const;
};
@@ -594,6 +594,7 @@ void buildResourceSpecialization(const IrResourcePlan& plan, ResourceSnapshot& s
entry.descriptorFormat = buffer.formatted ? decoded.Format() : IrBufferFormat::Invalid;
entry.descriptorSwizzle = buffer.formatted ? decoded.DstSelXYZW() : DstSel(4, 5, 6, 7);
entry.empty = decoded.GetSize() == 0u || decoded.Base48() == 0u;
entry.baseMisalignment = entry.empty ? 0u : static_cast<std::uint8_t>(decoded.Base48() & 3u);
result.buffers.push_back(entry);
}
@@ -682,6 +683,7 @@ void ResourceMaterializer::Apply(IrProgram& program, const ResourceSpecializatio
buffers[i].descriptorFormat = specialization.buffers[i].descriptorFormat;
buffers[i].descriptorSwizzle = specialization.buffers[i].descriptorSwizzle;
buffers[i].empty = specialization.buffers[i].empty;
buffers[i].baseMisalignment = specialization.buffers[i].baseMisalignment;
}
auto images = resources.info.images;
@@ -1035,7 +1037,7 @@ void ResourceMaterializer::CountBindlessRejection(BindlessRejection reason) {
}
bool ResourceSpecialization::Buffer::operator==(const Buffer& other) const {
return packedStride == other.packedStride && descriptorFormat == other.descriptorFormat && descriptorSwizzle == other.descriptorSwizzle && empty == other.empty;
return packedStride == other.packedStride && descriptorFormat == other.descriptorFormat && descriptorSwizzle == other.descriptorSwizzle && empty == other.empty && baseMisalignment == other.baseMisalignment;
}
bool ResourceSpecialization::Image::operator==(const Image& other) const {
+4 -1
View File
@@ -395,6 +395,7 @@ void encodeInfo(Writer& writer, const CompiledShaderInfo& compiled) {
out.Value(buffer.formatted);
out.Value(buffer.scalar);
out.Value(buffer.empty);
out.Value(buffer.baseMisalignment);
});
writer.List(info.images, [](Writer& out, const ImageResource& image) {
out.Value(image.source);
@@ -474,7 +475,7 @@ void decodeInfo(Reader& reader, CompiledShaderInfo& compiled) {
auto& info = compiled.info;
reader.Value(info.scratchDwords);
reader.Value(info.sharedMemoryBytes);
reader.List(info.buffers, 34, [](Reader& in, BufferResource& buffer) {
reader.List(info.buffers, 35, [](Reader& in, BufferResource& buffer) {
in.Value(buffer.source);
in.Value(buffer.firstUsePc);
in.Value(buffer.maxByteExtent);
@@ -488,6 +489,7 @@ void decodeInfo(Reader& reader, CompiledShaderInfo& compiled) {
in.Value(buffer.formatted);
in.Value(buffer.scalar);
in.Value(buffer.empty);
in.Value(buffer.baseMisalignment);
});
reader.List(info.images, 63, [](Reader& in, ImageResource& image) {
in.Value(image.source);
@@ -813,6 +815,7 @@ void BuildKey(const RecompileRequest& request, std::uint32_t hostSubgroupSize, c
out.Value(buffer.descriptorFormat);
out.Value(buffer.descriptorSwizzle);
out.Value(buffer.empty);
out.Value(buffer.baseMisalignment);
});
writer.List(specialization.images, [](Writer& out, const ResourceSpecialization::Image& image) {
out.Value(image.numericClass);
+1 -1
View File
@@ -12,7 +12,7 @@
namespace ShaderRecompiler::ShaderDiskCache {
inline constexpr std::uint32_t FormatVersion = 7;
inline constexpr std::uint32_t FormatVersion = 8;
enum class LoadStatus {
Loaded,
@@ -68,6 +68,7 @@ struct MemoryResourceAccess {
std::uint32_t byteOffset = 0;
bool addIndexOffset = false;
std::uint32_t memoryAccess = 0;
std::uint32_t misalignment = 0;
};
struct SpirvEmitterState {
@@ -99,8 +99,9 @@ MemoryResourceAccess PrepareStorageBufferResourceAccess(SpirvEmitterState& state
access.memoryAccess = mem.coherent ? spv::MemoryAccessVolatileMask : 0u;
access.length = state.module.AllocateId();
state.module.AddFunction(spv::OpArrayLength, TypeU32(state), access.length, access.objectPointer, 0u);
if (mem.resource < state.program.Info().buffers.size() && state.program.Info().buffers[mem.resource].empty) {
access.length = ConstantU32(state, 0u);
if (mem.resource < state.program.Info().buffers.size()) {
if (state.program.Info().buffers[mem.resource].empty) access.length = ConstantU32(state, 0u);
access.misalignment = state.program.Info().buffers[mem.resource].baseMisalignment;
}
return access;
}
@@ -151,8 +152,9 @@ std::uint32_t EmitMemoryElementIndex(SpirvEmitterState& state, const MemoryResou
}
std::uint32_t EmitMemoryElementInBounds(SpirvEmitterState& state, const MemoryResourceAccess& access, std::uint32_t index) {
const auto last = access.misalignment != 0u ? EmitAddU32(state, index, ConstantU32(state, 1u)) : index;
const auto inBounds = state.module.AllocateId();
state.module.AddFunction(spv::OpULessThan, TypeBool(state), inBounds, index, access.length);
state.module.AddFunction(spv::OpULessThan, TypeBool(state), inBounds, last, access.length);
return inBounds;
}
@@ -114,11 +114,51 @@ std::uint32_t ActiveArgument(SpirvValueEmitContext& ctx, const IrValue& inst) {
std::uint32_t LoadWordInBounds(SpirvValueEmitContext& ctx, const MemoryResourceAccess& resource, std::uint32_t index) {
auto& state = ctx.state;
const auto pointer = EmitMemoryElementPointer(state, resource, index);
const auto value = state.module.AllocateId();
if (resource.memoryAccess != 0u) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, resource.memoryAccess);
else state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer);
return value;
const auto load = [&](std::uint32_t element) {
const auto pointer = EmitMemoryElementPointer(state, resource, element);
const auto value = state.module.AllocateId();
if (resource.memoryAccess != 0u) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, resource.memoryAccess);
else state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer);
return value;
};
if (resource.misalignment == 0u) return load(index);
const auto shift = resource.misalignment * 8u;
const auto low = Binary(state, spv::OpShiftRightLogical, TypeU32(state), load(index), ConstantU32(state, shift));
const auto high = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), load(EmitAddU32(state, index, ConstantU32(state, 1u))), ConstantU32(state, 32u - shift));
return Binary(state, spv::OpBitwiseOr, TypeU32(state), low, high);
}
void StoreMisalignedBits(SpirvValueEmitContext& ctx, const MemoryResourceAccess& resource, std::uint32_t index, std::uint32_t mask, std::uint32_t value) {
auto& state = ctx.state;
const auto shift = resource.misalignment * 8u;
const auto merge = [&](std::uint32_t element, spv::Op direction, std::uint32_t amount) {
const auto partMask = Binary(state, direction, TypeU32(state), mask, ConstantU32(state, amount));
const auto partValue = Binary(state, direction, TypeU32(state), value, ConstantU32(state, amount));
AtomicUpdate(state, EmitMemoryElementPointer(state, resource, element), resource.kind, [&](std::uint32_t old) {
return Binary(state, spv::OpBitwiseOr, TypeU32(state), Binary(state, spv::OpBitwiseAnd, TypeU32(state), old, Unary(state, spv::OpNot, TypeU32(state), partMask)), partValue);
});
};
merge(index, spv::OpShiftLeftLogical, shift);
merge(EmitAddU32(state, index, ConstantU32(state, 1u)), spv::OpShiftRightLogical, 32u - shift);
}
void StoreMisalignedSubword(SpirvValueEmitContext& ctx, const MemoryResourceAccess& resource, std::uint32_t address, std::uint32_t index, std::uint32_t bits, std::uint32_t data) {
auto& state = ctx.state;
if (bits != 8u && bits != 16u) {
ctx.Fail("subword store has an unsupported width");
}
const auto shift = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), Binary(state, spv::OpBitwiseAnd, TypeU32(state), address, ConstantU32(state, 3u)), ConstantU32(state, 3u));
const auto fieldMask = ConstantU32(state, bits == 8u ? 0xffu : 0xffffu);
const auto mask = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), fieldMask, shift);
StoreMisalignedBits(ctx, resource, index, mask, Binary(state, spv::OpShiftLeftLogical, TypeU32(state), Binary(state, spv::OpBitwiseAnd, TypeU32(state), data, fieldMask), shift));
}
void RequireAlignedAtomic(SpirvValueEmitContext& ctx, const MemoryResourceAccess& resource) {
if (resource.misalignment != 0u) ctx.Fail("buffer atomic on a V# whose base is not DWORD aligned");
}
void RequireAlignedFormattedElement(SpirvValueEmitContext& ctx, const IrValue& inst, const MemoryResourceAccess& resource, const SpirvBufferFormatInfo& info) {
if (resource.misalignment % std::min(info.byteSize, 4u) != 0u) ctx.Fail(inst, "is a formatted buffer access through a V# whose base is not aligned to its element");
}
std::uint32_t LoadSubwordInBounds(SpirvValueEmitContext& ctx, const MemoryResourceAccess& resource, std::uint32_t address, std::uint32_t index, std::uint32_t bits, bool signExtend) {
@@ -361,6 +401,7 @@ std::uint32_t FormattedLoadPrepared(SpirvValueEmitContext& ctx, const IrValue& i
if (mem.d16) ctx.Fail(inst, "is a D16 format load with an unknown buffer format");
return LoadWordPrepared(ctx, inst, RebaseRawComponent(mem, outputComponent), resource);
}
RequireAlignedFormattedElement(ctx, inst, resource, info);
return LoadFormattedComponent(ctx, mem, info, outputComponent, [&](std::uint32_t component) {
return LoadWordPrepared(ctx, inst, RebaseFormattedComponent(mem, info, component), resource);
}, [&](std::uint32_t component, std::uint32_t bits, bool signExtend) {
@@ -377,6 +418,10 @@ std::uint32_t FormattedLoad(SpirvValueEmitContext& ctx, const IrValue& inst, con
void StoreWordInBounds(SpirvValueEmitContext& ctx, const MemoryResourceAccess& resource, std::uint32_t index, std::uint32_t data) {
auto& state = ctx.state;
if (resource.misalignment != 0u) {
StoreMisalignedBits(ctx, resource, index, ConstantU32(state, 0xffffffffu), data);
return;
}
if (resource.memoryAccess != 0u) state.module.AddFunction(spv::OpStore, EmitMemoryElementPointer(state, resource, index), data, resource.memoryAccess);
else state.module.AddFunction(spv::OpStore, EmitMemoryElementPointer(state, resource, index), data);
}
@@ -414,7 +459,8 @@ void StoreSubwordPrepared(SpirvValueEmitContext& ctx, const IrValue& inst, const
const auto rawIndex = Binary(state, spv::OpShiftRightLogical, TypeU32(state), address, ConstantU32(state, 2u));
const auto index = EmitMemoryElementIndex(state, resource, rawIndex);
EmitIfCondition(state, EmitMemoryElementInBounds(state, resource, index), [&]() {
StoreSubwordInBounds(ctx, mem, resource, address, index, bits, data);
if (resource.misalignment != 0u) StoreMisalignedSubword(ctx, resource, address, index, bits, data);
else StoreSubwordInBounds(ctx, mem, resource, address, index, bits, data);
});
}
@@ -455,6 +501,7 @@ enum class FormattedAccess {
PreparedFormattedMemory PrepareFormattedMemory(SpirvValueEmitContext& ctx, const IrValue& inst, const MemoryInfo& mem, const MemoryResourceAccess& resource, const SpirvBufferFormatInfo& info, std::uint32_t components, FormattedAccess access) {
auto& state = ctx.state;
RequireAlignedFormattedElement(ctx, inst, resource, info);
PreparedFormattedMemory plan;
plan.info = info;
plan.resource = resource;
@@ -552,7 +599,8 @@ void StoreFormattedElement(SpirvValueEmitContext& ctx, const MemoryInfo& mem, co
for (std::uint32_t component = 0; component < info.componentCount; component++) {
const auto bits = info.componentBits[component];
if (bits == 8u || bits == 16u) {
StoreSubwordInBounds(ctx, mem, plan.resource, plan.addresses.at(component), plan.indices.at(component), bits, encoded.at(component));
if (plan.resource.misalignment != 0u) StoreMisalignedSubword(ctx, plan.resource, plan.addresses.at(component), plan.indices.at(component), bits, encoded.at(component));
else StoreSubwordInBounds(ctx, mem, plan.resource, plan.addresses.at(component), plan.indices.at(component), bits, encoded.at(component));
} else {
StoreWordInBounds(ctx, plan.resource, plan.indices.at(component), encoded.at(component));
}
@@ -606,7 +654,7 @@ std::uint32_t LoadWideBuffer(SpirvValueEmitContext& ctx, const IrValue& inst, co
return EmitValueOrDefaultIfCondition(state, ActiveArgument(ctx, inst), TypeU32Composite(state, components), ConstantU32CompositeZero(state, components), [&]() {
const auto resource = PrepareMemoryResourceAccess(state, mem);
const auto info = MemoryFormatInfo(state, mem);
if (info.type == SpirvFormatComponentType::Unknown && components == 2u && mem.coherent && state.storageBufferU64Variable != 0u) {
if (info.type == SpirvFormatComponentType::Unknown && components == 2u && mem.coherent && state.storageBufferU64Variable != 0u && resource.misalignment == 0u) {
return LoadCoherentPair(ctx, inst, mem, resource);
}
if (info.type != SpirvFormatComponentType::Unknown) {
@@ -788,6 +836,7 @@ struct PreparedMemoryElement {
PreparedMemoryElement PrepareMemoryElement(SpirvValueEmitContext& ctx, const MemoryInfo& mem, std::uint32_t rawIndex) {
const auto resource = PrepareMemoryResourceAccess(ctx.state, mem);
RequireAlignedAtomic(ctx, resource);
return {resource, EmitMemoryElementIndex(ctx.state, resource, rawIndex)};
}
@@ -970,6 +1019,7 @@ std::uint32_t BufferAtomic64(SpirvValueEmitContext& ctx, const IrValue& inst) {
const auto& mem = BufferMemory(ctx, inst);
return EmitValueOrDefaultIfCondition(state, ActiveArgument(ctx, inst), TypeU64(state), ConstantU64(state, 0u), [&]() {
const auto resource = PrepareStorageBufferResourceAccess(state, mem, state.storageBufferU64Variable, TypeStorageBufferU64Pointer(state));
RequireAlignedAtomic(ctx, resource);
const auto byteAddress = Binary(state, spv::OpIAdd, TypeU32(state), ByteAddress(ctx, inst, mem), resource.byteOffset);
const auto index = Binary(state, spv::OpShiftRightLogical, TypeU32(state), byteAddress, ConstantU32(state, 3u));
return EmitValueOrDefaultIfCondition(state, EmitMemoryElementInBounds(state, resource, index), TypeU64(state), ConstantU64(state, 0u), [&]() {
@@ -1048,6 +1098,7 @@ std::uint32_t BufferAtomic64Update(SpirvValueEmitContext& ctx, const IrValue& in
const auto& mem = BufferMemory(ctx, inst);
return EmitValueOrDefaultIfCondition(state, ActiveArgument(ctx, inst), TypeU64(state), ConstantU64(state, 0u), [&]() {
const auto resource = PrepareStorageBufferResourceAccess(state, mem, state.storageBufferU64Variable, TypeStorageBufferU64Pointer(state));
RequireAlignedAtomic(ctx, resource);
const auto byteAddress = Binary(state, spv::OpIAdd, TypeU32(state), ByteAddress(ctx, inst, mem), resource.byteOffset);
const auto index = Binary(state, spv::OpShiftRightLogical, TypeU32(state), byteAddress, ConstantU32(state, 3u));
return EmitValueOrDefaultIfCondition(state, EmitMemoryElementInBounds(state, resource, index), TypeU64(state), ConstantU64(state, 0u), [&]() {
+2
View File
@@ -311,6 +311,8 @@ Throughout the project, every function at every stage either **does exactly what
- [Converted unorm images](../../core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp) (10_11_11_UNORM, read and written through an R32_UINT view): samples, gathers, LOD queries, 16-bit data and a DST_SEL of the missing W channel throw.
- [Converted unorm image loads](../../core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp) divide by 2^n - 1 with the buffer format path's `OpFDiv`, which Vulkan allows to be up to 2.5 ULP off, so some drivers are not bit-exact.
- [64-bit LDS atomics](../../core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp) (`ds_*_u64`, `ds_*_b64`, `ds_*_f64`) read and write the two dwords under a workgroup lock stored after the guest LDS, as LDS is a 32-bit array without 64-bit atomics. They are atomic with respect to each other only: 32-bit accesses to the same dwords issued concurrently are not ordered by the lock. 64-bit GDS atomics throw. `ds_min/max(_rtn)_f64` and `ds_cmpst(_rtn)_f64` follow the NaN and signed-zero rules measured for the f32 forms; the f64 forms were not measured on hardware.
- [V# bases off a DWORD boundary](../../core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp) (shader recompiler) - raw accesses use the exact bytes and `s_buffer_load` reads `(base & ~3) + (offset & ~3)`, as measured on gfx1035 (Linux, alignment mode UNALIGNED; the console's mode is unknown). Formatted accesses off their element's alignment and atomics throw.
- [Vector buffer offsets that are not a multiple of 4](../../core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp) (shader recompiler) - dword accesses count whole dwords from the V# base, where the hardware reads the exact bytes at base + offset.
- [Min/max S# reduction](../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestSamplerResource.cpp) (libSceAgcDriver) - `FILTER_MODE` 1 and 2 use Vulkan's min and max reduction (the same `SQ_IMG_FILTER_MODE` values RADV programs). Measured on RDNA2 (gfx1035), not on the console: only texels of non-zero weight are reduced, and the weight is taken after rounding to the 8-bit subtexel grid (a sample within 1/512 texel of a centre reduces that texel alone); a driver with other `subTexelPrecisionBits` reduces a different set there. Gathers ignore the mode.
- [Min/max S#](../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestSamplerResource.cpp) (libSceAgcDriver, shader recompiler) - throws with anisotropy, a linear mip filter, depth or color-texture compare, or bilinear filtering of an image the recompiler point-samples (sint, converted, depth-bits).
- [Raw `buffer_load_dwordx2`](../../core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp) is one 64-bit access on the hardware (with or without glc), so it never sees half of a `buffer_atomic_swap_x2`. Only a glc load that is 8-byte aligned and in bounds, in a program that has the 64-bit storage view (it uses 64-bit buffer atomics), is read with one 64-bit atomic load; every other dwordx2 load is two dword loads and can tear against a concurrent 64-bit write: loads without glc, and loads in a program without 64-bit buffer atomics while another shader writes the pair with `swap_x2`.