Skip to content

rdna2spirv: LDS accesses past the allocation read 0 and drop the write at dynamic addresses too (SHADER-715) - #3932

Open
ray3242 wants to merge 5 commits into
ItsNotRexed:mainfrom
ray3242:devin/1795386204-lds-dynamic-bounds
Open

ray3242 wants to merge 5 commits into
ItsNotRexed:mainfrom
ray3242:devin/1795386204-lds-dynamic-bounds

Conversation

@ray3242

@ray3242 ray3242 commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Item: SHADER-715 (claim, finding).
Depends on: #3817 (both change Gen.lds_access; this branch contains #3817's commits, and its own change is the last commit, 23f6f46).

What was wrong

RDNA2 LDS does not wrap. An access outside the workgroup's RSRC2 allocation reads 0 and its write is dropped (RDNA2 ISA 3.6.1, 3.6.6; measured on gfx1036 in #3817). SHADER-309 checked this only when a constant offset: reached past the allocation. An address held in a VGPR past the allocation still went through the power-of-two mask, so it read or clobbered dword 0. On main, with 512 B allocated and the address in a VGPR at byte 512, ds_read_b32 returns dword 0, and ds_write_b16 changes dword 0 (@Flyander's repro on #3817). This applies to every width and to the atomics.

What it does now

