Skip to content

cpu_emulation: count each emulated site and time the #UD trap; first retail boot measurement on Intel (RT-500 follow-up, depends on #7111) - #8537

Closed
AlexLopezDevelop wants to merge 11 commits into
ProjectLeonida:mainfrom
AlexLopezDevelop:rt-cpu-trap-stats
Closed

AlexLopezDevelop wants to merge 11 commits into
ProjectLeonida:mainfrom
AlexLopezDevelop:rt-cpu-trap-stats

Conversation

@AlexLopezDevelop

@AlexLopezDevelop AlexLopezDevelop commented Nov 23, 2026 •

Copy link
Copy Markdown

Claimed in the coordination issue as: new RT item, #7496 (comment)

Depends on: #7111 (this branch is on its head c5f025fac; it only adds to runtime/src/cpu_emulation.h and the files below)

What and why

docs/cpu_features.md in #7111 ends with "Not measured: which of these sites a boot reaches, and in which order." This adds the counters to answer that, and the first answer.

  • Per-site counts in the #UD handler (runtime/src/cpu_emulation.h): every emulated instruction is counted against its address, with the handler's own TSC ticks, in a fixed 256-entry open-addressing table filled with compare-and-swap, so the handler never allocates or takes a lock. A site that does not fit is still emulated and counted as dropped.
  • gta6rt (runtime/src/main.cpp): a cpu_emulated startup-trace event at each new site (instruction, at as module+RVA); a per-site summary on stderr at a normal exit; and with LEONIDA_CPU_EMU_STATS=N the same summary every N seconds while the counts change, so a run that ends in a crash or an assert keeps its counts. Nothing is printed when nothing is emulated (any Zen 2 or later host).
  • cpu_emulation_test checks the table (first hit reported once, hits and ticks per address, snapshot order, and the live CLWB sites on a host without CLWB). With --bench it times each of CLWB, CLZERO and EXTRQ the host lacks (the whole #UD round trip) against a NOP of the same length, and says there is nothing to time on a host that has all three; it checks nothing there, so a slow machine cannot fail it.
  • Docs: docs/cpu_features.md gets the measurement below, runtime/README.md the switch and the trace event.

Measurement (counts only, nothing from the executable)

Intel Core i9-9900K (Coffee Lake: no SSE4a, CLZERO, MONITORX or CLWB), Windows 11, own 1.0.2.1 copy, main with the open boot-chain PRs merged locally (stops 1-20, #7111, #7516 for the BVH builder):

What Result
One emulated instruction (--bench, 200,000 iterations) CLWB about 1.0 µs, CLZERO about 1.4 µs, EXTRQ about 1.0 µs on #7111 c5f025fac (1.5 to 1.9 µs before its hot-path change)
Sites the boot reached 1 of the 41: a CLWB in a cache-line write-back loop
Hits at that site 16 at the first compute pipeline (stop 18); 18 by the next stop
Time in the emulation, boot so far about 30 to 40 µs in all
INSERTQ/EXTRQ, CLZERO, MONITORX/MWAITX not reached yet

The boot stops about 4 s in, at a fatal assert right after the first device slot 41 command signature. So far the trap path costs nothing that matters, and the load-time patching from my claim is not needed for the sites a boot reaches today. The vector-code SSE4a sites are the ones to watch: at about 2 µs a trap, around 8,000 hits a frame would cost a 60 Hz frame. Anyone whose boot gets further on an Intel CPU can re-run with LEONIDA_CPU_EMU_STATS=5 and update the table.

Also seen in passing, for whoever owns stop 18: on this RTX 2080 Ti (driver 621.24) the console BVH builder's first CreateComputePipelineState hit the title's 30 s watchdog on both a cold and a warm driver cache (two runs, about 33 s each); with #7516 the boot goes past it.

Tested

  • cpu_emulation_test and cpu_emulation_test --bench: all checks pass on the i9-9900K (every form through the handler).
  • gta6rt --run on the retail executable as above, with --trace and LEONIDA_CPU_EMU_STATS=2/3: the cpu_emulated event and the summary appear, and the counts match between the trace and the summary.
  • python -I tests/test_docs_*.py and tests/test_boot_trace.py: pass, except test_docs_links.py, which fails on RT-500: gta6rt emulates the Zen 2 instructions an Intel CPU lacks (INSERTQ/EXTRQ, CLZERO, MONITORX/MWAITX, CLWB) #7111's head too (an anchor in docs/dev-tools.md); not touched here.
  • Build: MSVC 14.44 (VS 2022 Build Tools), RelWithDebInfo, Windows SDK 10.0.26100. GPU: NVIDIA RTX 2080 Ti, driver 621.24, LEONIDA_D3D12=vulkan.

AI-assisted: yes (Claude Code)

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (Not applicable: no translator change.)

🤖 Generated with Claude Code

Krashgamer and others added 6 commits November 23, 2026 16:44
… desktop CPU may lack

The runtime runs the Xbox Series (Zen 2) executable natively, so an instruction the host CPU lacks raises #UD
where it is reached. tools/cpu_feature_scan.py streams dumpbin /disasm like inline_scan.py, maps each
instruction to its CPUID feature or privilege class (AMD-only, newer-Intel-only, not on Zen 2, privileged,
kernel call, host query, baseline), and splits the counts by .pdata range.

docs/cpu_features.md records the 1.0.2.1 result (counts only): 19 SSE4a, 10 CLZERO and 4 MONITORX/MWAITX
sites (AMD only) and 8 CLWB sites, all real code; the privileged hits are jump-table data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the first

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…Q/EXTRQ, CLZERO, MONITORX/MWAITX, CLWB)

The executable uses SSE4a INSERTQ, CLZERO and MONITORX/MWAITX (AMD only) and CLWB (Intel since Ice Lake)
without asking CPUID (docs/cpu_features.md). A host without one raises #UD there. src/cpu_emulation.h adds
a vectored handler that recognises those encodings at the faulting RIP, does the same work on the CONTEXT
and steps past the instruction; gta6rt installs it before any image code runs, after the startup trace's
handler so it runs first. One [rt] line names what the host lacks, one more per instruction on first use.

cpu_emulation_test checks the decoder on hand-written encodings, the bit-field helpers and apply() on a
synthetic CONTEXT, then runs every form for real from an executable buffer: natively on a Zen host,
through the handler on an Intel one, with the same expected values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ult; accept 66 on 0F 01 FC/FA/FB

A line CLZERO cannot write now reaches the next handlers as the access violation (or guard-page
violation) the instruction raises, with the write flag and the line address, instead of the #UD.
The 66 prefix and segment overrides are accepted on CLZERO/MONITORX/MWAITX; F2/F3 (other
instructions there, F3 0F 01 FA is MCOMMIT) and LOCK stay #UD. Points raised by SirKingg on ItsNotRexed#7055.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… xmm1[127:64]; AMD prefix forms; no SEH

- INSERTQ xmm, xmm took the length and index from swapped fields. The APM (vol. 4) has the length in
  xmm2[69:64] and the index in xmm2[77:72]; a Ryzen 9800X3D and a Ryzen 5700X agree (TheHoracio,
  Mayzkl on ItsNotRexed#7111). The measured 0x0810 case is a unit check now.
- INSERTQ/EXTRQ zero xmm1[127:64], as the Zen 3 measured in the same review does in all four forms.
- Decode REX bytes among the legacy prefixes (a non-final REX is ignored) and accept F2/F3 on CLZERO,
  as Zen 3 runs them (ItsNotRexed#7055's reviews); F2/F3 stay #UD on MONITORX/MWAITX.
- Check the CLZERO line's page and the instruction bytes' readability with VirtualQuery instead of
  catching a fault in a local __try, which clang-cl without /EHa does not cover for inline stores
  (venetanji on ItsNotRexed#7111).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…on and xg_xs test targets)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@towade

towade commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 7f464ba6 (with #7111 at 39b757a6d) on an Intel Core i7-14700K (Raptor Lake), Windows 11 26300, MSVC 19.44 RelWithDebInfo, own 1.0.2.1 copy: pass, and a second Intel data point for the table in docs/cpu_features.md. Counts only, nothing from the executable.

Retail boot. Base: ASTROWwwW:ladder@ffc6f6da0 + #7858631e531 + this PR, merged locally (no conflict with this PR). GPU: Intel UHD Graphics 770 (32.0.101.7092), LEONIDA_D3D12=vulkan, LEONIDA_SHADERS = a work folder with the corpus, FSPX and BVH programs, LEONIDA_CPU_EMU_STATS=2, --trace.

What i9-9900K (this PR) i7-14700K (here)
Missing, per the runtime's [rt] cpu: line SSE4a, CLZERO, MONITORX, CLWB SSE4a, CLZERO, MONITORX (CLWB is native)
Sites the boot reached 1 (CLWB) 0
cpu_emulated events 16-18 hits at that site 0 in 2 of 2 runs
Where the boot stops the assert after the first device slot 41 call the same: 1,656 D3D12 calls (1,634 ok, 22 called), then that assert

So on Raptor Lake the cache-line write-back site runs natively and the trap path isn't entered before slot 41; no summary is printed, as the description says for a run with nothing emulated.

cpu_emulation_test: all checks passed. It reports host: SSE4a 0, MONITORX 0, CLZERO 0, CLWB 1; INSERTQ, EXTRQ, CLZERO and MONITORX/MWAITX go through the handler, CLWB runs native.

One nit in --bench: on a host with CLWB it times the native instruction and still labels it as the emulation's cost:

bench: 200000 iterations; nop 0.2 ns, clwb (native) 23.1 ns per iteration; the emulation costs 23 ns per instruction

On Zen 2+ and on Intel from Ice Lake/Alder Lake on, CLWB is native, so the "emulation costs" figure is the native CLWB there, not the #UD round trip. Benchmarking an instruction that is emulated on this host (CLZERO or EXTRQ, missing on every Intel CPU) would measure the trap on any machine, or the line could say that nothing was emulated.

Not run: a boot past slot 41, so the SSE4a vector sites stay unmeasured here too.

AI-assisted (Claude Code).

@fiestorra

Copy link
Copy Markdown
Contributor

Tested 7f464ba65 on an AMD Ryzen 7 7800X3D with the Radeon 780M integrated GPU (gfx1036, driver 32.0.21045.29003) and an NVIDIA RTX 4090 (driver 32.0.16.2124), Windows 11 Pro 10.0.26300, Python 3.13 and MSVC as shipped by the build script: pass. Claimed as the AMD half in #8868; @towade's check covers the Intel half.

Built with scripts/build_runtime.ps1 (693 targets, clean). The PR as posted, no local changes.

The emulation itself, on a host that has the instructions. cpu_emulation_test and cpu_emulation_test --bench both report:

host: SSE4a 1, MONITORX 1, CLZERO 1, CLWB 1
insertq imm: native    extrq: native    clzero: native    monitorx/mwaitx: native    clwb: native
cpu_emulation: all checks passed

exit 0. So on this Zen 4 desktop part every one of the four user-mode instructions the page flags is present, nothing goes through the handler, and the checks still pass on that path. That is the case the page can only infer from the ISA ("On an AMD Zen 2 or later host every flagged user-mode instruction runs as on the console"), and here it is the path the code actually took.

The counts reproduce on a second copy. python -I tools\cpu_feature_scan.py <game>\game_scarlett_master.exe on my own 1.0.2.1 copy:

instructions scanned: 26674075
.pdata entries: 299257, instructions inside them: 22435554
CLZERO  amd-only      10   in .pdata 0     MONITORX amd-only 4/4     SSE4A amd-only 19/17     CLWB newer-intel 8/6
PORT-IO privileged     6   in .pdata 1     SYSTEM privileged 2/1      INT kernel-call 1/1      CPUID 9/9   XGETBV 2/2

Every row of the table in docs/cpu_features.md matches, including the totals (26,674,075 / 22,435,554 / 299,257). The page's "Port I/O, cli/hlt — 8 sites, 2 inside .pdata" is the tool's PORT-IO (6/1) plus SYSTEM (2/1) summed; I checked the sums rather than assuming them. tests/test_cpu_feature_scan.py: Ran 22 tests … OK.

A retail boot here, with the counters on. LEONIDA_CPU_EMU_STATS=2, --trace, --trace-d3d12, this copy of the title: 0 cpu_emulated events and no per-site summary at exit — the counter stays empty, as expected with nothing to emulate. My run ended 1.5 s in with 5 module(s) mapped, 20 unimplemented import(s) and exit 0xc0000005, the same stop and the same 20 imports an unmodified main reaches on this machine, so the new code changed nothing in the boot. Two consequences for the page's table: "Sites the boot reached: 1 of the 41 (a CLWB)" is a property of the Intel host, and the row for an AMD host is "0 of 41, none trapped". I am not editing their page, just giving them the number.

One wording problem in --bench on a host that has CLWB. The run printed:

bench: 200000 iterations; nop 0.2 ns, clwb (native) 66.4 ns per iteration; the emulation costs 66 ns per instruction

bench() (runtime/test/cpu_emulation_test.cpp:318) times one loop whose 4 bytes are 66 0F AE 32 and prints wb - nop as "the emulation costs …" whatever path(host.clwb) (:175) returns. On this host that path is native, so the number is a native CLWB in a loop and the sentence calls it an emulation cost — and the two differ by more than an order of magnitude from the page's Intel row (1.5 to 1.9 µs). The comment above the function says what it is meant to measure ("the whole #UD round trip"), and on an AMD host this printout does not show that. Printing the trailing clause only when the path is emulated would make the line mean what the comment says.

Docs and unrelated files. tests -p "test_docs_*.py": Ran 37 tests … FAILED (failures=3) — test_docs_cli_flags on docs/embedded_shaders.md:372, test_docs_design_rows on README.md, and test_docs_links on docs/dev-tools.md. All three fail the same way on main without this PR, so nothing here adds a docs failure; the new LEONIDA_CPU_EMU_STATS is documented in runtime/README.md and docs/cpu_features.md, which is what test_docs_cli_flags asks for.

One thing to save the next reviewer some time: git diff origin/main 7f464ba65 shows runtime/test/d3d12_pso_validation_test.cpp and its CMake target as deleted. That is the older base, not this change — the file is absent at the merge-base 6dda0630b and main got it from #6689 (dfe4e4ad3) later; it is not in this PR's commits, and GitHub reports the PR mergeable.

@SpaghettiMaster545

Copy link
Copy Markdown

Tested 7f464ba65 merged onto main 867d922f0 (clean merge) on an AMD Zen 5 host (Ryzen 7 9800X3D), Windows 11 IoT Enterprise LTSC 2024 (26100), MSVC 14.50 (VS 2026) RelWithDebInfo + Ninja, Vulkan SDK 1.4.363.0, llvm-mc 23.1.6. Synthetic tests only, no game files. This is the first AMD host on this head; the earlier Zen runs were on #7111's 978d525d.

  • cpu_emulation_test, 3 runs: host SSE4a 1, MONITORX 1, CLZERO 1, CLWB 1. insertq imm, extrq, clzero, monitorx/mwaitx and clwb all run native, and every check passes, the new site-table checks included. ctest -R ^cpu_emulation$: 1/1.
  • --bench, 3 runs: nop 0.2 ns, clwb (native) 69.0 / 69.8 / 69.2 ns, printed as "the emulation costs 69 ns per instruction". So @towade's nit also holds on Zen 5: with CLWB on the host, that figure is native CLWB, not the #UD round trip.
  • Nothing emulated, nothing printed: gta6rt --run tiny_game --trace … -- hello 42 with LEONIDA_CPU_EMU_STATS=1 exits 0, prints no [rt] cpu: line and records 0 cpu_emulated events in the trace, as the description says.
  • Loader ctest subset (module_names, run_module_names, startup_trace, cpu_emulation, run_argv_modes, run_startup_cmdline, run_tiny_*, run_tiny_game*, gta6rt_*): 24/24 twice. main is 23/23 twice; it has no cpu_emulation.
  • run_tiny_frame and run_tiny_frame_queue_test_settings: 2/2, twice per GPU, the same on the PR and on main. The GPUs were the AMD Radeon Graphics iGPU (gfx1036, AMD 24.10.24, LEONIDA_VK_DEVICE=radeon) and an NVIDIA RTX 5070 Ti (621.24, LEONIDA_VK_DEVICE=5070).
  • Python tests: tests/test_cpu_feature_scan.py 22 OK. test_docs_cli_flags, test_docs_design_rows and test_docs_links fail exactly as on main.

Pass. AI-assisted (Claude Code).

Krashgamer and others added 2 commits November 23, 2026 21:53
…fix stay #UD

An x86 instruction is at most 15 bytes, so decode() now reads no further than
that: a CLZERO behind 13 prefixes or a 17-byte EXTRQ is refused even when more
bytes are readable (the handler already passed at most 15). MONITORX and MWAITX
are only taken without 66/F2/F3; CLZERO keeps the 66/F2/F3 forms measured on
Zen 3. The title's MONITORX/MWAITX sites carry no prefix.

New decoder checks cover both; they fail without the header change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
VirtualQuery sizes the run of pages with the same attributes after the address,
so its cost grows with the rest of the region: in a mapped image or a large
heap each emulated instruction took 0.4-1.5 ms (LastThylacine's measurement on
ItsNotRexed#7111; 1.5 ms per CLZERO and 0.5 ms per INSERTQ on an i7-10700K).

- The handler reads the instruction bytes in RIP's page without a query (the
  CPU just fetched them there) and queries only when the 15-byte window
  reaches into the next page.
- writable() asks QueryWorkingSetEx about the line's page first; a resident,
  plainly writable page returns at once. Anything else (not resident,
  read-only, guard) takes the VirtualQuery path as before.

Now about 2 us per emulated instruction. New live checks: CLZERO on a resident
read-only page still raises an access violation, on a resident guard page a
guard-page violation, and zeroes the line once the guard is gone.

Suggested by LastThylacine in the ItsNotRexed#7111 review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AlexLopezDevelop and others added 3 commits November 23, 2026 22:18
…low-up)

Every instruction the #UD handler emulates is counted against its address,
with the handler's own TSC ticks, in a fixed lock-free table. gta6rt writes a
`cpu_emulated` startup-trace event per new site, prints a per-site summary at a
normal exit, and every N seconds with LEONIDA_CPU_EMU_STATS=N so a run that
crashes still leaves its counts. cpu_emulation_test checks the table and, with
--bench, prints the cost of the whole #UD round trip against a NOP loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cost

cpu_features.md records the first measurement on an Intel i9-9900K: one CLWB
site, 16-18 hits up to boot stop 19, about 2 us per #UD round trip. The runtime
README documents the per-site summary, LEONIDA_CPU_EMU_STATS and the
cpu_emulated trace event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… docs: three hosts and the frame loop

--bench timed CLWB on every host and called the native instruction "the
emulation cost" where CLWB is native (towade, fiestorra, SpaghettiMaster545
on ItsNotRexed#8537). It now times each of CLWB, CLZERO and EXTRQ that the host lacks,
against a NOP of the same length, and says there is nothing to time on a host
that has all three.

cpu_features.md: the Raptor Lake and Zen 4/5 rows from the reviews, the
measured scope (up to the slot 41 assert), the CLZERO sites a boot that reaches
the frame loop adds, and ItsNotRexed#8783 for the hot CLZERO loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@AlexLopezDevelop

Copy link
Copy Markdown
Author

Thanks @towade, @fiestorra and @SpaghettiMaster545 for the three runs. All three of you caught the same --bench problem: on a host with native CLWB it timed the native instruction and called it the emulation cost. Fixed in 293fb2f6e:

AI-assisted (Claude Code).

@SpaghettiMaster545

Copy link
Copy Markdown

Re-tested 293fb2f6e on the AMD Zen 5 host (Ryzen 7 9800X3D, Windows 11 26100, MSVC 14.50 RelWithDebInfo + Ninja). This host has all three instructions natively.

  • cpu_emulation_test --bench, 2 runs: bench: this CPU runs CLWB, CLZERO and EXTRQ natively; nothing is emulated, so there is no trap to time, then cpu_emulation: all checks passed. It no longer times native CLWB as the emulation cost.
  • cpu_emulation_test without --bench: all checks pass, and clwb and monitorx/mwaitx are reported native.

Pass. AI-assisted (Claude Code).

@byPreaZy

Copy link
Copy Markdown

checked: #8537 (diff includes dep #7111's head) | with: applied the diff on main 5d74c27, built and ran cpu_emulation_test (MSVC 14.44, Ninja RelWithDebInfo) | on: Windows 11, RX 9060 XT host (Zen-based, all emulated instructions native: SSE4a/MONITORX/CLZERO/CLWB present) | result: PASS — cpu_emulation: all checks passed

Note: on this host every emulated site is native, so the #UD emulation paths themselves are not exercised here (the test validates the counter table, snapshot ordering and live-site reporting structurally). The per-site retail measurement in the docs came from an Intel host, which this machine is not.

AI-assisted check of the combined #7111+#8537 state.

@moistman7

Copy link
Copy Markdown

Tested 293fb2f6e merged onto main 867d922 (clean), built with scripts/build_runtime.ps1 (MSVC, VS Build Tools 2022), Windows 11 Pro 26200, on an AMD Ryzen 7 9800X3D (Zen 5). This adds the "has everything" data point the bench mode describes:

  • cpu_emulation_test: all checks pass, and every instruction family reports native (INSERTQ/EXTRQ, CLZERO, MONITORX/MWAITX, CLWB).
  • cpu_emulation_test --bench: this CPU runs CLWB, CLZERO and EXTRQ natively; nothing is emulated, so there is no trap to time, all checks pass.
  • ctest -R cpu_emulation passes; tests/test_cpu_feature_scan.py OK.

No retail boot (I have no game files), so nothing for the boot table.

AI-assisted (Claude Code)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants