runtime(cpu): add ahead-of-time AVX1/SSE4.2 stub compiler for pre-Haswell hosts #2414
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/2414"
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 ubiquitarianism/leonida. Originally posted by robot00f on 2026-11-26T23:57:18Z.
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)Imported from ubiquitarianism/leonida. Originally posted by akimfomin on 2026-11-27T00:16:50Z.
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.
Imported from ubiquitarianism/leonida. Originally posted by timbot103 on 2026-11-28T03:21:02Z.
Review: CHANGES_REQUESTED
Built and tested head
402035db4on native Windows 11 x64 (Ryzen 9 9950X3D, MSVC19.44.35230.0, Ninja RelWithDebInfo). Existing CTest targets (pe_loader,cpu_emulation,bmi_emulation,avx2_emulation,isa_jit_patch) pass 5/5 (isa_jit_patch_test: 51 single-insn families + 2 fused pairs + synthetic PE32+), along withtests/test_ctest_registration.py(6/6) andtests/test_docs_env_vars.py(5/5).However, static inspection and live execution against
runtime/src/isa_jit_patch.hreproduce three blocking correctness/stability bugs in the AOT stub compiler:FMA stubs lose fused rounding and suffer intermediate overflow (
runtime/src/isa_jit_patch.h:695-736, 1352-1363):emit_avx2_fma_bodylowers FMA3 to separateVMUL+VADD/VSUB(double rounding), diverging from both native FMA hardware and the existingstd::fmaf/std::fmaVEH fallback (runtime/src/avx2_emulation.h:845-865). The existing test (runtime/test/isa_jit_patch_test.cpp:339-340, 444) masks this by generating0.125fsteps and allowing1e-3fabsolute error. Live repro onvfmadd213ss xmm0, xmm1, xmm2:a=0x3F800001, b=0x3F7FFFFE, c=0xBF800000):std::fmaf= native =0xA8800000, AOT stub =0x00000000.a=0x7F000000, b=0x40000000, c=0xFF000000):std::fmaf= native =0x7F000000, AOT stub =0x7F800000(+inf).Keep FMA on the existing exact fallback until the emitted code implements fused rounding, and compare FMA test outputs bit-for-bit.
movbe [mem], rspstoresbswap64(original_rsp - 8)(runtime/src/isa_jit_patch.h:246-271):bmi_emulation::decodeacceptsmovbe qword ptr [r8], rsp(49 0F 38 F1 20), and the VEH fallback reads originalRSP. Inemit_bmi_body, pushing a scratch GPR decrementsRSPbefore copyingd.src1, and the RSP displacement adjustment only covers the memory operand — not a register source ofrsp. Live repro onmovbe qword ptr [r8], rsp(reading the stored 8 bytes byte-swapped back):rsp = 0x000000EA121AF9D8, stored value byte-swapped back =0x000000EA121AF9D8(diff = 0).rsp = 0x000000EA121AF9D8, stored value byte-swapped back =0x000000EA121AF9D0(diff = -8).Preserve the pre-push RSP value when
d.src1 == 4or decline to AOT-patchmovbe [mem], rsp.Stack-adjusting out-of-line stubs break Windows x64 SEH unwinding (
runtime/src/isa_jit_patch.h:829-836, 1496-1516,runtime/src/pe_loader.cpp:1617-1642, 2219-2227):Relocated AVX2 memory-operand stubs adjust the stack (
lea rsp, [rsp-64], spilling YMMs onto the stack) and then perform the original memory access at an out-of-image stub address with no Windows.pdata/runtime unwind table entry. If that memory access faults, Windows unwinds the stub PC as a leaf function, reads spilled scratch data from[rsp]as the return address, and cannot unwind to the protected caller/guest SEH handler. Live subprocess repro calling a leaf function executingvpaddd ymm0, ymm1, ymmword ptr [rcx](C4 E1 75 FE 01) withrcx = nullptrfrom a host__try / __exceptframe:__exceptcatches0xC0000005cleanly (exit 0).emit_avx2_fma_body: unwind fails and the process terminates unhandled with0xC0000005.Either register proper unwind/exception handling mapping stub faults back to the original site or keep stack-adjusting memory-accessing sites on the fallback until unwind coverage is in place.
No game data used. AI-assisted review (Codex static audit + Gemini live MSVC verification).
Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-11-28T23:58:06Z.
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.
Imported from ubiquitarianism/leonida. Originally posted by enlight3d on 2026-11-29T00:45:45Z.
Run of #2414 (
isa_jit_patch,bmi_emulation,avx2_emulation, pluspe_loaderas a regression check), red then green.402035db49. Current main:1bc055e6c2, merge base with the PR:39f52f39c(the branch is about 2,670 commits behind main).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).Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-11-29T01:02:54Z.
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.