Skip to main content

logicaffeine_compile/vm/
native_tier.rs

1//! Tier-up seam: the VM profiles calls and hands HOT functions to a pluggable
2//! native backend. The backend (the copy-and-patch JIT in
3//! `logicaffeine_forge`) is injected as a trait object by whatever binary
4//! links both crates — this crate publishes no new dependencies, and WASM
5//! builds simply never install a tier.
6//!
7//! Deopt contract: the native code only handles the integer subset, so the
8//! call site GUARDS — if any argument is not an Int, or compilation bailed,
9//! the bytecode path runs instead. Both paths are differentially tested to
10//! produce identical outcomes.
11
12use std::sync::atomic::{AtomicI64, Ordering};
13use std::sync::Arc;
14
15use serde::{Deserialize, Serialize};
16
17use super::instruction::{Constant, EnumTypeDef, Op};
18use super::value::Value;
19
20/// The per-program native ENTRY TABLE (EXODIA 4.7's hot-swap seam): two
21/// atomic slots per function — [entry pointer, register count] — written
22/// when a function's chain compiles, read by native call stencils through a
23/// patched slot address, and the place Tier-2 swaps optimized code in. The
24/// backing Vec never reallocates (fixed at construction), so slot addresses
25/// are stable for the program's lifetime.
26#[derive(Debug)]
27pub struct FnTable {
28    slots: Vec<AtomicI64>,
29}
30
31impl FnTable {
32    pub fn new(functions: usize) -> Self {
33        FnTable {
34            slots: (0..functions * 2).map(|_| AtomicI64::new(0)).collect(),
35        }
36    }
37
38    /// Publish a compiled entry (pointer + callee register count).
39    pub fn publish(&self, fi: usize, entry: i64, register_count: i64) {
40        self.slots[fi * 2 + 1].store(register_count, Ordering::Release);
41        self.slots[fi * 2].store(entry, Ordering::Release);
42    }
43
44    /// The address of function `fi`'s [entry, regcount] slot pair — patched
45    /// into call stencils as an immediate.
46    pub fn slot_addr(&self, fi: usize) -> i64 {
47        &self.slots[fi * 2] as *const AtomicI64 as i64
48    }
49}
50
51/// Per-program cells the native tier shares with every chain it compiles:
52/// the deopt status (any side-exit anywhere unwinds the whole native stack),
53/// and the LIVE LOGOS DEPTH the call stencils count against MAX_CALL_DEPTH.
54/// `Clone` is an `Arc` bump on each cell — a background-compile request carries a
55/// clone so the worker patches the same per-program table/status/depth the
56/// interpreter does.
57#[derive(Debug, Clone)]
58pub struct NativeCtx {
59    pub table: Arc<FnTable>,
60    pub status: Arc<AtomicI64>,
61    pub depth: Arc<AtomicI64>,
62}
63
64/// What one native function call produced.
65#[derive(Debug)]
66pub enum NativeOutcome {
67    /// A fully re-boxed return value (list-returning functions: the
68    /// backend owns the re-boxing because the allocation registry lives
69    /// on its side).
70    ReturnValue(Value),
71    /// Precise side exit: effects already landed stay landed; the VM
72    /// materializes `frames` as real CallFrames and resumes interpreting
73    /// at `resume_pc` (region-grade deopt for functions).
74    DeoptAt {
75        resume_pc: usize,
76        frames: Vec<NativeFrame>,
77    },
78    /// The function ran to its return.
79    Return(i64),
80    /// A checked op side-exited (zero divisor). The native code touched only
81    /// its private frame, and every adaptable body is effect-free, so the
82    /// caller simply re-runs the call on bytecode — where the kernel raises
83    /// the exact error at the exact point.
84    Deopt,
85}
86
87/// A final mutable argument: raw scalar bits or a borrowed list handle, or an
88/// owned value detached from the native allocation registry before it is drained.
89#[derive(Debug)]
90pub enum NativeWriteback {
91    Raw(i64),
92    Value(Value),
93}
94
95/// What one native region run produced.
96#[derive(Debug)]
97pub enum RegionOutcome {
98    /// The region ran to its exit; write-back may proceed.
99    Completed,
100    /// Side exit: discard the private frame (NO write-back) and let the
101    /// bytecode loop re-run from the head — VM registers are untouched, so
102    /// the replay recomputes deterministically up to the faulting op.
103    Deopt,
104    /// PRECISE side exit: the region's non-array scalar registers are live in
105    /// the frame; materialize them into the VM registers and resume the
106    /// bytecode AT `resume_pc` (the faulting op) — no replay-from-head, no
107    /// buffer truncate. This is the contract that lets a region with a
108    /// `ListPush` coexisting with an in-place `SetIndex` (BFS-style worklists)
109    /// tier up soundly: completed iterations' effects stand, and the faulting
110    /// op re-runs once on bytecode (raising the exact error or continuing).
111    DeoptAt { resume_pc: usize },
112    /// A native callee stopped inside this region's call. Restore the region
113    /// at the call site, then install the callee frames before resuming it.
114    DeoptCall {
115        call_pc: usize,
116        resume_pc: usize,
117        frames: Vec<NativeFrame>,
118    },
119}
120
121/// A `Return` statement INSIDE the region (the siftDown early-exit shape):
122/// the value slot, its re-boxing kind, and the flag slot the return path
123/// sets — after write-back the VM performs the actual function return.
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125pub struct RegionReturn {
126    pub flag_slot: u16,
127    pub value_slot: u16,
128    pub kind: RegionReturnKind,
129}
130
131/// How a region-return value travels.
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub enum RegionReturnKind {
134    /// The value slot holds the raw representation, re-boxed by SlotKind.
135    Slot(SlotKind),
136    /// The value slot holds a VM REGISTER NUMBER whose current value
137    /// returns (lists: mutated in place through their pins, the register
138    /// still holds the same Rc).
139    Register,
140}
141
142/// A natively-compiled function: integer registers in, integer result out.
143/// `depth` is the LIVE LOGOS frame count at the call (the callee's own frame
144/// included) — native self-calls count against the same MAX_CALL_DEPTH the
145/// bytecode enforces.
146pub trait NativeFn: Send + Sync {
147    /// `args` are the marshalled parameter slots (scalars by value, floats
148    /// as bits, list params as don't-care placeholders); `pins` are the
149    /// pre-extracted `[vec_handle, ptr, len]` triples, one per list
150    /// parameter in declaration order, landing in the frame's pin slots.
151    fn call(&self, args: &[i64], pins: &[i64], depth: usize) -> NativeOutcome;
152    /// On success, return each requested final argument exactly once. A list
153    /// output must either own a boxed value or be one of the boundary pin handles;
154    /// native temporary storage must remain valid until ownership is transferred.
155    /// A precise deopt carries output state in its frames instead. Backends
156    /// without an output-argument ABI decline before executing such a call.
157    fn call_with_writeback(
158        &self,
159        args: &[i64],
160        pins: &[i64],
161        depth: usize,
162        slots: &[u16],
163        writeback: &mut Vec<(u16, NativeWriteback)>,
164    ) -> NativeOutcome {
165        let _ = writeback;
166        if slots.is_empty() {
167            self.call(args, pins, depth)
168        } else {
169            NativeOutcome::Deopt
170        }
171    }
172
173    /// Materialize a precise side exit from a call made by a native region.
174    /// The frame starts at this function's entry window; pins name the
175    /// region's borrowed buffers. Owned values must detach before cleanup.
176    fn materialize_side_exit(
177        &self,
178        _status: i64,
179        _entry_depth: usize,
180        _frame: &[i64],
181        _pins: &[i64],
182    ) -> Option<NativeOutcome> {
183        None
184    }
185
186    /// How the result re-boxes: a scalar from the raw i64, or the IDENTITY
187    /// of one of the caller's list arguments (return-by-parameter).
188    fn ret(&self) -> NativeRet {
189        NativeRet::Scalar(SlotKind::Int)
190    }
191    /// The chain's entry pointer, for the program's [`FnTable`].
192    fn entry_ptr(&self) -> i64;
193    /// The regcount value to PUBLISH next to the entry pointer:
194    /// `frame_size − 3`, which the call stencil's bound math and limit
195    /// planting are calibrated against (the plain register count for the
196    /// classic layout).
197    fn published_regc(&self) -> i64;
198    /// The machine code behind this function, as `(start address, length)` extents — what the
199    /// `LOGOS_PERF_MAP` symbol map names. Default: none to report.
200    fn code_extents(&self) -> Vec<(usize, usize)> {
201        Vec::new()
202    }
203}
204
205/// How a native function's return value re-boxes.
206#[derive(Debug, Clone, Copy, PartialEq, Eq)]
207pub enum NativeRet {
208    Scalar(SlotKind),
209    /// The function returns its j-th parameter (a list passed through —
210    /// the caller re-boxes by cloning the argument's Rc, preserving
211    /// identity).
212    ListParam(u8),
213    /// The function returns a list BY VEC HANDLE: a registry-owned fresh
214    /// allocation (detach and wrap) or one of the caller's list arguments
215    /// (match the pin handles, clone that argument). The backend resolves
216    /// it and emits [`NativeOutcome::ReturnValue`].
217    ListByHandle,
218    /// The function returns one of the program's enum values: the raw result is an
219    /// `Rc::into_raw(Rc<InductiveValue>)` pointer carrying one strong count, which the caller
220    /// takes over. The other half of [`ParamKind::Inductive`]'s protocol.
221    Inductive,
222}
223
224/// A DECLARED parameter's native representation.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
226pub enum ParamKind {
227    Scalar(SlotKind),
228    /// `Seq of <scalar>` — pinned at the boundary exactly like a region
229    /// array (one borrow for the whole call, buffer pointer + length in
230    /// dedicated frame slots).
231    List(PinElem),
232    /// One of the program's own enum types. The argument travels as `Rc::as_ptr` of the VM's
233    /// shared node: BORROWED for the whole call, since the caller's register keeps the node
234    /// alive and a node is never mutated. Native code that keeps a node past the call, by
235    /// storing it in a new node or returning it, takes its own strong count.
236    Inductive,
237}
238
239/// One materialized native frame for a PRECISE deopt (outermost first).
240/// `offset`/`return_pc`/`return_reg` describe the link from the PREVIOUS
241/// frame (they are meaningless for index 0, whose link belongs to the
242/// interpreted call site).
243#[derive(Debug)]
244pub struct NativeFrame {
245    pub offset: usize,
246    pub return_pc: usize,
247    pub return_reg: u16,
248    pub regs: Vec<i64>,
249    pub kinds: Vec<RegBox>,
250    /// Registers whose values the BACKEND already re-boxed (native-owned
251    /// fresh lists detached from the allocation registry at deopt — they
252    /// must survive into the materialized frame).
253    pub resolved: Vec<(u16, Value)>,
254}
255
256/// How one raw register slot re-boxes during frame materialization.
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub enum RegBox {
259    /// A live empty loan slot.
260    Nothing,
261    /// Not defined at this point — leave the register as Nothing.
262    Dead,
263    Int,
264    Bool,
265    Float,
266    /// A `Word32` carried unboxed as its zero-extended `u32` value — re-boxes to
267    /// `RuntimeValue::Word(WordVal::W32(Word32(bits as u32)))`.
268    Word32,
269    /// A `Word64` carried unboxed as its 64-bit pattern — re-boxes to
270    /// `RuntimeValue::Word(WordVal::W64(Word64(bits as u64)))`.
271    Word64,
272    /// A `chr(code)` result carried unboxed as a (guaranteed-valid) Unicode scalar code point — re-boxes to
273    /// a 1-char `Text`. The producing native op deopts on an invalid code, so `char::from_u32` never fails.
274    CharText,
275    /// Holds the identity of list parameter j.
276    ListParam(u8),
277    /// Backend-resolved (see [`NativeFrame::resolved`]); the kind row
278    /// entry is a placeholder.
279    Resolved,
280}
281
282/// A backend that can try to compile one VM function to native code.
283pub trait NativeTier: Send + Sync {
284    /// Attempt to compile the function whose bytecode is `code`
285    /// (`code[0]` is the instruction at `entry_pc`; jump targets inside are
286    /// ABSOLUTE program pcs and need rebasing by `entry_pc`). Return None to
287    /// leave the function on the bytecode path forever.
288    ///
289    /// `enums` is the program's declared enum types, the payload kinds an `Inspect` arm binds.
290    ///
291    /// `callees` carries every program function's declared signature,
292    /// indexed by `FuncIdx` — calls to OTHER functions compile to table
293    /// dispatch when the callee's signature is all-scalar (an unpublished
294    /// callee deopts at the call until it tiers up on its own).
295    ///
296    /// `cow_exempt_regs` is the function's `CompiledFunction::cow_exempt_regs` — the ONLY registers
297    /// the VM writes a shared list through in place. Every other shared list is copied on its first
298    /// write, so a backend that stores into a list in place must prove the target is unshared or in
299    /// this set, or leave the function on bytecode.
300    #[allow(clippy::too_many_arguments)]
301    fn compile_function(
302        &self,
303        code: &[Op],
304        entry_pc: usize,
305        constants: &[Constant],
306        enums: &[EnumTypeDef],
307        param_count: u16,
308        register_count: u16,
309        self_fi: u16,
310        param_kinds: &[Option<ParamKind>],
311        cow_exempt_regs: &[u16],
312        ret_kind: Option<SlotKind>,
313        ctx: &NativeCtx,
314        callees: &[CalleeSig],
315    ) -> Option<Box<dyn NativeFn>>;
316
317    /// Attempt to compile a loop region. `code[0]` is the op at `head_pc`
318    /// (the back-edge target); the slice ends at the back-edge jump
319    /// (inclusive). Every jump out of the region must target `exit_pc`.
320    /// `named[r]` marks frame registers carrying a user-visible name — the
321    /// only slots whose post-region values are observable (scratches are
322    /// dead at statement boundaries by the compiler's allocation
323    /// discipline). `observed[r]` is the register's runtime kind at this hot
324    /// crossing — the speculation seed, re-checked by the guard set on every
325    /// entry. Default: regions stay on bytecode.
326    fn compile_region(
327        &self,
328        code: &[Op],
329        head_pc: usize,
330        exit_pc: usize,
331        constants: &[Constant],
332        register_count: u16,
333        named: &[bool],
334        observed: &[ObservedKind],
335        ctx: &NativeCtx,
336        callees: &[CalleeSig],
337    ) -> Option<Box<dyn RegionFn>> {
338        let _ = (
339            code,
340            head_pc,
341            exit_pc,
342            constants,
343            register_count,
344            named,
345            observed,
346            ctx,
347            callees,
348        );
349        None
350    }
351
352    /// The name this tier reports under `LOGOS_ENGINE_TRACE`.
353    fn engine_name(&self) -> &'static str {
354        "native"
355    }
356
357    /// Native compilation coverage accumulated by this tier.
358    fn compile_summary(&self) -> String {
359        String::new()
360    }
361
362    /// Stable reasons why attempted native compilations declined.
363    fn decline_summary(&self) -> String {
364        String::new()
365    }
366
367    /// Native-only optimizations that actually fired.
368    fn optimization_summary(&self) -> String {
369        String::new()
370    }
371
372    /// Actual native entries, completions and deoptimizations.
373    fn execution_summary(&self) -> String {
374        String::new()
375    }
376}
377
378/// The runtime kind a native frame slot carries: entry guards check the VM
379/// register's discriminant against it and copy the raw representation in
380/// (f64 travels as bits); write-back re-boxes by it.
381#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
382pub enum SlotKind {
383    Int,
384    Bool,
385    Float,
386    /// A `chr(code)` result carried as a (guaranteed-valid) Unicode scalar code point; write-back re-boxes
387    /// it to a 1-char `Text`. Valid ONLY as a region OUTPUT (write-back) — the region gate rejects it as a
388    /// live-in guard input (a `chr` result never enters a region from the VM side).
389    CharText,
390    /// A `Word32`/`Word16` ring value carried UNBOXED as a zero-extended masked `i64` (`0 ≤ slot < 2³²`).
391    /// UNLIKE `CharText`, this is BIDIRECTIONAL: the entry guard verifies the VM register is a
392    /// `RuntimeValue::Word(W32)` and copies its masked value in, and write-back re-boxes the low 32 bits to
393    /// `RuntimeValue::Word(W32(...))`. This is what lets a loop-carried Word (a `sha256`/MD5 hash word
394    /// `h0..h7`) tier as region state.
395    Word32,
396    /// A `Word64` ring value carried UNBOXED as the full 64-bit pattern in the `i64` slot. Bidirectional:
397    /// the entry guard verifies a `RuntimeValue::Word(W64)` and copies its bits in; write-back re-boxes to
398    /// `RuntimeValue::Word(W64(...))`.
399    Word64,
400}
401
402/// What the VM OBSERVED in each register at the hot back-edge that triggered
403/// region compilation — the kinds the adapter SPECULATES on (sound because
404/// every later entry re-checks them via the guard set).
405#[derive(Clone, Copy, Debug, PartialEq, Eq)]
406pub enum ObservedKind {
407    Int,
408    Bool,
409    Float,
410    /// A List whose payload is the unboxed all-Int repr.
411    IntList,
412    /// A List whose payload is the half-width (`Vec<i32>`) narrowed Int repr
413    /// (`ListRepr::IntsI32`). Pinned as a 4-byte-element buffer (sign-extending
414    /// loads, truncating stores) under `LOGOS_NARROW_VM`.
415    IntListI32,
416    /// A List whose payload is the unboxed all-Float repr.
417    FloatList,
418    /// A List whose payload is the unboxed all-Bool repr.
419    BoolList,
420    /// A Map (the boxed kernel storage rides a pinned pointer; the int
421    /// fast lane verifies keys/values per helper call).
422    Map,
423    /// An ASCII `Text` carried AS BYTES: char index == byte index and char
424    /// count == byte length, so `item i of text` is a pinned 1-byte load and
425    /// char compares are integer byte compares. Observed ONLY when the Text is
426    /// ASCII; a non-ASCII Text stays [`ObservedKind::Other`] (keeps bailing) so
427    /// the per-char decode path runs and the JIT can never diverge.
428    TextBytes,
429    /// A `Word32`/`Word16` ring value (`RuntimeValue::Word(W32)`) observed at the hot crossing — carried
430    /// UNBOXED as a zero-extended masked `i64`. Lets a loop-carried Word (a hash accumulator) tier.
431    Word32,
432    /// A `Word64` ring value (`RuntimeValue::Word(W64)`) observed at the hot crossing — carried as the full
433    /// 64-bit pattern in the `i64` slot.
434    Word64,
435    /// A packed `Word32` LIST (`ListRepr::Words32`) — pins with the IntList buffer machinery (masked `i64`
436    /// elements); an indexed read is tagged `Word32`. Lets a `Seq of Word32` table pin + tier.
437    Word32List,
438    /// Anything the native frame cannot carry (non-ASCII Text, boxed lists,
439    /// Nothing…).
440    Other,
441}
442
443/// One pinned array for a region run: the register holding the list, the
444/// frame slots that receive its buffer pointer and length at entry, and the
445/// element kind the region speculated on. The VM borrows each DISTINCT
446/// `Rc<RefCell<…>>` exactly once for the whole native run (aliased registers
447/// resolve to the same buffer, so native writes through one name are visible
448/// through every other — and there is zero refcount or borrow traffic inside
449/// the loop). Arrays mutate IN PLACE: no write-back, and the deopt replay is
450/// sound by prefix-idempotence (the replay recomputes exactly the values the
451/// native prefix already wrote).
452/// Element kind of a pinned buffer (decides the stencil's access width:
453/// 8-byte for Int/Float bits, 1-byte for Bool).
454#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
455pub enum PinElem {
456    Int,
457    /// A pinned half-width Int buffer (`ListRepr::IntsI32` = `Vec<i32>`): the
458    /// stencil/regalloc access width is 4 bytes — loads sign-extend (`movsxd`),
459    /// stores truncate the low 4 bytes. The narrowing proof guarantees every
460    /// stored value fits `i32`, so truncation is lossless; a region-entry pin
461    /// only admits an `IntsI32` buffer for this lane.
462    IntI32,
463    /// A pinned packed `Word32` buffer (`ListRepr::Words32` = masked values in `Vec<i64>`): the load/store
464    /// width and stencils are IDENTICAL to [`PinElem::Int`] (8-byte); the ONLY difference is that an indexed
465    /// read is tagged `Word32` (not `Int`), so the Word ops downstream accept it. Read pattern of a sha256
466    /// message schedule / round-constant table.
467    Word32,
468    Float,
469    Bool,
470    /// A pinned MAP: `vec_slot` carries `&mut MapStorage as *mut _`;
471    /// the ptr/len slots are unused. Get/set/contains go through pure
472    /// helpers against the kernel's own storage (iteration order is
473    /// untouched by construction).
474    Map,
475    /// A pinned ASCII `Text` carried AS BYTES: `ptr_slot` receives the string's
476    /// byte buffer pointer (`Rc<String>::as_bytes().as_ptr()`) and `len_slot`
477    /// its BYTE length (== char count for ASCII). Read-only — the `Rc<String>`
478    /// is never mutated in place, so no snapshot/rollback applies; the entry
479    /// pin RE-CHECKS ASCII and declines (deopt) on a non-ASCII Text.
480    TextBytes,
481    /// A pinned MUTABLE `Text` accumulator (`Set text to text + ch`): `vec_slot`
482    /// receives a `*mut Value` pointing AT THE VM REGISTER CELL (the cell is
483    /// stable for the whole native run, even though the `Rc<String>` inside it
484    /// reallocs/COWs on append). The `ptr_slot`/`len_slot` are unused. The
485    /// `logos_rt_str_append` helper grows the accumulator THROUGH this pointer
486    /// with EXACTLY the VM's `add_assign` semantics — in place when the
487    /// `Rc<String>` is sole-owned, copy-on-write (a fresh `Rc` written back into
488    /// the cell, the alias untouched) otherwise — so the tiered run is
489    /// bit-identical to the tree-walker for every alias case. The entry pin
490    /// declines (deopt to bytecode) if the observed value is not a `Text`. A
491    /// classic replay-from-head `Deopt` is NOT replay-idempotent over an
492    /// already-grown accumulator (it would double-append), so the VM SNAPSHOTS
493    /// the register's `Value` on entry and restores it before a classic replay
494    /// (see [`ArrayPin::mutated`]); a precise region resumes at the faulting op
495    /// and keeps the live grown value.
496    TextMut,
497}
498
499#[derive(Clone, Copy, Debug, PartialEq, Eq)]
500pub struct ArrayPin {
501    pub reg: u16,
502    /// Frame slot receiving `&mut Vec<…> as *mut _ as i64` — the handle the
503    /// push helper extends through.
504    pub vec_slot: u16,
505    pub ptr_slot: u16,
506    pub len_slot: u16,
507    pub elem: PinElem,
508    /// This register participates in an in-region list `RevSwap`. Native code
509    /// swaps the pin triples in O(1), so on completion (or precise deopt) the
510    /// VM register must be rebound to the `Rc` whose vector handle ended in
511    /// this pin. Ordinary pinned arrays leave this false and pay no rebind or
512    /// refcount traffic at the region boundary.
513    pub rebound: bool,
514    /// This buffer is written IN PLACE (`SetIndex`) in a region that can take a
515    /// recoverable side exit AND replays from the head on deopt (non-precise).
516    /// Such a write is NOT replay-idempotent (a read-modify-write or swap would
517    /// double-apply), so the VM snapshots this buffer's full contents on region
518    /// entry and restores them on a classic `Deopt` before replaying. Read-only
519    /// buffers, push-only buffers (length truncate suffices), and precise
520    /// regions (resume-at-op, no replay) leave this `false`.
521    pub mutated: bool,
522}
523
524/// A natively-compiled LOOP REGION (OSR-lite): no arguments, no return —
525/// every effect flows through the enclosing frame's registers.
526/// What a REGION needs to know about a function it might call: the
527/// declared signature (all-scalar = replay-pure = inlinable) and the
528/// function index for its table slot.
529#[derive(Debug, Clone)]
530pub struct CalleeSig {
531    /// Explicit mutable outputs, excluding inferred consume-and-return borrows.
532    pub inout_params: Vec<u16>,
533    pub param_kinds: Vec<Option<ParamKind>>,
534    /// Declared scalar return; `None` keeps the callee out of regions.
535    pub ret: Option<SlotKind>,
536    /// Declared list return element kind. This is separate from `ret` because
537    /// scalar returns ride one raw word while list returns ride a Vec handle.
538    /// Only element representations the native tier can materialize are
539    /// present here; `None` also covers void and unsupported composite returns.
540    pub list_ret: Option<PinElem>,
541    /// List-param call admission (a region may call a list-parameter function). Sound only when
542    /// the callee never reallocates a list-param buffer (no `Push` reaching a
543    /// list param) — then the caller's derived raw buffer pointer stays valid
544    /// across the call. `true` ⇒ list args don't move under the call.
545    pub list_params_stable: bool,
546    /// Every `Return` traces (through `Move`s) to a list PARAMETER, so the
547    /// returned handle aliases a passed-in (already-pinned) buffer rather than a
548    /// fresh one. Lets a LIST-returning callee be admitted; a scalar return is
549    /// governed by `ret` and ignores this. `false` for non-list / fresh-list
550    /// / multi-element-kind returns.
551    pub returns_list_param: bool,
552}
553
554/// A hoisted region-entry bounds check (V8 loop bound-check elimination): the
555/// loop's covered accesses run unchecked iff, at entry, the pinned array is
556/// long enough for the whole loop and the induction floor is in range. The VM
557/// declines the region (replays on bytecode) if it fails.
558#[derive(Debug, Clone, Copy)]
559pub struct HoistGuard {
560    /// Frame slot holding the pinned array's length (loaded by the prologue).
561    pub len_slot: u16,
562    /// VM register holding the loop's upper bound.
563    pub bound_reg: u16,
564    /// VM register holding the induction variable (its value at entry is the
565    /// loop's minimum for the remaining run).
566    pub iv_reg: u16,
567    /// `length >= bound + add_max` (max access index over the loop).
568    pub add_max: i32,
569    /// `iv + add_min >= 1` (min access index over the loop, 1-based).
570    pub add_min: i32,
571}
572
573pub trait RegionFn: Send + Sync {
574    /// Slots whose CURRENT values the region may read before writing (or
575    /// must preserve across a conditional write): the VM guards each one's
576    /// kind and copies its raw representation into the native frame.
577    fn guard_set(&self) -> &[(u16, SlotKind)];
578    /// Slots whose incoming values are provably DEAD (written before read,
579    /// e.g. the loop-condition scratch): no guard, no copy-in.
580    fn free_set(&self) -> &[u16];
581    /// Slots the region writes, with their re-boxing kinds.
582    fn write_set(&self) -> &[(u16, SlotKind)];
583    /// Arrays the region reads/writes through pinned buffers (see
584    /// [`ArrayPin`]). Default: none.
585    fn array_set(&self) -> &[ArrayPin] {
586        &[]
587    }
588    /// Hoisted region-entry bounds checks (see [`HoistGuard`]). Default: none.
589    fn hoist_guards(&self) -> &[HoistGuard] {
590        &[]
591    }
592    /// In-region `Return` support (see [`RegionReturn`]). Default: none —
593    /// such regions bail.
594    fn region_return(&self) -> Option<RegionReturn> {
595        None
596    }
597    fn frame_size(&self) -> usize;
598    /// Extra arena headroom beyond `frame_size` (regions that CALL
599    /// functions window their callees past the frame and need real call
600    /// arena depth). Default: none.
601    fn arena_slots(&self) -> usize {
602        0
603    }
604    /// PRECISE-deopt re-box kinds at `resume_pc`: one entry per VM register —
605    /// `Some(kind)` re-boxes the frame slot's raw bits, `None` keeps the VM
606    /// register's current value (a pinned array, or a read-only/unknown slot).
607    /// `None` overall ⇒ this region does not use precise deopt. Only meaningful
608    /// for a `RegionOutcome::DeoptAt { resume_pc }` outcome.
609    fn precise_kinds(&self, _resume_pc: usize) -> Option<&[Option<SlotKind>]> {
610        None
611    }
612    fn run(&self, frame: &mut [i64], depth: usize) -> RegionOutcome;
613    /// Run with access to the functions published in this VM's entry table,
614    /// so a callee side exit can transfer its live frames before cleanup.
615    fn run_with_callees<'a>(
616        &self,
617        frame: &mut [i64],
618        depth: usize,
619        _callees: &dyn Fn(u16) -> Option<&'a dyn NativeFn>,
620    ) -> RegionOutcome {
621        self.run(frame, depth)
622    }
623    /// The machine code behind this region, as `(start address, length)` extents — what the
624    /// `LOGOS_PERF_MAP` symbol map names. Default: none to report.
625    fn code_extents(&self) -> Vec<(usize, usize)> {
626        Vec::new()
627    }
628}
629
630/// The process-wide tier, installed once by the binary that links a backend
631/// (e.g. `logicaffeine-jit`). The live VM constructors attach it to every
632/// program they run; nothing installs it on WASM, so the browser stays pure
633/// bytecode.
634static INSTALLED_TIER: std::sync::OnceLock<&'static (dyn NativeTier + 'static)> =
635    std::sync::OnceLock::new();
636
637/// Install `tier` as the process-wide native tier. Idempotent: the first
638/// install wins and later calls return `false`.
639pub fn install_native_tier(tier: &'static (dyn NativeTier + 'static)) -> bool {
640    INSTALLED_TIER.set(tier).is_ok()
641}
642
643/// The installed process-wide tier, if any.
644pub fn installed_native_tier() -> Option<&'static (dyn NativeTier + 'static)> {
645    INSTALLED_TIER.get().copied()
646}
647
648/// Calls before a function is considered hot.
649pub const NATIVE_TIER_THRESHOLD: u32 = 100;
650
651/// Back-edge crossings before a Main loop is considered hot.
652pub const REGION_TIER_THRESHOLD: u32 = 100;
653
654/// Per-region tier state (keyed by loop-head pc).
655pub(crate) enum RegionSlot {
656    Failed,
657    Ready {
658        rf: Box<dyn RegionFn>,
659        exit_pc: usize,
660        /// Guard failures + side exits since compile. A region that keeps
661        /// missing (bounds-probing loops, repr churn) re-runs work on every
662        /// entry — demote it to Failed so pure bytecode takes over.
663        misses: u32,
664    },
665}
666
667/// Consecutive guard failures / side exits before a Ready region demotes.
668pub(crate) const REGION_DEMOTE_AFTER: u32 = 8;
669
670/// Per-function tier state.
671pub(crate) enum NativeSlot {
672    /// Still profiling (or below threshold).
673    Untried,
674    /// Submitted to the BACKGROUND compiler (HOTSWAP §6); runs bytecode until the
675    /// worker's result is drained and published. Not re-submitted while pending.
676    Pending,
677    /// Compilation was attempted and bailed — never retried.
678    Failed,
679    /// Compiled; the guard still applies per call.
680    Ready(Box<dyn NativeFn>),
681}