cpu: lower 32-bit and 64-bit BMI2 instructions #283

Merged
Vonsek merged 3 commits from upstream-pr/287 into main 2026-11-22 06:39:00 +00:00
Vonsek commented 2026-11-21 20:53:18 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Vonsek on 2026-11-21T20:53:18Z.


Change

  • Lower all eight 32-bit and 64-bit BMI2 instructions (bzhi, mulx, pdep, pext, rorx, sarx, shlx, shrx) in tools/ffx_version_query.py, preserving flags on the flag-free forms, updating ZF/CF on bzhi, zero-extending 32-bit destinations, and resolving same-destination mulx to the high half.
  • Add a source-built MASM fixture (tests/cpu/bmi2.asm, tests/cpu/bmi2.def) and differential test (tests/cpu/bmi2.py) wired into CMakeLists.txt as cpu_aot_bmi2, verifying all 17 exports (values, bzhi ZF/CF, preserved ZF/CF on rorx/shlx, and same-destination mulx64_same) against both the native DLL and a reference model.
  • Classify bmi2 -> cpu_aot_bmi2 in tools/form_coverage.py (covering 8/16 of the BMI/ADX group in docs/coverage/x64_zen2.tsv) and document the test in docs/experiments.md.

Verification

Tested on Windows 11 (VS 2022 Build Tools 17.14, MSVC 19.44, ML64 14.44, Windows SDK 10.0.26100, Python 3.12):

  • Before the change, cmake --build --preset dev --target cpu_bmi2_lifted failed with:
    ValueError: unsupported query operation at 0x1007: bzhi eax,ecx,edx
    
  • After the change:
    • cmake --build --preset dev --target cpu_bmi2_lifted succeeded.
    • ctest --preset dev --no-tests=error -R "^(cpu_aot_bmi2|cpu_aot_shift_count|cpu_aot_version_query|cpu_aot_address_size)$" -V: 4/4 passed (2249 BMI2 cases (32/64-bit values, BZHI flags, preserved flags, MULX same-dest) matched native and translated DLLs).
    • python -B tests/form_coverage_check.py: form coverage checks passed.

Evidence and follow-up

  • Covers all eight BMI2 mnemonics in docs/coverage/x64_zen2.tsv; complements #286 (BMI1, 6 mnemonics).
  • All binaries are source-built via MASM and CMake; no game files or external dumps are included.

Checklist

  • Focused, single-purpose change
  • Source-built test that fails without the change and passes with it
  • Verified locally on Windows
<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6534253367 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/287). Originally posted by [Vonsek](https://github.com/Vonsek) on 2026-11-21T20:53:18Z. --- ## Change - Lower all eight 32-bit and 64-bit BMI2 instructions (`bzhi`, `mulx`, `pdep`, `pext`, `rorx`, `sarx`, `shlx`, `shrx`) in `tools/ffx_version_query.py`, preserving flags on the flag-free forms, updating ZF/CF on `bzhi`, zero-extending 32-bit destinations, and resolving same-destination `mulx` to the high half. - Add a source-built MASM fixture (`tests/cpu/bmi2.asm`, `tests/cpu/bmi2.def`) and differential test (`tests/cpu/bmi2.py`) wired into `CMakeLists.txt` as `cpu_aot_bmi2`, verifying all 17 exports (values, `bzhi` ZF/CF, preserved ZF/CF on `rorx`/`shlx`, and same-destination `mulx64_same`) against both the native DLL and a reference model. - Classify `bmi2` -> `cpu_aot_bmi2` in `tools/form_coverage.py` (covering 8/16 of the BMI/ADX group in `docs/coverage/x64_zen2.tsv`) and document the test in `docs/experiments.md`. ## Verification Tested on Windows 11 (VS 2022 Build Tools 17.14, MSVC 19.44, ML64 14.44, Windows SDK 10.0.26100, Python 3.12): - Before the change, `cmake --build --preset dev --target cpu_bmi2_lifted` failed with: ```text ValueError: unsupported query operation at 0x1007: bzhi eax,ecx,edx ``` - After the change: - `cmake --build --preset dev --target cpu_bmi2_lifted` succeeded. - `ctest --preset dev --no-tests=error -R "^(cpu_aot_bmi2|cpu_aot_shift_count|cpu_aot_version_query|cpu_aot_address_size)$" -V`: 4/4 passed (`2249 BMI2 cases (32/64-bit values, BZHI flags, preserved flags, MULX same-dest) matched native and translated DLLs`). - `python -B tests/form_coverage_check.py`: `form coverage checks passed`. ## Evidence and follow-up - Covers all eight BMI2 mnemonics in `docs/coverage/x64_zen2.tsv`; complements #286 (BMI1, 6 mnemonics). - All binaries are source-built via MASM and CMake; no game files or external dumps are included. ## Checklist - [x] Focused, single-purpose change - [x] Source-built test that fails without the change and passes with it - [x] Verified locally on Windows
upstream-sync closed this pull request 2026-11-24 06:42:14 +00:00
chatgpt-codex-connector[bot commented 2026-11-24 06:42:15 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-21T20:59:54Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9905644587

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6008144625 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/287#pullrequestreview-6008144625). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-21T20:59:54Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `9905644587` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
chatgpt-codex-connector[bot commented 2026-11-24 06:48:01 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-21T20:56:01Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T20:59:56.100817Z 9905644 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7069112128 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/287#issuecomment-7069112128). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-21T20:56:01Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"990564458719910ff64c7ddad823999b363b4de1","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-21T20:59:56.100817Z">2026-11-21T20:59:56.100817Z</relative-time> | `9905644` | Draft marked ready | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
Vonsek commented 2026-11-24 06:48:07 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Vonsek on 2026-11-21T22:13:56Z.


Added a host_has_bmi2() CPUID leaf 7 EBX bit 8 check in the portable lifted DLL before loading/invoking the native BMI2 fixture, exiting 77 when BMI2 is absent, and registered SKIP_RETURN_CODE 77 on cpu_aot_bmi2 in CMakeLists.txt.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7070033386 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/287#issuecomment-7070033386). Originally posted by [Vonsek](https://github.com/Vonsek) on 2026-11-21T22:13:56Z. --- Added a `host_has_bmi2()` CPUID leaf 7 EBX bit 8 check in the portable lifted DLL before loading/invoking the native BMI2 fixture, exiting 77 when BMI2 is absent, and registered `SKIP_RETURN_CODE 77` on `cpu_aot_bmi2` in `CMakeLists.txt`.
chatgpt-codex-connector[bot commented 2026-11-24 06:50:36 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-21T20:59:54Z.

Code review location: tests/cpu/bmi2.py; line 147

@@ -0,0 +1,206 @@
+"""Compare native and translated BMI2 instructions (32-bit and 64-bit)."""
+import ctypes
+from pathlib import Path
+import sys
+
+import pefile
+from iced_x86 import Decoder
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools"))
+from cpu_leaf_aot import export_rva
+from cpu_ranges import function_ranges
+from ffx_version_query import INTEGER_HEADER, lower, region
+
+U64 = ctypes.c_uint64
+
+OUT2_EXPORTS = ("bzhi32", "bzhi64", "shlx32", "shlx64", "mulx32", "mulx64")
+OUT1_EXPORTS = ("rorx32", "rorx64")
+PLAIN2_EXPORTS = ("shrx32", "shrx64", "sarx32", "sarx64", "pdep32", "pdep64", "pext32", "pext64", "mulx64_same")
+
+
+def emit(image, output):
+    parts = [INTEGER_HEADER]
+    with pefile.PE(str(image), fast_load=True) as pe:
+        for name in OUT2_EXPORTS:
+            (bounds,) = function_ranges(pe, export_rva(pe, name))
+            body = region(pe, *bounds)
+            code = lower(body, ["rcx = a; rdx = b; r8 = out;"], {}, {}, {})
+            parts.append(f'extern "C" __declspec(dllexport) word {name}(word a, word b, word out) {{\n{code}\n}}\n')
+        for name in OUT1_EXPORTS:
+            (bounds,) = function_ranges(pe, export_rva(pe, name))
+            body = region(pe, *bounds)
+            code = lower(body, ["rcx = a; rdx = out;"], {}, {}, {})
+            parts.append(f'extern "C" __declspec(dllexport) word {name}(word a, word out) {{\n{code}\n}}\n')
+        for name in PLAIN2_EXPORTS:
+            (bounds,) = function_ranges(pe, export_rva(pe, name))
+            body = region(pe, *bounds)
+            code = lower(body, ["rcx = a; rdx = b;"], {}, {}, {})
+            parts.append(f'extern "C" __declspec(dllexport) word {name}(word a, word b) {{\n{code}\n}}\n')
+    output.write_text("".join(parts), encoding="ascii")
+
+
+def load_lib(path):
+    lib = ctypes.CDLL(str(Path(path).resolve()))
+    for name in OUT2_EXPORTS:
+        fn = getattr(lib, name)
+        fn.argtypes, fn.restype = [U64, U64, ctypes.POINTER(U64)], U64
+    for name in OUT1_EXPORTS:
+        fn = getattr(lib, name)
+        fn.argtypes, fn.restype = [U64, ctypes.POINTER(U64)], U64
+    for name in PLAIN2_EXPORTS:
+        fn = getattr(lib, name)
+        fn.argtypes, fn.restype = [U64, U64], U64
+    return lib
+
+
+def ref_bzhi(a, idx, bits):
+    mask = (1 << bits) - 1
+    a &= mask
+    n = idx & 0xff
+    if n >= bits:
+        v, cf = a, 2
+    else:
+        v, cf = a & ((1 << n) - 1), 0
+    return v, cf | (1 if v == 0 else 0)
+
+
+def ref_rorx(a, count, bits):
+    mask = (1 << bits) - 1
+    a &= mask
+    c = count & (bits - 1)
+    v = a if c == 0 else ((a >> c) | (a << (bits - c))) & mask
+    return v, 2  # preserved CF=1, ZF=0
+
+
+def ref_shlx(a, count, bits):
+    mask = (1 << bits) - 1
+    c = count & (bits - 1)
+    return ((a & mask) << c) & mask, 2  # preserved CF=1, ZF=0
+
+
+def ref_shrx(a, count, bits):
+    mask = (1 << bits) - 1
+    return (a & mask) >> (count & (bits - 1))
+
+
+def ref_sarx(a, count, bits):
+    mask = (1 << bits) - 1
+    sign = 1 << (bits - 1)
+    a &= mask
+    s = a - (1 << bits) if a & sign else a
+    return (s >> (count & (bits - 1))) & mask
+
+
+def ref_pdep(src, mask_val, bits):
+    out = 0
+    k = 0
+    for b in range(bits):
+        if (mask_val >> b) & 1:
+            if (src >> k) & 1:
+                out |= 1 << b
+            k += 1
+    return out
+
+
+def ref_pext(src, mask_val, bits):
+    out = 0
+    k = 0
+    for b in range(bits):
+        if (mask_val >> b) & 1:
+            if (src >> b) & 1:
+                out |= 1 << k
+            k += 1
+    return out
+
+
+def ref_mulx(a, b, bits):
+    mask = (1 << bits) - 1
+    prod = (a & mask) * (b & mask)
+    return (prod >> bits) & mask, prod & mask
+
+
+def check(native_path, lifted_path):
+    native, lifted = load_lib(native_path), load_lib(lifted_path)
+    slot = U64(0)
+    values = (
+        0, 1, 2, 0x55aa55aa, 0x7fffffff, 0x80000000, 0xffffffff,
+        0xdeadbeef00000000, 0xdeadbeef12345678, 0x8000000000000000,
+        0x7fffffffffffffff, 0xffffffffffffffff, 0x0123456789abcdef,
+    )
+    counts = (0, 1, 7, 15, 31, 32, 33, 63, 64, 65, 255, 0x100)
+    masks = (0, 1, 0x55555555, 0xaaaaaaaa, 0x0f0f0f0f, 0xffffffff, 0x00ff00ff00ff00ff, 0x8000000000000001, 0xffffffffffffffff)
+
+    cases = 0
+    for name, fn, bits, rhs_list in (
+        ("bzhi32", ref_bzhi, 32, counts),
+        ("bzhi64", ref_bzhi, 64, counts),
+        ("shlx32", ref_shlx, 32, counts),
+        ("shlx64", ref_shlx, 64, counts),
+        ("mulx32", ref_mulx, 32, values),
+        ("mulx64", ref_mulx, 64, values),
+    ):
+        for a in values:
+            for b in rhs_list:
+                want_v, want_out = fn(a, b, bits)
+                for lib, label in ((native, "native"), (lifted, "lifted")):
+                    slot.value = 0xdeadbeef
+                    got_v = getattr(lib, name)(a, b, ctypes.byref(slot))

P2 Badge Check host BMI2 support before executing the native fixture

On an x64 Windows host without BMI2, such as an Ivy Bridge CPU or a VM that masks the feature, the first native bzhi32 invocation raises an illegal-instruction exception. Because CMakeLists.txt:606-607 registers this test unconditionally, the standard CPU/full suite now fails on those hosts, and the portable lifted/reference checks never run. Probe BMI2 before executing native exports and either omit the unavailable native comparison while retaining reference coverage or report a configured capability skip.

AGENTS.md reference: AGENTS.md:L37-L39

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4654982614 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/287#discussion_r4654982614). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-21T20:59:54Z. **Code review location:** `tests/cpu/bmi2.py`; line 147 ~~~~diff @@ -0,0 +1,206 @@ +"""Compare native and translated BMI2 instructions (32-bit and 64-bit).""" +import ctypes +from pathlib import Path +import sys + +import pefile +from iced_x86 import Decoder + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import export_rva +from cpu_ranges import function_ranges +from ffx_version_query import INTEGER_HEADER, lower, region + +U64 = ctypes.c_uint64 + +OUT2_EXPORTS = ("bzhi32", "bzhi64", "shlx32", "shlx64", "mulx32", "mulx64") +OUT1_EXPORTS = ("rorx32", "rorx64") +PLAIN2_EXPORTS = ("shrx32", "shrx64", "sarx32", "sarx64", "pdep32", "pdep64", "pext32", "pext64", "mulx64_same") + + +def emit(image, output): + parts = [INTEGER_HEADER] + with pefile.PE(str(image), fast_load=True) as pe: + for name in OUT2_EXPORTS: + (bounds,) = function_ranges(pe, export_rva(pe, name)) + body = region(pe, *bounds) + code = lower(body, ["rcx = a; rdx = b; r8 = out;"], {}, {}, {}) + parts.append(f'extern "C" __declspec(dllexport) word {name}(word a, word b, word out) {{\n{code}\n}}\n') + for name in OUT1_EXPORTS: + (bounds,) = function_ranges(pe, export_rva(pe, name)) + body = region(pe, *bounds) + code = lower(body, ["rcx = a; rdx = out;"], {}, {}, {}) + parts.append(f'extern "C" __declspec(dllexport) word {name}(word a, word out) {{\n{code}\n}}\n') + for name in PLAIN2_EXPORTS: + (bounds,) = function_ranges(pe, export_rva(pe, name)) + body = region(pe, *bounds) + code = lower(body, ["rcx = a; rdx = b;"], {}, {}, {}) + parts.append(f'extern "C" __declspec(dllexport) word {name}(word a, word b) {{\n{code}\n}}\n') + output.write_text("".join(parts), encoding="ascii") + + +def load_lib(path): + lib = ctypes.CDLL(str(Path(path).resolve())) + for name in OUT2_EXPORTS: + fn = getattr(lib, name) + fn.argtypes, fn.restype = [U64, U64, ctypes.POINTER(U64)], U64 + for name in OUT1_EXPORTS: + fn = getattr(lib, name) + fn.argtypes, fn.restype = [U64, ctypes.POINTER(U64)], U64 + for name in PLAIN2_EXPORTS: + fn = getattr(lib, name) + fn.argtypes, fn.restype = [U64, U64], U64 + return lib + + +def ref_bzhi(a, idx, bits): + mask = (1 << bits) - 1 + a &= mask + n = idx & 0xff + if n >= bits: + v, cf = a, 2 + else: + v, cf = a & ((1 << n) - 1), 0 + return v, cf | (1 if v == 0 else 0) + + +def ref_rorx(a, count, bits): + mask = (1 << bits) - 1 + a &= mask + c = count & (bits - 1) + v = a if c == 0 else ((a >> c) | (a << (bits - c))) & mask + return v, 2 # preserved CF=1, ZF=0 + + +def ref_shlx(a, count, bits): + mask = (1 << bits) - 1 + c = count & (bits - 1) + return ((a & mask) << c) & mask, 2 # preserved CF=1, ZF=0 + + +def ref_shrx(a, count, bits): + mask = (1 << bits) - 1 + return (a & mask) >> (count & (bits - 1)) + + +def ref_sarx(a, count, bits): + mask = (1 << bits) - 1 + sign = 1 << (bits - 1) + a &= mask + s = a - (1 << bits) if a & sign else a + return (s >> (count & (bits - 1))) & mask + + +def ref_pdep(src, mask_val, bits): + out = 0 + k = 0 + for b in range(bits): + if (mask_val >> b) & 1: + if (src >> k) & 1: + out |= 1 << b + k += 1 + return out + + +def ref_pext(src, mask_val, bits): + out = 0 + k = 0 + for b in range(bits): + if (mask_val >> b) & 1: + if (src >> b) & 1: + out |= 1 << k + k += 1 + return out + + +def ref_mulx(a, b, bits): + mask = (1 << bits) - 1 + prod = (a & mask) * (b & mask) + return (prod >> bits) & mask, prod & mask + + +def check(native_path, lifted_path): + native, lifted = load_lib(native_path), load_lib(lifted_path) + slot = U64(0) + values = ( + 0, 1, 2, 0x55aa55aa, 0x7fffffff, 0x80000000, 0xffffffff, + 0xdeadbeef00000000, 0xdeadbeef12345678, 0x8000000000000000, + 0x7fffffffffffffff, 0xffffffffffffffff, 0x0123456789abcdef, + ) + counts = (0, 1, 7, 15, 31, 32, 33, 63, 64, 65, 255, 0x100) + masks = (0, 1, 0x55555555, 0xaaaaaaaa, 0x0f0f0f0f, 0xffffffff, 0x00ff00ff00ff00ff, 0x8000000000000001, 0xffffffffffffffff) + + cases = 0 + for name, fn, bits, rhs_list in ( + ("bzhi32", ref_bzhi, 32, counts), + ("bzhi64", ref_bzhi, 64, counts), + ("shlx32", ref_shlx, 32, counts), + ("shlx64", ref_shlx, 64, counts), + ("mulx32", ref_mulx, 32, values), + ("mulx64", ref_mulx, 64, values), + ): + for a in values: + for b in rhs_list: + want_v, want_out = fn(a, b, bits) + for lib, label in ((native, "native"), (lifted, "lifted")): + slot.value = 0xdeadbeef + got_v = getattr(lib, name)(a, b, ctypes.byref(slot)) ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Check host BMI2 support before executing the native fixture** On an x64 Windows host without BMI2, such as an Ivy Bridge CPU or a VM that masks the feature, the first native `bzhi32` invocation raises an illegal-instruction exception. Because `CMakeLists.txt:606-607` registers this test unconditionally, the standard CPU/full suite now fails on those hosts, and the portable lifted/reference checks never run. Probe BMI2 before executing native exports and either omit the unavailable native comparison while retaining reference coverage or report a configured capability skip. AGENTS.md reference: [AGENTS.md:L37-L39](https://github.com/R0Y00/Xbox2Windows/blob/990564458719910ff64c7ddad823999b363b4de1/AGENTS.md#L37-L39) Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
Sign in to join this conversation.
No reviewers
No labels
No milestone
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.

Reference
R0Y00/Xbox2Windows!283
No description provided.