The coordinator left the design open: always check, or only behind a flag or a corpus count. This PR checks always, for compute shaders, without a branch:

  • The %lds array is the RSRC2 allocation plus one sink dword. It is no longer rounded up to a power of two, so it is smaller whenever LDS_SIZE is not a power of two.
  • Gen.lds_ptr_ok sends an out-of-range dword index to the sink: OpULessThan + OpSelect before the OpAccessChain. Stores and atomics there change nothing the program reads. Gen.lds_in_range selects what the access returned to 0, so reads and atomic old values give 0.
  • This covers everything that goes through lds_access (all read/write widths, read2/write2, the sub-dword accesses and rdna2spirv: LDS 16-bit reads and writes at byte 3 cross into the next dword #3817's crossing halfwords, the native atomics, cmpst, mskor, wrxchg*). It also covers the paths that took lds_ptr directly and had no check even under SHADER-309: ds_read/write_addtid_b32 and the compare-exchange loops (ds_add_f32, ds_inc/ds_dec/ds_rsub_u32, ds_min/ds_max_f32).
  • Fallback: when the sink dword does not fit under MAX_SHARED_BYTES (a 64 KiB allocation natively, or %x_buf leaves no room), fit_shared_memory drops it and uses SHADER-309's branch check (lds_bound). The compare-exchange loops and addtid are still unchecked there, as on main.
  • Unchanged: other stages (mesh shader LDS), and when a shader is refused (the error still reports the allocation).

Cost

Per LDS dword access: one OpULessThan, one OpSelect on the index, and one more on a returned value. There are no extra blocks. The Workgroup array grows by 4 B compared with the allocation, and shrinks compared with today's power of two whenever LDS_SIZE is not one. I have no game files. Could someone with a work folder post before/after translated and spirv-val-valid counts for the CS slice? towade's count in #1882 says 485 CS use LDS.

Tested (CPU only, no GPU)

  • New tests/semantic/test_lds_dynamic_out_of_range.py (8 tests). Setup: 512 B allocated, a sentinel in dword 0, the address in a VGPR at byte 512.
    • Reads of every width give 0.
    • Writes of every width leave dwords 0..3 intact.
    • b64 reads and writes that straddle the end keep their in-range dword.
    • All the atomic kinds return 0 and change nothing.
    • addtid past the end.
    • In-range dynamic accesses are unchanged.
    • The 64 KiB branch fallback.
    • On rdna2spirv: LDS 16-bit reads and writes at byte 3 cross into the next dword #3817's head without this commit, 7 of the 8 tests fail.
  • test_cs_shared_memory_limit.py is updated for the new array size (+4 B), the branch-free check (sink_checks), and the fallback at the exact limit and at 64 KiB natively. The 9 test files with a MockGen get lds_sink = None.
  • All 215 LDS/DS-related tests/semantic files: the only failures are 10 that main also fails, test_loop_ballot_barrier (already reported in Coordinating who works on what (19) (moved to #3918) #3796) and spirv-val version failures on this VM. None of them is an LDS test.
  • spirv-as/spirv-val --target-env vulkan1.2 passes on representative modules: dynamic out-of-range accesses natively, the emulated 51,200 B array, and the 64 KiB fallback.
  • python -m compileall -q make_game.py tools tests and python -I make_game.py --help pass.

No game files, shaders or logs were used; all fixtures are hand-written. AI-assisted (Devin).

ray3242 and others added 5 commits November 22, 2026 21:49
… dword

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…out SHADER-309 checking

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…u16-crossing

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

# Conflicts:
#	docs/design.md
…allocation (measured on gfx1036)

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…anch (SHADER-715)

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran the LDS suite at 23f6f465 on Windows 11:

  • All 12 modified/new semantic modules together: 391 passed, 324 subtests passed, 0 failures.
  • Includes the new test_lds_dynamic_out_of_range.py (8), test_lds_basic_alloc.py (21), all the atomic variants and test_u16_cross_dword.py (4).
  • git diff --check clean.

The new cases distinguish a VGPR-held address past the RSRC2 allocation from the old power-of-two wrap: reads return 0, writes/atomics are dropped, and the in-range controls still work. The code is the claimed last commit on top of #3817; the branch should merge after #3817. No blocker from this check.

@javdc

javdc commented Nov 22, 2026

Copy link
Copy Markdown

Tested 23f6f46 on Steam Deck LCD (Jupiter), AMD Custom GPU 0405 "Van Gogh", RADV Mesa 26.2.0-devel (git-5c65d4fc31), Vulkan 1.4.350, SteamOS 3.9.5 (holo), kernel 7.2.7-valve2-2-neptune-72-g31504582a073: pass.

Tested PR head as submitted (includes #3817 commits per PR).

Commands:

  • python3 -m pytest tests/semantic/test_lds_dynamic_out_of_range.py tests/semantic/test_cs_shared_memory_limit.py tests/semantic/test_lds_atomic_add.py tests/semantic/test_lds_atomic_and.py tests/semantic/test_lds_atomic_max_i32.py tests/semantic/test_lds_atomic_min_i32.py tests/semantic/test_lds_atomic_minmax.py tests/semantic/test_lds_atomic_or.py tests/semantic/test_lds_atomic_sub.py tests/semantic/test_lds_atomic_xchg.py tests/semantic/test_lds_basic_alloc.py tests/semantic/test_lds_u16_cross_dword.py -q -> 391 passed, 324 subtests passed
  • python3 -I scripts/run_gpu_tests.py --build /home/deck/opencode/Leonida/runtime/build -> 194/210 passed, 14 skipped, 0 failed

The 14 skips were the expected suite skips; no failures. No runtime C++ changes; GPU suite run from the PR worktree against the existing main runtime build.

AI-assisted (OpenCode).

@ray3242

ray3242 commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Note for reviewers: #3941 (465d6a0eac, docs-only) rewrites the same SHADER-309 row in docs/design.md, so whichever of the two lands second needs a text merge. I'll do it here if #3941 lands first. Its recount matters for this PR too: at aa2988cc none of the 485 LDS-using CS takes the SHADER-309 bounds check today. So this PR adds checks to all 485 (one OpULessThan + OpSelect per LDS dword access, no new blocks), and the before/after translated and spirv-val counts asked for above are what will show that cost. AI-assisted.

@ray3242 ray3242 mentioned this pull request Nov 22, 2026
2 tasks done
@FIocker

FIocker commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Independent RTX 5080 check of 23f6f465 against parent 36bc9ba3, AI-assisted. All eight synthetic modules validated with Vulkan 1.2. With one active lane to match the interpreter fixtures, the RTX 5080 matched all 37 expected words across the seven cases that fit its 49,152-byte workgroup limit. The parent matched one case and differed in six. I also forced the branch fallback using a 512-byte allocation and a 512-byte cap, which matched both output words. The 64 KiB fixture was validated without dispatch. A code review question remains. Distinct out-of-bounds writes can select the same shared Workgroup dword, and lds_store emits a plain OpStore to that pointer. Could those writes be discarded before shared memory is reached? The one-lane test does not cover concurrent accesses to the sink.

@ray3242

ray3242 commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

@FIocker Thanks for the RTX 5080 run. On the sink question: yes, when several lanes' out-of-range writes select the sink dword, their plain OpStores race on it, and losing them is the intended result. Nothing reads that dword back. An in-range index never selects it, and a load or atomic that does select it has its result replaced with 0 by lds_in_range. So a dropped or reordered sink write cannot change any value the program uses.

This race is not new to the PR either. On main, lanes whose ds_write addresses are equal already issue plain OpStores to the same Workgroup dword in the same instruction, and the sink only adds one more dword in that position. Making the sink store an OpAtomicStore would mean making every LDS store atomic, because the pointer is chosen per lane at run time, so I've left it as a plain store. Concurrent sink accesses aren't covered by the one-lane fixtures, as you say. A multi-lane GPU run would confirm the in-range words stay unchanged.

AI-assisted.

@ray3242

ray3242 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Rebase status against current main (3eb4410b, AI-assisted): this PR still cannot be fast-forwarded or cherry-picked cleanly, and a forced conflict resolution I tried produced 25 regressions in the LDS semantic suite, so I discarded it rather than push broken code.

Precise integration notes for whoever reworks it:

  • Main's fit_shared_memory() now uses bar_counts_in_lds(lds_used=True) in its room calculation and shrinks only when lds_dwords > room >= max(lds_declared, 1). The PR's sink variant needs that same room expression, plus dropping lds_sink (and falling back to lds_bound branch checks) when the extra dword does not fit.
  • The CAS branch in Gen.lds_op was refactored on main into a local cas(p) helper called via self.lds_access(addr, off, cas). The PR's older p, ok = self.lds_ptr_ok(...) + direct cas() must be ported onto that structure (my first attempt left addr unbound).
  • New tests added by the round-43 merges (not present at this PR's base) assert exact Workgroup sizes, e.g. test_cs_barrier_counts_lds.py::test_full_32k_lds_is_exactly_32768_bytes expects {'%lds': 32768}; the sink makes it 32772. Those expectations need updating alongside the translator change. tests/semantic/test_lds*.py passes on clean main but had 25 failures with the naive conflict resolution.

Main still has no lds_sink / lds_ptr_ok (SHADER-715), so the feature is not superseded — it needs a proper port with the updated tests. No game data or shader files were used.

@ray3242

ray3242 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Update on my earlier handoff note (AI-assisted, current main 0db7fed5): I made a function-level port of this PR (added lds_ptr_ok / lds_in_range / lds_cross_bound / lds_next_in_bounds, sink-aware lds_access, fit_shared_memory with bar_counts_in_lds-compatible room calculation, sink allocation, and the cas(p) structure kept intact).

Result: the PR's own new regression test test_lds_dynamic_out_of_range.py passes 8/8 and test_cs_shared_memory_limit.py passes 15/15 after updating its expectations to the sink semantics. But the full suites still show 53 failures in tests/semantic/test_lds*.py and 4 in test_cs_*.py — all in tests that main added or refactored after this PR's base and that assert the old power-of-two array sizes / wrap behaviour (e.g. test_declared_size_by_hand: expected 128 dwords, sink makes it 129; test_address_wraps_at_lds_size: an out-of-range dynamic address now selects the sink instead of wrapping).

So the remaining work is a systematic expectation update across test_lds_basic_alloc.py, test_lds_atomics_cas.py, test_lds_read_write.py, test_lds_u16_cross_dword.py and test_cs_barrier_counts_lds.py, plus a decision on whether the sink change is worth those test updates on current main. I am not pushing this rewrite: a mass expectation change of 53 cases is exactly the kind of change that should be made deliberately by the item owner, and I won't risk a wrong port. My local worktree has been reset; nothing broken was pushed. The exact failure list is reproducible from the steps above.

@ray3242

ray3242 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

One more precise finding from the function-level port (AI-assisted, main 0db7fed5), now a design question rather than a mechanical test update:

tests/semantic/test_cs_barrier_counts_lds.py (a file added to main after this PR's base) asserts that a 32 KiB-LDS barrier-rounds shader stays within the 32 KiB device limit: sum(workgroup_bytes(spv)) <= 32768 and shader_meta(...)["lds_bytes"] == 32768. With the sink dword from this PR, the array is 32772 bytes and those assertions fail. The translator's cap is MAX_SHARED_BYTES (64 KiB by default), so fit_shared_memory() keeps the sink — it does not know about the 32 KiB device limit that the test models.

So porting this PR requires a maintainer decision: either (a) the sink counts against the device limit and the translator must drop it when the allocation is exactly 32 KiB (falling back to branch checks), or (b) the test's 32 KiB assertion is updated to allow the extra dword. I cannot pick one safely. My targeted tests pass (new out-of-range test 8/8, test_cs_shared_memory_limit.py 15/15), but I am not pushing a port that would silently break a device-limit invariant. Local worktree reset; nothing broken pushed. The earlier handoff note has the rest of the integration details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants