CPU Acceleration Plan (Zen 4 AVX-512 & Universal 64-Bit)
Status: Implemented (Phases 1–4 Complete). All three execution tiers (portable, avx512_c, avx512), the 256-page IvoryDcache, OS-independent SysV/Win64 hot assembly loop (emu/src/cpu_zen4_loop.S), and lockstep verification have landed. See docs/emulator/core-and-acceleration.md for the live architecture, runtime knobs (ISA_MODE, IVORY_ACCEL), and verified benchmark measurements (149.7–151.4 MIPS on 45M-step fep330 boot, 2.31× vs portable). This document is retained as the historical design record.
Companion Note: Builds on avx512.md and audits against the from-scratch C11 emulator in emu/ and emu/AGENTS.md.
1. Executive Summary & Settled Design Decisions
This plan accelerates the from-scratch C11 Ivory/XL1200 emulator on AMD Ryzen 9 7940HS (Zen 4) (AVX-512F/DQ/BW/VL/CD, VBMI, VBMI2, BITALG, VPOPCNTDQ, BMI1/2, LZCNT/TZCNT, zero AVX-512 clock downthrottling) while keeping the baseline portable to any 64-bit little-endian CPU & OS (Linux, Windows x64, macOS/BSD across x86_64, aarch64, riscv64, ppc64le, loongarch64) and making the hot x86-64 assembly OS-independent across Linux/SysV and Windows x64.
Settled Architectural Choices
- Default Build Mode (
ISA_MODE=runtime):make -C emudefaults toISA_MODE=runtime, building portable-O3baseline C11 code plusx86_64accelerated units selected at startup via statelessCPUID+XGETBV.ISA_MODE=portableandISA_MODE=nativeremain optional compile-time modes;IVORY_ACCEL=auto|portable|avx512_c|avx512overrides tier selection at runtime for lockstep A/B verification and benchmarking. - Decoded Page Cache Size (
256Pages): 256 decoded pages (~1.06 MiB) organized as 128 sets × 2 ways, fitting inside Zen 4's 1 MiB L2 / 16 MiB L3 cache. - Full Architectural RAM Readiness (Up to 4 GigaWords / \(2^{24}\) PPNs): Rather than an 8 MW-only
cached_ppn_bitmap(which would grow to2 MiBacross sparse MMIO holes at \(2^{24}\) PPNs),IvoryDcacheuses a fixed 1 KiB 2-way PPN tag directory (uint64_t ppn_pair[128]) folding all 24 PPN bits (+ 64-bit(size_t)pmahost indexing), scaling with O(1) memory and zero resizing from 8 MW to 4 GW. - Two Pre-Assembly Phases + OS-Independent Assembly:
- Phase 1: Pure C11/GNU C portable direct-threaded engine + 256-page
IvoryDcache+ 256-µs timer batching + inlineDATA_READ+ O(1) shell dirty-gating (zero intrinsics, zero assembly). - Phase 2: Stateless runtime
CPUID/XGETBVdispatch + OS-independent<immintrin.h>AVX-512 C kernels (256-word page decoder, 64B PHT bucket probe, 4-insnvpshufbitqmbPHT hash) + profiling gate before assembly. - Phase 3: OS-independent x86-64 hot assembly loop (
cpu_zen4_loop.S+asm_abi.h, ~28 hot opcodes + single C slow-path trampoline) supporting both System V AMD64 and Microsoft Windows x64 (_WIN64). - Phase 4: Profile-guided opcode tuning & optional stretch goals.
- Phase 1: Pure C11/GNU C portable direct-threaded engine + 256-page
| Component | Target Phase & Tier | Expected Impact |
|---|---|---|
| 1. 512-Slot Strided Decoded Page Cache (256 pp) + Direct Threading | Phase 1 (portable64, pure C11/GNU C goto *) | ~3–4× over current double-switch — eliminates per-insn fetch, Even/Odd extraction, CDR branches, and two-level k_opcode_router -> isa_* switch dispatch. |
2. Capped 256-µs Event-Horizon Timer Batching + Fast DATA_READ | Phase 1 (portable64, all hosts) | Cuts merlin_tick() calls by 99.6% in deterministic mode (cpu.c) and inlines non-forwarding RAM DATA_READ / CDR_READ. |
3. Stateless Runtime Dispatch + <immintrin.h> AVX-512 Kernels | Phase 2 (zen4_avx512 C intrinsics — Linux & Windows) | ~45–70 ns per 256-word page decode (vpermi2b + vpsrlvq), 4-insn vpshufbitqmb PHT hash, and 1-cache-line ZMM 4-way PHT bucket probe. |
| 4. OS-Independent x86-64 Assembly Fast-Loop (~28 Hot Opcodes) | Phase 3 (zen4_avx512 .S — SysV + Win64 ABI shim) | Additional ~1.4–1.7× (~150–250+ MIPS total) — pins hot state in universal non-volatile GPRs (rbx, rbp, r12..r15) with relocation-free .rodata per-handler dispatch. |
Non-Negotiable ABI, Hot-Reload & Source-Provenance Invariants (emu/AGENTS.md):
- Reference sources only: Consult only
genera-original/,I_Machine/,docs/hardware-reference/, andemu/. Never read, inspect, grep, or citelinux-vlm/,xl1200-emu/, orarchive/. - Frozen state struct sizes:
sizeof(IvoryCpu) == 4096U,sizeof(IvoryMem) == 32768U, andsizeof(MerlinBoard) == 278528Uacross LP64 (Linux) and LLP64 (Windows x64). - ELF zero-
.data/.bsshygiene: Everyemu/build/obj/core/*.omust retain 0 bytes in writable.dataand.bssverified viareadelf -WS(read-only.rodataand.data.rel.ro[.local]are permitted). - Export & hot-reload safety:
libivory_coreexports onlyivory_core_get_apiand must survive livedlclose/dlopenreloads and.snap/COW checkpoint rollbacks with zero dangling code pointers.
2. Portability, Build Modes & Runtime Dispatch (ISA_MODE=runtime Default)
2.1 Per-TU Target Flags (Fixing Makefile -march=native Leakage)
Currently, CORE_OPT_FLAGS passes -march=native -mtune=native to every file in CORE_SRCS, which makes GCC emit EVEX/AVX-512 instructions into baseline C translation units on Zen 4 (causing SIGILL if run on non-AVX-512 x86-64 machines). Under the new build setup:
flowchart LR
subgraph Build["Build Modes (Makefile: ISA_MODE ?= runtime)"]
M_RT["ISA_MODE=runtime (Default)<br/>Baseline CORE_SRCS: -O3 -funroll-loops (any 64-bit)<br/>x86_64 adds cpu_zen4_avx512.c (-march=znver4)<br/>+ Phase 3 cpu_zen4_loop.S"]
M_PORT["ISA_MODE=portable<br/>Pure C11 across all files (-DIVORY_FORCE_PORTABLE=1)<br/>Zero intrinsics / zero asm"]
M_NAT["ISA_MODE=native<br/>Compile-time -march=native across all CORE_SRCS"]
end
subgraph Runtime["Stateless Runtime Selection (0 .data / .bss)"]
CPUID["ivory_host_select_tier()<br/>OS-independent CPUID + XGETBV ((xcr0 & 0xE6)==0xE6)<br/>+ getenv('IVORY_ACCEL') override"]
VTBL["Read-Only Tier Table<br/>TIER_PORTABLE64 | TIER_AVX512_C | TIER_AVX512_ASM"]
CPUID --> VTBL
end
M_RT --> CPUID- Two Core Families (No Redundant AVX2 Middle Tier):
TIER_PORTABLE64(0): Universal 64-bit little-endian C11 (_Static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)matchingIvoryWordbitfields in ivory_hw.h). Uses GNU C computed-goto (&&lbl, supported by GCC and Clang under-std=c11 -Wall -Wextra -Werror) over the 512-slot decoded page cache, falling back to existingcpu_step_internal()if!defined(__GNUC__).TIER_AVX512_C(1, Phase 2) /TIER_AVX512_ASM(2, Phase 3): Compiled under#if defined(__x86_64__) && !defined(IVORY_FORCE_PORTABLE). Requires OS-enabledXMM/YMM/ZMM/opmaskstate ((xgetbv(0) & 0xE6) == 0xE6) +AVX512F/DQ/BW/VL+VBMI+VBMI2+BITALG+BMI1/2.
- Cross-Compiler Intrinsics Portability:
cpu_zen4_avx512.cuses standard<immintrin.h>intrinsics (-march=znver4on GCC/Clang across Linux/MinGW-w64/macOS/BSD, or/arch:AVX512onclang-cl/MSVC). - Hot-Reload & Snapshot State Placement:
- In snapshot.c, checkpoint save/restore performs whole-struct assignment (
*dst = *src) onIvoryCpuandMerlinBoard, whereasIvoryMemcopies onlyboot_comm,map_cache,io_sram,ram, andvram. - Therefore,
IvoryMemownsIvoryDcache *dcacheby carving 1uint64_tslot fromIvoryMem._reserved[938]->_reserved[937]in ivory_emu.h (sizeof(IvoryMem)stays32768U), allocated inivory_mem_initand freed inivory_mem_destroy. - Never store raw function pointers in
IvoryDcache:IvoryDcachestores onlyuint8_t accel_tieranduintptr_t core_cookie = (uintptr_t)&ivory_core_get_api, indexing a read-only.data.rel.ro.localvtable inside the currently mappedlibivory_core. Whencore_cookiechanges after a livereload,dcacheflushes its decoded pages and refreshesaccel_tier+core_cookie.
- In snapshot.c, checkpoint save/restore performs whole-struct assignment (
3. Decoded Page Cache & Architectural Max-RAM Scaling (8 MW -> 4 GW)
3.1 Ivory & Merlin-II Architectural RAM Ceilings Beyond 8 MW
Per genera-original/sys.sct/i-sys/sysdef.lisp, genera-original/sys.sct/i-sys/configuration.lisp (local-only when present), and ivory_hw.h, there are three RAM ceilings above the standard 8 MW (0x00800000):
| RAM Ceiling | Physical Address Layout | Pages (256 W/pg) | Host IvoryWord Footprint | Hardware / Genera Constraints |
|---|---|---|---|---|
1. Zone-31 Contiguous Max (127.875 MW) | 0x00000000 .. 0x07FDFFFF (2,046 quanta) | 523,776 pages | ~1.00 GiB | Directly addressable via unmapped Zone 31 (VMA & 0x07FFFFFF) right up to IVORY_BOOT_PROM_BASE_PMA (0x07FE0000) and MERLIN_TIMER_BASE_PMA (0x08000000). |
2. Merlin-II Hardware Max (895.875 MW) | Main (127.875 MW) + 3 merlin-memory-board slots at 0x10000000, 0x20000000, 0x30000000 (3 × 256 MW, below MERLIN_IO_BOARD0 0x40000000) | 3,669,504 pages (discontiguous) | ~7.00 GiB (virtual; sparse on-demand) | Genera find-merlin-boards (genera-original/sys.sct/i-sys/configuration.lisp) probes all 3 expansion slots when ECO nibbles <15:4> != 0xF. Accessed via PHT (Zones 0..30) and DTP-PHYSICAL-ADDRESS. |
3. Ivory VLSI Architectural Max (4 GigaWords, minus MMIO holes) | %%PHT1-PPN is 24 bits (<31:8>), %MMPT-Y-BITS = 16 + %MMPT-X-BITS = 8, %%MAIN-MEMORY-MAP-QUANTUM = (byte 24 0) | Up to 16,777,216 PPNs (2^24) | Up to 32 GiB virtual reservation (sparse on-demand) | Requires 64-bit (size_t)pma host indexing (since pma >= 512 MW exceeds 32-bit byte offsets) and sparse host reservation (mmap(MAP_NORESERVE) / VirtualAlloc(MEM_RESERVE)). |
3.2 O(1) 1 KiB 2-Way Set-Associative PPN Tag Directory
Because IvoryDcache holds 256 active pages, we organize it as 128 sets × 2 ways indexed by a 7-bit hash folding all 24 architectural PPN bits:
#define IVORY_DCACHE_SETS 128U
#define IVORY_DCACHE_WAYS 2U /* 256 decoded pages total (~1.06 MiB) */
static inline uint32_t ivory_dcache_set_idx(uint32_t ppn) {
return (ppn ^ (ppn >> 7) ^ (ppn >> 14) ^ (ppn >> 21)) & (IVORY_DCACHE_SETS - 1U);
}
- 1 KiB L1d-Resident Tag Array:
uint64_t ppn_pair[128](1,024bytes = 16 cache lines) packs{ uint32_t way0_ppn, uint32_t way1_ppn }(0xFFFFFFFFU= empty; Boot PROM pages use sentinel0x80000000U | prom_pageoutside the 24-bit RAM PPN space). - Universal Write-Coherence Hook (
ivory_mem_note_ram_write_pma):WARNINGIn mem.c,
write_word_with_translation()writes Zone 31 and Map-Cache hits directly intomem->ram[pma]andmc->host_page[off]without callingivory_mem_raw_write_pma(), andifep_install()(loader.c) writesmem->ramdirectly during boot andpower-reset.- Route RAM dirty-marking + code-cache invalidation through a single inline
ivory_mem_note_ram_write_pma(mem, pma)called bywrite_word_with_translation(),ivory_mem_raw_write_pma(), andivory_mem_mark_ram_dirty()(and callivory_mem_mark_ram_dirty()fromifep_install()). - On each write,
ppn = pma >> 8loadsuint64_t pair = dcache->ppn_pair[set]and invalidates any matching way ((uint32_t)pair == ppn || (uint32_t)(pair >> 32) == ppn) in 1 L1d load with 0% false positives and zero scaling cost up to 4 GW. - Flush
memset(dcache->ppn_pair, 0xFF, sizeof(dcache->ppn_pair))(~8 ns) inivory_mem_reset(),ivory_mem_invalidate_map_cache()(also called on checkpoint restore in snapshot.c), andivory_cpu_reset(). - Virtual-to-physical entry still validates
CpuIcache64againstmem->map_epoch, so single-VPN remaps (ivory_mem_invalidate_map_entry/ivory_mem_load_map_entry) take effect immediately. - Ensure all
mem->rampointer indexing uses(size_t)pmasopma >= 512 MW(>= 4 GiBbyte offset) never truncates on Linux LP64 or Windows LLP64.
- Route RAM dirty-marking + code-cache invalidation through a single inline
3.3 8-Byte IvoryDecodedSlot & Boundary Sentinels
typedef struct IvoryDecodedSlot {
uint16_t handler_id; /* 0..511 index into read-only dispatch table (reload-safe) */
int8_t stride; /* Sequential delta: -1 (CDR=2), +1, +2 (CDR=3/FW), +3 (Odd CDR=3) */
uint8_t aux; /* DTP for constants/calls, min_args for ENTRY, or mode */
uint32_t imm; /* 32-bit pointer/constant payload, branch delta, or offset */
} IvoryDecodedSlot; /* 8 bytes -> 8 slots per 64B cache line */
typedef struct IvoryDecodedPage {
const IvoryWord *raw_page; /* Underlying 256-word RAM/PROM page for cold paths */
uint32_t ppn_tag; /* 24-bit RAM PPN or 0x80000000|prom_pg */
uint8_t lru_bit;
uint8_t _pad[3];
IvoryDecodedSlot raw_slots[516];/* [0]=slot -1, [1..512]=0..511, [513..515]=512..514 */
} IvoryDecodedPage;
#define DPAGE_SLOTS(dp) (&(dp)->raw_slots[1])
- Exact stride parity with cpu.c:
CDR=0:+1(packed) /+2(fullword).CDR=1(IVORY_SEQ_FENCE): both Even and Odd emitHANDLER_TRAP_FENCE(IVORY_REV4_USTATE_I_STAGE_ERROR).CDR=2(IVORY_SEQ_PC_MINUS_1):-1(slot == 0steps cleanly intoDPAGE_SLOTS(dp)[-1], avoiding C11 negative-index UB).CDR=3(IVORY_SEQ_PC_EVEN_2_ODD_3):+2on Even/fullword,+3on Odd packed (slots 510..511step cleanly intoDPAGE_SLOTS(dp)[512..514]).- Non-packed Odd slots emit
HANDLER_TRAP_ODD_FULLWORD(IVORY_REV4_USTATE_I_STAGE_ERROR).
- Zero
raw_pageload for 40-bit inline constants: Inline literals (tag < 0o50) pushCDR = IVORY_CDR_NEXT (0), reconstructed directly from((uint64_t)slot.aux << 32) | slot.imm. - O(1) intra-page branches: Branch/loop targets satisfying
0 <= slot + delta < 512anddelta != 0(delta == 0trapsBRANCH_DOT_ERROR) adjustip += deltadirectly; backward intra-page branches decrementrem_budgetso tight loops never starve timers/IRQs.
4. Phase-by-Phase Technical Design
Phase 1: Universal Portable Threaded Baseline & Timer Batching (portable64)
- Direct-Threaded Loop (
cpu_decode.c/cpu.c):- Single-function GNU C computed-goto interpreter (
goto *k_portable_disp[slot.handler_id],#elsefallback tocpu_step_internal()for non-GNU compilers). - Falls back to
cpu_step_internal()whenevertrace_enabled,has_break,num_watchpoints > 0,(cr.raw & 0x38000000U) != 0(trace_pending | call_trace | instruction_trace), orivory_mem_resolve_icache_page()returnsNULL(stack_cacheoverlap or first 64-wordboot_commPROM page).
- Single-function GNU C computed-goto interpreter (
- Capped 256-µs Event-Horizon Timer Batching (cpu.c):
- In deterministic
!cpu->external_clockmode, batchmerlin_tick()up tomin(merlin_us_until_next_timer_irq(board), 256U)µs (<= 1,024insns, preservingeth_82586_poll_rx's 256-µs divider in merlin.c even when PIT channels are disarmed and returnUINT64_MAX). - Flush accrued cycles (
delta_us = accrued >> 2) lazily beforeOP_READ/WRITE_INTERNAL_REGISTER(0047clock,0023preempt),OP_COPROCESSOR_READ/WRITE(01002), and anymerlin_io_read/write(including PIT Counter Latch writes to0x08000003), and serviceboard->dma_service_pendingimmediately when non-zero after MMIO. - Check deferred async interrupts at backward branches, calls, page exits, and immediately after
OP_RETURN_*(which restorescr.rawand can droptrap_modetoEMULATOR, unmasking pending sequence breaks/preempt!),OP_WRITE_INTERNAL_REGISTER,OP_CHECK_PREEMPT_REQUEST,OP_UNBIND_N,OP_RESTORE_BINDING_STACK, andOP_CATCH_CLOSE.
- In deterministic
- Portable Micro-Optimizations:
- 15-op grouped bit-run
ivory_pht_hash()fallback (replacing ~130 scalar ops in ivory_hw.h). - Unified
pht_probe_bucket()in mem.c shared bypht_search()andpht_sync_write_attributes(). - Inline non-forwarding
ivory_fast_data_read()forisa_lisp.c(preservingcpu->memory_data = wordandtransport_trap && is_oldspace_pointerchecks). - Host-shell pure-C11 wins: O(1)
(vram_write_count, video_ctrl)caching indebug_ctl_compute_vram_metrics()(debug_ctl.c) and__builtin_ctzll(dirty_bm[w])clean-page skipping in snapshot.c.
- 15-op grouped bit-run
Phase 2: Runtime Dispatch & OS-Independent AVX-512 C Intrinsics (cpu_zen4_avx512.c)
Implemented in portable C11 + <immintrin.h> (compiles identically on Linux and Windows x64 before introducing assembly):
- Stateless
CPUID+XGETBVCapability Detector:- Verifies OS
XMM/YMM/ZMM/opmasksave state ((xcr0 & 0xE6) == 0xE6) plusAVX512F/DQ/BW/VL,VBMI,VBMI2,BITALG, andBMI1/2.
- Verifies OS
- AVX-512 256-Word Page Decoder (~45–70 ns/page):
- 32
ZMMiterations (8IvoryWords ->16IvoryDecodedSlots per iteration). - Register-resident 256-opcode LUT in 4
ZMMconstants usingAVX512_VBMI_mm512_permutex2var_epi8(zerovpgatherddport pressure), 1-cycle fullword DTP legality bitmask viavpsrlvq, pre-pairedENTRY(0176/0177)min_args+ Odd-halfwordmax_args, and branchless Even/Odd stride interleave.
- 32
- AVX-512 PHT Bucket Probe & 4-Insn
vpshufbitqmbHash:_mm512_loadu_si512loads all 4IvoryPhtEntrypairs (64 B = 1 cache line). Mask<31:8>(_mm512_and_epi64(..., 0xFFFFFF00ULL)) soage/fault_request/end_collision_chainnever cause false misses, and compare with even-lane opmask0x55(_mm512_mask_cmpeq_epi64_mask(0x55, ...)) sopht1.ppnin odd lanes never causes false hits.- Two
_mm256_bitshuffle_epi64_mask(vpshufbitqmb) +_kxor_mask32compute all 23 XOR bits ofivory_pht_hash(vma)in 4 instructions.
- Benchmarking & Profiling Gate:
- Measure
IVORY_ACCEL=portablevsIVORY_ACCEL=avx512_cMIPS andperf statcounters across IFEP boot and Genera workloads to validate hot-opcode coverage prior to Phase 3.
- Measure
Phase 3: OS-Independent x86-64 Assembly Hot Loop (Linux/SysV + Windows x64)
Cross-OS Assembly Design (cpu_zen4_loop.S + asm_abi.h)
Standard x86-64 assembly breaks on Windows (_WIN64) due to: (1) %rcx/%rdx vs %rdi/%rsi arg registers, (2) %rdi/%rsi and XMM6..15 being non-volatile on Win64, (3) Win64 requiring 32 bytes of caller shadow space before call plus .seh_* unwind directives instead of ELF .cfi_*/.note.GNU-stack, and (4) 32-bit long (LLP64).
We isolate all OS differences inside a ~35-line asm_abi.h header so 100% of the ~28 hot opcode handlers share one identical assembly body (buildable with GCC or Clang/clang-cl on Linux, Windows MinGW-w64, Windows MSVC-ABI clang-cl, macOS, and BSD):
flowchart TD
C_CALLER["C Caller: ivory_cpu_run_zen4_asm(&ctx)<br/>Single pointer arg: IvoryAsmLoopCtx *ctx"] --> PROLOGUE
PROLOGUE["asm_abi.h Prologue (~20 lines)<br/>• _WIN64: %rcx -> ctx, emits .seh_proc/.seh_pushreg, saves %rdi/%rsi<br/>• SysV: %rdi -> ctx, emits .cfi_startproc<br/>• Both: reserves 32B shadow space + 32B locals (64B aligned frame)"]
PROLOGUE --> HOT_LOOP["OS-Independent Hot Threaded Loop (~320 LOC)<br/>• Pinned universal non-volatile GPRs: rbx=cpu, rbp=ip, r12=tos, r13d=sp, r14d=fp, r15=tbl<br/>• Scratch GPRs: rax, rcx, rdx, rsi, rdi, r8..r11 (zero XMM6..15 used!)<br/>• Relocation-free 2 KiB .rodata relative jump table (.long .L_op - .L_tbl)"]
HOT_LOOP -->|"Cold opcode (~190 ops) / Miss / Trap"| TRAMP["Single Slow-Path Trampoline (~15 lines)<br/>Flushes r12..r14 & PC/current_instruction to IvoryCpu;<br/>sets ABI_ARG0 = %rsp, ABI_ARG1 = reason;<br/>call ivory_cpu_slow_trampoline (uses pre-reserved 32B shadow space!)"]
TRAMP -->|"Reloads ip, sp, fp, tos or exits"| HOT_LOOP- Single-Pointer Entry & Single-Helper Exit:
- Entry
ivory_cpu_run_zen4_asm(IvoryAsmLoopCtx *ctx)and slow-pathivory_cpu_slow_trampoline(IvoryAsmLoopCtx *ctx, uint32_t reason)reduce ABI argument differences to two macros (ABI_ARG0 = %rcx/%rdi,ABI_ARG1_32 = %edx/%esi).
- Entry
- Universal Non-Volatile Register Pinning & Write-Through
tos:%rbx(cpu),%rbp(ip),%r12(tos),%r13d(sp_vma),%r14d(fp_vma), and%r15(disp_table) are callee-saved on both System V AMD64 and Windows x64 (note:%r10/%r11are caller-saved scratch!).%r12(tos) must be write-through intocpu->stack_cache[sp_vma & 127](and refreshed if a store hitsvma == sp_vma) so aliasedFP+k,LP+k,SP-255, orDTP_LOCATIVEstack-cache accesses never read stale values.- Saving
%rdiand%rsionce in the prologue makes all 9 scratch GPRs (%rax, %rcx, %rdx, %rsi, %rdi, %r8..%r11) identical across OSes; touching zeroXMMregisters avoids Win64XMM6..15save/restore; always reserving0(%rsp)..31(%rsp)as shadow space keepsrem_budgetanddpagestack offsets identical.
- Relocation-Free 2 KiB Relative Jump Table (
.rodata/.rdata):disp_tablestores 512 × 32-bit signed offsets (.long .L_op_k - .L_disp_tbl) in pure read-only.rodata/.rdata(zero dynamic relocations on ELF.so, Windows.dll, and Mach-O.dylib; 2 KiB L1d footprint):movsbq 2(%rbp), %rcx # current slot.stride (-1, +1, +2, +3) leaq (%rbp,%rcx,8), %rbp # ip += stride movq (%rbp), %rdx # load next 8-byte IvoryDecodedSlot movzwl %dx, %eax # handler_id shrq $32, %rdx # next slot.imm in %edx movslq (%r15,%rax,4), %rcx # PIC/DLL-clean 32-bit relative handler offset addq %r15, %rcx jmp *%rcx # per-handler indirect jmp -> Zen 4 ITTAGE friendly
- Slow-Path State Materialization & LP64/LLP64 Offset Guards:
- Before calling
ivory_cpu_slow_trampoline, materializecpu->pc,cpu->d_pc,cpu->sp,cpu->macro_sp = pre_insn_sp(required for pre-trapSProllback in cpu.c),cpu->fp,cpu->scratchpad[0] = tos, andcpu->current_instruction = dpage->raw_page[slot >> 1] & IVORY_WORD_MASK(required forpost_trap,FINISH_CALL,CATCH_CLOSE, and%REGISTER-INSTRUCTION0040..0042). Note thativory_isa_exec_fullword_call()(isa_call.c) advancescpu->pcinternally — do not double-advance! - Guard all assembly struct offsets via
ivory_asm_offsets.hwith C_Static_assert(offsetof(...) == ...)checks across LP64 and LLP64, and pair__declspec(dllexport)/LoadLibraryAshims inivory_core_api.handcore_loader.cfor Windows DLL builds.
- Before calling
- Top ~28 Inlined Hot Opcodes:
- Stack & Constants: Fullword
PUSH_CONST,OP_PUSH(FP/LP/SP-pop/SP-idx/IMM),OP_POP,OP_MOVEM,OP_PUSH_ADDRESS,OP_SET_SP_TO_ADDRESS,OP_SET_SP_TO_ADDRESS_SAVE_TOS. - Branches & Loops: Intra/inter-page
OP_BRANCH,OP_BRANCH_TRUE*/OP_BRANCH_FALSE*(0060..0077),OP_LOOP_DECREMENT_TOS,OP_LOOP_INCREMENT_TOS_LESS_THAN. - Predicates:
OP_EQ/NO_POP,OP_EQL/NO_POP,OP_ZEROP,OP_PLUSP,OP_MINUSP,OP_ENDP,OP_TYPE_MEMBER_*, FixnumOP_LESSP/GREATERP/EQUAL_NUMBER/LOGTEST. - Fixnum ALU & Bitfields: Fixnum
OP_ADD/OP_SUB(jo-> C trap),OP_INCREMENT/DECREMENT,OP_32_BIT_PLUS/DIFFERENCE,OP_LOGAND/LOGIOR/LOGXOR,OP_LDB(rorx+bzhi),OP_DPB,OP_TAG,OP_POINTER_PLUS,OP_POINTER_INCREMENT. - List & Fast Call/Return:
OP_CAR,OP_CDR,OP_SET_TO_CAR,OP_SET_TO_CDR,OP_SET_TO_CDR_PUSH_CAR,DTP_CALL_COMPILED_EVEN/ODD,OP_FINISH_CALL_N,OP_ENTRY_REST_NOT_ACCEPTED,OP_RETURN_SINGLE.
- Stack & Constants: Fullword
5. Implementation Roadmap & Verification Gates
| Phase | Scope & Files | Verification & Gate Criteria |
|---|---|---|
Phase 1: Portable Threaded Engine, 4 GW-Ready IvoryDcache & Timer Batching | Makefile (ISA_MODE ?= runtime), ivory_emu.h, ivory_hw.h, mem.c, cpu.c, isa_lisp.c, loader.c, debug_ctl.c, snapshot.c, new emu/src/cpu_decode.c (+ update test_cpu_core / test_mem link rules in Makefile) | • ISA_MODE=portable & ISA_MODE=runtime pass make -C emu clean all test test-e2e.• sizeof (4096, 32768, 278528) & readelf -WS (0 .data/.bss in core/*.o) pass.• Record Phase 1 MIPS baseline vs current switch interpreter. |
Phase 2: Runtime Dispatch + <immintrin.h> AVX-512 Kernels (Pre-ASM Gate) | New emu/src/cpu_zen4_avx512.c (-march=znver4 / /arch:AVX512), test_cpu_core.c, test_mem.c | • Bit-exact memcmp parity of IvoryDecodedSlot[516] (scalar vs AVX-512) across rom.dump + IFEP-Kernel + edge-case CDR/DTP words.• 1M-VMA randomized ivory_pht_hash & PHT bucket parity tests.• Profiling checkpoint: Measure MIPS & hot-opcode histogram before starting Phase 3. |
| Phase 3: OS-Independent x86-64 Assembly Hot Loop (Linux + Windows x64) | New emu/include/ivory_asm_offsets.h, emu/src/asm_abi.h, emu/src/cpu_zen4_loop.S (~320–380 LOC), Windows DLL export/loader shims in ivory_core_api.h & core_loader.c | • readelf -lW (RW GNU_STACK), readelf -WS (0 .data/.bss), and cross-target clang -target x86_64-pc-windows-msvc -c cpu_zen4_loop.S object check.• 10M+ insn lockstep gate: IVORY_ACCEL=portable vs IVORY_ACCEL=avx512 match instr_count, pc, sp, fp, lp, cr, vram_hash + mid-run live reload swap test. |
| Phase 4: Profile-Guided Tuning & Optional Stretch Goals | Tune ~28 ASM opcode set against live Genera 8.3 profiles; optional AVX-512 .y4m 1bpp->ARGB8888 blitter; optional sparse mmap/VirtualAlloc backing if >127.875 MW / Merlin expansion RAM is enabled | • Final perf stat report (MIPS, L1i/µop-cache hit rate, ITTAGE indirect branch miss rate). |