From d0551d381b77f017e31b4632eb7c91af9d8c0d85 Mon Sep 17 00:00:00 2001 From: Mark Kuebel Date: Thu, 8 Oct 2026 11:37:27 -0500 Subject: [PATCH] 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.