runtime(cpu): emulate F16C, FMA3 and AVX2 via XSTATE_AVX on AVX1 hosts #2191

Open
github-bot wants to merge 4 commits from github-bot/gh-2191 into main AGit
Owner

@⁠robot00f on GitHub · 2026-11-26 04:10 UTC · original
robot00f:feat/rt-cpu-fma-f16c-avx2 → main · +2827 −0 · 8 files · 4 commits · open

Summary

Add runtime/src/avx2_emulation.h and wire it into gta6rt so pre-Haswell AVX1 + SSE4.2 hosts (Intel Sandy Bridge and Ivy Bridge) can execute the game's F16C, FMA3, and AVX2 vector instructions using the OS-saved 256-bit YMM0..YMM15 registers (docs/cpu_features.md, PR #2188):

  • Full 256-bit XSTATE_AVX register access:
    • Reads and writes XMM0..XMM15 ([127:0]) from CONTEXT::FltSave.XmmRegisters and YMM0..YMM15[255:128] via GetXStateFeaturesMask / LocateXStateFeature(c, XSTATE_AVX, &len) / SetXStateFeaturesMask.
    • Enforces the x86-64 VEX upper-128 zeroing rule (YMM[dst][255:128] = 0) on every 128-bit VEX register write, and zero-initializes the other 15 upper lanes before enabling XSTATE_MASK_AVX when transitioning out of a clean (vzeroupper) state.
    • Leaves native AVX1 instructions (including 256-bit vptest, vperm2f128, vpermilps, vmovups/vmovdqu, etc.) to execute directly on hardware.
  • Instruction coverage (#UD / STATUS_ILLEGAL_INSTRUCTION):
    • F16C: vcvtph2ps and vcvtps2ph (register and memory destinations, imm8 RN/RD/RU/RZ and MXCSR.RC rounding, subnormals, signed zero, Inf, and quiet NaN payloads).
    • FMA3: all 60 0F38 forms (132, 213, 231; single and double precision; 128-bit and 256-bit packed, scalar ss/sd preserving dst[127:32]/[127:64], and vfmaddsub*/vfmsubadd*) via single-rounding std::fmaf / std::fma.
    • AVX2: 256-bit integer SIMD promotions (2-byte C5 and 3-byte C4 VEX), vbroadcastss / vbroadcastsd (including ModRM.mod == 3 register-source forms), vbroadcasti128, vpbroadcastb/w/d/q, vinserti128, vextracti128, vperm2i128, vpermq, vpermpd, vpermd, vpermps, vpblendd (128/256), vpblendw, vpblendvb, vpsllvd/q, vpsrlvd/q, vpsravd, vpmovsx* / vpmovzx*, vpmovmskb, and vpmaskmovd / vpmaskmovq (reading/writing only enabled mask < 0 lanes so disabled lanes crossing into unmapped/PAGE_NOACCESS pages never fault).
  • Tests (runtime/test/avx2_emulation_test.cpp):
    • IEEE-754 half/float edge cases, 2-byte/3-byte VEX decoding + AVX1 non-interception, InitializeContext(..., CONTEXT_XSTATE) upper-lane and vpmaskmovd page-boundary tests, and live 256-bit YMM execution (vmovups/vmovdqu -> #UD FMA3 / F16C / AVX2 -> vmovups/vmovdqu -> vzeroupper) on hardware.

Validation

  • Built and executed ctest 3x (avx2_emulation, bmi_emulation, cpu_emulation, clzero_patch, run_tiny_game) on an Intel Core i7-2600 (Sandy Bridge, AVX1 + SSE4.2, AVX2=0 FMA=0 F16C=0), verifying live 256-bit YMM round-trips through Windows XSTATE_AVX on real pre-Haswell hardware.
  • python -I -m unittest discover -s tests -p "test_ctest_registration.py" and test_text_write_line_endings.py (OK).
  • python -I scripts/check_no_game_data.py (clean).

Depends on: #2190
Claim: #1608
AI-assisted: yes (Antigravity, Gemini 4 Carbon)

**@⁠robot00f** on GitHub · 2026-11-26 04:10 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2191) `robot00f:feat/rt-cpu-fma-f16c-avx2` → `main` · +2827 −0 · 8 files · 4 commits · open ## Summary Add `runtime/src/avx2_emulation.h` and wire it into `gta6rt` so pre-Haswell `AVX1 + SSE4.2` hosts (Intel Sandy Bridge and Ivy Bridge) can execute the game's `F16C`, `FMA3`, and `AVX2` vector instructions using the OS-saved 256-bit `YMM0..YMM15` registers (`docs/cpu_features.md`, PR #2188): - **Full 256-bit `XSTATE_AVX` register access:** - Reads and writes `XMM0..XMM15` (`[127:0]`) from `CONTEXT::FltSave.XmmRegisters` and `YMM0..YMM15[255:128]` via `GetXStateFeaturesMask` / `LocateXStateFeature(c, XSTATE_AVX, &len)` / `SetXStateFeaturesMask`. - Enforces the x86-64 VEX upper-128 zeroing rule (`YMM[dst][255:128] = 0`) on every 128-bit VEX register write, and zero-initializes the other 15 upper lanes before enabling `XSTATE_MASK_AVX` when transitioning out of a clean (`vzeroupper`) state. - Leaves native `AVX1` instructions (including 256-bit `vptest`, `vperm2f128`, `vpermilps`, `vmovups`/`vmovdqu`, etc.) to execute directly on hardware. - **Instruction coverage (`#UD` / `STATUS_ILLEGAL_INSTRUCTION`):** - **F16C:** `vcvtph2ps` and `vcvtps2ph` (register and memory destinations, `imm8` `RN`/`RD`/`RU`/`RZ` and `MXCSR.RC` rounding, subnormals, signed zero, `Inf`, and quiet `NaN` payloads). - **FMA3:** all 60 `0F38` forms (`132`, `213`, `231`; single and double precision; 128-bit and 256-bit packed, scalar `ss`/`sd` preserving `dst[127:32]`/`[127:64]`, and `vfmaddsub*`/`vfmsubadd*`) via single-rounding `std::fmaf` / `std::fma`. - **AVX2:** 256-bit integer SIMD promotions (2-byte `C5` and 3-byte `C4` VEX), `vbroadcastss` / `vbroadcastsd` (including `ModRM.mod == 3` register-source forms), `vbroadcasti128`, `vpbroadcastb/w/d/q`, `vinserti128`, `vextracti128`, `vperm2i128`, `vpermq`, `vpermpd`, `vpermd`, `vpermps`, `vpblendd` (128/256), `vpblendw`, `vpblendvb`, `vpsllvd/q`, `vpsrlvd/q`, `vpsravd`, `vpmovsx*` / `vpmovzx*`, `vpmovmskb`, and `vpmaskmovd` / `vpmaskmovq` (reading/writing only enabled `mask < 0` lanes so disabled lanes crossing into unmapped/`PAGE_NOACCESS` pages never fault). - **Tests (`runtime/test/avx2_emulation_test.cpp`):** - IEEE-754 half/float edge cases, 2-byte/3-byte VEX decoding + `AVX1` non-interception, `InitializeContext(..., CONTEXT_XSTATE)` upper-lane and `vpmaskmovd` page-boundary tests, and live 256-bit `YMM` execution (`vmovups`/`vmovdqu` -> `#UD` `FMA3` / `F16C` / `AVX2` -> `vmovups`/`vmovdqu` -> `vzeroupper`) on hardware. ## Validation - Built and executed `ctest` 3x (`avx2_emulation`, `bmi_emulation`, `cpu_emulation`, `clzero_patch`, `run_tiny_game`) on an **Intel Core i7-2600** (Sandy Bridge, `AVX1 + SSE4.2`, `AVX2=0 FMA=0 F16C=0`), verifying live 256-bit `YMM` round-trips through Windows `XSTATE_AVX` on real pre-Haswell hardware. - `python -I -m unittest discover -s tests -p "test_ctest_registration.py"` and `test_text_write_line_endings.py` (OK). - `python -I scripts/check_no_game_data.py` (clean). Depends on: #2190 Claim: https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608 AI-assisted: yes (Antigravity, Gemini 4 Carbon)
Add runtime/src/bmi_emulation.h and wire it into gta6rt and Loader::protect_sections
so pre-Haswell AVX1 + SSE4.2 CPUs (Intel Sandy Bridge and Ivy Bridge) can execute
the game's integer Haswell/ABM instruction delta:

- Decode and emulate VEX-encoded BMI1 (andn, bextr, blsi, blsmsk, blsr), BMI2
  (bzhi, mulx, pdep, pext, rorx, sarx, shlx, shrx), and legacy 16/32/64-bit MOVBE
  on STATUS_ILLEGAL_INSTRUCTION (#UD), using SEH-guarded non-inlined __movsb copies
  so valid pages take zero syscalls while xmem first-touch, write-watched shadow
  pages, read-only faults and unmapped faults behave like native accesses.
- Patch non-faulting legacy TZCNT (F3 0F BC) and LZCNT (F3 0F BD) before executable
  sections are protected by walking .pdata functions and 0xCC-delimited leaf
  routines: >=5-byte 32/64-bit register sites jump to branchless BSF/BSR + CMOV +
  BT stubs within 2 GiB, and 4-byte, 16-bit or memory sites become UD2 (0F 0B)
  backed by a side-table for the #UD handler (configurable via LEONIDA_LZCNT_PATCH).
- Add runtime/test/bmi_emulation_test.cpp covering decoding, synthetic CONTEXT
  application, immediate byte-trap rejection, stub/UD2 flag consumers, and live
  execution on hardware.

Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7181466437
AI-assisted: yes (Antigravity, Gemini 4 Carbon)
Add runtime/src/avx2_emulation.h and wire it into gta6rt so pre-Haswell AVX1 +
SSE4.2 CPUs (Intel Sandy Bridge and Ivy Bridge) can execute the game's vector
Haswell instruction delta using the host's native 256-bit YMM0..YMM15 state:

- Read and write 256-bit YMM registers through CONTEXT::FltSave.XmmRegisters
  (bits [127:0]) and LocateXStateFeature(XSTATE_AVX) (bits [255:128]), zeroing
  YMM[dst][255:128] on every 128-bit VEX register write and zero-initializing
  untouched upper lanes when transitioning XSTATE_MASK_AVX from clean (0).
- Emulate F16C (vcvtph2ps, vcvtps2ph with RN/RD/RU/RZ and MXCSR rounding), all
  60 FMA3 forms (132/213/231 packed 128/256, scalar ss/sd preserving [127:32] /
  [127:64], and alternating fmaddsub/fmsubadd) via single-rounding std::fmaf /
  std::fma, and AVX2 (256-bit integer SIMD promotions, register/memory
  vbroadcastss/sd/i128 and vpbroadcastb/w/d/q, vinserti128, vextracti128,
  vperm2i128, vpermq, vpermpd, vpermd, vpermps, vpblendd/w/vb, vpsllv*/vpsrlv*/
  vpsravd, vpmovsx*/vpmovzx*, vpmovmskb, and per-lane fault-accurate
  vpmaskmovd/vpmaskmovq).
- Add runtime/test/avx2_emulation_test.cpp covering IEEE-754 F16C conversions,
  VEX decoding, XSTATE_AVX + VPMASKMOVD page-boundary semantics, and live
  256-bit YMM execution on hardware.

Depends on: #2190
Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7181466437
AI-assisted: yes (Antigravity, Gemini 4 Carbon)
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:21:50 +00:00
Author
Owner

@⁠ecox982745 on GitHub · 2026-11-26 04:17 UTC · original

I found one F16C result mismatch at 9ec6b209af7853f6f1665a76a37c56b610d73a45. The VCVTPS2PH path reads the saved rounding mode but does not honor the saved MXCSR denormals-are-zero (DAZ) bit on its binary32 inputs. On a Windows Ryzen 7 7800X3D, with DAZ set and rounding toward negative infinity, native F16C converts input bits 0x80000001 to half 0x8000 (negative zero). The PR returns 0x8001. The same difference occurs with the largest negative binary32 subnormal, 0x807fffff.

I compared native _mm_cvtps_ph with decode + apply for the 128-bit register form, using 12 synthetic inputs, all four rounding modes, both immediate and MXCSR-selected rounding, and both FTZ settings. With all FP exceptions masked, the PR matched native on 192/192 lanes with DAZ clear and 176/192 with DAZ set. This compares result bits only.

A local edit to the conversion loop at line 762 matched native on 384/384. When c->FltSave.MxCsr & (1u << 6) is set and the input exponent bits are zero, write uint16_t((src.u32[k] >> 16) & 0x8000u) to preserve the sign of zero. Otherwise use the existing f32_to_f16. Keeping this check on the binary32 input preserves valid half-subnormal outputs even with FTZ set. The PR's existing avx2_emulation_test passed all 38 checks on both versions. The two-case regression I'd add is the smallest negative binary32 subnormal with round-down, DAZ clear (0x8001) and DAZ set (0x8000).

CPU-only, synthetic data. AI-assisted review (OpenAI Codex). Intel's specification covers DAZ for legacy VCVTPS2PH.

**@⁠ecox982745** on GitHub · 2026-11-26 04:17 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2191#issuecomment-7182457972) I found one F16C result mismatch at `9ec6b209af7853f6f1665a76a37c56b610d73a45`. The `VCVTPS2PH` path reads the saved rounding mode but does not honor the saved MXCSR denormals-are-zero (DAZ) bit on its binary32 inputs. On a Windows Ryzen 7 7800X3D, with DAZ set and rounding toward negative infinity, native F16C converts input bits `0x80000001` to half `0x8000` (negative zero). The PR returns `0x8001`. The same difference occurs with the largest negative binary32 subnormal, `0x807fffff`. I compared native `_mm_cvtps_ph` with `decode` + `apply` for the 128-bit register form, using 12 synthetic inputs, all four rounding modes, both immediate and MXCSR-selected rounding, and both FTZ settings. With all FP exceptions masked, the PR matched native on **192/192 lanes with DAZ clear** and **176/192 with DAZ set**. This compares result bits only. A local edit to the conversion loop at line 762 matched native on **384/384**. When `c->FltSave.MxCsr & (1u << 6)` is set and the input exponent bits are zero, write `uint16_t((src.u32[k] >> 16) & 0x8000u)` to preserve the sign of zero. Otherwise use the existing `f32_to_f16`. Keeping this check on the binary32 input preserves valid half-subnormal outputs even with FTZ set. The PR's existing `avx2_emulation_test` passed all 38 checks on both versions. The two-case regression I'd add is the smallest negative binary32 subnormal with round-down, DAZ clear (`0x8001`) and DAZ set (`0x8000`). CPU-only, synthetic data. AI-assisted review (OpenAI Codex). [Intel's specification covers DAZ for legacy VCVTPS2PH](https://cdrdv2-public.intel.com/678970/intel-avx512-fp16.pdf).
This pull request has changes conflicting with the target branch.
  • runtime/src/main.cpp
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2191/head:github-bot/gh-2191'
git switch 'github-bot/gh-2191'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2191'
git switch 'github-bot/gh-2191'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2191'
git switch 'github-bot/gh-2191'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2191'
git switch 'main'
git merge --squash 'github-bot/gh-2191'
git switch 'main'
git merge --ff-only 'github-bot/gh-2191'
git switch 'main'
git merge 'github-bot/gh-2191'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.