Expand description
§logicaffeine-jit
The native execution tier for the LOGOS bytecode VM: it translates hot functions and loop regions into forge micro-ops and runs them as x86-64 machine code. Where the VM dispatches one boxed op at a time, a tiered loop runs as one native chain over unboxed slots, and anything the tier cannot prove sound stays on bytecode, so tiering changes speed, not output. Machine code and executable memory belong to logicaffeine-forge; this crate is the bridge and its soundness contract.
Part of the Logicaffeine workspace, tier 5. Native-only: it compiles on x86-64 System V (Linux and macOS) and to nothing elsewhere, where the VM runs bytecode. The execution-tier story is in execution-and-performance.md.
§Role in the workspace
The bytecode VM in logicaffeine-compile profiles function calls and Main-loop back-edges; when something goes hot it asks its installed NativeTier to compile it. This crate is that tier. ForgeTier translates VM bytecode (Op) into the forge’s MicroOp subset, both whole functions (ChainFn) and hot loop regions (RegionChain), compiles each to a native stencil chain or the register-allocating backend via logicaffeine-forge, and hands the compiled unit back.
Anything outside the supported subset (see What tiers) returns None from compile_* and stays on bytecode for good: the deopt contract.
logicaffeine-compile (VM) ──tier seam──▶ logicaffeine-jit ──backend──▶ logicaffeine-forgeIt implements compile’s vm::{NativeTier, NativeFn, RegionFn, Op, Constant, …} traits and calls install_native_tier; it drives forge’s jit::{compile_straightline_*, MicroOp, CompiledChain}, regalloc::*, and segv_trace. Consumed by apps/logicaffeine_cli and the differential logicaffeine-tests.
§What tiers
A value rides a native slot unboxed, by kind:
Int(exact:+/-/*overflow side-exits and the VM promotes to a big integer),Bool,Float;Word32/Word16as the zero-extended value andWord64as its bit pattern, re-boxed throughRegBox::Word32/RegBox::Word64at an exit, a deopt or a function’s return. Same-width modular+/-/*(includingacc += x),xor,&and|stay in the Word; aWord16is consumed only byintOfWord16;- a
chr(code)result as its code point, behind aChrGuardthat side-exits on an invalid Unicode scalar, re-boxed to a one-characterText; - pinned lists of
Int(full or half-widthi32storage),Word32,FloatandBool, anInt-keyed map, ASCII text carried as bytes, and a mutable-text append accumulator (appending a byte, anInt’s decimal text, or a constant); - a node of one of the program’s own enums, as the VM’s own
Rc<InductiveValue>pointer:a new Node with …, anInspectarm’s test and bindings (Int,Bool,Floatand node fields, the kind read from the declared variant and checked at run time), and an enum parameter or return, through runtime helpers theHostmicro-op calls.
Builtin calls lowered natively: sqrt; abs, min, max on Int; count_ones, leading_zeros, trailing_zeros; floor, ceil, round of a Float to an Int (round ties away from zero); pow with an Int base and a constant exponent in 0..=32 (unrolled checked multiplies); word32, word64, word16, word_and, word_or, word_not, word64And, intOfWord16, intOfWord32, intOfWord64, word64Shl, word32Shr, word64Shr, rotl, rotr; and chr, with length of chr(k) as the UTF-8 byte length. An op whose instruction the CPU lacks (popcnt, lzcnt, bmi1, sse4.1) declines to the VM. word8/intOfWord8 decline. crates/logicaffeine_tests/tests/forge_builtin_compliance_ratchet.rs classifies every BuiltinId as tiered, a gap, or host-only, and runs a hot ground-truth program for each tiered one.
§The deopt contract (soundness)
Soundness rests on these legs, all differentially tested in logicaffeine-tests:
- the kind-inference dataflow (
kind_flow): forward and flow-sensitive per pc; a parameter starts at its declared kind, constants carry their pool type, comparisons areBool, arithmetic promotes as the semantics core does (Int×Int→Int, anyFloat→Float, same-width Word→Word); merges join per slot (Unknown ⊔ k = k, conflict →Mixed, bail on use). List-ness is read per pc (holds_list_at), so a register the bytecode compiler reuses for anIntand a list is never treated as a list where it holds theInt; - per-call / per-entry guards: an argument whose discriminant does not match the declared parameter kind routes the call back to bytecode;
- the region write-back contract: incoming-dead scratch needs no guard; writes re-box by inferred kind;
- list ownership: a store into a list that may be shared (a parameter’s, or a self-call’s result) first copies it through
logos_rt_list_own, the native twin of the VM’s copy-on-write; at a deopt every alias of one native-owned list re-boxes to one shared value; - a region that reads a list element and can
Returnout of the function declines to the VM; - node ownership (
inductive.rs), a forward dataflow per register: a parameter, and a field read out of one, is borrowed and costs no refcount traffic; a node the function builds, a call’s result and a field of an owned node carry one strong count, which moves into a new node or the return value at its last use, or is released on the control-flow edge where its register dies (a landing pad on a branch’s taken edge). Where a borrowed node and an owned one meet in one register, the borrowed copies take a count of their own; an owned node meeting a value that is not one keeps the function on bytecode. A side exit hands every node back to the VM: an owned one transfers its count, a borrowed one is shared.
Two deopt flavors: classic discard-and-replay-from-head (sound for replay-idempotent regions; the VM rolls pinned buffers back to entry length), and precise DeoptAt, which materializes the native frame and resumes at the faulting op, as push and in-place SetIndex worklist shapes require. Every reachable pc of a precise function is a resume point, so an Int overflow anywhere in a list-parameter or enum function resumes on the VM, and a reachable ReturnNothing (the fall-through after an Inspect whose arms cover every variant) side-exits so the VM returns Nothing from the same pc. A const build assert pins the semantics core’s MAX_CALL_DEPTH to the forge’s baked call-depth so deep native recursion can never side-exit at the wrong depth.
§Public API
pub mod image: build a self-contained, versioned bytecode image withimage::build, then decode and execute it through a caller-suppliedForgeTierwithimage::run; native machine code is never serialized.pub fn install() -> &'static ForgeTier: install the forge tier process-wide. Idempotent (OnceLock); call once at startup.LOGOS_NATIVE_TIER=0returns the tier without wiring it into the VM.pub fn segv_trace_install(): arm the diagnostic SIGSEGV/SIGBUS tracer (no-op unlessLOGOS_SEGV_TRAPis set).pub struct ForgeTier(impl NativeTier;ForgeTier::new()), the forge-backed tier with compile observability:function_counts() -> (u32, u32),region_counts() -> (u32, u32),pinned_self_call_count() -> u32,regalloc_region_count() -> u32,regalloc_precise_region_count() -> u32,regalloc_function_count() -> u32, andruntime_stats() -> (u64, u64, u64, u64)(entries, completions, deopts, precise_deopts: actual VM↔native crossings).pub fn adapt(ops: &[Op], constants: &[Constant], register_count: usize) -> Option<(Vec<MicroOp>, usize)>: translate a whole-program Main body (terminalShow; Halt) into the micro subset.pub fn native_alloc_registry_len() -> usize,pub static REGION_RUNS/REGION_DEOPTS: AtomicU64,pub const LOGOS_MEMMEM_DEOPT: i64 = i64::MIN(the memmem-failure sentinel).logos_rt_*pub unsafe extern "C"runtime helpers the stencils call by baked address (no relocations):alloc_list_i64,list_triple,list_own(copy-on-write of a shared list),push_{i64,i32,f64,bool},clear_{i64,i32,f64,bool},map_{get_ii,set_ii,has_i},str_append(mirrors the VM’sadd_assignCOW exactly),memmem/memmem_frame, andside_exit(aHosthelper that always side-exits).
§Internals
lib.rs, plus inductive.rs for the enum lane (the ownership dataflow, the payload-kind seeding from the program’s declared enum types, and the node helpers). ChainFn::call runs the chain on a 2²¹-slot thread-local arena, handling Return / classic Deopt / precise DeoptAt (materialize walks the live native frames). RegionChain carries guard / free / write / array sets, hoist guards, and per-resume-pc re-box kinds. adapt_function (scalar and precise list-parameter forms) and adapt_region lower to MicroOp over the narrow Kind lattice (Int/Bool/Float, Word32/Word64/Word16, a chr code point, pinned Int/Word32/Float/Bool lists incl. half-width i32, maps, ASCII text-as-bytes and single ASCII bytes, mutable-text and constant-text append operands). They run a loop-depth-weighted linear-scan pin selector (select_pins), apply array/float fusions (RMW, two-buffer load, FMA, cond/uncond swap, affine index), then prefer the regalloc backend over the per-piece stencil tier. A thread-local ALLOC_REGISTRY owns every fresh list: success detaches the returned one, deopt drains all, so replay is leak-free.
§Usage
logicaffeine_jit::segv_trace_install();
if std::env::var_os("LOGOS_NO_JIT").is_none() {
logicaffeine_jit::install();
}LOGOS_NO_JIT is the caller-side gate (apps/logicaffeine_cli’s convention); the crate’s own kill switch is LOGOS_NATIVE_TIER=0 inside install(). Live VM constructors in logicaffeine-compile then pick the tier up for every program they run.
§Tests & env knobs
The unit tests live in the #[cfg(test)] modules of lib.rs, their bodies in crates/logicaffeine_tests/unit/logicaffeine_jit/ behind one-line #[path] stubs: memmem_safety_tests (substring-scan memory-safety guards), select_pins_tests (pin-budget soundness, e.g. a float result reused as an integer array index must not be float-pinned), and fuse_rmw_tests, fuse_ld2_tests, fuse_affine_tests (the array/float fusion peepholes). The end-to-end VM↔native byte-equivalence and deopt-replay tests live in logicaffeine-tests.
cargo nextest run -p logicaffeine-jit # this crate's unit tests (native-only, no Z3)
./scripts/run-all-tests-fast.sh # full workspace, parity-proven nextest runnerThe crate’s own knobs are below; forge’s are in its README. Each is a diagnostic or a kill switch, and every kill switch falls back byte-identically to the per-piece tier (or to bytecode):
| Variable | Effect |
|---|---|
LOGOS_NATIVE_TIER=0 | install() skips wiring the tier into the VM, isolating pure-bytecode wall time. |
LOGOS_SEGV_TRAP (set) | arm the SIGSEGV/SIGBUS tracer from segv_trace_install() to localize faults in JIT’d code. |
LOGOS_JIT_REGALLOC=0 / LOGOS_REGALLOC=0 | disable the register-allocating backend (function + region). |
LOGOS_REGALLOC_PRECISE=0 | disable its precise list-parameter path (in-place SetIndex). |
LOGOS_LEVERB=0 | stop tiering regions that call a list-parameter function. |
LOGOS_JIT_NODES=0 | keep every function that handles enum values on bytecode. |
LOGOS_MEMMEM=0 | disable the memmem substring idiom. |
LOGOS_COPYPROP/LOGOS_RMW/LOGOS_LD2/LOGOS_FMA/LOGOS_CONDSWAP/LOGOS_SWAP/LOGOS_AFFINE =0 | disable the matching fusion / copy-prop pass (all default on). |
LOGOS_NO_PINNED_ARGS (set) | disable pinned-argument passing into compiled functions. |
LOGOS_ARRPTR (set) | allow array-pointer GP pinning when fewer than 4 GP pins are in use. |
LOGOS_JIT_TRACE (set) | trace tier-up decisions. |
LOGOS_RDIAG (set) | region adapter diagnostics. |
LOGOS_FUSE_TRACE (set) | trace the fusion passes. |
LOGOS_DUMP_REGION=<head_pc> | dump the region whose head pc matches. |
LOGOS_DUMP_MICRO=<head_pc> | dump the lowered MicroOp stream for that head pc. |
§Dependencies
- Internal:
logicaffeine-compile(the VM, trait seam) on every target;logicaffeine-forge(executable memory, stencils, regalloc, segv_trace) only undercfg(all(target_arch = "x86_64", not(target_os = "windows"))). - External: none beyond the standard library.
§License
MIT License — see LICENSE.md.
Modules§
- image
- Build and execute self-contained optimized bytecode images. Precompiled bytecode images for the native JIT.
Structs§
- Forge
Tier - The forge-backed native tier, with compile observability.
- JitBackend
Optimization Trace - Stage-separated evidence for one execution through the production run-optimizer -> VM -> forge-JIT pipeline.
- JitOptimization
Trace - Monotonic firing counts. Snapshot before and after one benchmark run and subtract to obtain that program’s exact native-JIT optimization trace.
Enums§
- JitOptimization
- Native-only JIT optimizations which run after LOGOS bytecode has been
produced. These cannot honestly share an
Optbit with the Rust emitter: they transform JIT micro-ops, so they have their own named trace and are reported alongside the shared compiler trace.
Constants§
- LOGOS_
MEMMEM_ DEOPT - The deopt sentinel
logos_rt_memmemreturns when the recognized search nest would, on bytecode, take an access the helper cannot reproduce in-bounds — a checked needle index past the needle buffer (needleLen > len(needle)). The caller’s stencil routes this to a side exit so the VM replays from the region head on bytecode and raises the EXACT same error at the EXACT same point.i64::MINis never a legitimate count (a count is in[0, haystack_len]).
Statics§
Functions§
- adapt
- Translate WHOLE-PROGRAM Main bytecode into the J2 micro-op subset.
- install
- logos_
rt_ ⚠adopt_ list_ i64 - Adopt a list-returning callee’s Vec into a region’s pinned destination. The two input slots hold the returned and destination handles. An owned result moves; a borrowed result is copied. Pin refresh is a separate ListTriple micro-op, so every frame access is visible to code generation.
- logos_
rt_ ⚠alloc_ list_ i64 - Allocate a fresh Int list and plant its pin triple.
- logos_
rt_ ⚠alloc_ list_ i64_ fixed - Allocate a proof-sized Int list. The adapter places the capacity in
len_slot; this helper consumes it and restores the observable length 0. - logos_
rt_ ⚠alloc_ scope_ enter - Start one native function’s allocation lifetime.
- logos_
rt_ ⚠alloc_ scope_ leave - Release one native function’s scratch allocations, retaining its exported list handles for the caller. The first input is the return word; the rest are final mutable list parameters. A nonzero imm marks a scalar return.
- logos_
rt_ ⚠clear_ bool - See
logos_rt_clear_i64—Vec<bool>buffer. - logos_
rt_ ⚠clear_ f64 - See
logos_rt_clear_i64—Vec<f64>buffer. - logos_
rt_ ⚠clear_ i32 - See
logos_rt_clear_i64— half-widthVec<i32>buffer. - logos_
rt_ ⚠clear_ i64 - In-place clear of a pinned list:
vec.clear()(truncate to empty, KEEP the buffer/capacity) and refresh the pinned ptr/len slots (ptr unchanged — clear never reallocs — but refreshed for parity with push). Lowers an in-regionNewEmptyListon a pinned array: an in-place mutation (like SetIndex), so the PRECISE region resumes over it soundly. Seelogos_rt_push_i64for the frame-slot convention. - logos_
rt_ ⚠list_ own - Copy-on-write: give the list in
frame[handle_slot]its own registry-owned buffer — a copy of the shared one — and re-plant the register’s handle and pin triple on it. The native twin of the VM’s first write to a shared list; the original (a parameter’s, or a caller’s through a passthrough) is untouched from here on. - logos_
rt_ ⚠list_ triple - Plant the pin triple for a list handle RETURNED by a self-call (the caller’s view of the callee’s result list).
- logos_
rt_ ⚠map_ get_ ii - logos_
rt_ ⚠map_ has_ i - Map membership for an Int key.
- logos_
rt_ ⚠map_ set_ ii - Map insert on the kernel’s own storage — identical hashing, identical iteration order.
- logos_
rt_ ⚠memmem - Count OVERLAPPING occurrences of an ASCII needle in an ASCII haystack,
reproducing the LOGOS naive-search nest BIT-IDENTICALLY (the string_search
benchmark idiom). The recognizer in
adapt_regioncollapses the per-byte nested-loop region to a single call to this helper. - logos_
rt_ ⚠memmem_ frame - Frame-driven entry the
MicroOp::MemMemstencil calls: reads the search nest’s live values out of the JIT frame, runslogos_rt_memmem, and on success ADDS the count intocount_slotand advancesi_slotto the loop’s exit value (bound + 1). Returns1on success and0on the deopt sentinel — the stencil routes0to its side-exit continuation, untouched. - logos_
rt_ ⚠push_ bool - See
logos_rt_push_i64— nonzero storestrue. - logos_
rt_ ⚠push_ f64 - See
logos_rt_push_i64— f64 value travels as bits. - logos_
rt_ ⚠push_ i32 - Push helper for pinned half-width Int lists (
ListRepr::IntsI32=Vec<i32>): the value TRUNCATES to its low 4 bytes. The narrowing proof guarantees every pushed value fitsi32, so the truncation is lossless;debug_assertcatches a proof violation in test builds. The refreshedptr_slotis theVec<i32>element buffer (4-byte stride — the stencil and regalloc loadsmovsxdfrom it). - logos_
rt_ ⚠push_ i64 - Push helper for pinned Int lists.
- logos_
rt_ ⚠region_ alloc_ reset - Reclaim native lists whose allocation-site registers are dead at the hot loop backedge. The region adapter emits this only when every allocation destination is non-live-in and has no list-handle copy/rebind.
- logos_
rt_ ⚠side_ exit - An unconditional side exit: answers 0, so a precise chain resumes on the VM at the op that holds it.
- logos_
rt_ ⚠str_ append - MUTABLE-Text append helper for the
MicroOp::StrAppendregalloc lowering of aSet text to text + <s>build loop.frame[handle_slot]holds a*mut Valuepointing AT THE VM REGISTER CELL holding the accumulator (planted at region entry).src/src_lencarry the appended operand: - native_
alloc_ registry_ len - Registry depth — drained-to-zero is part of every boundary’s contract (asserted by the test gates).
- native_
alloc_ scope_ counts - Cumulative scope entries and successful leaves.
- native_
alloc_ scope_ depth - Native allocation-scope depth. Success and deopt boundaries restore this to zero; exposed so parity tests can lock the lifetime invariant.
- native_
region_ alloc_ reset_ count - Number of hot-loop iteration boundaries that reclaimed dead native list temporaries. Exposed for the benchmark-shape lock test.
- optimization_
trace_ jit - Execute through the production eager optimizer and a fresh private forge
tier, returning both shared-pass and native-lowering evidence. Native
refusals enter the common fallback channel as
Jit -> Vm, so a missed tier can no longer hide behind a successful bytecode completion. - segv_
trace_ install - Install the forge tier as the process-wide native tier. Idempotent — the first call wins; later calls return the already-installed tier.