runtime(cpu): add ahead-of-time AVX1/SSE4.2 stub compiler for pre-Haswell hosts #2414
No reviewers
No assignees
Labels
No labels
bug
dependencies
documentation
enhancement
missing claim
needs rebase
needs-triage
question
ready-for-agent
submodules
No project
No milestone
Dependencies
No dependencies set
Notifications
1 participant
Due date
No due date set.
Reference
leonida/mandy!2414
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/rt-cpu-avx1-aot-patch"
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?
Pull request successfully merged and closed
Claimed in the coordination issue as: RT-CPU-AVX1-AOT-PATCH (https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7205557017)
Depends on: #2190, #2191
What and why
While #2190 and #2191 enable pre-Haswell
AVX1 + SSE4.2hosts (Intel Sandy Bridge and Ivy Bridge) to executeBMI1,BMI2,MOVBE,F16C,FMA3andAVX2instructions via#UD(STATUS_ILLEGAL_INSTRUCTION), each#UDround-trip throughKiUserExceptionDispatchercosts ~4,000–6,000 cycles, stalling hot decompression and SIMD loops.Add
runtime/src/isa_jit_patch.hand wire it intoLoader::protect_sections(runtime/src/pe_loader.cpp) before executable sections are write-protected (LEONIDA_ISA_PATCH=0disables it):AVX1VEX rewrites (zero stub overhead): rewrites bit-identical 256-bitvpand/vpandn/vpor/vpxor(-> vandps/vandnps/vorps/vxorps),vextracti128/vinserti128/vperm2i128(-> *f128),vbroadcasti128 m128(-> vbroadcastf128),vpblendd(-> vblendps),vpbroadcastd m32(-> vbroadcastss), andvpbroadcastq ymm, m64(-> vbroadcastsd).x86-64+AVX1stubs (jmp rel32within±2 GiB):>=5-byteBMI1,BMI2, andMOVBEsites compile to native GPR sequences preserving or computing exact architecturalRFLAGS(including[rsp + disp]stack adjustments,[rip + disp32]relocation,rcx/rax/rdxregister-aliasing handling, and 16-bitmovbe).>=5-byteAVX2andFMA3sites compile to nativeAVX1(YMM+2x128-bitXMMviavextractf128/vinsertf128, flag-preservinglea rsp, [rsp ± N]scratch spills, and upper-128 zeroing on scalarFMA3).4-byte0xC5AVX2sites fuse forward with the immediately following instruction when a whole-module target scan (exports, relocations,.pdataunwind scopes, data/gap RVA tables, and direct branches) confirms the interior boundary is never targeted.F16C,vpmaskmov*,pdep/pext, unfusable 4-byte sites) stays intact and falls back cleanly to#UDemulation (#2190, #2191). Zero changes tocpu_emulation.h.Tested
ctest -R "^(isa_jit_patch|bmi_emulation|avx2_emulation|pe_loader)$"live on an Intel Core i7-2600 (Sandy Bridge,AVX1 + SSE4.2,bmi1=0 bmi2=0 movbe=0 avx2=0 fma=0 f16c=0, Windows 1019045):isa_jit_patch_test: 45 instruction families × 8 randomized GPR/YMM/RFLAGStrials + 2 fused4B+6B/4B+8BRIP-relative pairs + syntheticPE32+image test (in-place rewrites, BMI/AVX2/FMA3 stubs, unmarked 4B fusion, RVA-table fusion refusal, andLEONIDA_ISA_PATCH=0), all executing with0#UDtraps and exact state parity.python -I tests/test_ctest_registration.py,python -I tests/test_docs_env_vars.py,test_docs_links.py,test_docs_repo_paths.py,test_text_write_line_endings.py, andpython -I scripts/check_no_game_data.py: all clean.GPUs tested: n/a (CPU runtime; tested on Intel Core i7-2600, Sandy Bridge, AVX1 + SSE4.2, Windows 10 19045)
AI-assisted: yes
Checklist
mainand merges cleanly (a conflicting pull request is labeledneeds rebase).docs/design.md, with how it was confirmed. (n/a — x86-64 CPU runtime only)On native Windows / i5-13600KF I built and ran your exact synthetic test at 8cde0bef: 51 instruction families, two fused pairs and one synthetic PE image passed. LLVM-MinGW required -fms-extensions for SEH and emitted a missing explicit __cpuidex declaration warning. The host has AVX2/FMA/BMI; native pre-Haswell coverage remains open.
The useful next report is this same synthetic program on an AVX1-only host, with its printed capability line and exit code. If you have a volunteer or a receiving backport, PortBridge Test Lab can carry this one narrow task and return the credited result here. AI-assisted native test.
Windows 11 Native Verification Report (
402035db49merged ontoorigin/maina9e247cd69)origin/main(a9e247cd69) and clean in a 5-PRruntime/batch merge.10.0.26200, x64), MSVC19.44.35228, Python3.12.10(synthetic machine-code pages and PE32+ fixtures only; zero game binaries).Diff Audit (
10files,+4,987/-0)runtime/src/avx2_emulation.h: VEX decoder and vectored#UD(STATUS_ILLEGAL_INSTRUCTION) handler forF16C,FMA3, andAVX2, reading/writing 256-bitYMM0..YMM15throughCONTEXT::FltSave.XmmRegistersandLocateXStateFeature(XSTATE_AVX)(zeroingYMM[dst][255:128]on 128-bit VEX writes, zero-initializing untouched upper lanes whenXSTATE_MASK_AVXtransitions from clean to active, and suppressing faults on disabledVPMASKMOV*lanes).runtime/src/bmi_emulation.h:#UDdecoder/handler forBMI1,BMI2,MOVBE, andTZCNT/LZCNTplus.pdata/leafTZCNT/LZCNTrewriting (>= 5-byte 32/64-bit register sites to branchlessBSF/BSR + CMOV + BTstubs; 4-byte/16-bit/memory/RSPsites toUD2+ side-table).runtime/src/isa_jit_patch.h: Ahead-of-timeAVX1 + SSE4.2 + x86-64rewriter and trampoline compiler invoked inLoader::protect_sections(same-lengthAVX1VEX rewrites,>= 5-byteBMI1/BMI2/MOVBE/AVX2/FMA3out-of-line stubs within+-2 GiBregistered inLoader::ranges_,LEONIDA_ISA_PATCH=0kill-switch, and opt-inLEONIDA_ISA_FUSE_4B=14-byte0xC5fusion guarded against exports, relocations,.pdataunwind scopes, data/gap RVA tables, direct branches, and Clang table-relative.rdataswitch tables).Red -> Green Verification
origin/maina9e247cd69):runtime/src/avx2_emulation.h,runtime/src/bmi_emulation.h, andruntime/src/isa_jit_patch.hare absent onorigin/main.#2414+origin/main):bmi_emulation_test.exe(/O2 /MD /EHsc /W4 /permissive- /utf-8,0warnings):bmi_emulation_test: OK (65 checks)(0.06 s,rc=0).avx2_emulation_test.exe(/O2 /MD /EHsc /W4 /permissive- /utf-8,0warnings):avx2_emulation_test: OK (38 checks)(0.07 s,rc=0), verifyingF16CRN/RD/RU/RZ rounding + subnormals/NaN, VEX negative rejections,XSTATE_AVX256-bit state &VPMASKMOVDPAGE_NOACCESSboundary handling, and live 256-bitFMA3/F16C/AVX2execution.isa_jit_patch_test.exe(/O2 /MD /EHsc /W4 /permissive- /utf-8):isa_jit_patch_test: OK (51 single-insn families + 2 fused pairs + synthetic PE32+ image)(0.07 s,rc=0), verifying0#UDtraps and exact GPR/YMM/RFLAGS parity across 8 randomized trials per family plusLEONIDA_ISA_PATCH=0andLEONIDA_ISA_FUSE_4B=1RVA & Clang relative switch-table refusal.loader_test.exe(/O2 /MD /EHsc /W4 /permissive- /utf-8,0warnings):115 checks, 0 failed(20.11 s,rc=0).runtime/src/main.cpp(/c /O2 /MD /EHsc /W4 /permissive- /utf-8 /DLEONIDA_VULKAN_DEVICE): compiled cleanly (rc=0).test_docs_env_vars.py,test_docs_repo_paths.py,test_docs_table_rows.py,test_docs_encoding.py,test_ctest_registration.py, andtest_ci_registration.pyall passed (OK,rc=0).Non-Blocking Audit Notes
VirtualSize == 0executable sections inpe_loader.cpp:2261:isa_jit_patch::patch_image(isa_jit_patch.h:1150) usessec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData, whereas theTZCNT/LZCNTloop inpe_loader.cpp:2261usesstd::min(cs->Misc.VirtualSize, cs->SizeOfRawData)(yielding0if an executable section hasMisc.VirtualSize == 0andSizeOfRawData > 0).0x64(FS:) prefix inbmi_emulation::decode/avx2_emulation::decode: both decoders accept0x64(FS) intod.segwhileeffective_addr()only addsNtCurrentTeb()for0x65(GS) and treats0x64as flat0(isa_jit_patchalready rejectsd.seg != 0).isa.stubsadjustsRSP(push/lea rsp, [rsp - 64]) withoutRtlAddFunctionTableunwind metadata; first-touchxmemandtitle_page_watchVEH handlers (EXCEPTION_CONTINUE_EXECUTION) work transparently, though guest__try/__exceptframe unwinding across an unhandled memory fault inside an out-of-line stub would treat the stub as a leaf function.Verdict: PASS (with minor non-blocking notes above).
AI-assisted.
Run of #2414 (
isa_jit_patch,bmi_emulation,avx2_emulation, pluspe_loaderas a regression check), red then green.git merge-tree --write-tree main <head>merges cleanly. I tested the PR head as it is, not the merge result.Commands (in a vcvars64 shell, build folder inside the worktree):
Green (PR head): 4/4 passed (pe_loader 0.12 s, bmi_emulation 0.08 s, avx2_emulation 0.02 s, isa_jit_patch 0.02 s).
Red (non-test changes reverted to the merge base:
bmi_emulation.h,avx2_emulation.h,isa_jit_patch.hremoved,main.cppandpe_loader.cpprestored; tests and CMake registration kept): the three new test targets do not build (C1083: cannot open include filefor each header) and ctest givesbmi_emulation,avx2_emulation,isa_jit_patch(Not Run), 1 of 4 passed.pe_loaderstill passes, as expected: the PR does not changepe_loader_test, so it is only a regression check. Red is a build failure because the PR adds new headers. The stale test executables from the green build were deleted before this ctest.Stack (checked with
git merge-base --is-ancestor): #2190 is contained in #2191, which is contained in this PR, so merging #2414 brings both.Link check: merged into main 1bc055e6c, gta6rt.exe builds and links (RelWithDebInfo, MSVC 19.44); new imports vs main: fma and fmaf (C runtime, api-ms-win-crt-math), GetXStateFeaturesMask, LocateXStateFeature and SetXStateFeaturesMask (KERNEL32).
Merged after enlight3d (Thib)'s red/green run (RUN, RTX 3090, driver 621.40, Windows 11: green with this PR, red without it, and
gta6rt.exestill links) and a re-check here: no conflict withmain16f505304, same head as run,no-game-datagreen, and the only ctest failures in the Windows/macOS CI jobs are tests this diff does not touch (known onmainor Vulkan: vk_xdxr_postbuild_readback vk_bindless_dimensions d3d12_compile_pool xbox_present ).AI-assisted (Claude Code, Claude Opus 5.5), merged for MoonEyes.