fix(shader): order an image store before a later image atomic on MoltenVK #10652
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/10652"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by maximilianfv on 2026-10-24T15:14:22Z.
What
An invocation that stores to a storage image and then runs a 32-bit image atomic on the same texel got the value from before the store under MoltenVK. On MoltenVK only, this emits
OpMemoryBarrier(Device scope,AcquireRelease | ImageMemory) beforeOpImageTexelPointerin the 32-bit path ofEmitAtomicOp(SpirvImageEmitter.cpp), so it covers every 32-bit image atomic there, the compare-exchange loops included. A newSpirvTarget::imageAtomicStoreBarriersflag, set inVulkanDevice::buildTargetwhen the driver ID isVK_DRIVER_ID_MOLTENVK, gates it, aswaveLdsMemoryBarriersanddeviceScopeLdsMemoryBarriersgate their driver workarounds. The flag is part of the shader cache key, andagc_shader_disk_cachechecks that it changes the key.agc_shader_replaygets an--image-atomic-store-barriersswitch, as the other two have. No test checks the SPIR-V for the barrier with the flag on and off: the two execution tests below fail without it only on MoltenVK.Cause, from a MoltenVK shader dump of the two failing tests: the recompiler emitted
OpImageWrite, thenOpImageTexelPointer+OpAtomicIAdd, with no barrier between them (the onlyOpMemoryBarrier, Device | AcquireRelease | UniformMemory, comes after the atomic). MoltenVK 1.4.2's SPIRV-Cross turned that intoimage.write(...)directly followed byimage.atomic_fetch_add(...)with no fence. SPIRV-Cross'sreadwrite_texture_fencesfences a write before a later read only, not before an atomic, and Metal makes a thread's texture write visible to its own later texture atomic only after a texture fence. So the atomic returned the texel from before the store (the tests'0xdeadbeeffill). SPIRV-Cross writes the new barrier asatomic_thread_fence(mem_flags::mem_texture, ...)only when the target is MSL 3.2 or later (CompilerMSL::emit_barrieremitsatomic_thread_fencewhen the barrier has no execution scope andsupports_msl_version(3, 2)holds, and athreadgroup_barrierotherwise). Upstream issue for the missing fence: KhronosGroup/SPIRV-Cross#2723. The gap this leaves is recorded indocs/dev/debt/shader.md.Vulkan already orders an invocation's store and its later atomic by program order, so other drivers gave the right result before. They now get the same SPIR-V as on
main, with no barrier and no cost. On MoltenVK the barrier costs one texture fence per 32-bit image atomic. I have not measured that cost.Limits:
CompilerMSL::emit_barrieremits nothing outside compute, task, mesh and tessellation control shaders, so on MoltenVK a store followed by an atomic on the same texel in a pixel or vertex shader can still return the old value. The fix that covers every stage belongs in SPIRV-Cross (KhronosGroup/SPIRV-Cross#2723).threadgroup_barrierinside the per-lane divergent control flow thatEmitValueOrZeroIfConditionemits around the atomic, which Metal does not allow. This does not raise the floor thatmainalready has: every image and buffer atomic onmainis followed by a device-scopeOpMemoryBarrierwith no execution scope (EmitDeviceAtomicMemoryBarrier,SpirvFormatConvert.cpp), inside the same per-lane branch (SpirvImageEmitter.cpp, after theOpAtomic*). So below MSL 3.2, SPIRV-Cross already writes athreadgroup_barrierthere for every atomic. MoltenVK picks the MSL version from the OS (MVKDevice.mm, thesetMSLVersionladder): 3.2 on macOS 15 / iOS 18 when MoltenVK is built with Xcode 16 or later, and 4.0 on macOS 26 and later when built with Xcode 26. So this needs macOS 15 or later, which I propose as the floor for the macOS port. I did not add a host OS check:mainhas no macOS-specific code inVulkanDevice.cpp, and an OS check cannot see which Xcode MoltenVK was built with. The debt entry records the floor. Only macOS 27.0.1 (MoltenVK 1.4.2, LunarG SDK 1.4.363) was tested, so only an MSL 3.2 or later target ran.Prior art and credit:
58fe1ed167"fix(macos): order image stores before image atomics under Metal" (authored 2026-10-05) from mugurc's macOS port branch. As its own commit it reached a PR only through the closed #7332 (ycarogabriel-lgtm), which merged that branch. The same barrier in the same place, now emitted only on MoltenVK. The original's code comment is dropped under the no-comments rule. Credited with aCo-authored-by:trailer.58fe1ed167. It fixed the same two tests differently inea9da4fc72(2026-10-21): the same barrier after every image store, macOS only (#ifdef __APPLE__). None of the PRs #8658 was split into (#10362, #10419) carry it.b949b38295(2026-10-12), which brings in mugurc's macOS port branch as a prerequisite for native ARM64 graphics. This PR carries only this one fix so it can land on its own. I asked in #5021 about the merge order (https://github.com/boykopovar/AnyPS5/pull/5021#issuecomment-6385876747) and have had no answer. Proposed order: if this lands first, #5021 drops its copy of the line when it rebases; if #5021 lands first, I close this PR or reduce it to the MoltenVK gate. No other open PR adds an image-memory barrier to the SPIR-V backend.Tested
Apple M1 Pro, macOS 27.0.1, x86_64 build under Rosetta 2, Vulkan through MoltenVK 1.4.2 from the LunarG Vulkan SDK 1.4.363.
maindoes not build on macOS by itself. I tested on mugurc's macOS series (ci/macos-series-2, 27e968974) merged withmainat522e32e3b6, plus local copies of #10540, #10641, #10642, #10650, #10651, #10857, #10858 and #10859 and the macOS build parts of #10419 and #10562. All of these were identical in both runs. Theagc_shader_replayswitch was added after these runs and only builds. Only this PR's flag was toggled between runs: "without" setsimageAtomicStoreBarriersto false inbuildTarget, which emits the same SPIR-V asmain.All runs used
ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation.ctest --test-dir build -R '^(agc_driver_image_cache_bits|agc_driver_image_texel_status|agc_shader_disk_cache)$' -E 'audio_in|voice' -V, three runs each way:agc_shader_disk_cachepasses.agc_driver_image_cache_bitsfails withimage_store dlc: thread 0 is 0xdeadbeef, expected 0x00000000, andagc_driver_image_texel_statusfails withimage_store tfe: thread 0 is 0xdeadbeef, expected 0x00000000.ctest --test-dir build -R 'image|atomic|shader_recompiler|spirv|recompiler' -E 'audio_in|voice' -j4 --timeout 300 -V(108 tests), once each way:agc_driver_image_plane_bias_on_single_level_volumefails both ways.was not found but was requested by env var VK_INSTANCE_LAYERSline. Both logs have 130Validation Errorlines with the same count for every VUID: 54imageViewFormatSwizzle-04465, 50imageViewFormatReinterpretation-04466, 15vkCreateDescriptorSetLayout-support-09582, 9imageCreateMaxMipLevels-02251, 1imageView2DOn3DImage-04459and 1pProperties-04451. So the change adds no validation errors.main's. MaxLikesCode (NVIDIA) and tablefrogpillow (RADV on three AMD GPUs) ran the earlier unconditional version in this PR's comments and found no regressions. Not tested on an MSL target below 3.2. Not tested on Linux or Windows.Checklist
main; no other open PR implements the same functions (except #5021, a 324-file consolidation that also carries mugurc's line; see What)NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-24T15:20:38Z.
Review: COMMENTED
Reviewed exact head
720af6ea444f3e7b7f441946a35db9c844fab919. The targeted MoltenVK report is detailed, but I’m leaving this review commented pending three items. First, the exact barrier line is also present in open #5021; your comment there proposes #10652 first, but I see no agreement yet, and this checklist still saysDepends on: none. Please record the agreed landing order in both checklists so the second PR retains only one copy. Second, the PR body says MSL targets older than 3.2 translate this barrier into an illegalthreadgroup_barrierinside divergent atomic control flow; please establish the project’s supported MSL floor or make this path valid for supported older targets. Third, this inserts a barrier before every 32-bit image atomic on every backend, and the PR reports no performance measurement. Please bound that cost with a hot-path measurement or narrow the emitted barrier to the backend/conditions that need it. The full GPU matrix was not run here; hosted policy checks pass and product jobs are skipped.Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-27T01:35:50Z.
Review: COMMENTED
A second Apple GPU run, plus MoltenVK main, at head
3036ca6a5b.Machine: Apple M2 Max, macOS 27.2, x86_64 build under Rosetta 2, Release. Method: #8658 (
feat/macos-port) @564e005acb+ this PR's diff, notmain. The diff applied with small conflicts, all frommain'sdeviceScopeLdsMemoryBarriers, which #8658 doesn't have; I left that flag out. #8658 also carriesea9da4fc72, the#ifdef __APPLE__barrier after every image store. I disabled that barrier for the PR and control runs, so this PR's barrier is the only one.ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation. The loader log confirms the layer and which driver was used.ctest -R '^(agc_driver_image_cache_bits|agc_driver_image_texel_status|agc_shader_disk_cache)$' --repeat until-fail:3:buildTargetimage_store dlc: thread 0 is 0xdeadbeef, expected 0x00000000,image_store tfe: thread 0 is 0xdeadbeef, expected 0x00000000VUID-VkDeviceCreateInfo-pProperties-04451(portability subset), in both runs. The PR adds no VUIDs.^agcsuite (938 entries, MoltenVK 1.4.2,-j1): this PR, with #8658's store barrier disabled, fails the same 22 tests as unmodified #8658 with its store barrier. These are the known MoltenVK gaps: float denormals, tessellation, sample order, clip/cull and so on. Moving from a barrier after every store to one before every 32-bit atomic changes no result in the suite.GPUs tested: Apple M2 Max (MoltenVK 1.4.2; MoltenVK main 5189f8de + SPIRV-Cross #2704)
Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T11:13:37Z.
Review: CHANGES_REQUESTED
Re-checked — changes requested
The update resolves two technical concerns from my earlier review: the barrier is now gated to MoltenVK and the flag participates in the shader-cache key; the PR also documents the macOS/MSL floor. The remaining blockers are landing coordination and current-main integration.
The same barrier line is still present in open #5021, while this PR's checklist says
Depends on: none. The author's proposed “whichever lands second drops its copy” is reasonable, but I could not find agreement from #5021's author or matching dependency/order entries in both checklists. Please get that agreement and record the order in both PRs. The branch is also based on811ffe10af, not currentmainba5b5330b3; the author update itself says it conflicts with main. Please integrate current main and rerun the focused MoltenVK tests and validation comparison on that exact integration. I did not independently reproduce the MSL/GPU behavior locally.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-14T08:19:22Z.
Review: APPROVED
Reviewed — looks good
Nothing blocks this change; the points below are optional.
What I ran
Reviewed head
9e7921f8d86ccf5f895c48e7cc166c275cd1b98eusingrepo_read.pyto inspect the prepared diff, metadata, and targeted source ranges. No tests or builds were run.Results
Findings
Blocking
None.
Non-blocking
Not verified
VulkanDevice.cppfile; only the changedbuildTargetrange was read.ShaderDiskCache.cpp,ShaderReplay.cpp,CacheKey.hpp,Recompiler.hpp,SpirvEmitterState.hpp,SpirvEmitter.cpp,SpirvImageEmitter.cpp, anddocs/dev/debt/shader.md. The full text of the other changed files was present in the review folder but not read:Recompiler.cppandSpirvEmitter.hpp.To get this to a good state
Nothing is required. Consider adding a focused SPIR-V assertion for the flag-on and flag-off cases.
Pull request closed