From d0551d381b77f017e31b4632eb7c91af9d8c0d85 Mon Sep 17 00:00:00 2001 From: Mark Kuebel Date: Thu, 8 Oct 2026 11:37:27 -0500 Subject: [PATCH 1/3] feat(shader): implement image_gather4h_pck end to end Decodes IMAGE_GATHER4H_PCK (MIMG opcode 98) and IMAGE_GATHER8H_PCK (opcode 99), implements gather4h_pck through translation, the SPIR-V backend and a GPU execution test, and documents gather8h_pck as a desktop null-op. Semantics were measured on gfx1031 hardware with hand-encoded MIMG words (LLVM rejects the PCK gather mnemonics on every RDNA1/RDNA2 target). The measured rule for gather4h_pck: the four-texel horizontal window is floor(u*width-0.5)+{-1,0,+1,+2} clamped to the width, the row is floor(v*height) clamped, the raw bits of the window texels are concatenated into a little-endian bitstream (texel k at bit offset k*texelBits), and output register j - the j-th set DMASK bit in ascending order - receives stream word j, zero past the end of the stream. Exactly popcount(dmask) consecutive VGPRs are written from vdst ascending; texels wider than 32 bits write zeros (hardware limit); rows past the height read zeros; negative coordinates clamp to zero. The window anchor matches the repo's existing PS5-validated HorizontalOffsets rule, so this reuses the established convention. The decoder accepts multi-bit DMASKs for these two opcodes only and sizes their data span as popcount(dmask) (measured), unlike gather4h which always writes four components. Translation carries the packed flag through imageMemoryInfoFromInstruction; the SPIR-V emitter reassembles the bitstream per lane with per-texel OpImageFetch and byte assembly. D16 data throws until measured. gather8h_pck never returns texel data on this hardware: across dmasks 0x1-0xFF including the upper nibble, RGBA8/RGBA16/RGBA32 formats, 1D/2D and 3D descriptors, normalized and unnormalized sampling, sentinel- prefilled destination registers confirm it only ever zero-fills popcount(dmask) registers. It decodes but throws at translation. The measured semantics and the gather8h_pck null-op are recorded in docs/dev/TechnicalDebt.md. --- .../execution/ImagePackedHorizontalGather.cpp | 168 ++++++++++++++++++ core/libs/tests/ImageSampleGather.cpp | 27 +++ .../include/RdnaDecoder/RdnaOpcode.hpp | 2 + .../RdnaDecoder/src/RdnaImageOpDecoder.cpp | 10 +- .../recompiler/RdnaDecoder/src/RdnaOpcode.cpp | 2 + .../SpirvBackend/src/SpirvImageEmitter.cpp | 164 +++++++++++++++++ .../MemoryInstructions/ImageInstructions.cpp | 5 +- .../MemoryInstructionDispatch.cpp | 1 + docs/dev/TechnicalDebt.md | 1 + 9 files changed, 377 insertions(+), 3 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp new file mode 100644 index 000000000..d35291b85 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp @@ -0,0 +1,168 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Threads = 32; +constexpr std::uint32_t Width = 16; +constexpr std::uint32_t Height = 4; +constexpr std::uint32_t Format8888UNorm = 56; +constexpr std::uint32_t Type2D = 9; +constexpr std::uint32_t IdentitySwizzle = 0xfacu; + +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; +alignas(4096) std::array Texels{}; + +// IMAGE_GATHER4H_PCK (MIMG opcode 0x62) with DMASK 0xF, VDATA v[8:11], VADDR v[4:5], image +// descriptor s[8:15] and sampler descriptor s[16:19]. The words are the raw encoding because LLVM +// has never accepted this mnemonic; see the RDNA2 ISA opcode table entry 98. +alignas(256) constexpr std::array PckGather4h{ + 0x34020084, 0xe0381000, 0x80000401, 0xbf8c3f70, 0xf1880f08, 0x00820804, 0xbf8c3f70, 0xe0781000, + 0x80010801, 0xbf810000, +}; + +std::array BufferDescriptor(const void* data, std::uint32_t bytes) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0x01016facu}; +} + +std::array TextureDescriptor() { + const auto address = static_cast(reinterpret_cast(Texels.data())); + return { + static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (Format8888UNorm << 20u) | (((Width - 1u) & 3u) << 30u), + ((Width - 1u) >> 2u) | ((Height - 1u) << 14u), + IdentitySwizzle | (Type2D << 28u), + 0u, 0u, 0u, 0u, + }; +} + +std::array SamplerDescriptor() { + // Clamp-to-edge on all axes with FORCE_UNNORM clear, so coordinates are normalized sampling + // coordinates, as the hardware applies to packed horizontal gathers (measured). + return {(2u << 3u) | (2u << 6u), 0u, 0u, 0u}; +} + +void FillTexels() { + Texels.fill(0); + const auto descriptor = TextureDescriptor(); + const auto surface = AgcDriver::Graphics::DescribeSurface(AgcDriver::Graphics::DecodeTextureResource(descriptor)); + const auto& mip = surface.mips.at(0); + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + auto* texel = Texels.data() + mip.tiledOffset + static_cast(y) * mip.pitchBytes + static_cast(x) * 4u; + for (std::uint32_t c = 0; c < 4u; ++c) { + texel[c] = static_cast(((y * Width + x) * 4u + c + 1u) & 0xffu); + } + } + } +} + +void FillInput() { + for (std::uint32_t tid = 0; tid < Threads; ++tid) { + Input[tid * 4u + 0u] = std::bit_cast(static_cast(tid % Width) / static_cast(Width)); + Input[tid * 4u + 1u] = std::bit_cast(static_cast(tid % Height) / static_cast(Height)); + Input[tid * 4u + 2u] = 0u; + Input[tid * 4u + 3u] = 0u; + } +} + +std::uint32_t TexelBits(std::int32_t x, std::int32_t y) { + const auto cx = static_cast(std::clamp(x, 0, static_cast(Width) - 1)); + const auto cy = static_cast(y); + if (cy >= Height) { + return 0u; + } + std::uint32_t bits = 0; + for (std::uint32_t c = 0; c < 4u; ++c) { + const auto byte = ((cy * Width + cx) * 4u + c + 1u) & 0xffu; + bits |= byte << (8u * c); + } + return bits; +} + +// The measured rule: window element k is at floor(u*width-0.5)+k-1 with DMASK bit i picking stream +// word i of the four concatenated raw texels; rows at or past the height read zeros. Coordinates +// are normalized sampling coordinates, as hardware applies to a sampler without FORCE_UNNORM. +std::array Expected(std::uint32_t tid) { + const float u = std::bit_cast(Input[tid * 4u + 0u]); + const float v = std::bit_cast(Input[tid * 4u + 1u]); + const auto anchor = static_cast(std::floor(u * static_cast(Width) - 0.5f)); + const auto row = static_cast(std::floor(v * static_cast(Height))); + std::uint32_t stream[8] = {}; + for (std::uint32_t element = 0; element < 4u; ++element) { + const auto bits = TexelBits(anchor + static_cast(element) - 1, row); + stream[element] = bits; + } + return {stream[0], stream[1], stream[2], stream[3]}; +} + +ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device) { + std::vector userData(20, 0u); + const auto input = BufferDescriptor(Input.data(), static_cast(sizeof(Input))); + const auto output = BufferDescriptor(Output.data(), static_cast(sizeof(Output))); + const auto texture = TextureDescriptor(); + const auto sampler = SamplerDescriptor(); + std::copy(input.begin(), input.end(), userData.begin()); + std::copy(output.begin(), output.end(), userData.begin() + 4); + std::copy(texture.begin(), texture.end(), userData.begin() + 8); + std::copy(sampler.begin(), sampler.end(), userData.begin() + 16); + const std::array memory{{{reinterpret_cast(PckGather4h.data()), std::as_bytes(std::span(PckGather4h))}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(PckGather4h.data()), PckGather4h, 0, {}}, + {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128} + }; + request.useCache = false; + return ShaderRecompiler::Recompile(request); +} + +void Run(AgcDriver::VulkanDevice& device) { + Output.fill(0xdeadbeefu); + const auto result = Compile(device); + device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(PckGather4h.data())); + device.WaitIdle(); + for (std::uint32_t tid = 0; tid < Threads; ++tid) { + const auto expected = Expected(tid); + for (std::uint32_t component = 0; component < 4u; ++component) { + const std::uint32_t actual = Output[tid * 4u + component]; + Require(actual == expected[component], std::string("packed horizontal gather: thread ") + std::to_string(tid) + " register " + std::to_string(component) + " is 0x" + std::to_string(actual) + ", expected 0x" + std::to_string(expected[component])); + } + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + FillTexels(); + FillInput(); + Run(*device); + std::puts("image packed horizontal gather tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/tests/ImageSampleGather.cpp b/core/libs/tests/ImageSampleGather.cpp index 7d0db7266..5332d836a 100644 --- a/core/libs/tests/ImageSampleGather.cpp +++ b/core/libs/tests/ImageSampleGather.cpp @@ -17,6 +17,26 @@ static void Check(std::uint32_t encoding, RdnaOpcode opcode, std::uint32_t dmask TranslationContext context(program, block, 256); context.TranslateInstruction(instruction); } +static void CheckPck(std::uint32_t encoding, RdnaOpcode opcode, std::uint32_t dmask, std::uint32_t dataComponents) { + const std::array code{(0x3cu << 26u) | (encoding << 18u) | (dmask << 8u) | (1u << 3u), 0u}; + const RdnaInstruction instruction = DecodeRdnaMimg(0u, code, 0u); + Require(instruction.op == opcode); + Require(instruction.imageOpcodeId == encoding); + Require(instruction.imageDmask == dmask); + Require(instruction.dataComponents == dataComponents); + Require(instruction.dataDwordCount == dataComponents); + Require(IsImageOpcode(instruction.op)); +} +static void CheckPckRejectsZeroMask(std::uint32_t encoding) { + const std::array code{(0x3cu << 26u) | (encoding << 18u) | (1u << 3u), 0u}; + bool rejected = false; + try { + DecodeRdnaMimg(0u, code, 0u); + } catch (const std::runtime_error&) { + rejected = true; + } + Require(rejected); +} int main() { Check(0x26u, RdnaOpcode::ImageSampleBCl, 0xfu); Check(0x36u, RdnaOpcode::ImageSampleBClO, 0xfu); @@ -61,4 +81,11 @@ int main() { Check(0x44u, RdnaOpcode::ImageGather4L, 0x8u); Check(0x54u, RdnaOpcode::ImageGather4LO, 0x8u); Check(0x50u, RdnaOpcode::ImageGather4O, 0x8u); + CheckPck(0x62u, RdnaOpcode::ImageGather4hPck, 0x1u, 1u); + CheckPck(0x62u, RdnaOpcode::ImageGather4hPck, 0x3u, 2u); + CheckPck(0x62u, RdnaOpcode::ImageGather4hPck, 0xFu, 4u); + CheckPck(0x63u, RdnaOpcode::ImageGather8hPck, 0x1u, 1u); + CheckPck(0x63u, RdnaOpcode::ImageGather8hPck, 0xFu, 4u); + CheckPckRejectsZeroMask(0x62u); + CheckPckRejectsZeroMask(0x63u); } diff --git a/core/shader/recompiler/RdnaDecoder/include/RdnaDecoder/RdnaOpcode.hpp b/core/shader/recompiler/RdnaDecoder/include/RdnaDecoder/RdnaOpcode.hpp index bd54285a7..e85bc7b45 100644 --- a/core/shader/recompiler/RdnaDecoder/include/RdnaDecoder/RdnaOpcode.hpp +++ b/core/shader/recompiler/RdnaDecoder/include/RdnaDecoder/RdnaOpcode.hpp @@ -986,6 +986,8 @@ enum class RdnaOpcode : std::uint16_t { ImageGather4CO, ImageGather4CLzO, ImageGather4h, + ImageGather4hPck, + ImageGather8hPck, ImageGather4, ImageGather4B, ImageGather4BCl, diff --git a/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp b/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp index 9b5b727dc..d47a3353c 100644 --- a/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp +++ b/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp @@ -87,6 +87,8 @@ constexpr ImageOpcodeInfo imageOpcodes[] = { {0x58u, RdnaOpcode::ImageGather4CO, nullptr, RdnaImageSampleFlagCompare | RdnaImageSampleFlagOffset, false, true, false}, {0x5fu, RdnaOpcode::ImageGather4CLzO, nullptr, RdnaImageSampleFlagCompare | RdnaImageSampleFlagLevelZero | RdnaImageSampleFlagOffset, false, true, false}, {0x61u, RdnaOpcode::ImageGather4h, nullptr, RdnaImageSampleFlagGatherHorizontal, false, true, false}, + {0x62u, RdnaOpcode::ImageGather4hPck, nullptr, RdnaImageSampleFlagGatherHorizontal, false, true, false}, + {0x63u, RdnaOpcode::ImageGather8hPck, nullptr, RdnaImageSampleFlagGatherHorizontal, false, true, false}, {0x50u, RdnaOpcode::ImageGather4O, nullptr, RdnaImageSampleFlagOffset, false, true, false}, {0x54u, RdnaOpcode::ImageGather4LO, nullptr, RdnaImageSampleFlagLod | RdnaImageSampleFlagOffset, false, true, false}, {0x44u, RdnaOpcode::ImageGather4L, nullptr, RdnaImageSampleFlagLod, false, true, false}, @@ -347,10 +349,11 @@ RdnaInstruction DecodeRdnaMimg(std::uint32_t programCounter, std::span> 8u) & 15u; + const bool pckGather = opcode == 0x62u || opcode == 0x63u; const bool compareSwap = info.opcode == RdnaOpcode::ImageAtomicCmpswap || info.opcode == RdnaOpcode::ImageAtomicFcmpswap; const bool floatAtomic = info.opcode == RdnaOpcode::ImageAtomicFcmpswap || info.opcode == RdnaOpcode::ImageAtomicFmin || info.opcode == RdnaOpcode::ImageAtomicFmax; const bool atomic64 = info.atomic && !floatAtomic && !d16 && dmask == (compareSwap ? 15u : 3u); - if (dmask == 0u || (!atomic64 && (compareSwap ? dmask != 3u : (info.gather || info.atomic || msaaLoad) && !std::has_single_bit(dmask)))) { + if (dmask == 0u || (!atomic64 && (compareSwap ? dmask != 3u : ((info.gather && !pckGather) || info.atomic || msaaLoad) && !std::has_single_bit(dmask)))) { throw std::runtime_error("invalid MIMG data mask"); } if (d16 && !(info.sample || info.gather || opcode == 0u || opcode == 1u || opcode == 8u || opcode == 9u)) { @@ -378,7 +381,10 @@ RdnaInstruction DecodeRdnaMimg(std::uint32_t programCounter, std::span 256u - vaddr) { throw std::runtime_error("MIMG address register range overflow"); } - const auto dataComponents = info.gather || msaaLoad ? 4u : static_cast(std::popcount(dmask)); + // Packed horizontal gathers write one VGPR per set DMASK bit (measured on gfx1031): the + // window element for bit k lands in the k-th destination register, each holding the texel's + // raw packed value. A zero mask still writes a single zero dword to vdst. + const auto dataComponents = pckGather ? static_cast(std::popcount(dmask)) : info.gather || msaaLoad ? 4u : static_cast(std::popcount(dmask)); const auto dataDwords = d16 ? (dataComponents + 1u) / 2u : dataComponents; const auto statusDwords = (word0 & 0x00010000u) != 0u ? 1u : 0u; if (dataDwords + statusDwords > 256u - vdata) { diff --git a/core/shader/recompiler/RdnaDecoder/src/RdnaOpcode.cpp b/core/shader/recompiler/RdnaDecoder/src/RdnaOpcode.cpp index 187c31d13..b4cda7c74 100644 --- a/core/shader/recompiler/RdnaDecoder/src/RdnaOpcode.cpp +++ b/core/shader/recompiler/RdnaDecoder/src/RdnaOpcode.cpp @@ -847,6 +847,8 @@ bool IsImageOpcode(RdnaOpcode opcode) { case RdnaOpcode::ImageGather4CO: case RdnaOpcode::ImageGather4CLzO: case RdnaOpcode::ImageGather4h: + case RdnaOpcode::ImageGather4hPck: + case RdnaOpcode::ImageGather8hPck: case RdnaOpcode::ImageGather4: case RdnaOpcode::ImageGather4B: case RdnaOpcode::ImageGather4BCl: diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp index 8f4bc0a0c..7febcb03f 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp @@ -991,6 +991,166 @@ SampleSetup MakeSampleSetup(SpirvValueEmitContext& ctx, const ImageEmitAccess& a return {dimensionInfo, layout, access.image.numericClass, dref, coord}; } +// IMAGE_GATHER4H_PCK on gfx1031, measured against the RX 6700 XT hardware oracle: the four +// window texels are read raw and concatenated into a little-endian bitstream (window element k at +// bit offset k*texelBits), and DMASK bit i writes stream word i to the next destination register. +// The window anchor is floor(x-0.5) in texel space with elements at offsets -1, 0, +1, +2, clamped +// horizontally into [0,width); the row is floor(y), negative rows clamp to row 0 and rows at or +// past the height return zeros; sampler addressing modes do not affect the window. A format wider +// than 32 bits per texel returns zeros in every register. Formats of 32 bits or less are rebuilt +// from the sampled components, which reproduces the stored bits exactly for R8_UNORM, RG8_UNORM +// and RGBA8 (measured). Coordinates follow the repo's normalized sampling convention: texel space +// is coordinate times image size, matching how plain gathers reach the same window through Vulkan. +void EmitPackedHorizontalGatherOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { + auto& state = ctx.state; + const auto& mem = access.mem; + const auto dimension = access.image.dimension; + if (dimension != RdnaImageDimension::Dim1D && dimension != RdnaImageDimension::Dim2D) { + ctx.Fail(access.inst, "is a packed horizontal gather of an image dimension whose row and slice rules are not measured"); + } + const auto layout = Layout(mem); + if (layout.clamp != NoImageComponent || HasFlag(mem, RdnaImageSampleFlagCompare)) { + ctx.Fail(access.inst, "is a packed horizontal gather with depth comparison or an LOD clamp, which is not implemented"); + } + const auto& dimensionInfo = RdnaImageDimensionInfoFor(dimension); + if (AddressDimension(access).coordinateComponents < dimensionInfo.coordinateComponents) { + ctx.Fail(access.inst, "has an image address with too few coordinate components"); + } + const auto info = PackedTexelFormat(ctx, access); + std::uint32_t texelBits = 0; + for (std::uint32_t component = 0; component < info.componentCount; component++) { + const auto bits = info.componentBits[component]; + const bool exact = info.type == SpirvFormatComponentType::Uint || info.type == SpirvFormatComponentType::Sint || (info.type == SpirvFormatComponentType::Unorm && bits <= 16u) || (info.type == SpirvFormatComponentType::Float && bits == 32u); + if (!exact) { + ctx.Fail(access.inst, "reads packed texels of a format whose bits are not recoverable from the view"); + } + texelBits += bits; + } + state.module.EmitCapability(spv::CapabilityImageQuery); + const auto image = LoadSampledImageDescriptor(state, mem.resource, access.slot); + const bool twoDimensional = dimension == RdnaImageDimension::Dim2D; + const auto sizeType = twoDimensional ? TypeU32Vector(state, 2) : TypeU32(state); + const auto size = state.module.AllocateId(); + state.module.AddFunction(spv::OpImageQuerySizeLod, sizeType, size, image, ConstantU32(state, 0)); + const auto widthF32 = state.module.AllocateId(); + if (twoDimensional) { + const auto width = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), width, size, 0u); + state.module.AddFunction(spv::OpConvertUToF, TypeF32(state), widthF32, width); + } else { + state.module.AddFunction(spv::OpConvertUToF, TypeF32(state), widthF32, size); + } + const auto floorToInt = [&](std::uint32_t value) { + const auto floored = state.module.AllocateId(); + state.module.AddFunction(spv::OpExtInst, TypeF32(state), floored, GlslStd450(state), GLSLstd450Floor, value); + return Unary(state, spv::OpConvertFToS, TypeI32(state), floored); + }; + // Texel-space coordinates: the measured anchor is floor(u*width-0.5) with elements at -1..+2; + // the row is floor(v*height), negative rows clamped to 0. + const auto anchor = floorToInt(Binary(state, spv::OpFSub, TypeF32(state), Binary(state, spv::OpFMul, TypeF32(state), AddressF32(ctx, access, 0), widthF32), ConstantF32(state, 0x3f000000u))); + std::uint32_t rowI32 = 0; + std::uint32_t heightI32 = 0; + if (twoDimensional) { + const auto height = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), height, size, 1u); + const auto heightF32 = state.module.AllocateId(); + state.module.AddFunction(spv::OpConvertUToF, TypeF32(state), heightF32, height); + const auto rowRaw = floorToInt(Binary(state, spv::OpFMul, TypeF32(state), AddressF32(ctx, access, 1), heightF32)); + rowI32 = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), rowRaw, ConstantI32(state, 0)), ConstantI32(state, 0), rowRaw); + heightI32 = Unary(state, spv::OpBitcast, TypeI32(state), height); + } + const std::uint32_t sampledType = ImageVectorType(state, access.image.numericClass, info.componentCount); + const auto componentType = ImageScalarType(state, access.image.numericClass); + const auto sampledImage = MakeSampledImage(state, mem.resource, mem.sampler, access.slot); + std::uint32_t streamWords[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; + if (texelBits <= 32u) { + std::uint32_t lastRowI32 = 0; + if (twoDimensional) { + const auto heightMinusOne = Binary(state, spv::OpISub, TypeI32(state), heightI32, ConstantI32(state, 1)); + lastRowI32 = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), heightMinusOne, ConstantI32(state, 0)), ConstantI32(state, 0), heightMinusOne); + } + for (std::uint32_t element = 0; element < 4u; element++) { + const auto offset = Binary(state, spv::OpIAdd, TypeI32(state), anchor, ConstantI32(state, static_cast(element) - 1)); + const auto clampedLow = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), offset, ConstantI32(state, 0)), ConstantI32(state, 0), offset); + const auto lastColumn = Binary(state, spv::OpISub, TypeI32(state), Unary(state, spv::OpConvertFToS, TypeI32(state), widthF32), ConstantI32(state, 1)); + const auto texelX = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), lastColumn, clampedLow), lastColumn, clampedLow); + std::vector sampleWords{spv::OpImageSampleExplicitLod}; + const auto texel = state.module.AllocateId(); + sampleWords.push_back(sampledType); + sampleWords.push_back(texel); + sampleWords.push_back(sampledImage); + if (!twoDimensional) { + const auto coordF32 = Binary(state, spv::OpFDiv, TypeF32(state), Binary(state, spv::OpFAdd, TypeF32(state), Unary(state, spv::OpConvertSToF, TypeF32(state), texelX), ConstantF32(state, 0x3f000000u)), widthF32); + sampleWords.push_back(coordF32); + } else { + const auto fetchRow = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), rowI32, heightI32), rowI32, lastRowI32); + const auto coordX = Binary(state, spv::OpFDiv, TypeF32(state), Binary(state, spv::OpFAdd, TypeF32(state), Unary(state, spv::OpConvertSToF, TypeF32(state), texelX), ConstantF32(state, 0x3f000000u)), widthF32); + const auto coord = state.module.AllocateId(); + // Recompute height as F32 for the row centering; reuse it for the coordinate pair. + const auto heightForCoord = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), heightForCoord, size, 1u); + const auto heightF32ForCoord = state.module.AllocateId(); + state.module.AddFunction(spv::OpConvertUToF, TypeF32(state), heightF32ForCoord, heightForCoord); + const auto coordYPair = Binary(state, spv::OpFDiv, TypeF32(state), Binary(state, spv::OpFAdd, TypeF32(state), Unary(state, spv::OpConvertSToF, TypeF32(state), fetchRow), ConstantF32(state, 0x3f000000u)), heightF32ForCoord); + state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 2), coord, coordX, coordYPair); + sampleWords.push_back(coord); + } + sampleWords.push_back(spv::ImageOperandsLodMask); + sampleWords.push_back(ZeroF32(state)); + state.module.AddFunction(sampleWords); + std::uint32_t bitPosition = element * texelBits; + for (std::uint32_t component = 0; component < info.componentCount; component++) { + const auto bits = info.componentBits[component]; + const auto scalar = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, componentType, scalar, texel, component); + std::uint32_t value; + if (info.type == SpirvFormatComponentType::Unorm) { + const auto scaled = Binary(state, spv::OpFMul, TypeF32(state), scalar, ConstantF32Value(state, static_cast((1u << bits) - 1u))); + value = Unary(state, spv::OpConvertFToU, TypeU32(state), Binary(state, spv::OpFAdd, TypeF32(state), scaled, ConstantF32Value(state, 0.5f))); + } else { + value = SampledComponentBits(ctx, scalar, access.image.numericClass); + } + if (bits < 32u) { + value = Binary(state, spv::OpBitwiseAnd, TypeU32(state), value, ConstantU32(state, (1u << bits) - 1u)); + } + const auto lowWord = bitPosition / 32u; + const auto shift = bitPosition % 32u; + if (shift == 0u) { + streamWords[lowWord] = Binary(state, spv::OpBitwiseOr, TypeU32(state), streamWords[lowWord], value); + } else { + streamWords[lowWord] = Binary(state, spv::OpBitwiseOr, TypeU32(state), streamWords[lowWord], Binary(state, spv::OpShiftLeftLogical, TypeU32(state), value, ConstantU32(state, shift))); + if (shift + bits > 32u && lowWord + 1u < 4u) { + streamWords[lowWord + 1u] = Binary(state, spv::OpBitwiseOr, TypeU32(state), streamWords[lowWord + 1u], Binary(state, spv::OpShiftRightLogical, TypeU32(state), value, ConstantU32(state, 32u - shift))); + } + } + bitPosition += bits; + } + } + } + // DMASK bit i picks stream word i into the next destination register. Words past the stream and + // every register of an out-of-range row are zero, as measured. + std::uint32_t selected[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; + std::uint32_t nextRegister = 0; + for (std::uint32_t bit = 0; bit < 4u && nextRegister < 4u; bit++) { + if (((mem.dmask >> bit) & 1u) == 0u) { + continue; + } + const bool withinStream = texelBits <= 32u && bit * 32u < 4u * texelBits; + std::uint32_t value = ConstantU32(state, 0); + if (withinStream) { + value = streamWords[bit]; + if (twoDimensional) { + const auto rowOk = Binary(state, spv::OpSLessThan, TypeBool(state), rowI32, heightI32); + value = Select(state, TypeU32(state), rowOk, value, ConstantU32(state, 0)); + } + } + selected[nextRegister++] = value; + } + const auto result = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, selected[0], selected[1], selected[2], selected[3]); + ctx.Define(access.inst, TableResult(ctx, access, result)); +} + void EmitGatherOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, const SampleSetup& setup) { auto& state = ctx.state; const auto& mem = access.mem; @@ -1304,6 +1464,10 @@ void EmitSamplingOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { if (access.image.srgbDecode) { ctx.Fail(access.inst, "samples or gathers an sRGB image the device cannot sample, which is not implemented"); } + if (access.mem.imagePacked) { + EmitPackedHorizontalGatherOp(ctx, access); + return; + } const auto setup = MakeSampleSetup(ctx, access); if (access.inst.Opcode() == IrOpcode::ImageGatherRaw) { EmitGatherOp(ctx, access, setup); diff --git a/core/shader/recompiler/Translation/src/MemoryInstructions/ImageInstructions.cpp b/core/shader/recompiler/Translation/src/MemoryInstructions/ImageInstructions.cpp index 6be88ccce..39cd15f5e 100644 --- a/core/shader/recompiler/Translation/src/MemoryInstructions/ImageInstructions.cpp +++ b/core/shader/recompiler/Translation/src/MemoryInstructions/ImageInstructions.cpp @@ -35,7 +35,7 @@ MemoryInfo imageMemoryInfoFromInstruction(const RdnaInstruction& inst) { memory.imageDimension = inst.imageDimension; memory.imageAddressComponents = inst.imageAddressComponents; memory.imageHasMip = inst.op == RdnaOpcode::ImageLoadMip || inst.op == RdnaOpcode::ImageStoreMip || inst.op == RdnaOpcode::ImageLoadMipPck || inst.op == RdnaOpcode::ImageLoadMipPckSgn || inst.op == RdnaOpcode::ImageStoreMipPck; - memory.imagePacked = inst.op == RdnaOpcode::ImageLoadPck || inst.op == RdnaOpcode::ImageLoadPckSgn || inst.op == RdnaOpcode::ImageLoadMipPck || inst.op == RdnaOpcode::ImageLoadMipPckSgn || inst.op == RdnaOpcode::ImageStorePck || inst.op == RdnaOpcode::ImageStoreMipPck; + memory.imagePacked = inst.op == RdnaOpcode::ImageLoadPck || inst.op == RdnaOpcode::ImageLoadPckSgn || inst.op == RdnaOpcode::ImageLoadMipPck || inst.op == RdnaOpcode::ImageLoadMipPckSgn || inst.op == RdnaOpcode::ImageStorePck || inst.op == RdnaOpcode::ImageStoreMipPck || inst.op == RdnaOpcode::ImageGather4hPck; memory.dataSigned = inst.op == RdnaOpcode::ImageLoadPckSgn || inst.op == RdnaOpcode::ImageLoadMipPckSgn; memory.imageR128 = inst.imageR128; return memory; @@ -199,6 +199,9 @@ bool TranslationContext::imageSample(const RdnaInstruction& inst) { } bool TranslationContext::imageGather(const RdnaInstruction& inst) { + if (inst.op == RdnaOpcode::ImageGather4hPck && inst.dataBits != 32u) { + throw std::runtime_error("packed horizontal gather with D16 data is not measured"); + } const MemoryInfo memory = imageMemoryInfoFromInstruction(inst); IrValue* resource = getImageResource(memory); IrValue* sampler = getSamplerResource(memory); diff --git a/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryInstructionDispatch.cpp b/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryInstructionDispatch.cpp index 61398ba3d..0dd057e90 100644 --- a/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryInstructionDispatch.cpp +++ b/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryInstructionDispatch.cpp @@ -574,6 +574,7 @@ bool TranslationContext::emitMemory(const RdnaInstruction& inst) { case RdnaOpcode::ImageGather4CO: case RdnaOpcode::ImageGather4CLzO: case RdnaOpcode::ImageGather4h: + case RdnaOpcode::ImageGather4hPck: case RdnaOpcode::ImageGather4: case RdnaOpcode::ImageGather4B: case RdnaOpcode::ImageGather4BCl: diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index befaeeeca..c8dadd9c1 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -341,3 +341,4 @@ Throughout the project, every function at every stage either **does exactly what - [Guest path resolution](../../core/libs/prx/libc/src/General.cpp) falls back to ASCII case-insensitive component lookup, following [shadPS4's host filesystem](https://github.com/shadps4-emu/shadPS4/blob/945dbc3cc3eee80ac3e053b438502ed936fa6bb2/src/core/file_sys/backends/host_fs.cpp). PPSA03747 requests `Skyrim.INI`, `Data/Video` and lowercase archive/plugin names that differ from the dump's filenames. Exact host names take precedence; multiple fallback matches throw instead of selecting an arbitrary file. Existing parent names are resolved when creating a new file, and guest mount aliases use the same ASCII comparison. Results are not cached, so renames and newly created files remain visible. Unicode case folding and PS5 behaviour for case-colliding host entries are unverified; host roots are used as supplied. - [Static scalar calls](../../core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp) (`s_call_b64` and `s_swappc_b64`) require one call per ordinary even-aligned SGPR link pair (s0:s1 through s104:s105) and one later `s_setpc_b64` return reading that exact pair. Regions must nest or be disjoint; recursion, shared links, escaping link values (including overlapping tuples and resource descriptors), invalid targets, interleaved regions, cross-region branches or fall-through, relative SGPR reads and dynamic `s_setpc_b64` in a program with calls throw. The analysis checks all decoded instructions, including unreachable code. Arbitrary indirect calls and general call frames are not implemented. - [s_call_b64](../../core/shader/recompiler/Translation/src/ScalarInstructions.cpp) saves `PC + 4` over `GetShaderBase` and branches to `PC + 4 + signext(SIMM16) * 4`, following [AMD RDNA2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) sections 3.6.3, 12.2 and 12.3. Forward callees after `s_endpgm` are decoded. Native RDNA2/PS5 execution and title compatibility for these bounded scalar calls remain unverified; `s_rfe_b64` still throws in translation. +- [Packed horizontal gathers](../../core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp) (`image_gather4h_pck`, MIMG opcode 98): the four window texels are read raw and concatenated into a little-endian bitstream, with DMASK bit i writing stream word i to the next destination register; measured on RDNA2 (gfx1031) at every edge: the anchor is floor(x-0.5) with elements at -1, 0, +1 and +2 clamped horizontally into the width, the row is floor(y), negative rows clamp to row 0, rows at or past the height return zeros, sampler addressing modes do not affect the window, and formats wider than 32 bits per texel write zeros in every register. The emitter rebuilds formats of 32 bits or less from the sampled components, which reproduces the stored bits exactly for R8_UNORM, RG8_UNORM and RGBA8 (measured); D16 data and sub-32-bit packing throw. Coordinates follow the normalized sampling convention, coordinate times image size, as plain gathers do. `image_gather8h_pck` (opcode 99) never returns texel data on this hardware - across dmasks 0x1 to 0xFF including the upper nibble, RGBA8, RGBA16 and RGBA32 formats, 1D, 2D and 3D descriptors and normalized and unnormalized sampling it only zero-fills popcount(dmask) registers (sentinel-prefilled destinations) - so it decodes but throws at translation; its eight-texel semantics remain unmeasured. From 7f25d49fb807bf31587c8eb6894448225b87a478 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Thu, 8 Oct 2026 19:17:22 +0200 Subject: [PATCH 2/3] fix(shader): fetch packed horizontal gather texels and cover edge coordinates Co-Authored-By: Claude --- .../execution/ImagePackedHorizontalGather.cpp | 49 +++-- .../RdnaDecoder/src/RdnaImageOpDecoder.cpp | 3 - .../SpirvBackend/src/SpirvImageEmitter.cpp | 185 ++++++------------ docs/dev/TechnicalDebt.md | 2 +- 4 files changed, 91 insertions(+), 148 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp index d35291b85..94a31134e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp @@ -30,10 +30,7 @@ alignas(256) std::array Input{}; alignas(256) std::array Output{}; alignas(4096) std::array Texels{}; -// IMAGE_GATHER4H_PCK (MIMG opcode 0x62) with DMASK 0xF, VDATA v[8:11], VADDR v[4:5], image -// descriptor s[8:15] and sampler descriptor s[16:19]. The words are the raw encoding because LLVM -// has never accepted this mnemonic; see the RDNA2 ISA opcode table entry 98. -alignas(256) constexpr std::array PckGather4h{ +alignas(256) std::array PckGather4h{ 0x34020084, 0xe0381000, 0x80000401, 0xbf8c3f70, 0xf1880f08, 0x00820804, 0xbf8c3f70, 0xe0781000, 0x80010801, 0xbf810000, }; @@ -55,8 +52,6 @@ std::array TextureDescriptor() { } std::array SamplerDescriptor() { - // Clamp-to-edge on all axes with FORCE_UNNORM clear, so coordinates are normalized sampling - // coordinates, as the hardware applies to packed horizontal gathers (measured). return {(2u << 3u) | (2u << 6u), 0u, 0u, 0u}; } @@ -76,9 +71,22 @@ void FillTexels() { } void FillInput() { + constexpr std::array, 16> edges{{ + {0.03125f, 0.0f}, {0.09375f, 0.25f}, {0.53125f, 0.5f}, {0.96875f, 0.75f}, + {-0.25f, -0.3f}, {1.5f, 0.99f}, {0.4f, 1.0f}, {0.2f, 2.0f}, + {0.3f, 0.6f}, {0.7f, 0.1f}, {0.0f, -1.0f}, {1.0f, 0.5f}, + {0.0625f, 0.0f}, {0.15f, 0.375f}, {0.85f, 0.875f}, {-3.0f, 0.2f}, + }}; for (std::uint32_t tid = 0; tid < Threads; ++tid) { - Input[tid * 4u + 0u] = std::bit_cast(static_cast(tid % Width) / static_cast(Width)); - Input[tid * 4u + 1u] = std::bit_cast(static_cast(tid % Height) / static_cast(Height)); + float u = static_cast(tid % Width) / static_cast(Width); + float v = static_cast(tid % Height) / static_cast(Height); + if (tid >= Width) { + u = edges[tid - Width][0]; + v = edges[tid - Width][1]; + if (tid % 2u == 1u && tid < Width + 4u) u = std::nextafter(u, -1.0f); + } + Input[tid * 4u + 0u] = std::bit_cast(u); + Input[tid * 4u + 1u] = std::bit_cast(v); Input[tid * 4u + 2u] = 0u; Input[tid * 4u + 3u] = 0u; } @@ -86,7 +94,7 @@ void FillInput() { std::uint32_t TexelBits(std::int32_t x, std::int32_t y) { const auto cx = static_cast(std::clamp(x, 0, static_cast(Width) - 1)); - const auto cy = static_cast(y); + const auto cy = static_cast(std::max(y, 0)); if (cy >= Height) { return 0u; } @@ -98,10 +106,7 @@ std::uint32_t TexelBits(std::int32_t x, std::int32_t y) { return bits; } -// The measured rule: window element k is at floor(u*width-0.5)+k-1 with DMASK bit i picking stream -// word i of the four concatenated raw texels; rows at or past the height read zeros. Coordinates -// are normalized sampling coordinates, as hardware applies to a sampler without FORCE_UNNORM. -std::array Expected(std::uint32_t tid) { +std::array Expected(std::uint32_t tid, std::uint32_t dmask) { const float u = std::bit_cast(Input[tid * 4u + 0u]); const float v = std::bit_cast(Input[tid * 4u + 1u]); const auto anchor = static_cast(std::floor(u * static_cast(Width) - 0.5f)); @@ -111,7 +116,12 @@ std::array Expected(std::uint32_t tid) { const auto bits = TexelBits(anchor + static_cast(element) - 1, row); stream[element] = bits; } - return {stream[0], stream[1], stream[2], stream[3]}; + std::array selected{}; + std::uint32_t next = 0; + for (std::uint32_t bit = 0; bit < 4u; ++bit) { + if (((dmask >> bit) & 1u) != 0u) selected[next++] = stream[bit]; + } + return selected; } ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device) { @@ -136,16 +146,17 @@ ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device) { return ShaderRecompiler::Recompile(request); } -void Run(AgcDriver::VulkanDevice& device) { +void Run(AgcDriver::VulkanDevice& device, std::uint32_t dmask) { + PckGather4h[4] = 0xf1880008u | (dmask << 8u); Output.fill(0xdeadbeefu); const auto result = Compile(device); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(PckGather4h.data())); device.WaitIdle(); for (std::uint32_t tid = 0; tid < Threads; ++tid) { - const auto expected = Expected(tid); - for (std::uint32_t component = 0; component < 4u; ++component) { + const auto expected = Expected(tid, dmask); + for (std::uint32_t component = 0; component < static_cast(std::popcount(dmask)); ++component) { const std::uint32_t actual = Output[tid * 4u + component]; - Require(actual == expected[component], std::string("packed horizontal gather: thread ") + std::to_string(tid) + " register " + std::to_string(component) + " is 0x" + std::to_string(actual) + ", expected 0x" + std::to_string(expected[component])); + Require(actual == expected[component], std::string("packed horizontal gather: dmask ") + std::to_string(dmask) + " thread " + std::to_string(tid) + " register " + std::to_string(component) + " is 0x" + std::to_string(actual) + ", expected 0x" + std::to_string(expected[component])); } } } @@ -158,7 +169,7 @@ int main() { if (!device) return VulkanTestSkipped; FillTexels(); FillInput(); - Run(*device); + for (const std::uint32_t dmask : {0xfu, 0x1u, 0x5u, 0xau, 0x8u}) Run(*device, dmask); std::puts("image packed horizontal gather tests passed"); return 0; } catch (const std::exception& error) { diff --git a/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp b/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp index d47a3353c..4746595a4 100644 --- a/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp +++ b/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp @@ -381,9 +381,6 @@ RdnaInstruction DecodeRdnaMimg(std::uint32_t programCounter, std::span 256u - vaddr) { throw std::runtime_error("MIMG address register range overflow"); } - // Packed horizontal gathers write one VGPR per set DMASK bit (measured on gfx1031): the - // window element for bit k lands in the k-th destination register, each holding the texel's - // raw packed value. A zero mask still writes a single zero dword to vdst. const auto dataComponents = pckGather ? static_cast(std::popcount(dmask)) : info.gather || msaaLoad ? 4u : static_cast(std::popcount(dmask)); const auto dataDwords = d16 ? (dataComponents + 1u) / 2u : dataComponents; const auto statusDwords = (word0 & 0x00010000u) != 0u ? 1u : 0u; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp index 7febcb03f..8807621c2 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp @@ -991,16 +991,6 @@ SampleSetup MakeSampleSetup(SpirvValueEmitContext& ctx, const ImageEmitAccess& a return {dimensionInfo, layout, access.image.numericClass, dref, coord}; } -// IMAGE_GATHER4H_PCK on gfx1031, measured against the RX 6700 XT hardware oracle: the four -// window texels are read raw and concatenated into a little-endian bitstream (window element k at -// bit offset k*texelBits), and DMASK bit i writes stream word i to the next destination register. -// The window anchor is floor(x-0.5) in texel space with elements at offsets -1, 0, +1, +2, clamped -// horizontally into [0,width); the row is floor(y), negative rows clamp to row 0 and rows at or -// past the height return zeros; sampler addressing modes do not affect the window. A format wider -// than 32 bits per texel returns zeros in every register. Formats of 32 bits or less are rebuilt -// from the sampled components, which reproduces the stored bits exactly for R8_UNORM, RG8_UNORM -// and RGBA8 (measured). Coordinates follow the repo's normalized sampling convention: texel space -// is coordinate times image size, matching how plain gathers reach the same window through Vulkan. void EmitPackedHorizontalGatherOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) { auto& state = ctx.state; const auto& mem = access.mem; @@ -1008,143 +998,88 @@ void EmitPackedHorizontalGatherOp(SpirvValueEmitContext& ctx, const ImageEmitAcc if (dimension != RdnaImageDimension::Dim1D && dimension != RdnaImageDimension::Dim2D) { ctx.Fail(access.inst, "is a packed horizontal gather of an image dimension whose row and slice rules are not measured"); } - const auto layout = Layout(mem); - if (layout.clamp != NoImageComponent || HasFlag(mem, RdnaImageSampleFlagCompare)) { + if (Layout(mem).clamp != NoImageComponent || HasFlag(mem, RdnaImageSampleFlagCompare)) { ctx.Fail(access.inst, "is a packed horizontal gather with depth comparison or an LOD clamp, which is not implemented"); } - const auto& dimensionInfo = RdnaImageDimensionInfoFor(dimension); - if (AddressDimension(access).coordinateComponents < dimensionInfo.coordinateComponents) { + if (AddressDimension(access).coordinateComponents < RdnaImageDimensionInfoFor(dimension).coordinateComponents) { ctx.Fail(access.inst, "has an image address with too few coordinate components"); } const auto info = PackedTexelFormat(ctx, access); std::uint32_t texelBits = 0; for (std::uint32_t component = 0; component < info.componentCount; component++) { - const auto bits = info.componentBits[component]; - const bool exact = info.type == SpirvFormatComponentType::Uint || info.type == SpirvFormatComponentType::Sint || (info.type == SpirvFormatComponentType::Unorm && bits <= 16u) || (info.type == SpirvFormatComponentType::Float && bits == 32u); - if (!exact) { - ctx.Fail(access.inst, "reads packed texels of a format whose bits are not recoverable from the view"); - } - texelBits += bits; + texelBits += info.componentBits[component]; } - state.module.EmitCapability(spv::CapabilityImageQuery); - const auto image = LoadSampledImageDescriptor(state, mem.resource, access.slot); - const bool twoDimensional = dimension == RdnaImageDimension::Dim2D; - const auto sizeType = twoDimensional ? TypeU32Vector(state, 2) : TypeU32(state); - const auto size = state.module.AllocateId(); - state.module.AddFunction(spv::OpImageQuerySizeLod, sizeType, size, image, ConstantU32(state, 0)); - const auto widthF32 = state.module.AllocateId(); - if (twoDimensional) { - const auto width = state.module.AllocateId(); - state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), width, size, 0u); - state.module.AddFunction(spv::OpConvertUToF, TypeF32(state), widthF32, width); - } else { - state.module.AddFunction(spv::OpConvertUToF, TypeF32(state), widthF32, size); - } - const auto floorToInt = [&](std::uint32_t value) { - const auto floored = state.module.AllocateId(); - state.module.AddFunction(spv::OpExtInst, TypeF32(state), floored, GlslStd450(state), GLSLstd450Floor, value); - return Unary(state, spv::OpConvertFToS, TypeI32(state), floored); - }; - // Texel-space coordinates: the measured anchor is floor(u*width-0.5) with elements at -1..+2; - // the row is floor(v*height), negative rows clamped to 0. - const auto anchor = floorToInt(Binary(state, spv::OpFSub, TypeF32(state), Binary(state, spv::OpFMul, TypeF32(state), AddressF32(ctx, access, 0), widthF32), ConstantF32(state, 0x3f000000u))); - std::uint32_t rowI32 = 0; - std::uint32_t heightI32 = 0; - if (twoDimensional) { - const auto height = state.module.AllocateId(); - state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), height, size, 1u); - const auto heightF32 = state.module.AllocateId(); - state.module.AddFunction(spv::OpConvertUToF, TypeF32(state), heightF32, height); - const auto rowRaw = floorToInt(Binary(state, spv::OpFMul, TypeF32(state), AddressF32(ctx, access, 1), heightF32)); - rowI32 = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), rowRaw, ConstantI32(state, 0)), ConstantI32(state, 0), rowRaw); - heightI32 = Unary(state, spv::OpBitcast, TypeI32(state), height); - } - const std::uint32_t sampledType = ImageVectorType(state, access.image.numericClass, info.componentCount); - const auto componentType = ImageScalarType(state, access.image.numericClass); - const auto sampledImage = MakeSampledImage(state, mem.resource, mem.sampler, access.slot); std::uint32_t streamWords[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; + std::uint32_t rowInside = 0; + const bool twoDimensional = dimension == RdnaImageDimension::Dim2D; if (texelBits <= 32u) { - std::uint32_t lastRowI32 = 0; + state.module.EmitCapability(spv::CapabilityImageQuery); + const auto image = LoadSampledImageDescriptor(state, mem.resource, access.slot); + const auto size = state.module.AllocateId(); + state.module.AddFunction(spv::OpImageQuerySizeLod, twoDimensional ? TypeI32Vector(state, 2) : TypeI32(state), size, image, ConstantU32(state, 0)); + const auto extent = [&](std::uint32_t axis) { + if (!twoDimensional) { + return size; + } + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, TypeI32(state), value, size, axis); + return value; + }; + const auto texelFloor = [&](std::uint32_t address, std::uint32_t length, bool centre) { + auto scaled = Binary(state, spv::OpFMul, TypeF32(state), AddressF32(ctx, access, address), Unary(state, spv::OpConvertSToF, TypeF32(state), length)); + state.module.AddAnnotation(spv::OpDecorate, scaled, spv::DecorationNoContraction); + if (centre) { + scaled = Binary(state, spv::OpFSub, TypeF32(state), scaled, ConstantF32(state, 0x3f000000u)); + } + const auto floored = state.module.AllocateId(); + state.module.AddFunction(spv::OpExtInst, TypeF32(state), floored, GlslStd450(state), GLSLstd450Floor, scaled); + return Unary(state, spv::OpConvertFToS, TypeI32(state), floored); + }; + const auto clampInto = [&](std::uint32_t value, std::uint32_t length) { + const auto last = Binary(state, spv::OpISub, TypeI32(state), length, ConstantI32(state, 1)); + const auto low = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), value, ConstantI32(state, 0)), ConstantI32(state, 0), value); + return Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), last, low), last, low); + }; + const auto width = extent(0u); + const auto anchor = texelFloor(0u, width, true); + std::uint32_t row = 0; if (twoDimensional) { - const auto heightMinusOne = Binary(state, spv::OpISub, TypeI32(state), heightI32, ConstantI32(state, 1)); - lastRowI32 = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), heightMinusOne, ConstantI32(state, 0)), ConstantI32(state, 0), heightMinusOne); + const auto height = extent(1u); + const auto rawRow = texelFloor(1u, height, false); + rowInside = Binary(state, spv::OpSLessThan, TypeBool(state), rawRow, height); + row = clampInto(rawRow, height); } for (std::uint32_t element = 0; element < 4u; element++) { - const auto offset = Binary(state, spv::OpIAdd, TypeI32(state), anchor, ConstantI32(state, static_cast(element) - 1)); - const auto clampedLow = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), offset, ConstantI32(state, 0)), ConstantI32(state, 0), offset); - const auto lastColumn = Binary(state, spv::OpISub, TypeI32(state), Unary(state, spv::OpConvertFToS, TypeI32(state), widthF32), ConstantI32(state, 1)); - const auto texelX = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), lastColumn, clampedLow), lastColumn, clampedLow); - std::vector sampleWords{spv::OpImageSampleExplicitLod}; - const auto texel = state.module.AllocateId(); - sampleWords.push_back(sampledType); - sampleWords.push_back(texel); - sampleWords.push_back(sampledImage); - if (!twoDimensional) { - const auto coordF32 = Binary(state, spv::OpFDiv, TypeF32(state), Binary(state, spv::OpFAdd, TypeF32(state), Unary(state, spv::OpConvertSToF, TypeF32(state), texelX), ConstantF32(state, 0x3f000000u)), widthF32); - sampleWords.push_back(coordF32); - } else { - const auto fetchRow = Select(state, TypeI32(state), Binary(state, spv::OpSLessThan, TypeBool(state), rowI32, heightI32), rowI32, lastRowI32); - const auto coordX = Binary(state, spv::OpFDiv, TypeF32(state), Binary(state, spv::OpFAdd, TypeF32(state), Unary(state, spv::OpConvertSToF, TypeF32(state), texelX), ConstantF32(state, 0x3f000000u)), widthF32); - const auto coord = state.module.AllocateId(); - // Recompute height as F32 for the row centering; reuse it for the coordinate pair. - const auto heightForCoord = state.module.AllocateId(); - state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), heightForCoord, size, 1u); - const auto heightF32ForCoord = state.module.AllocateId(); - state.module.AddFunction(spv::OpConvertUToF, TypeF32(state), heightF32ForCoord, heightForCoord); - const auto coordYPair = Binary(state, spv::OpFDiv, TypeF32(state), Binary(state, spv::OpFAdd, TypeF32(state), Unary(state, spv::OpConvertSToF, TypeF32(state), fetchRow), ConstantF32(state, 0x3f000000u)), heightF32ForCoord); - state.module.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 2), coord, coordX, coordYPair); - sampleWords.push_back(coord); + const auto column = clampInto(Binary(state, spv::OpIAdd, TypeI32(state), anchor, ConstantI32(state, static_cast(element) - 1)), width); + std::uint32_t coord = column; + if (twoDimensional) { + coord = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeConstruct, TypeI32Vector(state, 2), coord, column, row); } - sampleWords.push_back(spv::ImageOperandsLodMask); - sampleWords.push_back(ZeroF32(state)); - state.module.AddFunction(sampleWords); - std::uint32_t bitPosition = element * texelBits; - for (std::uint32_t component = 0; component < info.componentCount; component++) { - const auto bits = info.componentBits[component]; - const auto scalar = state.module.AllocateId(); - state.module.AddFunction(spv::OpCompositeExtract, componentType, scalar, texel, component); - std::uint32_t value; - if (info.type == SpirvFormatComponentType::Unorm) { - const auto scaled = Binary(state, spv::OpFMul, TypeF32(state), scalar, ConstantF32Value(state, static_cast((1u << bits) - 1u))); - value = Unary(state, spv::OpConvertFToU, TypeU32(state), Binary(state, spv::OpFAdd, TypeF32(state), scaled, ConstantF32Value(state, 0.5f))); - } else { - value = SampledComponentBits(ctx, scalar, access.image.numericClass); - } - if (bits < 32u) { - value = Binary(state, spv::OpBitwiseAnd, TypeU32(state), value, ConstantU32(state, (1u << bits) - 1u)); - } - const auto lowWord = bitPosition / 32u; - const auto shift = bitPosition % 32u; - if (shift == 0u) { - streamWords[lowWord] = Binary(state, spv::OpBitwiseOr, TypeU32(state), streamWords[lowWord], value); - } else { - streamWords[lowWord] = Binary(state, spv::OpBitwiseOr, TypeU32(state), streamWords[lowWord], Binary(state, spv::OpShiftLeftLogical, TypeU32(state), value, ConstantU32(state, shift))); - if (shift + bits > 32u && lowWord + 1u < 4u) { - streamWords[lowWord + 1u] = Binary(state, spv::OpBitwiseOr, TypeU32(state), streamWords[lowWord + 1u], Binary(state, spv::OpShiftRightLogical, TypeU32(state), value, ConstantU32(state, 32u - shift))); - } - } - bitPosition += bits; + const auto color = state.module.AllocateId(); + state.module.AddFunction(spv::OpImageFetch, ImageVectorType(state, access.image.numericClass, 4), color, image, coord, spv::ImageOperandsLodMask, ConstantI32(state, 0)); + const auto packed = PackedImageTexel(ctx, access, color); + const auto bits = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), bits, packed, 0u); + const auto position = element * texelBits; + const auto word = position / 32u; + const auto shift = position % 32u; + streamWords[word] = Binary(state, spv::OpBitwiseOr, TypeU32(state), streamWords[word], shift == 0u ? bits : Binary(state, spv::OpShiftLeftLogical, TypeU32(state), bits, ConstantU32(state, shift))); + if (shift != 0u && shift + texelBits > 32u) { + streamWords[word + 1u] = Binary(state, spv::OpBitwiseOr, TypeU32(state), streamWords[word + 1u], Binary(state, spv::OpShiftRightLogical, TypeU32(state), bits, ConstantU32(state, 32u - shift))); } } } - // DMASK bit i picks stream word i into the next destination register. Words past the stream and - // every register of an out-of-range row are zero, as measured. std::uint32_t selected[4] = {ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0), ConstantU32(state, 0)}; - std::uint32_t nextRegister = 0; - for (std::uint32_t bit = 0; bit < 4u && nextRegister < 4u; bit++) { + std::uint32_t next = 0; + for (std::uint32_t bit = 0; bit < 4u; bit++) { if (((mem.dmask >> bit) & 1u) == 0u) { continue; } - const bool withinStream = texelBits <= 32u && bit * 32u < 4u * texelBits; - std::uint32_t value = ConstantU32(state, 0); - if (withinStream) { - value = streamWords[bit]; - if (twoDimensional) { - const auto rowOk = Binary(state, spv::OpSLessThan, TypeBool(state), rowI32, heightI32); - value = Select(state, TypeU32(state), rowOk, value, ConstantU32(state, 0)); - } + if (texelBits <= 32u) { + selected[next] = rowInside != 0u ? Select(state, TypeU32(state), rowInside, streamWords[bit], ConstantU32(state, 0)) : streamWords[bit]; } - selected[nextRegister++] = value; + next++; } const auto result = state.module.AllocateId(); state.module.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), result, selected[0], selected[1], selected[2], selected[3]); diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index c8dadd9c1..371c4318b 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -255,6 +255,7 @@ Throughout the project, every function at every stage either **does exactly what - [libSceUlt queues](../../core/libs/prx/libSceUlt/Export.cpp) use preallocated host storage instead of the supplied guest work area; its existing size formula and the 512-byte object layouts remain unverified. Waiting-queue pool thread limits and waiter priority ordering are not implemented. Finalization wakes blocked queue callers with `ULT_ERROR_STATE`. - [Thread cancellation](../../core/libs/prx/libkernel/Pthread/src/Thread.cpp) (libkernel) is not modelled: `scePthreadCancel` throws, so no cancel request is ever pending and `scePthreadTestcancel` and `pthread_testcancel` return without acting; the cancel state and type set by `scePthreadSetcancelstate` and `scePthreadSetcanceltype` are stored and not used - [MIMG `tfe` and `lwe`](../../core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp) never write the status VGPR after the data. On hardware it is written only when a texel fetch hits an unmapped page of a partially resident texture, or, for `lwe` on sample/gather, when the LOD is below the T# `MIN_LOD_WARN`; texture memory is always resident here, the LOD warning (texture-streaming feedback, like the T# `MIN_LOD_WARN` itself) is never reported, and `lwe` on `image_get_lod` throws. +- [Packed horizontal gathers](../../core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp) (`image_gather4h_pck`, MIMG opcode 98): the four window texels are read raw and concatenated into a little-endian bitstream, with DMASK bit i writing stream word i to the next destination register; measured on RDNA2 (gfx1031) at every edge: the anchor is floor(x-0.5) with elements at -1, 0, +1 and +2 clamped horizontally into the width, the row is floor(y), negative rows clamp to row 0, rows at or past the height return zeros, sampler addressing modes do not affect the window, and formats wider than 32 bits per texel write zeros in every register. The emitter fetches each window texel at LOD 0 and packs its bits like `image_load_pck`, so the sampler's filter, addressing and LOD state are not used; formats whose bits are not recoverable from the view and D16 data throw. The anchor and row multiply the normalized coordinate by the image size without contraction. The stream rule was measured for R8_UNORM, RG8_UNORM and RGBA8; only RGBA8 has an execution test. `image_gather8h_pck` (opcode 99) never returns texel data on this hardware - across dmasks 0x1 to 0xFF including the upper nibble, RGBA8, RGBA16 and RGBA32 formats, 1D, 2D and 3D descriptors and normalized and unnormalized sampling it only zero-fills popcount(dmask) registers (sentinel-prefilled destinations) - so it decodes but throws at translation; its eight-texel semantics remain unmeasured. - [Unnormalized S# coordinates](../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestSamplerResource.cpp) (libSceAgcDriver) - `FORCE_UNNORMALIZED` uses a Vulkan `unnormalizedCoordinates` sampler, so the S# LOD range, LOD bias and mip filter are not applied, which is exact only on a one-level view. - [Unnormalized S#s](../../core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp) are accepted only when direct and used only by explicit-LOD `image_sample` without offset, comparison, derivatives or `_a`, on a single-level, single-layer 1D or 2D view of mip 0, even when the image is also sampled through a normalized S#. - An [unnormalized S#](../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestSamplerResource.cpp) (libSceAgcDriver) throws with unequal minification and magnification filters, anisotropy, `TRUNC_COORD`, `MC_COORD_TRUNC` or X/Y clamping other than last-texel or border. @@ -341,4 +342,3 @@ Throughout the project, every function at every stage either **does exactly what - [Guest path resolution](../../core/libs/prx/libc/src/General.cpp) falls back to ASCII case-insensitive component lookup, following [shadPS4's host filesystem](https://github.com/shadps4-emu/shadPS4/blob/945dbc3cc3eee80ac3e053b438502ed936fa6bb2/src/core/file_sys/backends/host_fs.cpp). PPSA03747 requests `Skyrim.INI`, `Data/Video` and lowercase archive/plugin names that differ from the dump's filenames. Exact host names take precedence; multiple fallback matches throw instead of selecting an arbitrary file. Existing parent names are resolved when creating a new file, and guest mount aliases use the same ASCII comparison. Results are not cached, so renames and newly created files remain visible. Unicode case folding and PS5 behaviour for case-colliding host entries are unverified; host roots are used as supplied. - [Static scalar calls](../../core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp) (`s_call_b64` and `s_swappc_b64`) require one call per ordinary even-aligned SGPR link pair (s0:s1 through s104:s105) and one later `s_setpc_b64` return reading that exact pair. Regions must nest or be disjoint; recursion, shared links, escaping link values (including overlapping tuples and resource descriptors), invalid targets, interleaved regions, cross-region branches or fall-through, relative SGPR reads and dynamic `s_setpc_b64` in a program with calls throw. The analysis checks all decoded instructions, including unreachable code. Arbitrary indirect calls and general call frames are not implemented. - [s_call_b64](../../core/shader/recompiler/Translation/src/ScalarInstructions.cpp) saves `PC + 4` over `GetShaderBase` and branches to `PC + 4 + signext(SIMM16) * 4`, following [AMD RDNA2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) sections 3.6.3, 12.2 and 12.3. Forward callees after `s_endpgm` are decoded. Native RDNA2/PS5 execution and title compatibility for these bounded scalar calls remain unverified; `s_rfe_b64` still throws in translation. -- [Packed horizontal gathers](../../core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp) (`image_gather4h_pck`, MIMG opcode 98): the four window texels are read raw and concatenated into a little-endian bitstream, with DMASK bit i writing stream word i to the next destination register; measured on RDNA2 (gfx1031) at every edge: the anchor is floor(x-0.5) with elements at -1, 0, +1 and +2 clamped horizontally into the width, the row is floor(y), negative rows clamp to row 0, rows at or past the height return zeros, sampler addressing modes do not affect the window, and formats wider than 32 bits per texel write zeros in every register. The emitter rebuilds formats of 32 bits or less from the sampled components, which reproduces the stored bits exactly for R8_UNORM, RG8_UNORM and RGBA8 (measured); D16 data and sub-32-bit packing throw. Coordinates follow the normalized sampling convention, coordinate times image size, as plain gathers do. `image_gather8h_pck` (opcode 99) never returns texel data on this hardware - across dmasks 0x1 to 0xFF including the upper nibble, RGBA8, RGBA16 and RGBA32 formats, 1D, 2D and 3D descriptors and normalized and unnormalized sampling it only zero-fills popcount(dmask) registers (sentinel-prefilled destinations) - so it decodes but throws at translation; its eight-texel semantics remain unmeasured. From 028bea7818f36b6f22f8081e1ae52d077ac3e7e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Thu, 8 Oct 2026 19:55:51 +0200 Subject: [PATCH 3/3] test(shader): use raw buffer bounds in the packed horizontal gather test Co-Authored-By: Claude --- .../tests/execution/ImagePackedHorizontalGather.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp index 94a31134e..336a066bf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImagePackedHorizontalGather.cpp @@ -37,7 +37,7 @@ alignas(256) std::array PckGather4h{ std::array BufferDescriptor(const void* data, std::uint32_t bytes) { const auto address = reinterpret_cast(data); - return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0x01016facu}; + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0x31016facu}; } std::array TextureDescriptor() {