perf(loader): binary-patch immediate SSE4a extrq/insertq to native stubs (D3D12-LOADER-PATCH-SSE4A) #3375
Open
github-bot
wants to merge 1 commit from
github-bot/gh-3375 into main
AGit
pull from: github-bot/gh-3375
merge into: github:main
github:main
github:perf/darner-title-priority-ceiling
github:gh-readonly-queue/main/pr-3311-b5c45b663dbc5a9c3532bb3f307e5f81b32faefa
github:gh-readonly-queue/main/pr-3088-af22e7847ff5808f72d1a1881c24be2fafd20b54
github:gh-readonly-queue/main/pr-3123-7f3fa026a94c6646e89244f28e1ce22290361867
github:gh-readonly-queue/main/pr-3354-637baa0b77ba47222e7280b17c1a59c6a1781d57
github:gh-readonly-queue/main/pr-3365-d7a0e0196a43834813014b4bd3aa5502a8263b14
github:gh-readonly-queue/main/pr-3361-5dfe8bbd05ed12fb2f2e1718d9af77a7c5f46fd8
github:gh-readonly-queue/main/pr-3366-8da9148204e9d12c585efa9ac2b7cc1ab08c7682
github:fix/runtime-test-conservative-fixtures
github:ci/shard-semantic-linux
github:docs/fg-limit-fps-switch
github:fix/runtime-test-fixture-paths
github:fix/runtime-test-fixture-readers
github:fix/read-file-hard-link
github:fix/book-slot-heap-never-read
github:fix/depth-resolve-spv-path
github:fix/indirect-unused-batched
github:gh-pr/3358/base
github:fix/xmem-refusal-diagnostics
github:gh-pr/3357/base
github:ci/shorten-ci-time
github:fix/alias-later-queued-submissions
github:claude/gallant-sagan-aamatr
github:gh-pr/3342/base
github:gh-pr/3341/base
github:d3d12/agility-sdk-621
github:gh-pr/3293/base
github:gh-pr/3319/base
github:gh-pr/3318/base
github:gh-pr/3315/base
github:gh-pr/3313/base
github:gh-pr/3314/base
github:claude/fervent-curie-m19lnr
github:gh-pr/3216/base
github:gh-pr/3272/base
github:gh-pr/3276/base
github:gh-pr/3279/base
github:gh-pr/3257/base
github:gh-pr/3258/base
github:gh-pr/3271/base
github:codex/skip-no-hit-ray-passes
github:gh-pr/3230/base
github:gh-pr/3266/base
github:gh-pr/3247/base
github:gh-pr/3246/base
github:gh-pr/3244/base
github:claude/sharp-sagan-1jqnp3
github:t3/preserve-fsr-sdk-restart-path
github:t3/propagate-host-failure-hresult
github:t3/launcher-custom-parameters
github:t3/series-x-2160-startup
github:codex/d3d12-uncapped-simulation
github:ci/less-to-run
github:perf/native-compute-shader-forms
github:claude/blissful-franklin-ukp7ag
github:codex/full-precompile-default
github:gh-pr/3166/base
github:gh-pr/3148/base
github:gh-pr/3138/base
github:gh-pr/3106/base
github:gh-pr/3057/base
github:gh-pr/2756/base
github:gh-pr/2812/base
github:gh-pr/3032/base
github:gh-pr/2992/base
github:notes/card-time-and-plant-flicker
github:gh-pr/2986/base
github:gh-pr/3000/base
github:gh-pr/2966/base
github:gh-pr/2924/base
github:gh-pr/726/base
github:gh-pr/2761/base
github:gh-pr/2663/base
github:gh-pr/2861/base
github:gh-pr/2862/base
github:gh-pr/2820/base
github:gh-pr/2811/base
github:gh-pr/2803/base
github:rt-call-trace
github:gh-pr/2802/base
github:gh-pr/2766/base
github:perf/ahead-split
github:gh-pr/2589/base
github:gh-pr/2699/base
github:gh-pr/2696/base
github:docs/readme-runtime-proposal
github:gh-pr/1346/base
github:codex/coord-claim-check-20261124-7e48
No reviewers
Labels
Clear labels
accessibility
Barrier affecting people with disabilities
area: ci
.github/ workflows and settings
area: d3d12
The D3D12 runtime in d3d12/ (Rust: leonida.exe and its crates)
area: docs
Documentation
area: launcher
The launcher (launcher/)
area: runtime (legacy)
The earlier Vulkan runtime in runtime/
area: shader translator
The shader translator (leonida-shader, tools/rdna2spirv) and its tests
area: tools
tools/ and scripts/
area: viewer
The map viewer (viewer/)
bug
Something isn't working
dependencies
Pull requests that update a dependency file
documentation
Improvements or additions to documentation
duplicate
This issue or pull request already exists
enhancement
New feature or request
good first issue
Good for newcomers
help wanted
Extra attention is needed
invalid
This doesn't seem right
missing claim
Needs a claim in #14
needs in-game run
Changes the code a frame runs through: needs the 300 s in-game gate (docs/game_gate.md)
needs rebase
Conflicts with the base branch: rebase it on main
needs-triage
Needs maintainer evaluation before the next triage state
question
Further information is requested
ready-for-agent
Fully specified and ready for an AFK agent
submodules
Pull requests that update submodules code
wontfix
This will not be worked on
No labels
accessibility
area: ci
area: d3d12
area: docs
area: launcher
area: runtime (legacy)
area: shader translator
area: tools
area: viewer
bug
dependencies
documentation
duplicate
enhancement
good first issue
help wanted
invalid
missing claim
needs in-game run
needs rebase
needs-triage
question
ready-for-agent
submodules
wontfix
Milestone
Clear milestone
No items
No milestone
Assignees
Clear assignees
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".
No due date set.
Dependencies
No dependencies set
Reference
github/ubiquitarianism--leonida!3375
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-3375"
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?
@Bilalatss on GitHub · 2026-12-03 17:44 UTC · original
Bilalatss:perf/loader-patch-sse4a→main· +521 −14 · 2 files · 1 commits · openClaimed in the coordination issue as: D3D12-LOADER-PATCH-SSE4A (#3312)
What and why
leonida-loader::console_insnalready binary-patches wait instructions (monitorx/mwaitx) andclzeroloops after their first#UDtrap, but still emulated immediate-form SSE4aextrq(66 0F 78) andinsertq(F2 0F 78) on every execution. On CPUs lacking AMD SSE4a (such as Intel), hot immediateextrq/insertqsites incur a Windows kernel/VEH exception round-trip on every hit and contend on the VEH lock withwatch's page-guard handler.This change:
SSE4A_STUBS(Vec<(usize, usize)>) andalloc_sse4a_stub(withFlushInstructionCacheand bidirectionaljmp rel32reach checks), leavingpatch_clzeroandSTUBSuntouched so there is zero overlap withD3D12-CLZERO-STUB-REGIONS.sse4a_stub,patch_slice, andpatch_sse4ato atomically patch 5..=16 byte immediateextrq/insertqinstructions inside a single 16-byte aligned block viacmpxchg16btojmp rel32+ trailing NOPs, using flag-free SSE2 / SSE4.1-gated fast paths and a flag-preserving general bit-field path matchingdecode::extrq/decode::insertq(including upper-64-bit zeroing andxmm0..xmm15).[u8; 16]stack buffer inemulate(avoiding&[u8]aliasing againstcmpxchg16b) and guards concurrent#UDfaults at the same site (compiler_fence(SeqCst)+patched_jump_to_sse4a_stub+PatchOutcome::AlreadyPatched) so racing threads resume cleanly atripinstead of crashing or misdecoding torn bytes across an 8-byte boundary.LEONIDA_PATCH_SSE4A=0opt-out (matchingLEONIDA_PATCH_CLZERO=0andLEONIDA_PATCH_WAITS=0) and regeneratesd3d12/docs/switches.mdwithtools/d3d12_switches.py.Tested
python -I scripts/check_no_game_data.py— passed (exit 0).python -I tests/test_d3d12_switches.py— 21/21 passed.python -I scripts/red_green.py perf/loader-patch-sse4a --base origin/main --no-fetch— verdict:red then green(exit 0):leonida_loader::console_insn::tests::sse4a_stubs_match_emulation_and_preserve_flags(red -> green; live-executes 21 cases acrossxmm0..xmm15,len=8/16/32/64,len=0withidx>0,fidx+flen==64, bit-63 crossing,dst==src,len/idx >= 64, EFLAGS and source XMM preservation, concurrent re-entry at a patched site, plus straddling-16B and 4-byte register-form unpatched edges)pass on both: 94(0 failures).cargo clippy -p leonida-loader --all-targets --no-deps --locked -- -D warnings— passed (0 warnings).cargo clippy -p leonida-loader --features diagnostics --all-targets --no-deps --locked -- -D warnings— passed (0 warnings).cargo build --workspace --all-targets --locked— passed.cargo build -p leonida --features diagnostics,mimalloc --locked— passed.cargo test -p leonida-loader --locked -- --test-threads=1— 95/95 passed (92 unit + 2load_probe+ 1title_dlls).cargo test -p leonida-loader --features diagnostics --locked -- --test-threads=1— 98/98 passed (95 unit + 2load_probe+ 1title_dlls).cargo test -p leonida-gpu --features diagnostics --test replay --locked— 1/1 passed (a_frame_is_recorded_and_replayed).GPUs tested: Profile M (desktop, 16 GB VRAM), NVIDIA GeForce RTX 5070 Ti, driver 621.47 (32.0.16.2147), Windows 11 Pro (10.0.26200) (for
replay;leonida-loadertests are CPU-only)AI-assisted: yes (authored with Gemini 4 Neon; audited by an independent read-only reviewer subagent using Gemini 4 Neon)
Checklist
mainand merges cleanly (a conflicting pull request is labeledneeds rebase).docs/design.md, with how it was confirmed. (n/a — loader-only change)@Kal0s-design on GitHub · 2026-12-03 17:59 UTC · original
Ran natively on Windows 11, head
88c4db792merged into currentmain(0f0f268de, clean merge).The stubs are bit-exact. They matched
decode::extrq/decode::insertqin every case I ran, about 1.03 million, and on this machine they also matched the real instructions. Flags,raxand the other XMM registers came through unchanged, and the upper 64 bits were zeroed. Racing faults at one site always ended correctly. The one thing I found is small: every thread that loses the race still builds its own stub, and that stub is never used.The tests ran on a CPU with SSE4a, so the
#UDpath never fires there on its own. I droveemulatewith synthetic contexts, as the PR's test does, and ran the stubs and the original instructions natively from a harness.Your checks (measured)
cargo clippy -p leonida-loader --all-targets -- -D warnings--features diagnosticsrustfmt --checkonconsole_insn.rsmaineither (31 hunks). The merge has 52, so the PR adds about 21, all long lines in its new codecargo test -p leonida-loader --lib --locked, 4 threadsmain: 91 passed. Merge: 92 passed, the extra one beingsse4a_stubs_match_emulation_and_preserve_flags. With--features diagnostics: 95 passedLEONIDA_PATCH_SSE4A=0: 50/50Bit-exactness (throwaway harness, not in the PR). The harness loads all 16 XMM registers with random 128-bit values, sets random CF/PF/AF/ZF/SF/OF/DF with
popfqand a sentinel inrax, then runs three things on the same input: (a) the PR'ssse4a_stuboutput, reached byjmp rel32+ NOPs, (b) the original instruction run natively, and (c)decode::*. After each run it stores all 16 registers, the flags andrax. The seed is fixed.raxchangedlen0..63 ×idx0..63,extrq xmm3andinsertq xmm5, xmm9, 3 values eachdst×src0..15 forinsertq, everydstforextrq, 13 fields covering each path (16/32/8-bit aligned, 64@0,len=0,len=0withidx>0,idx+len=64,idx+len>64, 1@63)& 63matters), random values and flagslen=0is 64 in all three.idx+len=64is exact.idx+len>64is undefined per AMD. The stub gives what the emulator gives:extrqis a plain right shift byidx, andinsertqis the mask truncated at bit 63. The hardware here gave the same low qword in every case.pinsrb/pinsrdfast paths. The general-path fallback that those fields would take without SSE4.1 wasn't exercised. Other fields cover the general path.Concurrency (measured, throwaway tests)
emulateon the same unpatched site at once, behind a barrier. 50 sites, alternatinginsertq(general path) andextrqE9. In each round, 1 thread emulated and advancedripwith the right value, and the other 7 returnedCONTINUE_EXECUTIONwithripunchanged. 0 wrong. The patched site run natively afterwards gave the right resultemulate, 50 sitesraxstayed intact across the switch from instruction tojmpLEONIDA_PATCH_SSE4A=0, same 8-thread race, 10 sitesrip. No stub bytes usedLosing racers leak their stub. In the 8-thread race, the stub slab's used bytes grew by 13,824 for 50 sites. One stub per site would be about 2.4 KB: 64 B for the
insertqgeneral path and 32 B for thisextrq, after rounding to 16. So about 5–6 of the 8 racing threads each built a stub that nothing jumps to. From reading the code:patch_sse4acheckspatched_jump_to_sse4a_stub, then callsalloc_sse4a_stub, thenpatch_slice, and no lock covers the three. Each thread that faults before the winner'scmpxchg16blands builds and keeps a stub. The cost is bounded at one stub per racing thread per site, and it's only paid once per site, so it's cosmetic. HoldingPATCHING(or a per-site check underSSE4A_STUBS) across allocate-and-patch would close it. Alternatively, a losing thread could roll backusedif its stub is still the slab's last one.Read, not run
(at & 15) + insn_len > 16→Skipped). The PR's test covers this at offset 14. The 16-byte block never crosses a page, so a site near a page end is either patched within one page or skipped.near()probes 64 KBVirtualAllocs at 1 MB steps out to ±1.75 GB, so it never reserves a large range. If none is free, orjumpoverflows either way, the site isSkippedand emulated. One small leak: whennear()succeeds butbuildreturnsNone, the new 64 KB slab stays in the list unused. It gets reused for the next site in reach.PAGE_EXECUTE_READWRITEonly for thecmpxchg16b, then put back, and followed byFlushInstructionCache(unchanged frompatch). Stub slabs stay RWX for the life of the process, like the existingclzeroSTUBS.alloc_sse4a_stubflushes the stub before returning the jump.SSE4A_STUBSandPATCHINGare never held together.emulate, a re-read of*ripaftercompiler_fenceand beforedecode, relies on x86 not reordering loads with other loads, plus the single 16-byte atomic store. That reasoning holds. Thedecode→None→patched_jump_to_sse4a_stubfallback also covers it.rsp. A stack walk of a thread caught inside one would be wrong, the same as for theclzerostub. Nothing in the stub can fault except stack growth, which the kernel handles without unwinding.Conflicts. No other open PR touches
console_insn.rs. 45 open PRs touchswitches.md. Against this merge, 10 of them conflict (#3299, #3248, #3225, #3197, #3185, #3171, #3140, #3128, #3126, #3119), and all 10 already conflict withmain. This PR adds no conflicts.Not checked: the title, so no measured speedup, and no real
#UDon a CPU without SSE4a. That means the vectored-handler path end to end, including aCONTEXTcaptured by Windows rather than built by hand. The no-SSE4.1 fallback for 8/32-bit fields.--release. Slab exhaustion past 64 KB, where a second slab is used.GPUs tested: n/a (CPU-only tests).
AI-assisted: yes (Claude Code).
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.