Skip to main content

logicaffeine_jit/
lib.rs

1// Native tier is available only where the forge JIT is (x86_64 System V — Linux +
2// macOS). On Windows/aarch64/wasm this crate is empty and the VM runs bytecode.
3#![cfg(all(target_arch = "x86_64", not(target_os = "windows")))]
4#![doc = include_str!("../README.md")]
5
6/// Build and execute self-contained optimized bytecode images.
7pub mod image;
8
9use std::sync::atomic::{AtomicU32, Ordering};
10
11static ALLOC_SCOPE_ENTERS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
12static ALLOC_SCOPE_LEAVES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
13static REGION_ALLOC_RESETS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
14
15use logicaffeine_compile::vm::{
16    install_native_tier, ArrayPin, CalleeSig, Constant, EnumTypeDef, FnTable, HoistGuard,
17    NativeCtx, NativeFn, NativeFrame, NativeOutcome, NativeRet, NativeTier, ObservedKind, Op,
18    ParamKind, PinElem, RegBox, RegionFn, RegionOutcome, SlotKind,
19};
20use logicaffeine_forge::jit::{
21    compile_straightline_coded, compile_straightline_pinned_float, compile_straightline_with,
22    ChainOutcome, Cmp, CompiledChain, FOp, IOp, MicroOp, RmwOp,
23};
24
25// The precise/self call stencils BAKE the depth limit (their holes are all
26// spoken for), so the kernel's `MAX_CALL_DEPTH` and the forge's baked value
27// MUST agree — otherwise native recursion would side-exit at a different depth
28// than the kernel raises its error, diverging from the tree-walker. Pinned at
29// compile time so any future change to either constant fails the BUILD here
30// rather than silently miscompiling deep recursion.
31mod inductive;
32
33const _: () = assert!(
34    logicaffeine_compile::semantics::MAX_CALL_DEPTH as i64
35        == logicaffeine_forge::jit::BAKED_CALL_DEPTH,
36    "MAX_CALL_DEPTH and the forge's baked call-depth limit have drifted; \
37     update stencils/int_stencils.rs and jit.rs BAKED_CALL_DEPTH to match",
38);
39
40/// Runtime push helpers the push stencil calls indirectly (their addresses
41/// are baked as constants — no relocations). Each pushes the value with the
42/// kernel's representation and refreshes the pinned pointer/length slots
43/// after a possible realloc.
44///
45/// # Safety
46/// The vec-handle slot must hold a live `*mut Vec<…>` of the matching
47/// element type, pinned (borrowed) by the VM for the whole region run.
48/// The NATIVE ALLOCATION REGISTRY: every list a chain allocates lives
49/// here until its boundary. On success the returned list detaches;
50/// everything else drops. On deopt everything drops — fresh lists never
51/// escape mid-run, so replay is leak-free and double-build-free.
52std::thread_local! {
53    static ALLOC_REGISTRY: std::cell::RefCell<Vec<*mut Vec<i64>>> =
54        const { std::cell::RefCell::new(Vec::new()) };
55    /// Registry watermarks for nested native function invocations. Each
56    /// function releases its scratch lists when it returns, while preserving
57    /// handles it hands to its caller through the return and mutable parameters.
58    static ALLOC_SCOPES: std::cell::RefCell<Vec<usize>> =
59        const { std::cell::RefCell::new(Vec::new()) };
60}
61
62/// Registry depth — drained-to-zero is part of every boundary's contract
63/// (asserted by the test gates).
64pub fn native_alloc_registry_len() -> usize {
65    ALLOC_REGISTRY.with(|r| r.borrow().len())
66}
67
68/// Native allocation-scope depth. Success and deopt boundaries restore this
69/// to zero; exposed so parity tests can lock the lifetime invariant.
70pub fn native_alloc_scope_depth() -> usize {
71    ALLOC_SCOPES.with(|s| s.borrow().len())
72}
73
74/// Cumulative scope entries and successful leaves.
75pub fn native_alloc_scope_counts() -> (u64, u64) {
76    (
77        ALLOC_SCOPE_ENTERS.load(Ordering::Relaxed),
78        ALLOC_SCOPE_LEAVES.load(Ordering::Relaxed),
79    )
80}
81
82/// Number of hot-loop iteration boundaries that reclaimed dead native list
83/// temporaries. Exposed for the benchmark-shape lock test.
84pub fn native_region_alloc_reset_count() -> u64 {
85    REGION_ALLOC_RESETS.load(Ordering::Relaxed)
86}
87
88fn alloc_registry_drain() {
89    ALLOC_REGISTRY.with(|r| {
90        for ptr in r.borrow_mut().drain(..) {
91            drop(unsafe { Box::from_raw(ptr) });
92        }
93    });
94    let aborted = ALLOC_SCOPES.with(|s| {
95        let mut scopes = s.borrow_mut();
96        let n = scopes.len() as u64;
97        scopes.clear();
98        n
99    });
100    ALLOC_SCOPE_LEAVES.fetch_add(aborted, Ordering::Relaxed);
101}
102
103/// Start one native function's allocation lifetime.
104///
105/// # Safety
106/// Called only by generated `Host` micro-ops; the frame operands are unused.
107pub unsafe extern "C" fn logos_rt_alloc_scope_enter(
108    _frame: *mut i64,
109    _dst: i64,
110    _src: i64,
111    _count: i64,
112    _imm: i64,
113) -> i64 {
114    let mark = native_alloc_registry_len();
115    ALLOC_SCOPES.with(|s| s.borrow_mut().push(mark));
116    ALLOC_SCOPE_ENTERS.fetch_add(1, Ordering::Relaxed);
117    // Host micro-ops interpret zero as a request to side-exit. Entering an
118    // allocation scope succeeded, so return the nonzero success sentinel.
119    1
120}
121
122/// Reclaim native lists whose allocation-site registers are dead at the hot
123/// loop backedge. The region adapter emits this only when every allocation
124/// destination is non-live-in and has no list-handle copy/rebind.
125///
126/// # Safety
127/// Called only at the generated region head after the static lifetime gate.
128pub unsafe extern "C" fn logos_rt_region_alloc_reset(
129    _frame: *mut i64,
130    _dst: i64,
131    _src: i64,
132    _count: i64,
133    _imm: i64,
134) -> i64 {
135    alloc_registry_drain();
136    REGION_ALLOC_RESETS.fetch_add(1, Ordering::Relaxed);
137    // Host micro-ops interpret zero as a request to side-exit. The reset is a
138    // completed native operation, so continue along the success edge.
139    1
140}
141
142/// Release one native function's scratch allocations, retaining its exported
143/// list handles for the caller. The first input is the return word; the rest
144/// are final mutable list parameters. A nonzero imm marks a scalar return.
145///
146/// # Safety
147/// The input window contains count readable slots, with at least one return
148/// slot. Every list export is a live handle; dst is writable.
149pub unsafe extern "C" fn logos_rt_alloc_scope_leave(
150    frame: *mut i64,
151    dst: i64,
152    src: i64,
153    count: i64,
154    imm: i64,
155) -> i64 {
156    let exports = std::slice::from_raw_parts(frame.add(src as usize), count as usize);
157    let returned = exports[0];
158    let handles = &exports[usize::from(imm != 0)..];
159    let mark = ALLOC_SCOPES.with(|s| s.borrow_mut().pop()).unwrap_or(0);
160    ALLOC_REGISTRY.with(|r| {
161        let mut registry = r.borrow_mut();
162        let mut position = 0;
163        registry.retain(|&ptr| {
164            let keep = position < mark || handles.contains(&(ptr as i64));
165            position += 1;
166            if !keep {
167                drop(Box::from_raw(ptr));
168            }
169            keep
170        });
171    });
172    *frame.add(dst as usize) = returned;
173    ALLOC_SCOPE_LEAVES.fetch_add(1, Ordering::Relaxed);
174    1
175}
176
177/// Detach one allocation by handle (the boundary's success path for a
178/// returned fresh list). `None` when the handle is not registry-owned
179/// (a param passthrough).
180/// A list native code built, handed to the VM in the VM's representation of its elements: packed words for a
181/// `Seq of Word32` (an empty one is the VM's empty list of Ints, as before its first push), a list of Ints otherwise.
182/// Native allocation sites hold only these two lanes.
183fn list_value(items: Vec<i64>, elem: PinElem) -> logicaffeine_compile::vm::Value {
184    match elem {
185        PinElem::Word32 => logicaffeine_compile::vm::Value::word32_list(items),
186        _ => logicaffeine_compile::vm::Value::int_list(items),
187    }
188}
189
190fn alloc_registry_detach(handle: i64) -> Option<Vec<i64>> {
191    ALLOC_REGISTRY.with(|r| {
192        let mut reg = r.borrow_mut();
193        let pos = reg.iter().position(|&p| p as i64 == handle)?;
194        let ptr = reg.swap_remove(pos);
195        Some(*unsafe { Box::from_raw(ptr) })
196    })
197}
198
199/// Adopt a list-returning callee's Vec into a region's pinned destination.
200/// The two input slots hold the returned and destination handles. An owned
201/// result moves; a borrowed result is copied. Pin refresh is a separate
202/// ListTriple micro-op, so every frame access is visible to code generation.
203///
204/// # Safety
205/// The input window contains two live Vec handles and dst is writable.
206pub unsafe extern "C" fn logos_rt_adopt_list_i64(
207    frame: *mut i64,
208    dst: i64,
209    src: i64,
210    _count: i64,
211    _imm: i64,
212) -> i64 {
213    let returned = *frame.add(src as usize);
214    let destination = *frame.add(src as usize + 1);
215    if returned != destination {
216        let replacement = match alloc_registry_detach(returned) {
217            Some(items) => items,
218            None => (&*(returned as *const Vec<i64>)).clone(),
219        };
220        *(destination as *mut Vec<i64>) = replacement;
221    }
222    *frame.add(dst as usize) = destination;
223    1
224}
225
226/// An unconditional side exit: answers 0, so a precise chain resumes on the VM at the op that holds it.
227///
228/// # Safety
229/// Reads nothing; the signature is the `Host` helper contract.
230pub unsafe extern "C" fn logos_rt_side_exit(
231    _frame: *mut i64,
232    _dst: i64,
233    _src: i64,
234    _count: i64,
235    _imm: i64,
236) -> i64 {
237    0
238}
239
240/// Allocate a fresh Int list and plant its pin triple.
241///
242/// # Safety
243/// `frame` slots must be this chain's live frame.
244pub unsafe extern "C" fn logos_rt_alloc_list_i64(
245    frame: *mut i64,
246    vec_slot: i64,
247    ptr_slot: i64,
248    len_slot: i64,
249) {
250    let boxed: Box<Vec<i64>> = Box::new(Vec::new());
251    let raw = Box::into_raw(boxed);
252    ALLOC_REGISTRY.with(|r| r.borrow_mut().push(raw));
253    *frame.add(vec_slot as usize) = raw as i64;
254    *frame.add(ptr_slot as usize) = (*raw).as_mut_ptr() as i64;
255    *frame.add(len_slot as usize) = 0;
256}
257
258/// Allocate a proof-sized Int list. The adapter places the capacity in
259/// `len_slot`; this helper consumes it and restores the observable length 0.
260pub unsafe extern "C" fn logos_rt_alloc_list_i64_fixed(
261    frame: *mut i64,
262    vec_slot: i64,
263    ptr_slot: i64,
264    len_slot: i64,
265) {
266    let capacity = (*frame.add(len_slot as usize)).max(0) as usize;
267    let boxed: Box<Vec<i64>> = Box::new(Vec::with_capacity(capacity));
268    let raw = Box::into_raw(boxed);
269    ALLOC_REGISTRY.with(|r| r.borrow_mut().push(raw));
270    *frame.add(vec_slot as usize) = raw as i64;
271    *frame.add(ptr_slot as usize) = (*raw).as_mut_ptr() as i64;
272    *frame.add(len_slot as usize) = 0;
273}
274
275/// Plant the pin triple for a list handle RETURNED by a self-call (the
276/// caller's view of the callee's result list).
277///
278/// # Safety
279/// `frame[handle_slot]` must be a live `*mut Vec<i64>` (registry-owned or
280/// a pinned param's vec).
281pub unsafe extern "C" fn logos_rt_list_triple(
282    frame: *mut i64,
283    handle_slot: i64,
284    vec_slot: i64,
285    ptr_slot: i64,
286    len_slot: i64,
287) {
288    let raw = *frame.add(handle_slot as usize) as *mut Vec<i64>;
289    *frame.add(vec_slot as usize) = raw as i64;
290    *frame.add(ptr_slot as usize) = (*raw).as_mut_ptr() as i64;
291    *frame.add(len_slot as usize) = (*raw).len() as i64;
292}
293
294/// Copy-on-write: give the list in `frame[handle_slot]` its own registry-owned buffer — a copy of the
295/// shared one — and re-plant the register's handle and pin triple on it. The native twin of the VM's
296/// first write to a shared list; the original (a parameter's, or a caller's through a passthrough) is
297/// untouched from here on.
298///
299/// # Safety
300/// `frame[handle_slot]` must be a live `*mut Vec<i64>`.
301pub unsafe extern "C" fn logos_rt_list_own(
302    frame: *mut i64,
303    handle_slot: i64,
304    vec_slot: i64,
305    ptr_slot: i64,
306    len_slot: i64,
307) {
308    let shared = *frame.add(handle_slot as usize) as *const Vec<i64>;
309    let raw = Box::into_raw(Box::new((*shared).clone()));
310    ALLOC_REGISTRY.with(|r| r.borrow_mut().push(raw));
311    *frame.add(handle_slot as usize) = raw as i64;
312    *frame.add(vec_slot as usize) = raw as i64;
313    *frame.add(ptr_slot as usize) = (*raw).as_mut_ptr() as i64;
314    *frame.add(len_slot as usize) = (*raw).len() as i64;
315}
316
317pub unsafe extern "C" fn logos_rt_map_get_ii(
318    map: i64,
319    key: i64,
320    frame: *mut i64,
321    dst_slot: i64,
322) -> i64 {
323    use logicaffeine_compile::interpreter::{MapStorage, RuntimeValue};
324    let storage = &*(map as *const MapStorage);
325    match storage.get(&RuntimeValue::Int(key)) {
326        Some(RuntimeValue::Int(v)) => {
327            *frame.add(dst_slot as usize) = *v;
328            1
329        }
330        // Miss or non-Int value: the side exit replays on bytecode, where
331        // the kernel raises its exact error or hands back the boxed value.
332        _ => 0,
333    }
334}
335
336/// Map insert on the kernel's own storage — identical hashing, identical
337/// iteration order.
338///
339/// # Safety
340/// `map` must be a live `*mut MapStorage` pinned for the run.
341pub unsafe extern "C" fn logos_rt_map_set_ii(map: i64, key: i64, value: i64) {
342    use logicaffeine_compile::interpreter::{MapStorage, RuntimeValue};
343    let storage = &mut *(map as *mut MapStorage);
344    storage.insert(RuntimeValue::Int(key), RuntimeValue::Int(value));
345}
346
347/// Map membership for an Int key.
348///
349/// # Safety
350/// As for [`logos_rt_map_set_ii`].
351pub unsafe extern "C" fn logos_rt_map_has_i(map: i64, key: i64) -> i64 {
352    use logicaffeine_compile::interpreter::{MapStorage, RuntimeValue};
353    let storage = &*(map as *const MapStorage);
354    storage.contains_key(&RuntimeValue::Int(key)) as i64
355}
356
357/// Push helper for pinned Int lists.
358///
359/// # Safety
360/// `frame` slots must be the caller's live pins.
361pub unsafe extern "C" fn logos_rt_push_i64(
362    frame: *mut i64,
363    vec_slot: i64,
364    ptr_slot: i64,
365    len_slot: i64,
366    value: i64,
367) {
368    let vec = *frame.add(vec_slot as usize) as *mut Vec<i64>;
369    (*vec).push(value);
370    *frame.add(ptr_slot as usize) = (*vec).as_mut_ptr() as i64;
371    *frame.add(len_slot as usize) = (*vec).len() as i64;
372}
373
374/// Push helper for pinned half-width Int lists (`ListRepr::IntsI32` =
375/// `Vec<i32>`): the value TRUNCATES to its low 4 bytes. The narrowing proof
376/// guarantees every pushed value fits `i32`, so the truncation is lossless;
377/// `debug_assert` catches a proof violation in test builds. The refreshed
378/// `ptr_slot` is the `Vec<i32>` element buffer (4-byte stride — the stencil and
379/// regalloc loads `movsxd` from it).
380///
381/// # Safety
382/// See [`logos_rt_push_i64`]; `vec_slot` must be a live `*mut Vec<i32>`.
383pub unsafe extern "C" fn logos_rt_push_i32(
384    frame: *mut i64,
385    vec_slot: i64,
386    ptr_slot: i64,
387    len_slot: i64,
388    value: i64,
389) {
390    let vec = *frame.add(vec_slot as usize) as *mut Vec<i32>;
391    debug_assert!(
392        i32::try_from(value).is_ok(),
393        "LOGOS_NARROW_VM: pushed value {value} out of i32 range on a narrowed buffer"
394    );
395    (*vec).push(value as i32);
396    *frame.add(ptr_slot as usize) = (*vec).as_mut_ptr() as i64;
397    *frame.add(len_slot as usize) = (*vec).len() as i64;
398}
399
400/// See [`logos_rt_push_i64`] — f64 value travels as bits.
401///
402/// # Safety
403/// See [`logos_rt_push_i64`].
404pub unsafe extern "C" fn logos_rt_push_f64(
405    frame: *mut i64,
406    vec_slot: i64,
407    ptr_slot: i64,
408    len_slot: i64,
409    value: i64,
410) {
411    let vec = *frame.add(vec_slot as usize) as *mut Vec<f64>;
412    (*vec).push(f64::from_bits(value as u64));
413    *frame.add(ptr_slot as usize) = (*vec).as_mut_ptr() as i64;
414    *frame.add(len_slot as usize) = (*vec).len() as i64;
415}
416
417/// See [`logos_rt_push_i64`] — nonzero stores `true`.
418///
419/// # Safety
420/// See [`logos_rt_push_i64`].
421pub unsafe extern "C" fn logos_rt_push_bool(
422    frame: *mut i64,
423    vec_slot: i64,
424    ptr_slot: i64,
425    len_slot: i64,
426    value: i64,
427) {
428    let vec = *frame.add(vec_slot as usize) as *mut Vec<bool>;
429    (*vec).push(value != 0);
430    *frame.add(ptr_slot as usize) = (*vec).as_mut_ptr() as i64;
431    *frame.add(len_slot as usize) = (*vec).len() as i64;
432}
433
434/// In-place clear of a pinned list: `vec.clear()` (truncate to empty, KEEP the
435/// buffer/capacity) and refresh the pinned ptr/len slots (ptr unchanged — clear
436/// never reallocs — but refreshed for parity with push). Lowers an in-region
437/// `NewEmptyList` on a pinned array: an in-place mutation (like SetIndex), so the
438/// PRECISE region resumes over it soundly. See [`logos_rt_push_i64`] for the
439/// frame-slot convention.
440///
441/// # Safety
442/// `frame` slots must be the caller's live pins; `vec_slot` a live `*mut Vec<i64>`.
443pub unsafe extern "C" fn logos_rt_clear_i64(
444    frame: *mut i64,
445    vec_slot: i64,
446    ptr_slot: i64,
447    len_slot: i64,
448) {
449    let vec = *frame.add(vec_slot as usize) as *mut Vec<i64>;
450    (*vec).clear();
451    *frame.add(ptr_slot as usize) = (*vec).as_mut_ptr() as i64;
452    *frame.add(len_slot as usize) = 0;
453}
454
455/// See [`logos_rt_clear_i64`] — half-width `Vec<i32>` buffer.
456///
457/// # Safety
458/// See [`logos_rt_clear_i64`]; `vec_slot` must be a live `*mut Vec<i32>`.
459pub unsafe extern "C" fn logos_rt_clear_i32(
460    frame: *mut i64,
461    vec_slot: i64,
462    ptr_slot: i64,
463    len_slot: i64,
464) {
465    let vec = *frame.add(vec_slot as usize) as *mut Vec<i32>;
466    (*vec).clear();
467    *frame.add(ptr_slot as usize) = (*vec).as_mut_ptr() as i64;
468    *frame.add(len_slot as usize) = 0;
469}
470
471/// See [`logos_rt_clear_i64`] — `Vec<f64>` buffer.
472///
473/// # Safety
474/// See [`logos_rt_clear_i64`].
475pub unsafe extern "C" fn logos_rt_clear_f64(
476    frame: *mut i64,
477    vec_slot: i64,
478    ptr_slot: i64,
479    len_slot: i64,
480) {
481    let vec = *frame.add(vec_slot as usize) as *mut Vec<f64>;
482    (*vec).clear();
483    *frame.add(ptr_slot as usize) = (*vec).as_mut_ptr() as i64;
484    *frame.add(len_slot as usize) = 0;
485}
486
487/// See [`logos_rt_clear_i64`] — `Vec<bool>` buffer.
488///
489/// # Safety
490/// See [`logos_rt_clear_i64`].
491pub unsafe extern "C" fn logos_rt_clear_bool(
492    frame: *mut i64,
493    vec_slot: i64,
494    ptr_slot: i64,
495    len_slot: i64,
496) {
497    let vec = *frame.add(vec_slot as usize) as *mut Vec<bool>;
498    (*vec).clear();
499    *frame.add(ptr_slot as usize) = (*vec).as_mut_ptr() as i64;
500    *frame.add(len_slot as usize) = 0;
501}
502
503/// MUTABLE-Text append helper for the `MicroOp::StrAppend` regalloc lowering of a
504/// `Set text to text + <s>` build loop. `frame[handle_slot]` holds a `*mut Value`
505/// pointing AT THE VM REGISTER CELL holding the accumulator (planted at region
506/// entry). `src`/`src_len` carry the appended operand:
507/// * `src_len < 0` — BYTE form: `src` is a single ASCII byte VALUE (0..=127); the
508///   appended text is that one character.
509/// * `src_len >= 0` — CONST form: `src` is a `*const u8` to `src_len` bytes (a
510///   baked ASCII literal).
511///
512/// The grow reproduces the VM's `Vm::add_assign` semantics EXACTLY so the
513/// tiered run is BIT-IDENTICAL to the tree-walker for every alias case:
514/// * if the accumulator is a sole-owned `Rc<String>` (`Rc::get_mut` succeeds), it
515///   is extended IN PLACE (`String::push_str`);
516/// * otherwise (the `Rc` is aliased — a captured `Set saved to text`) it is grown
517///   COPY-ON-WRITE through the kernel's `arith::add` (`Rc::new(format!("{a}{b}"))`,
518///   the SAME path `add_assign` falls through to), and the FRESH `Rc` replaces the
519///   accumulator's cell — the alias keeps its own (unchanged) `Rc`;
520/// * a non-`Text` accumulator (never planted — the entry pin declines a non-Text)
521///   still falls to the kernel `add`, matching the bytecode.
522///
523/// # Safety
524/// `frame[handle_slot]` must be the live `*mut Value` planted by the region-entry
525/// pin loop; for the CONST form `src` must point to `src_len` readable ASCII bytes
526/// valid for the call. The single accumulator cell is exclusively reachable for
527/// the native run (no other code touches that register), so the `&mut Value` is
528/// non-aliasing.
529pub unsafe extern "C" fn logos_rt_str_append(
530    frame: *mut i64,
531    handle_slot: i64,
532    src: i64,
533    src_len: i64,
534) {
535    use logicaffeine_compile::interpreter::RuntimeValue;
536    use logicaffeine_compile::vm::Value;
537    use std::rc::Rc;
538
539    let cell = *frame.add(handle_slot as usize) as *mut Value;
540    let acc = &mut *cell;
541
542    // The appended text: a byte (`src_len == -1`; ASCII, by the region's `TextByte` gate), an Int written as the VM
543    // writes `Text + Int` (`src_len == -2`, the very `to_display_string` the kernel's `add` calls), or a baked
544    // ASCII constant (`src_len` its length).
545    let byte_buf: [u8; 1];
546    let digits: String;
547    let appended: &str = match src_len {
548        -1 => {
549            byte_buf = [src as u8];
550            std::str::from_utf8_unchecked(&byte_buf)
551        }
552        -2 => {
553            digits = RuntimeValue::Int(src).to_display_string();
554            &digits
555        }
556        len => std::str::from_utf8_unchecked(std::slice::from_raw_parts(
557            src as *const u8,
558            len as usize,
559        )),
560    };
561
562    // Mirror `add_assign`: sole-owned Text grows in place; everything else (a
563    // shared Rc, or a non-Text) takes the kernel `add` (COW for Text+Text).
564    if matches!(acc.as_runtime_ref(), Some(RuntimeValue::Text(_))) {
565        if let RuntimeValue::Text(rc) = acc.as_runtime_mut() {
566            if let Some(s) = Rc::get_mut(rc) {
567                s.push_str(appended);
568                return;
569            }
570        }
571    }
572    // COW / non-Text fallthrough — bit-identical to `add_assign`'s
573    // `self.reg(dst).add(self.reg(src))` for `(Text, Text)`.
574    let rhs = Value::text(appended.to_string());
575    match acc.add(&rhs) {
576        Ok(v) => *acc = v,
577        // `add` over two Texts never errors; an Err would mean a non-Text
578        // accumulator the pin should have declined. Leave the cell untouched
579        // (the region's differential gate would catch any divergence).
580        Err(_) => {}
581    }
582}
583
584/// The deopt sentinel `logos_rt_memmem` returns when the recognized search nest
585/// would, on bytecode, take an access the helper cannot reproduce in-bounds — a
586/// checked needle index past the needle buffer (`needleLen > len(needle)`). The
587/// caller's stencil routes this to a side exit so the VM replays from the region
588/// head on bytecode and raises the EXACT same error at the EXACT same point.
589/// `i64::MIN` is never a legitimate count (a count is in `[0, haystack_len]`).
590pub const LOGOS_MEMMEM_DEOPT: i64 = i64::MIN;
591
592/// Count OVERLAPPING occurrences of an ASCII needle in an ASCII haystack,
593/// reproducing the LOGOS naive-search nest BIT-IDENTICALLY (the string_search
594/// benchmark idiom). The recognizer in `adapt_region` collapses the per-byte
595/// nested-loop region to a single call to this helper.
596///
597/// Parameters mirror the nest's live values at region entry:
598/// - `haystack_ptr` / `haystack_len`: the pinned `text` byte buffer (char index
599///   == byte index for the ASCII pin) and `length of text`.
600/// - `needle_ptr` / `needle_buf_len`: the pinned `needle` byte buffer and its
601///   actual length (the pinned len slot).
602/// - `needle_len`: the PROGRAM's `needleLen` value (the inner loop bound), which
603///   may differ from `needle_buf_len`.
604/// - `start`: the 1-based outer index `i` at region entry.
605///
606/// Semantics, matching the nest `while i <= textLen - needleLen + 1 { … }`:
607/// - the outer bound is `haystack_len - needle_len + 1` (recomputed here from
608///   the SAME inputs the nest used, so it agrees exactly);
609/// - a position `i` (1-based) counts iff `haystack[i-1 + j] == needle[j]` for
610///   all `j` in `[0, needle_len)` (0-based byte compare);
611/// - an empty needle (`needle_len == 0`) matches at EVERY outer position;
612/// - a needle longer than the haystack (bound `< start`) yields zero;
613/// - if a needle index `j` would read past `needle_buf_len` (i.e.
614///   `needle_len > needle_buf_len`, the nest's CHECKED `Index` on `needle`),
615///   the helper returns [`LOGOS_MEMMEM_DEOPT`] WITHOUT scanning — the caller
616///   side-exits and bytecode reproduces the exact `index out of bounds` error.
617///   (Text accesses are guaranteed in-bounds by the bound, exactly as the nest's
618///   `IndexUnchecked` on `text` relies on.)
619///
620/// Counting is via a first-byte scan + window verify (`memchr`-style) which is
621/// bit-identical to the nested loop: it visits the same positions and applies
622/// the same byte equality, just without per-op bytecode dispatch.
623///
624/// # Safety
625/// `haystack_ptr` must point to `haystack_len` readable bytes and `needle_ptr`
626/// to `needle_buf_len` readable bytes, both pinned (borrowed) for the call.
627pub unsafe extern "C" fn logos_rt_memmem(
628    haystack_ptr: i64,
629    haystack_len: i64,
630    needle_ptr: i64,
631    needle_buf_len: i64,
632    needle_len: i64,
633    start: i64,
634    _bound_unused: i64,
635) -> i64 {
636    // Lengths arrive as raw `i64` from the JIT frame. A negative (or larger than
637    // `isize::MAX`) value would make `len as usize` a ~2^64 slice length and turn
638    // the `from_raw_parts` calls below into immediate undefined behavior
639    // (`from_raw_parts` requires `len <= isize::MAX`). Treat any out-of-range length
640    // as the recoverable bail path — bytecode then reproduces the exact semantics —
641    // exactly as for an over-long needle access. Without this, a negative
642    // `needle_len`/`haystack_len` is a reachable OOB / arbitrary-length read.
643    if haystack_len < 0
644        || needle_buf_len < 0
645        || needle_len < 0
646        || haystack_len as u64 > isize::MAX as u64
647        || needle_len as u64 > isize::MAX as u64
648    {
649        return LOGOS_MEMMEM_DEOPT;
650    }
651    // A checked needle access past its buffer is the nest's recoverable error
652    // path: bail to bytecode rather than read OOB or guess the count.
653    if needle_len > needle_buf_len {
654        return LOGOS_MEMMEM_DEOPT;
655    }
656    // The nest recomputes `bound = textLen - needleLen + 1` every outer
657    // iteration from loop-invariant inputs; recompute it here from the same
658    // values so the range agrees exactly (the passed `_bound_unused` is the
659    // VM's live copy, kept in the ABI for parity but never trusted).
660    let bound = haystack_len - needle_len + 1;
661    if start > bound {
662        return 0;
663    }
664    let haystack = std::slice::from_raw_parts(haystack_ptr as *const u8, haystack_len as usize);
665    let needle = std::slice::from_raw_parts(needle_ptr as *const u8, needle_len as usize);
666
667    // Empty needle: matches at every outer position in `[start, bound]`.
668    if needle_len == 0 {
669        return bound - start + 1;
670    }
671
672    // 1-based positions `[start, bound]` correspond to 0-based haystack offsets
673    // `[start - 1, bound - 1]`. Each offset `p` matches iff
674    // `haystack[p .. p + needle_len] == needle`.
675    let first = needle[0];
676    let nlen = needle_len as usize;
677    let lo = (start - 1) as usize;
678    // `bound - 1` is the last 0-based start offset; the window end is
679    // `bound - 1 + nlen == haystack_len`, in bounds by construction.
680    let hi = (bound - 1) as usize; // inclusive last start offset
681    let mut count = 0i64;
682    let mut p = lo;
683    while p <= hi {
684        // First-byte scan to the next candidate (memchr semantics).
685        match memchr(first, &haystack[p..=hi]) {
686            Some(off) => {
687                let cand = p + off;
688                if haystack[cand..cand + nlen] == *needle {
689                    count += 1;
690                }
691                p = cand + 1;
692            }
693            None => break,
694        }
695    }
696    count
697}
698
699/// First-byte scan helper (a tiny `memchr`): the offset of the first `needle`
700/// byte in `hay`, or `None`. A plain byte loop — bit-identical to the nest's
701/// position-by-position visit; a SIMD (SSE2/AVX2) replacement can drop in here
702/// once the scalar path is proven against the differential gate.
703#[inline]
704fn memchr(needle: u8, hay: &[u8]) -> Option<usize> {
705    hay.iter().position(|&b| b == needle)
706}
707
708/// Frame-driven entry the [`MicroOp::MemMem`] stencil calls: reads the search
709/// nest's live values out of the JIT frame, runs [`logos_rt_memmem`], and on
710/// success ADDS the count into `count_slot` and advances `i_slot` to the loop's
711/// exit value (`bound + 1`). Returns `1` on success and `0` on the deopt
712/// sentinel — the stencil routes `0` to its side-exit continuation, untouched.
713///
714/// # Safety
715/// `frame` must be the running chain's live frame; the named slots must hold the
716/// pinned haystack/needle pointer+length pairs, the `needleLen` value, the
717/// 1-based `i`, and the `count` accumulator.
718#[allow(clippy::too_many_arguments)]
719pub unsafe extern "C" fn logos_rt_memmem_frame(
720    frame: *mut i64,
721    h_ptr_slot: i64,
722    h_len_slot: i64,
723    n_ptr_slot: i64,
724    n_len_slot: i64,
725    needle_len_slot: i64,
726    i_slot: i64,
727    count_slot: i64,
728) -> i64 {
729    let h_ptr = *frame.add(h_ptr_slot as usize);
730    let h_len = *frame.add(h_len_slot as usize);
731    let n_ptr = *frame.add(n_ptr_slot as usize);
732    let n_buf_len = *frame.add(n_len_slot as usize);
733    let needle_len = *frame.add(needle_len_slot as usize);
734    let start = *frame.add(i_slot as usize);
735    let result = logos_rt_memmem(h_ptr, h_len, n_ptr, n_buf_len, needle_len, start, 0);
736    if result == LOGOS_MEMMEM_DEOPT {
737        return 0;
738    }
739    *frame.add(count_slot as usize) += result;
740    // Advance `i` to the nest's natural exit value: the first index for which
741    // `i > bound` (`bound = h_len - needle_len + 1`). If the loop never ran
742    // (`start > bound`), `i` keeps its entry value — exactly the bytecode's
743    // `while i <= bound { … i = i + 1 }` post-state.
744    let bound = h_len - needle_len + 1;
745    let exit_i = core::cmp::max(start, bound + 1);
746    *frame.add(i_slot as usize) = exit_i;
747    1
748}
749
750/// Register kinds for the adapter's sound dataflow.
751#[derive(Clone, Copy, PartialEq, Debug)]
752enum Kind {
753    /// A list a function allocated at this pc that nothing has been pushed into yet. Seen only while
754    /// [`fresh_list_kinds`] discovers each allocation site's element kind; every flow a gate reads resolves it.
755    FreshList(u32),
756    Unknown,
757    Nothing,
758    Int,
759    Bool,
760    Float,
761    /// A pinned unboxed Int list (the register itself never rides a slot —
762    /// its buffer pointer/length live in dedicated pin slots).
763    IntList,
764    /// A pinned half-width (`Vec<i32>`) Int list (`ListRepr::IntsI32`): the
765    /// element access width is 4 bytes (sign-extending loads, truncating
766    /// stores). Behaves exactly like [`Kind::IntList`] for register/pin gating;
767    /// only the array op width differs.
768    IntListI32,
769    /// A pinned packed `Word32` list (`ListRepr::Words32` = masked values in `Vec<i64>`). The pin/load is
770    /// IDENTICAL to [`Kind::IntList`] (8-byte elements); the ONLY difference is that an indexed read yields a
771    /// [`Kind::Word32`] (so the Word ops accept it), never an `Int`. Lets a `Seq of Word32` table pin + tier.
772    Word32List,
773    /// A pinned unboxed Float list.
774    FloatList,
775    /// A pinned unboxed Bool list.
776    BoolList,
777    /// A pinned MAP (boxed kernel storage behind a pointer pin; int fast
778    /// lane verified per helper call).
779    IntMap,
780    /// A pinned ASCII `Text` carried AS BYTES (char index == byte index, char
781    /// count == byte length): `item i of text` is a 1-byte pinned load and the
782    /// extracted char rides the [`Kind::TextByte`] lane.
783    TextBytes,
784    /// A single ASCII character extracted from a [`Kind::TextBytes`] (or a
785    /// 1-char ASCII text constant): the integer byte value 0..=127. Equality
786    /// between two `TextByte`s is an exact integer compare — which matches the
787    /// tree-walker's `Text == Text` string compare for single ASCII chars.
788    TextByte,
789    /// A pinned MUTABLE-Text accumulator (the `dst` of a `Set text to text + …`
790    /// build loop): it rides the [`PinElem::TextMut`] channel (a `*mut Value`
791    /// handle), not a scalar frame slot. The only op that consumes it is the
792    /// append (`AddAssign`), lowered to [`MicroOp::StrAppend`]; any other use
793    /// (a `Move`, an `Index`, …) is rejected so the region bails — keeping the
794    /// accumulator's growth confined to the proven-sound append path.
795    TextMut,
796    /// A MULTI-character ASCII text CONSTANT (`text + "XXXXX"`): a baked byte
797    /// slice. Valid ONLY as the source of a `StrAppend`; every other use gate
798    /// rejects it (so the region bails).
799    TextConst,
800    /// A `Word32` — the ℤ/2³² wrapping ring (the MD5/SHA-1/SHA-256 crypto substrate) carried UNBOXED as
801    /// its zero-extended `u32` value in a plain i64 slot (so `0 ≤ slot < 2³²`; the invariant every Word32
802    /// op preserves or re-establishes). Produced by `word32`/`word16Make`, consumed to an `Int` by
803    /// `IntOfWord32`/`IntOfWord16`, or re-boxed to `RuntimeValue::Word` at a deopt/exit via `RegBox::Word32`.
804    Word32,
805    /// A `Word64` — the ℤ/2⁶⁴ wrapping ring carried UNBOXED as its full 64-bit pattern in an i64 slot (no
806    /// masking; the i64 bits ARE the u64 bits). Re-boxed via `RegBox::Word64`.
807    Word64,
808    /// A `Word16` — the ℤ/2¹⁶ ring, produced by `word16(n)` as its masked value (`0 ≤ slot < 2¹⁶`). Its
809    /// ONLY in-region consumer is `intOfWord16`: no op here wraps at 2¹⁶, so arithmetic, a write-back, a
810    /// live-in, and a deopt capture all reject it and the region stays on the VM.
811    Word16,
812    /// A `chr(code)` result carried UNBOXED as the Unicode-scalar CODE POINT in an i64 slot, re-boxed to a
813    /// 1-char `Text` (`Rc<String>`) at a deopt/exit via `RegBox::CharText`. The producing `chr` op is a
814    /// `ChrGuard` that DEOPTS to the VM on an invalid code (surrogate / `> 0x10FFFF`), so a slot of this
815    /// Kind ALWAYS holds a valid scalar — materialization can `char::from_u32(..).unwrap()` soundly.
816    CharText,
817    /// A node of one of the program's own enums: `Rc::as_ptr` of the VM's `Rc<InductiveValue>` in a
818    /// plain slot. Whether the register owns a count of it is the enum lane's business
819    /// ([`inductive::Hold`]).
820    Inductive,
821    Mixed,
822}
823
824impl Kind {
825    fn slot_kind(self) -> Option<SlotKind> {
826        match self {
827            Kind::Int => Some(SlotKind::Int),
828            Kind::Bool => Some(SlotKind::Bool),
829            Kind::Float => Some(SlotKind::Float),
830            // A `CharText` re-boxes to a 1-char Text at write-back. Valid as an OUTPUT only; the region
831            // gate rejects a `CharText` live-in guard input (see the entry-guard bail).
832            Kind::CharText => Some(SlotKind::CharText),
833            // A Word rides UNBOXED as a masked i64 — BIDIRECTIONAL: it marshals in as a live-in guard (the
834            // VM verifies the `RuntimeValue::Word` width) and re-boxes on write-back. This is what lets a
835            // loop-carried Word (a hash accumulator `h0..h7`) tier as region state.
836            Kind::Word32 => Some(SlotKind::Word32),
837            Kind::Word64 => Some(SlotKind::Word64),
838            _ => None,
839        }
840    }
841}
842
843/// The single ASCII byte of a 1-character ASCII text constant, or `None` if the
844/// constant is not exactly one ASCII char. A `Kind::TextByte` comparison loads
845/// one byte from the pinned text, so a constant on the other side must be that
846/// same single byte; the tree-walker compares the two 1-char Texts as strings,
847/// which agrees with the byte compare exactly for single ASCII chars.
848fn text_const_byte(s: &str) -> Option<u8> {
849    let b = s.as_bytes();
850    (b.len() == 1 && b[0] < 128).then(|| b[0])
851}
852
853/// Recover the constant ASCII byte slice of a `StrAppend`'s `TextConst` source
854/// (`text + "XXXXX"`) and bake it into a `'static` allocation so the regalloc
855/// stencil can hold a stable `(ptr, len)`. The source register `src` is loaded by
856/// a `LoadConst` in the same region; scan BACKWARD from the append for the nearest
857/// def of `src` and require it to be a `LoadConst` of a `Constant::Text`. Returns
858/// `None` (declining the region) if the source is not a direct constant load — a
859/// conservative bail to bytecode. The leak is one-time per compiled region (there
860/// are a handful of such constants) and the bytes outlive the chain.
861fn const_text_slice(
862    ops: &[Op],
863    i: usize,
864    base_pc: usize,
865    src: u16,
866    constants: &[Constant],
867) -> Option<(i64, i64)> {
868    let _ = base_pc;
869    let mut j = i;
870    while j > 0 {
871        j -= 1;
872        let (_, defs) = region_use_def(&ops[j])?;
873        if defs.contains(&src) {
874            if let Op::LoadConst { idx, .. } = ops[j] {
875                if let Some(Constant::Text(s)) = constants.get(idx as usize) {
876                    if s.is_ascii() && !s.is_empty() {
877                        let leaked: &'static [u8] = s.clone().into_bytes().leak();
878                        return Some((leaked.as_ptr() as i64, leaked.len() as i64));
879                    }
880                }
881            }
882            // The nearest def of `src` is not a constant Text load — bail.
883            return None;
884        }
885    }
886    None
887}
888
889fn observed_kind(o: ObservedKind) -> Kind {
890    match o {
891        ObservedKind::Int => Kind::Int,
892        ObservedKind::Bool => Kind::Bool,
893        ObservedKind::Float => Kind::Float,
894        ObservedKind::IntList => Kind::IntList,
895        ObservedKind::IntListI32 => Kind::IntListI32,
896        ObservedKind::Word32List => Kind::Word32List,
897        ObservedKind::FloatList => Kind::FloatList,
898        ObservedKind::BoolList => Kind::BoolList,
899        ObservedKind::Map => Kind::IntMap,
900        ObservedKind::TextBytes => Kind::TextBytes,
901        // A loop-carried Word entering the region as state — carried unboxed as a masked i64.
902        ObservedKind::Word32 => Kind::Word32,
903        ObservedKind::Word64 => Kind::Word64,
904        ObservedKind::Other => Kind::Mixed,
905    }
906}
907
908/// Per-pinned-register slot assignments for translation.
909#[derive(Clone, Copy)]
910struct PinSlots {
911    vec_slot: u16,
912    ptr_slot: u16,
913    len_slot: u16,
914    elem: PinElem,
915}
916
917/// Everything a SELF-call lowering needs baked into its stencil.
918struct CallCtx<'t> {
919    table_addr: i64,
920    depth_addr: i64,
921    status_addr: i64,
922    limit_slot: u16,
923    depth_limit: i64,
924    self_fi: u16,
925    /// The program's function table — non-self calls bake the CALLEE's
926    /// slot address for table dispatch.
927    table: &'t FnTable,
928    callees: &'t [CalleeSig],
929}
930
931/// The result kind of an arithmetic op over two operand kinds, mirroring the
932/// kernel's promotion: Int×Int→Int, any Float→Float. None = not arithmetic
933/// (the use gate bails).
934fn arith_result(l: Kind, r: Kind) -> Option<Kind> {
935    match (l, r) {
936        (Kind::Int, Kind::Int) => Some(Kind::Int),
937        (Kind::Float, Kind::Float) | (Kind::Int, Kind::Float) | (Kind::Float, Kind::Int) => {
938            Some(Kind::Float)
939        }
940        // Same-width Word arithmetic is modular (2³²/2⁶⁴): `Word + Word`/`- `/`* ` stays that Word. Mixed
941        // widths (or a Word with an Int) is a type error the tree-walker rejects, so it never reaches here.
942        (Kind::Word32, Kind::Word32) => Some(Kind::Word32),
943        (Kind::Word64, Kind::Word64) => Some(Kind::Word64),
944        _ => None,
945    }
946}
947
948fn join(a: Kind, b: Kind) -> Kind {
949    match (a, b) {
950        (Kind::Unknown, x) | (x, Kind::Unknown) => x,
951        (Kind::FreshList(_), x @ (Kind::IntList | Kind::Word32List))
952        | (x @ (Kind::IntList | Kind::Word32List), Kind::FreshList(_)) => x,
953        (x, y) if x == y => x,
954        _ => Kind::Mixed,
955    }
956}
957
958/// Forward, flow-SENSITIVE kind dataflow over a bytecode slice (a function
959/// body or a loop region). Each reachable op gets the kind vector holding
960/// BEFORE it executes; merge points join per slot (`Unknown ⊔ k = k`,
961/// `k ⊔ k = k`, else `Mixed`). Constants carry their pool type (Int, Float,
962/// Bool); arithmetic promotes like the kernel (any Float operand → Float).
963/// Jump targets outside the slice are exits. Returns per-op kind-in vectors
964/// (None = unreachable), or None when any reachable use violates the gates.
965fn kind_flow(
966    ops: &[Op],
967    base_pc: usize,
968    constants: &[Constant],
969    entry: Vec<Kind>,
970    calls: Option<&dyn Fn(u16) -> Option<(Kind, Vec<Kind>)>>,
971    binds: &[Kind],
972) -> Option<Vec<Option<Vec<Kind>>>> {
973    let fresh = fresh_list_kinds(ops, base_pc, constants, entry.clone(), calls, binds)?;
974    kind_flow_sited(ops, base_pc, constants, entry, calls, binds, &fresh)
975}
976
977/// What a function's own allocations (`NewEmptyList`) hold.
978enum FreshSites {
979    /// Every allocation is a list of Ints (the classic scalar-only mode).
980    Ints,
981    /// Discovering each site's element kind: a site is [`Kind::FreshList`] until the first push of an Int or a Word32
982    /// into it decides it, recorded here by allocation pc, and the gates wait. A decision is a guess the flow that
983    /// follows checks: every push into the site must then pass its gate, or the function stays on the VM.
984    Discover(std::cell::RefCell<std::collections::HashMap<usize, Kind>>),
985    /// Each site's element kind, as discovered (a site nothing is pushed into is a list of Ints, as on the VM).
986    Known(std::collections::HashMap<usize, Kind>),
987}
988
989/// The element kind of each list a function allocates, from the first Int or Word32 pushed into it: a `Seq of Word32`
990/// (the VM retags its empty list on the first word pushed) or a list of Ints; a site nothing decides is a list of Ints.
991/// The caller's flow checks every push against the decision.
992fn fresh_list_kinds(
993    ops: &[Op],
994    base_pc: usize,
995    constants: &[Constant],
996    entry: Vec<Kind>,
997    calls: Option<&dyn Fn(u16) -> Option<(Kind, Vec<Kind>)>>,
998    binds: &[Kind],
999) -> Option<FreshSites> {
1000    let discover = FreshSites::Discover(std::cell::RefCell::new(std::collections::HashMap::new()));
1001    kind_flow_sited(ops, base_pc, constants, entry, calls, binds, &discover)?;
1002    let FreshSites::Discover(found) = discover else {
1003        unreachable!()
1004    };
1005    Some(FreshSites::Known(found.into_inner()))
1006}
1007
1008fn kind_flow_sited(
1009    ops: &[Op],
1010    base_pc: usize,
1011    constants: &[Constant],
1012    entry: Vec<Kind>,
1013    calls: Option<&dyn Fn(u16) -> Option<(Kind, Vec<Kind>)>>,
1014    binds: &[Kind],
1015    fresh: &FreshSites,
1016) -> Option<Vec<Option<Vec<Kind>>>> {
1017    let n = ops.len();
1018    let in_slice = |t: usize| t >= base_pc && t < base_pc + n;
1019    let const_kind = |idx: u32| -> Kind {
1020        match constants.get(idx as usize) {
1021            Some(Constant::Nothing) => Kind::Nothing,
1022            Some(Constant::Int(_)) => Kind::Int,
1023            Some(Constant::Float(_)) => Kind::Float,
1024            Some(Constant::Bool(_)) => Kind::Bool,
1025            // A 1-char ASCII text/char literal compares against an extracted
1026            // `item i of text` as an integer byte (the strings benchmark's
1027            // `item i of result equals " "`). A multi-char or non-ASCII text is
1028            // not a single byte — it stays Mixed and bails.
1029            Some(Constant::Char(c)) if c.is_ascii() => Kind::TextByte,
1030            Some(Constant::Text(s)) if text_const_byte(s).is_some() => Kind::TextByte,
1031            // A MULTI-char ASCII text constant is valid only as a `StrAppend`
1032            // source (`text + "XXXXX"`); every other gate rejects `TextConst`.
1033            Some(Constant::Text(s)) if !s.is_empty() && s.is_ascii() => Kind::TextConst,
1034            _ => Kind::Mixed,
1035        }
1036    };
1037    let mut kin: Vec<Option<Vec<Kind>>> = vec![None; n];
1038    kin[0] = Some(entry);
1039    let mut work: Vec<usize> = vec![0];
1040    while let Some(i) = work.pop() {
1041        let Some(cur) = kin[i].clone() else { continue };
1042        let mut out = cur;
1043        match ops[i] {
1044            Op::LoadConst { dst, idx } => out[dst as usize] = const_kind(idx),
1045            Op::Add { dst, lhs, rhs }
1046            | Op::Sub { dst, lhs, rhs }
1047            | Op::Mul { dst, lhs, rhs }
1048            | Op::Div { dst, lhs, rhs } => {
1049                out[dst as usize] =
1050                    arith_result(out[lhs as usize], out[rhs as usize]).unwrap_or(Kind::Mixed)
1051            }
1052            Op::AddAssign { dst, src } => {
1053                out[dst as usize] = if out[dst as usize] == Kind::TextMut {
1054                    // A pinned mutable-Text accumulator stays the accumulator —
1055                    // it grows in place / COW through `StrAppend`.
1056                    Kind::TextMut
1057                } else {
1058                    arith_result(out[dst as usize], out[src as usize]).unwrap_or(Kind::Mixed)
1059                }
1060            }
1061            Op::Mod { dst, .. }
1062            | Op::DivPow2 { dst, .. }
1063            | Op::MagicDivU { dst, .. }
1064            | Op::Shl { dst, .. }
1065            | Op::Shr { dst, .. } => out[dst as usize] = Kind::Int,
1066            // `xor` / `&` / `|` (generic operators): Int×Int → Int, Bool×Bool → Bool, and — since each
1067            // PRESERVES the width mask — a same-width Word × Word → that Word (this is how `sha256` combines
1068            // words with the generic operators; `word_and`/`word_or` are the builtin spellings of the same op).
1069            Op::BitXor { dst, lhs, rhs }
1070            | Op::BitAnd { dst, lhs, rhs }
1071            | Op::BitOr { dst, lhs, rhs } => {
1072                out[dst as usize] = match (out[lhs as usize], out[rhs as usize]) {
1073                    (Kind::Int, Kind::Int) => Kind::Int,
1074                    (Kind::Word32, Kind::Word32) => Kind::Word32,
1075                    (Kind::Word64, Kind::Word64) => Kind::Word64,
1076                    (Kind::Bool, Kind::Bool) => Kind::Bool,
1077                    _ => Kind::Mixed,
1078                }
1079            }
1080            Op::Not { dst, src } => {
1081                out[dst as usize] = match out[src as usize] {
1082                    Kind::Bool => Kind::Bool,
1083                    _ => Kind::Mixed,
1084                }
1085            }
1086            Op::Lt { dst, .. }
1087            | Op::Gt { dst, .. }
1088            | Op::LtEq { dst, .. }
1089            | Op::GtEq { dst, .. }
1090            | Op::Eq { dst, .. }
1091            | Op::NotEq { dst, .. } => out[dst as usize] = Kind::Bool,
1092            Op::Move { dst, src } => out[dst as usize] = out[src as usize],
1093            // `Swap a and b`: each register takes the other's value, so each takes the other's kind.
1094            Op::RevSwap { a, b } => out.swap(a as usize, b as usize),
1095            Op::Index {
1096                dst, collection, ..
1097            }
1098            | Op::IndexUnchecked {
1099                dst, collection, ..
1100            } => {
1101                out[dst as usize] = match out[collection as usize] {
1102                    Kind::IntList | Kind::IntListI32 => Kind::Int,
1103                    // `item i of <Seq of Word32>` yields a `Word32` (so the Word ops downstream accept it).
1104                    Kind::Word32List => Kind::Word32,
1105                    Kind::FloatList => Kind::Float,
1106                    Kind::BoolList => Kind::Bool,
1107                    // Map int fast lane: a non-Int value is a helper miss
1108                    // (side exit), so the in-region kind is Int.
1109                    Kind::IntMap => Kind::Int,
1110                    // `item i of text` on an ASCII text: a single ASCII byte.
1111                    Kind::TextBytes => Kind::TextByte,
1112                    _ => Kind::Mixed,
1113                }
1114            }
1115            Op::Length { dst, .. } => out[dst as usize] = Kind::Int,
1116            Op::Contains { dst, .. } => out[dst as usize] = Kind::Bool,
1117            // A function's own allocation holds what its pushes put in it (see `FreshSites`).
1118            Op::NewEmptyList { dst }
1119            | Op::NewEmptyListWithCapacity { dst, .. }
1120            | Op::NewEmptyListFixed { dst, .. } => {
1121                out[dst as usize] = match fresh {
1122                    FreshSites::Ints => Kind::IntList,
1123                    FreshSites::Discover(_) => Kind::FreshList(i as u32),
1124                    FreshSites::Known(sites) => sites.get(&i).copied().unwrap_or(Kind::IntList),
1125                }
1126            }
1127            // While sites are discovered, the first push of an Int or a Word32 into one still undecided decides it.
1128            // Any other value decides nothing: mid-fixpoint it may not have its final kind yet.
1129            Op::ListPush { list, value } if matches!(out[list as usize], Kind::FreshList(_)) => {
1130                let Kind::FreshList(site) = out[list as usize] else {
1131                    unreachable!()
1132                };
1133                let decided = match out[value as usize] {
1134                    Kind::Int => Some(Kind::IntList),
1135                    Kind::Word32 => Some(Kind::Word32List),
1136                    _ => None,
1137                };
1138                if let (Some(kind), FreshSites::Discover(found)) = (decided, fresh) {
1139                    out[list as usize] = *found.borrow_mut().entry(site as usize).or_insert(kind);
1140                }
1141            }
1142            Op::NewInductive { dst, .. } => out[dst as usize] = Kind::Inductive,
1143            Op::TestArm { dst, .. } => out[dst as usize] = Kind::Bool,
1144            // The payload kind the declared variant names (`inductive::bind_kinds`), checked at run time.
1145            Op::BindArm { dst, .. } => {
1146                out[dst as usize] = binds.get(i).copied().unwrap_or(Kind::Mixed)
1147            }
1148            Op::NewList { dst, start, count } => {
1149                out[dst as usize] = if (start..start + count).all(|r| out[r as usize] == Kind::Int)
1150                {
1151                    Kind::IntList
1152                } else {
1153                    Kind::Mixed
1154                };
1155            }
1156            Op::Call { dst, func, .. } => {
1157                let Some((ret, _)) = calls.and_then(|c| c(func)) else {
1158                    if std::env::var_os("LOGOS_JIT_TRACE").is_some() {
1159                        eprintln!(
1160                            "jit-trace: kind flow cannot type the call to fn#{func} at pc {}",
1161                            base_pc + i
1162                        );
1163                    }
1164                    return None;
1165                };
1166                out[dst as usize] = ret;
1167            }
1168            Op::CallBuiltin {
1169                dst,
1170                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Sqrt,
1171                ..
1172            } => out[dst as usize] = Kind::Float,
1173            // `abs(x)` preserves the argument's kind (Int→Int, Float→Float); the Int lane tiers via a
1174            // branchless composition in `translate_op`, the Float lane declines there (no sign-mask stencil).
1175            Op::CallBuiltin {
1176                dst,
1177                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Abs,
1178                args_start,
1179                arg_count,
1180            } if arg_count == 1 => out[dst as usize] = out[args_start as usize],
1181            // `min(a,b)` / `max(a,b)` preserve the operand kind; the Int lane tiers via a branchless
1182            // select in `translate_op`, the Float lane declines there (no minsd/maxsd stencil yet).
1183            Op::CallBuiltin {
1184                dst,
1185                builtin:
1186                    logicaffeine_compile::semantics::builtins::BuiltinId::Min
1187                    | logicaffeine_compile::semantics::builtins::BuiltinId::Max,
1188                args_start,
1189                arg_count,
1190            } if arg_count == 2 => out[dst as usize] = out[args_start as usize],
1191            // `count_ones`/`leading_zeros`/`trailing_zeros` — Int bit-counts; each tiers to its native
1192            // instruction stencil (`popcnt`/`lzcnt`/`tzcnt`, MicroOp::Popcnt/Lzcnt/Tzcnt).
1193            Op::CallBuiltin {
1194                dst,
1195                builtin:
1196                    logicaffeine_compile::semantics::builtins::BuiltinId::CountOnes
1197                    | logicaffeine_compile::semantics::builtins::BuiltinId::LeadingZeros
1198                    | logicaffeine_compile::semantics::builtins::BuiltinId::TrailingZeros,
1199                arg_count,
1200                ..
1201            } if arg_count == 1 => out[dst as usize] = Kind::Int,
1202            // `floor`/`ceil`/`round` of a Float → an Int (`roundsd`+`cvttsd2si`, MicroOp::Floor/Ceil/RoundToInt).
1203            Op::CallBuiltin {
1204                dst,
1205                builtin:
1206                    logicaffeine_compile::semantics::builtins::BuiltinId::Floor
1207                    | logicaffeine_compile::semantics::builtins::BuiltinId::Ceil
1208                    | logicaffeine_compile::semantics::builtins::BuiltinId::Round,
1209                args_start,
1210                arg_count,
1211            } if arg_count == 1 && matches!(out[args_start as usize], Kind::Float) => {
1212                out[dst as usize] = Kind::Int
1213            }
1214            // `pow(base: Int, const_exp)` → Int (unrolled Muls; the arg guard + const-exp check are in
1215            // translate_op, which declines a Float base / variable or negative exponent).
1216            Op::CallBuiltin {
1217                dst,
1218                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Pow,
1219                args_start,
1220                arg_count,
1221            } if arg_count == 2 && matches!(out[args_start as usize], Kind::Int) => {
1222                out[dst as usize] = Kind::Int
1223            }
1224            // Word producers (from an Int): `word32` → Word32; `word16` → Word16; `word64` → Word64.
1225            Op::CallBuiltin {
1226                dst,
1227                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word32,
1228                arg_count,
1229                ..
1230            } if arg_count == 1 => out[dst as usize] = Kind::Word32,
1231            Op::CallBuiltin {
1232                dst,
1233                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word16Make,
1234                arg_count,
1235                ..
1236            } if arg_count == 1 => out[dst as usize] = Kind::Word16,
1237            Op::CallBuiltin {
1238                dst,
1239                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word64,
1240                arg_count,
1241                ..
1242            } if arg_count == 1 => out[dst as usize] = Kind::Word64,
1243            // `IntOfWord32`/`IntOfWord16`/`IntOfWord64`: a Word → an Int.
1244            Op::CallBuiltin {
1245                dst,
1246                builtin:
1247                    logicaffeine_compile::semantics::builtins::BuiltinId::IntOfWord32
1248                    | logicaffeine_compile::semantics::builtins::BuiltinId::IntOfWord16
1249                    | logicaffeine_compile::semantics::builtins::BuiltinId::IntOfWord64,
1250                arg_count,
1251                ..
1252            } if arg_count == 1 => out[dst as usize] = Kind::Int,
1253            // `chr(code: Int)` → a `CharText` (a valid code carried unboxed, re-boxed to a 1-char Text).
1254            Op::CallBuiltin {
1255                dst,
1256                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Chr,
1257                args_start,
1258                arg_count,
1259            } if arg_count == 1 && matches!(out[args_start as usize], Kind::Int) => {
1260                out[dst as usize] = Kind::CharText
1261            }
1262            // `Wand`/`Wor`: same-width Word in, same-width Word out (result kind = the first arg's).
1263            Op::CallBuiltin {
1264                dst,
1265                builtin:
1266                    logicaffeine_compile::semantics::builtins::BuiltinId::Wand
1267                    | logicaffeine_compile::semantics::builtins::BuiltinId::Wor,
1268                args_start,
1269                arg_count,
1270            } if arg_count == 2
1271                && matches!(out[args_start as usize], Kind::Word32 | Kind::Word64) =>
1272            {
1273                out[dst as usize] = out[args_start as usize]
1274            }
1275            // `word64And` → Word64 (the translate_op arm guards both args are Word64).
1276            Op::CallBuiltin {
1277                dst,
1278                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word64And,
1279                arg_count,
1280                ..
1281            } if arg_count == 2 => out[dst as usize] = Kind::Word64,
1282            // `word64Shl` → Word64; `word32Shr` → Word32 (2-arg: word, shift-count Int).
1283            Op::CallBuiltin {
1284                dst,
1285                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word64Shl,
1286                arg_count,
1287                ..
1288            } if arg_count == 2 => out[dst as usize] = Kind::Word64,
1289            Op::CallBuiltin {
1290                dst,
1291                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word32Shr,
1292                arg_count,
1293                ..
1294            } if arg_count == 2 => out[dst as usize] = Kind::Word32,
1295            // `word64Shr` → Word64 (translate_op tiers only a constant shift count via mask-off-sign).
1296            Op::CallBuiltin {
1297                dst,
1298                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word64Shr,
1299                arg_count,
1300                ..
1301            } if arg_count == 2 => out[dst as usize] = Kind::Word64,
1302            // `word_not` (1-arg) → same width as its arg.
1303            Op::CallBuiltin {
1304                dst,
1305                builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Wnot,
1306                args_start,
1307                arg_count,
1308            } if arg_count == 1
1309                && matches!(out[args_start as usize], Kind::Word32 | Kind::Word64) =>
1310            {
1311                out[dst as usize] = out[args_start as usize]
1312            }
1313            // `rotl`/`rotr` (2-arg: word, count Int) → same width as the word arg.
1314            Op::CallBuiltin {
1315                dst,
1316                builtin:
1317                    logicaffeine_compile::semantics::builtins::BuiltinId::Rotl
1318                    | logicaffeine_compile::semantics::builtins::BuiltinId::Rotr,
1319                args_start,
1320                arg_count,
1321            } if arg_count == 2
1322                && matches!(out[args_start as usize], Kind::Word32 | Kind::Word64) =>
1323            {
1324                out[dst as usize] = out[args_start as usize]
1325            }
1326            _ => {}
1327        }
1328        let mut succs: Vec<usize> = Vec::with_capacity(2);
1329        match ops[i] {
1330            Op::Jump { target } => {
1331                if in_slice(target) {
1332                    succs.push(target - base_pc);
1333                }
1334            }
1335            Op::JumpIfFalse { target, .. } | Op::JumpIfTrue { target, .. } => {
1336                if i + 1 < n {
1337                    succs.push(i + 1);
1338                }
1339                if in_slice(target) {
1340                    succs.push(target - base_pc);
1341                }
1342            }
1343            Op::Return { .. } | Op::ReturnNothing => {}
1344            _ => {
1345                if i + 1 < n {
1346                    succs.push(i + 1);
1347                }
1348            }
1349        }
1350        for s in succs {
1351            match &mut kin[s] {
1352                slot @ None => {
1353                    *slot = Some(out.clone());
1354                    work.push(s);
1355                }
1356                Some(prev) => {
1357                    let mut changed = false;
1358                    for (a, b) in prev.iter_mut().zip(&out) {
1359                        let j = join(*a, *b);
1360                        if j != *a {
1361                            *a = j;
1362                            changed = true;
1363                        }
1364                    }
1365                    if changed {
1366                        work.push(s);
1367                    }
1368                }
1369            }
1370        }
1371    }
1372    // Discovery wants only the decisions its pushes recorded; the gates judge the flow that uses them.
1373    if matches!(fresh, FreshSites::Discover(_)) {
1374        return Some(kin);
1375    }
1376    // Gates on every reachable use, at that use's program point.
1377    for (i, op) in ops.iter().enumerate() {
1378        let Some(k) = &kin[i] else { continue };
1379        let int_at = |r: u16| k[r as usize] == Kind::Int;
1380        let num_at = |r: u16| matches!(k[r as usize], Kind::Int | Kind::Float);
1381        // A same-width Word pair (`Word32×Word32` / `Word64×Word64`) — modular `+`/`-`/`*` lowers to the
1382        // masked-i64 op, and the mask-preserving `xor`/`&`/`|` to the plain one. `Div` (signed i64 div ≠
1383        // unsigned Word64 div) and ordered comparisons stay numeric-only, so a Word there declines to the VM.
1384        let word_pair = |l: u16, r: u16| {
1385            matches!(
1386                (k[l as usize], k[r as usize]),
1387                (Kind::Word32, Kind::Word32) | (Kind::Word64, Kind::Word64)
1388            )
1389        };
1390        // Each gate refuses by returning from this closure, so the refusing op can be named.
1391        let gate = || -> Option<()> {
1392            match *op {
1393                // Modular Word arithmetic OR numeric (mixed Int/Float promotes via an inserted conversion).
1394                Op::Add { lhs, rhs, .. } | Op::Sub { lhs, rhs, .. } | Op::Mul { lhs, rhs, .. } => {
1395                    if !(num_at(lhs) && num_at(rhs)) && !word_pair(lhs, rhs) {
1396                        return None;
1397                    }
1398                }
1399                // Division and ordered comparisons: numeric operands only.
1400                Op::Div { lhs, rhs, .. }
1401                | Op::Lt { lhs, rhs, .. }
1402                | Op::Gt { lhs, rhs, .. }
1403                | Op::LtEq { lhs, rhs, .. }
1404                | Op::GtEq { lhs, rhs, .. } => {
1405                    if !num_at(lhs) || !num_at(rhs) {
1406                        return None;
1407                    }
1408                }
1409                Op::AddAssign { dst, src } => {
1410                    if k[dst as usize] == Kind::TextMut {
1411                        // A pinned mutable-Text append: the source is a 1-char runtime
1412                        // byte (`TextByte`), an `Int` (appended as its decimal text) or
1413                        // a multi-char ASCII constant (`TextConst`). `StrAppend` lowers it.
1414                        if !matches!(
1415                            k[src as usize],
1416                            Kind::TextByte | Kind::Int | Kind::TextConst
1417                        ) {
1418                            return None;
1419                        }
1420                    // A same-width Word `acc += x` is modular addition (the sha256 `h += a` / list-read
1421                    // accumulator shape) — lowers like `Op::Add`'s Word branch (masked-i64 add).
1422                    } else if !(num_at(dst) && num_at(src)) && !word_pair(dst, src) {
1423                        return None;
1424                    }
1425                }
1426                // Equality: numeric pairs (promoting), Bool×Bool, or TextByte×
1427                // TextByte (two extracted ASCII chars, or an extracted char vs a
1428                // 1-char ASCII literal — both sides are integer bytes, the compare
1429                // is exact, matching the tree-walker's single-char Text compare).
1430                Op::Eq { lhs, rhs, .. } | Op::NotEq { lhs, rhs, .. } => {
1431                    let bools = k[lhs as usize] == Kind::Bool && k[rhs as usize] == Kind::Bool;
1432                    let bytes =
1433                        k[lhs as usize] == Kind::TextByte && k[rhs as usize] == Kind::TextByte;
1434                    if !bools && !bytes && (!num_at(lhs) || !num_at(rhs)) {
1435                        return None;
1436                    }
1437                }
1438                // Int-only ops.
1439                Op::Mod { lhs, rhs, .. } | Op::Shl { lhs, rhs, .. } | Op::Shr { lhs, rhs, .. } => {
1440                    if !int_at(lhs) || !int_at(rhs) {
1441                        return None;
1442                    }
1443                }
1444                // `xor`: both-Int OR a same-width Word pair (mask-preserving, so no extra mask). NOT Bool — a
1445                // `Bool xor Bool` keeps its prior VM path unchanged.
1446                Op::BitXor { lhs, rhs, .. } => {
1447                    if !(int_at(lhs) && int_at(rhs)) && !word_pair(lhs, rhs) {
1448                        return None;
1449                    }
1450                }
1451                // `& |`: both-Int (bitwise), both-Bool (logical 0/1), or a same-width Word pair — `&`/`|` of two
1452                // masked Words stays masked, so the plain i64 op needs no extra mask (as with `xor`).
1453                Op::BitAnd { lhs, rhs, .. } | Op::BitOr { lhs, rhs, .. } => {
1454                    let ints = int_at(lhs) && int_at(rhs);
1455                    let bools = k[lhs as usize] == Kind::Bool && k[rhs as usize] == Kind::Bool;
1456                    if !ints && !bools && !word_pair(lhs, rhs) {
1457                        return None;
1458                    }
1459                }
1460                // `not` is LOGICAL (truthiness → Bool); only a Bool operand has a
1461                // 0/1 register form the stencils can negate. `not <Int>` (rare —
1462                // an emptiness idiom) stays on the VM.
1463                Op::Not { src, .. } => {
1464                    if !matches!(k[src as usize], Kind::Bool) {
1465                        return None;
1466                    }
1467                }
1468                // Scalars swap their frame slots, whatever their kinds. Equal-kind lists swap their
1469                // complete pinned (Vec, ptr, len) triples in translate_op; a scalar/list or mixed-list
1470                // exchange declines.
1471                Op::RevSwap { a, b } => {
1472                    let scalar = |r: u16| {
1473                        matches!(
1474                            k[r as usize],
1475                            Kind::Int
1476                                | Kind::Bool
1477                                | Kind::Float
1478                                | Kind::TextByte
1479                                | Kind::Word32
1480                                | Kind::Word64
1481                        )
1482                    };
1483                    let same_list_kind = k[a as usize] == k[b as usize]
1484                        && matches!(
1485                            k[a as usize],
1486                            Kind::IntList
1487                                | Kind::IntListI32
1488                                | Kind::Word32List
1489                                | Kind::FloatList
1490                                | Kind::BoolList
1491                        );
1492                    if !(scalar(a) && scalar(b)) && !same_list_kind {
1493                        return None;
1494                    }
1495                }
1496                Op::Move { src, .. } => {
1497                    // List buffers never ride frame slots (they are pinned
1498                    // separately) — but a list-kind Move is legal as STAGING:
1499                    // the slot value is a placeholder and pin identity travels
1500                    // statically. Any real USE of an unpinned destination still
1501                    // fails closed at translate (pins lookup).
1502                    if !matches!(
1503                        k[src as usize],
1504                        Kind::Int
1505                            | Kind::Bool
1506                            | Kind::Float
1507                            | Kind::IntList
1508                            | Kind::IntListI32
1509                            | Kind::Word32List
1510                            | Kind::FloatList
1511                            | Kind::BoolList
1512                            // A 1-char ASCII byte (`text + ch`'s `ch`) rides a plain
1513                            // frame slot as its integer byte value — a raw-copy Move.
1514                            | Kind::TextByte
1515                            // A Word rides as a masked i64; `Set h to <word>` (a loop-carried
1516                            // hash accumulator) is a raw-copy Move of that masked value.
1517                            | Kind::Word32
1518                            | Kind::Word64
1519                            // A node pointer; the enum lane decides what the copy owns.
1520                            | Kind::Inductive
1521                    ) {
1522                        return None;
1523                    }
1524                }
1525                Op::TestArm { target, .. } | Op::BindArm { target, .. } => {
1526                    if k[target as usize] != Kind::Inductive {
1527                        return None;
1528                    }
1529                }
1530                Op::JumpIfFalse { cond, .. } | Op::JumpIfTrue { cond, .. } => {
1531                    if k[cond as usize] != Kind::Bool {
1532                        return None;
1533                    }
1534                }
1535                Op::Index {
1536                    collection, index, ..
1537                }
1538                | Op::IndexUnchecked {
1539                    collection, index, ..
1540                } => {
1541                    if !matches!(
1542                        k[collection as usize],
1543                        Kind::IntList
1544                            | Kind::IntListI32
1545                            | Kind::Word32List
1546                            | Kind::FloatList
1547                            | Kind::BoolList
1548                            | Kind::IntMap
1549                            | Kind::TextBytes
1550                    ) || !int_at(index)
1551                    {
1552                        return None;
1553                    }
1554                }
1555                Op::SetIndex {
1556                    collection,
1557                    index,
1558                    value,
1559                }
1560                | Op::SetIndexUnchecked {
1561                    collection,
1562                    index,
1563                    value,
1564                } => {
1565                    let elem_ok = match k[collection as usize] {
1566                        Kind::IntList | Kind::IntListI32 => k[value as usize] == Kind::Int,
1567                        Kind::Word32List => k[value as usize] == Kind::Word32,
1568                        Kind::FloatList => k[value as usize] == Kind::Float,
1569                        Kind::BoolList => k[value as usize] == Kind::Bool,
1570                        Kind::IntMap => k[value as usize] == Kind::Int,
1571                        _ => false,
1572                    };
1573                    if !elem_ok || !int_at(index) {
1574                        return None;
1575                    }
1576                }
1577                Op::Contains {
1578                    collection, value, ..
1579                } => {
1580                    if k[collection as usize] != Kind::IntMap || !int_at(value) {
1581                        return None;
1582                    }
1583                }
1584                Op::Length { collection, .. } => {
1585                    if !matches!(
1586                        k[collection as usize],
1587                        Kind::IntList | Kind::IntListI32 | Kind::Word32List | Kind::FloatList | Kind::BoolList
1588                            | Kind::TextBytes
1589                            // `length of chr(code)` — a single Unicode scalar is exactly ONE character (the
1590                            // translate_op lowers it to the constant 1), the shape that lets `chr` tier.
1591                            | Kind::CharText
1592                    ) {
1593                        return None;
1594                    }
1595                }
1596                // SELF-calls only (the callee's entry contract is its own: Int
1597                // params, known return kind); every argument must be Int at the
1598                // call point — exactly the per-call guard the bytecode boundary
1599                // enforces.
1600                Op::Call {
1601                    func,
1602                    args_start,
1603                    arg_count,
1604                    ..
1605                } => {
1606                    let Some((_, params)) = calls.and_then(|c| c(func)) else {
1607                        return None;
1608                    };
1609                    if arg_count as usize != params.len() {
1610                        return None;
1611                    }
1612                    for (j, a) in (args_start..args_start + arg_count).enumerate() {
1613                        if k[a as usize] != params[j] {
1614                            return None;
1615                        }
1616                    }
1617                }
1618                Op::CallBuiltin {
1619                    builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Sqrt,
1620                    args_start,
1621                    arg_count,
1622                    ..
1623                } => {
1624                    if arg_count != 1 || !matches!(k[args_start as usize], Kind::Int | Kind::Float)
1625                    {
1626                        return None;
1627                    }
1628                }
1629                Op::ListPush { list, value } => {
1630                    let elem_ok = match k[list as usize] {
1631                        Kind::IntList | Kind::IntListI32 => k[value as usize] == Kind::Int,
1632                        Kind::Word32List => k[value as usize] == Kind::Word32,
1633                        Kind::FloatList => k[value as usize] == Kind::Float,
1634                        Kind::BoolList => k[value as usize] == Kind::Bool,
1635                        _ => false,
1636                    };
1637                    if !elem_ok {
1638                        return None;
1639                    }
1640                }
1641                Op::Return { src } => {
1642                    // A return carries a scalar (re-boxed by its SlotKind, a Word as its masked value), a
1643                    // pinned list (by register) or an enum node; the function adapter then checks that every
1644                    // return agrees with the kind it assumed.
1645                    if !matches!(
1646                        k[src as usize],
1647                        Kind::Int
1648                            | Kind::Bool
1649                            | Kind::Float
1650                            | Kind::Word32
1651                            | Kind::Word64
1652                            | Kind::IntList
1653                            | Kind::IntListI32
1654                            | Kind::Word32List
1655                            | Kind::FloatList
1656                            | Kind::BoolList
1657                            | Kind::Inductive
1658                    ) {
1659                        return None;
1660                    }
1661                }
1662                _ => {}
1663            }
1664            Some(())
1665        };
1666        if gate().is_none() {
1667            if std::env::var_os("LOGOS_JIT_TRACE").is_some() {
1668                eprintln!(
1669                    "jit-trace: kind gate refused pc {} {:?} with kinds {:?}",
1670                    base_pc + i,
1671                    op,
1672                    k
1673                );
1674            }
1675            return None;
1676        }
1677    }
1678    Some(kin)
1679}
1680
1681/// Translate WHOLE-PROGRAM Main bytecode into the J2 micro-op subset.
1682///
1683/// Requirements (else `None`):
1684/// - ops drawn from {LoadConst(Int), Move, Add, Sub, Mul, Lt, Gt, Eq,
1685///   Jump, JumpIfFalse, JumpIfTrue, Show};
1686/// - exactly ONE Show, and it is the final op (it becomes Return);
1687/// - no comparison-produced value is the shown register (bool-taint).
1688///
1689/// Returns the micro program and the frame size it needs.
1690#[allow(clippy::type_complexity)]
1691pub fn adapt(
1692    ops: &[Op],
1693    constants: &[Constant],
1694    register_count: usize,
1695) -> Option<(Vec<MicroOp>, usize)> {
1696    // The shown register must not be a comparison result anywhere.
1697    let mut tainted: Vec<u16> = Vec::new();
1698    let mut shows = 0usize;
1699    for op in ops {
1700        match *op {
1701            Op::Lt { dst, .. }
1702            | Op::Gt { dst, .. }
1703            | Op::LtEq { dst, .. }
1704            | Op::GtEq { dst, .. }
1705            | Op::Eq { dst, .. }
1706            | Op::NotEq { dst, .. } => tainted.push(dst),
1707            Op::Show { .. } => shows += 1,
1708            _ => {}
1709        }
1710    }
1711    // Terminal shape: `Show; Halt` (or a bare trailing Show). Anything that
1712    // jumps PAST the Show (to the Halt) would print nothing on the VM while
1713    // the JIT still returns a value — bail on those.
1714    let n = ops.len();
1715    let (show_pc, halt_pc) = match (n.checked_sub(2).map(|i| &ops[i]), ops.last()) {
1716        (Some(Op::Show { .. }), Some(Op::Halt)) => (n - 2, Some(n - 1)),
1717        (_, Some(Op::Show { .. })) => (n - 1, None),
1718        _ => return None,
1719    };
1720    if shows != 1 {
1721        return None;
1722    }
1723    for op in ops {
1724        if let Op::Jump { target }
1725        | Op::JumpIfFalse { target, .. }
1726        | Op::JumpIfTrue { target, .. } = *op
1727        {
1728            if target > show_pc {
1729                return None;
1730            }
1731        }
1732    }
1733    let _ = halt_pc;
1734
1735    let frame_size = register_count;
1736
1737    // Pass 1: translate, recording vm-pc → micro-index. Jump targets hold VM
1738    // pcs until pass 2 remaps them.
1739    let mut micro: Vec<MicroOp> = Vec::with_capacity(ops.len());
1740    let mut pc_to_micro: Vec<usize> = Vec::with_capacity(ops.len());
1741    // (micro index, vm target) needing remap.
1742    let mut fixups: Vec<usize> = Vec::new();
1743
1744    for op in ops {
1745        pc_to_micro.push(micro.len());
1746        match *op {
1747            Op::LoadConst { dst, idx } => match constants.get(idx as usize)? {
1748                Constant::Int(v) => micro.push(MicroOp::LoadConst { dst, value: *v }),
1749                _ => return None,
1750            },
1751            Op::Move { dst, src } => micro.push(MicroOp::Move { dst, src }),
1752            Op::EnsureOwned { .. } => {} // interpreter-only COW barrier — no-op in a native region
1753            Op::Add { dst, lhs, rhs } => micro.push(MicroOp::Add { dst, lhs, rhs }),
1754            Op::AddAssign { dst, src } => micro.push(MicroOp::Add {
1755                dst,
1756                lhs: dst,
1757                rhs: src,
1758            }),
1759            Op::Div { dst, lhs, rhs } => match const_pow2_div(ops, rhs, constants) {
1760                Some(k) => micro.push(MicroOp::DivPow2 { dst, lhs, k }),
1761                None => micro.push(MicroOp::Div { dst, lhs, rhs }),
1762            },
1763            Op::DivPow2 { dst, lhs, k } => micro.push(MicroOp::DivPow2 {
1764                dst,
1765                lhs,
1766                k: k as u32,
1767            }),
1768            Op::MagicDivU {
1769                dst,
1770                lhs,
1771                magic,
1772                more,
1773                mul_back,
1774                divisor: _,
1775                wrap: _,
1776            } => micro.push(MicroOp::MagicDivU {
1777                dst,
1778                lhs,
1779                magic,
1780                more,
1781                mul_back,
1782            }),
1783            Op::Mod { dst, lhs, rhs } => micro.push(MicroOp::Mod { dst, lhs, rhs }),
1784            Op::Sub { dst, lhs, rhs } => micro.push(MicroOp::Sub { dst, lhs, rhs }),
1785            Op::Mul { dst, lhs, rhs } => micro.push(MicroOp::Mul { dst, lhs, rhs }),
1786            Op::Lt { dst, lhs, rhs } => micro.push(MicroOp::Lt { dst, lhs, rhs }),
1787            Op::Gt { dst, lhs, rhs } => micro.push(MicroOp::Gt { dst, lhs, rhs }),
1788            Op::Eq { dst, lhs, rhs } => micro.push(MicroOp::Eq { dst, lhs, rhs }),
1789            Op::LtEq { dst, lhs, rhs } => micro.push(MicroOp::LtEq { dst, lhs, rhs }),
1790            Op::GtEq { dst, lhs, rhs } => micro.push(MicroOp::GtEq { dst, lhs, rhs }),
1791            Op::NotEq { dst, lhs, rhs } => micro.push(MicroOp::Neq { dst, lhs, rhs }),
1792            Op::Jump { target } => {
1793                fixups.push(micro.len());
1794                micro.push(MicroOp::Jump { target });
1795            }
1796            Op::JumpIfFalse { cond, target } => {
1797                fixups.push(micro.len());
1798                micro.push(MicroOp::JumpIfFalse { cond, target });
1799            }
1800            Op::JumpIfTrue { cond, target } => {
1801                fixups.push(micro.len());
1802                micro.push(MicroOp::JumpIfTrue { cond, target });
1803            }
1804            Op::Show { src } => {
1805                if tainted.contains(&src) {
1806                    return None;
1807                }
1808                micro.push(MicroOp::Return { src });
1809            }
1810            // The trailing Halt after the Show: unreachable past Return.
1811            Op::Halt => {}
1812            _ => return None,
1813        }
1814    }
1815
1816    // Pass 2: remap jump targets from VM pcs to micro indices.
1817    for &i in &fixups {
1818        match &mut micro[i] {
1819            MicroOp::Jump { target }
1820            | MicroOp::JumpIfFalse { target, .. }
1821            | MicroOp::JumpIfTrue { target, .. } => {
1822                *target = *pc_to_micro.get(*target)?;
1823            }
1824            _ => unreachable!(),
1825        }
1826    }
1827    Some((micro, frame_size))
1828}
1829
1830/// Everything the precise-deopt boundary needs at runtime, built once at
1831/// adapt time (functions with list parameters).
1832struct PreciseInfo {
1833    register_count: usize,
1834    /// Per-register re-box kinds at every potential pause point: each
1835    /// deoptable op's pc and each self-call's pc.
1836    kinds_by_pc: std::collections::HashMap<usize, Vec<RegBox>>,
1837    /// NATIVE-OWNED list registers per pause point: (register, the frame
1838    /// slot of its pin's vec handle, its elements). At materialization the handle either
1839    /// detaches from the allocation registry (fresh list — re-boxed here)
1840    /// or matches a boundary pin (param passthrough — rewritten to
1841    /// ListParam for the VM side).
1842    owned_by_pc: std::collections::HashMap<usize, Vec<(u16, u16, PinElem)>>,
1843    /// Where each boundary pin triple (param order) lands in the frame:
1844    /// the vec slot of THAT PARAM REGISTER's pin (per-register pins are
1845    /// not in param order).
1846    param_pin_scatter: Vec<u16>,
1847    /// The enum lane's nodes per pause point: (register, what it holds). A side exit hands each
1848    /// back to the VM ([`inductive::rebox`]).
1849    nodes_by_pc: std::collections::HashMap<usize, Vec<(u16, inductive::Hold)>>,
1850}
1851
1852/// The shapes the enum lane's helpers read through their operand, owned by the compiled function.
1853#[derive(Default)]
1854struct NodeShapes {
1855    constructs: Vec<Box<inductive::Construct>>,
1856    variants: Vec<Box<String>>,
1857}
1858
1859/// What adapt_function hands back: micro code, frame size, return shape,
1860/// per-micro deopt codes and the precise-walk tables.
1861struct AdaptedFn {
1862    micro: Vec<MicroOp>,
1863    frame_size: usize,
1864    ret: NativeRet,
1865    /// The elements of a list the function returns ([`NativeRet::ListByHandle`]): Int or Word32.
1866    ret_elem: PinElem,
1867    deopt_codes: Option<Vec<i64>>,
1868    precise: Option<PreciseInfo>,
1869    shapes: NodeShapes,
1870}
1871
1872/// Which mode-B lanes a function body needs: list pins (list parameters or allocation sites) and
1873/// the enum lane (an enum parameter or an enum op).
1874fn function_lanes(code: &[Op], param_kinds: &[Option<ParamKind>]) -> (bool, bool) {
1875    let lists = param_kinds
1876        .iter()
1877        .any(|k| matches!(k, Some(ParamKind::List(_))))
1878        || code.iter().any(|op| {
1879            matches!(
1880                op,
1881                Op::NewEmptyList { .. }
1882                    | Op::NewEmptyListWithCapacity { .. }
1883                    | Op::NewEmptyListFixed { .. }
1884            )
1885        });
1886    let nodes = inductive::uses_nodes(
1887        code,
1888        param_kinds
1889            .iter()
1890            .any(|k| matches!(k, Some(ParamKind::Inductive))),
1891    );
1892    (lists, nodes)
1893}
1894
1895/// A function's frame size. Mode A keeps the classic [regs | conv ×2 | limit]; mode B inserts the
1896/// plant slots, the pin triples and, for the enum lane, the hold slot an overwritten node waits in
1897/// until the op that reads it is done: [regs | conv ×2 | window | resume | dst | pins ×3p | hold? |
1898/// exports | limit]. The export window makes every helper input explicit to
1899/// register allocation.
1900fn function_scope_export_slots(ops: &[Op], param_count: u16, nodes: bool) -> usize {
1901    if !nodes
1902        && ops.iter().any(|op| {
1903            matches!(
1904                op,
1905                Op::NewEmptyList { .. }
1906                    | Op::NewEmptyListWithCapacity { .. }
1907                    | Op::NewEmptyListFixed { .. }
1908                    | Op::NewList { .. }
1909                    // A first write through an alias may call list_own even
1910                    // when the source contains no list constructor.
1911                    | Op::SetIndex { .. }
1912                    | Op::SetIndexUnchecked { .. }
1913            )
1914        })
1915    {
1916        usize::from(param_count) + 1
1917    } else {
1918        0
1919    }
1920}
1921
1922fn function_frame_size(
1923    register_count: usize,
1924    mode_b: bool,
1925    npins: usize,
1926    nodes: bool,
1927    exports: usize,
1928) -> usize {
1929    if mode_b {
1930        register_count + 6 + 3 * npins + nodes as usize + exports
1931    } else {
1932        register_count + 3
1933    }
1934}
1935
1936/// The precise-deopt tables for a REGION (push+SetIndex worklist). `deopt_codes`
1937/// tag every micro with its bytecode op's encoded resume pc; `kinds_by_pc` maps
1938/// each resume pc to the per-register re-box kind used when materializing the
1939/// frame's scalars back into the VM registers (`None` = keep the VM register's
1940/// live value — a pinned array, or a read-only/unknown slot).
1941struct RegionPrecise {
1942    /// Completed exits return their bytecode PC for typed frame materialization.
1943    resume_on_return: bool,
1944    deopt_codes: Vec<i64>,
1945    kinds_by_pc: std::collections::HashMap<usize, Vec<Option<SlotKind>>>,
1946}
1947
1948/// LIST-REGISTER discovery (shared by the adapter and the frame-size
1949/// pre-computation): every register that ever holds a list — params,
1950/// allocation sites, Move aliases, list-returning self-call results.
1951fn discover_list_regs(
1952    ops: &[Op],
1953    list_param_regs: &[u16],
1954    fn_returns_lists: bool,
1955    self_fi: u16,
1956    nregs: usize,
1957) -> Vec<bool> {
1958    let mut is_list = vec![false; nregs];
1959    for &r in list_param_regs {
1960        is_list[r as usize] = true;
1961    }
1962    loop {
1963        let mut changed = false;
1964        for op in ops {
1965            match *op {
1966                Op::NewEmptyList { dst }
1967                | Op::NewEmptyListWithCapacity { dst, .. }
1968                | Op::NewEmptyListFixed { dst, .. }
1969                | Op::NewList { dst, .. } => {
1970                    if !is_list[dst as usize] {
1971                        is_list[dst as usize] = true;
1972                        changed = true;
1973                    }
1974                }
1975                Op::Move { dst, src } => {
1976                    if is_list[src as usize] && !is_list[dst as usize] {
1977                        is_list[dst as usize] = true;
1978                        changed = true;
1979                    }
1980                }
1981                Op::RevSwap { a, b } => {
1982                    if is_list[a as usize] != is_list[b as usize] {
1983                        is_list[a as usize] = true;
1984                        is_list[b as usize] = true;
1985                        changed = true;
1986                    }
1987                }
1988                Op::Call { dst, func, .. } if func == self_fi && fn_returns_lists => {
1989                    if !is_list[dst as usize] {
1990                        is_list[dst as usize] = true;
1991                        changed = true;
1992                    }
1993                }
1994                _ => {}
1995            }
1996        }
1997        if !changed {
1998            break;
1999        }
2000    }
2001    is_list
2002}
2003
2004/// Whether register `r` holds a list BEFORE op `i`, by the flow-sensitive kind dataflow — the question a
2005/// translation decision about `r` at `i` must ask (see the Move arm of the precise adapter).
2006fn holds_list_at(kin: &[Option<Vec<Kind>>], i: usize, r: u16) -> bool {
2007    kin[i].as_ref().is_some_and(|k| {
2008        matches!(
2009            k[r as usize],
2010            Kind::IntList | Kind::IntListI32 | Kind::Word32List | Kind::FloatList | Kind::BoolList
2011        )
2012    })
2013}
2014
2015fn jt(which: &str) {
2016    if std::env::var_os("LOGOS_JIT_TRACE").is_some() {
2017        eprintln!("jit-trace: mode-B bail at {which}");
2018    }
2019}
2020
2021/// Translate a FUNCTION body (terminal = Op::Return, absolute pcs rebased by
2022/// `entry_pc`) into the J2 subset.
2023///
2024/// J4 kind dataflow (sound fixpoint): params are Int (the entry guard),
2025/// comparisons produce Bool, arithmetic requires Int operands (a Bool
2026/// flowing into `+` errors on the VM — native code must NOT compute it),
2027/// Move propagates, conflicting writes go Mixed (bail on use). All reachable
2028/// returns must agree on Int or Bool; the bool flag re-boxes the result.
2029fn adapt_function(
2030    ops: &[Op],
2031    entry_pc: usize,
2032    constants: &[Constant],
2033    enums: &[EnumTypeDef],
2034    param_count: u16,
2035    register_count: u16,
2036    self_fi: u16,
2037    param_kinds: &[Option<ParamKind>],
2038    cow_exempt_regs: &[u16],
2039    declared_ret: Option<SlotKind>,
2040    call_ctx_in: &CallCtx,
2041    callees: &[CalleeSig],
2042) -> Option<AdaptedFn> {
2043    // Every jump must stay inside the body slice — a function is self-contained.
2044    for op in ops {
2045        if let Op::Jump { target }
2046        | Op::JumpIfFalse { target, .. }
2047        | Op::JumpIfTrue { target, .. } = *op
2048        {
2049            if target < entry_pc || target >= entry_pc + ops.len() {
2050                jt("jump-outside-body");
2051                return None;
2052            }
2053        }
2054    }
2055
2056    // Flow-sensitive kinds: every parameter starts at its DECLARED kind
2057    // (the per-call boundary guard checks the matching discriminant before
2058    // entry, so the seed is sound, not speculative); everything else starts
2059    // Unknown and the gates inside kind_flow enforce soundness at every
2060    // reachable use.
2061    // Return kind: a declared return type pins it in one pass; otherwise
2062    // the self-recursive Int/Bool inference (assume, verify, retry) stands.
2063    if param_kinds.len() != param_count as usize {
2064        return None;
2065    }
2066    let mut param_entry: Vec<Kind> = Vec::with_capacity(param_count as usize);
2067    let mut list_params: Vec<(u16, PinElem)> = Vec::new();
2068    for (i, pk) in param_kinds.iter().enumerate() {
2069        let Some(pk) = *pk else {
2070            jt("param-kind");
2071            return None;
2072        };
2073        param_entry.push(match pk {
2074            ParamKind::Scalar(SlotKind::Int) => Kind::Int,
2075            ParamKind::Scalar(SlotKind::Bool) => Kind::Bool,
2076            ParamKind::Scalar(SlotKind::Float) => Kind::Float,
2077            ParamKind::Scalar(SlotKind::CharText) => Kind::CharText,
2078            ParamKind::Scalar(SlotKind::Word32) => Kind::Word32,
2079            ParamKind::Scalar(SlotKind::Word64) => Kind::Word64,
2080            ParamKind::List(elem) => {
2081                list_params.push((i as u16, elem));
2082                match elem {
2083                    PinElem::Int => Kind::IntList,
2084                    PinElem::Word32 => Kind::Word32List,
2085                    PinElem::Float => Kind::FloatList,
2086                    PinElem::Bool => Kind::BoolList,
2087                    // A half-width buffer is a VM-local storage decision, never a
2088                    // declared list-param type — bail rather than speculate it.
2089                    PinElem::IntI32 => return None,
2090                    // Declared kinds never produce a Map or Text list-param.
2091                    PinElem::Map | PinElem::TextBytes | PinElem::TextMut => return None,
2092                }
2093            }
2094            // A node the VM writes back through the parameter is not one the callee may borrow.
2095            ParamKind::Inductive if cow_exempt_regs.contains(&(i as u16)) => return None,
2096            ParamKind::Inductive => Kind::Inductive,
2097        });
2098    }
2099    // ALLOCATION SITES make a function mode B even without list params, and so does the enum lane:
2100    // its side exits hand nodes back precisely.
2101    let (list_mode, nodes) = function_lanes(ops, param_kinds);
2102    let mode_b = list_mode || nodes;
2103    // Mode B leans on the PRECISE call stencil, whose depth limit is baked
2104    // at the kernel's locked MAX_CALL_DEPTH.
2105    if mode_b && call_ctx_in.depth_limit != logicaffeine_compile::semantics::MAX_CALL_DEPTH as i64 {
2106        return None;
2107    }
2108    // Does this function RETURN lists? Declared scalar returns say no;
2109    // otherwise list params or sites make it possible — the fixpoint
2110    // verifies every return site agrees.
2111    let fn_returns_lists = declared_ret.is_none() && list_mode;
2112
2113    // LIST REGISTERS (mode B): one pin triple PER REGISTER that ever
2114    // holds a list — every list assignment (param entry, allocation,
2115    // Move alias, self-call result) REFRESHES that register's own triple,
2116    // so reassignment patterns (quicksort's `result`) cannot conflict.
2117    // Push eligibility is static: a register every one of whose list
2118    // sources is an allocation site is definitely registry-owned — a push
2119    // anywhere else could stale another holder's pinned slots.
2120    let nregs_pin = register_count as usize + 2;
2121    let list_param_regs: Vec<u16> = list_params.iter().map(|(r, _)| *r).collect();
2122    let is_list = discover_list_regs(ops, &list_param_regs, fn_returns_lists, self_fi, nregs_pin);
2123    let inout_params = callees
2124        .get(self_fi as usize)
2125        .map_or(&[][..], |sig| sig.inout_params.as_slice());
2126    // An in-out parameter hands its final value back through the caller's register as a raw slot, and a node
2127    // parameter is borrowed for the whole call: a function that can reassign one stays on the VM.
2128    if inout_params.iter().any(|&r| {
2129        matches!(
2130            param_kinds.get(r as usize),
2131            Some(Some(ParamKind::Inductive))
2132        )
2133    }) {
2134        jt("inout-node");
2135        return None;
2136    }
2137    let live = liveness_with_outputs(ops, entry_pc, nregs_pin, inout_params)?;
2138    // Provenance TAINT, FLOW-SENSITIVE: at each program point, which
2139    // registers may hold a list some OTHER holder pins (params; call
2140    // results, which may be param passthroughs). Moves propagate taint;
2141    // a NewEmptyList CLEANSES its destination (fresh, registry-owned).
2142    // Pushes are legal only into point-wise clean registers — mergesort's
2143    // `Set left to mergeSort(left)` taints `left` only AFTER the pushes.
2144    // NATIVE COPY-ON-WRITE. The element stores at these pcs target a list that may be shared (a param's,
2145    // or a self-call result that may be a param passed through) through a register the VM does not
2146    // exempt from copy-on-write — so, exactly as the VM does on a shared list's first write, the store is
2147    // preceded by a copy into a fresh registry-owned buffer, and the register is clean from there on.
2148    let mut own_before: std::collections::HashSet<usize> = std::collections::HashSet::new();
2149    if mode_b {
2150        let in_body = |t: usize| t >= entry_pc && t < entry_pc + ops.len();
2151        let mut taint_in: Vec<Option<Vec<bool>>> = vec![None; ops.len()];
2152        let mut entry_taint = vec![false; nregs_pin];
2153        for (preg, _) in &list_params {
2154            entry_taint[*preg as usize] = true;
2155        }
2156        taint_in[0] = Some(entry_taint);
2157        let mut work: Vec<usize> = vec![0];
2158        while let Some(i) = work.pop() {
2159            let Some(cur) = taint_in[i].clone() else {
2160                continue;
2161            };
2162            let mut out = cur;
2163            match ops[i] {
2164                Op::NewEmptyList { dst }
2165                | Op::NewEmptyListWithCapacity { dst, .. }
2166                | Op::NewEmptyListFixed { dst, .. }
2167                | Op::NewList { dst, .. } => out[dst as usize] = false,
2168                Op::RevSwap { a, b } => out.swap(a as usize, b as usize),
2169                Op::Move { dst, src } => {
2170                    out[dst as usize] = out[src as usize];
2171                    // A still-live source and its copy now share even when the
2172                    // buffer was allocated by this native invocation.
2173                    if dst != src
2174                        && is_list[src as usize]
2175                        && live.get(i + 1).is_some_and(|row| row[src as usize])
2176                    {
2177                        out[src as usize] = true;
2178                        out[dst as usize] = true;
2179                    }
2180                }
2181                Op::RevSwap { a, b } => out.swap(a as usize, b as usize),
2182                Op::Call {
2183                    dst,
2184                    func,
2185                    args_start,
2186                    ..
2187                } => {
2188                    if func == self_fi && fn_returns_lists {
2189                        out[dst as usize] = true;
2190                    }
2191                    if let Some(sig) = callees.get(func as usize) {
2192                        for &r in &sig.inout_params {
2193                            if matches!(
2194                                sig.param_kinds.get(r as usize),
2195                                Some(Some(ParamKind::List(_)))
2196                            ) {
2197                                out[(args_start + r) as usize] = true;
2198                            }
2199                        }
2200                    }
2201                }
2202                // A store into a shared, non-exempt list first copies it (NATIVE COPY-ON-WRITE, above):
2203                // the register holds its own fresh buffer afterwards.
2204                Op::SetIndex { collection, .. } | Op::SetIndexUnchecked { collection, .. }
2205                    if out[collection as usize] && !cow_exempt_regs.contains(&collection) =>
2206                {
2207                    out[collection as usize] = false;
2208                }
2209                _ => {}
2210            }
2211            let mut succs: Vec<usize> = Vec::with_capacity(2);
2212            match ops[i] {
2213                Op::Jump { target } => {
2214                    if in_body(target) {
2215                        succs.push(target - entry_pc);
2216                    }
2217                }
2218                Op::JumpIfFalse { target, .. } | Op::JumpIfTrue { target, .. } => {
2219                    if i + 1 < ops.len() {
2220                        succs.push(i + 1);
2221                    }
2222                    if in_body(target) {
2223                        succs.push(target - entry_pc);
2224                    }
2225                }
2226                Op::Return { .. } | Op::ReturnNothing => {}
2227                _ => {
2228                    if i + 1 < ops.len() {
2229                        succs.push(i + 1);
2230                    }
2231                }
2232            }
2233            for sidx in succs {
2234                match &mut taint_in[sidx] {
2235                    slot @ None => {
2236                        *slot = Some(out.clone());
2237                        work.push(sidx);
2238                    }
2239                    Some(prev) => {
2240                        let mut changed = false;
2241                        for (p, &o) in prev.iter_mut().zip(&out) {
2242                            if !*p && o {
2243                                *p = true;
2244                                changed = true;
2245                            }
2246                        }
2247                        if changed {
2248                            work.push(sidx);
2249                        }
2250                    }
2251                }
2252            }
2253        }
2254        for (i, op) in ops.iter().enumerate() {
2255            match *op {
2256                Op::ListPush { list, .. } => {
2257                    let clean = taint_in[i]
2258                        .as_ref()
2259                        .map(|t| is_list[list as usize] && !t[list as usize])
2260                        // Unreachable pushes never run.
2261                        .unwrap_or(true);
2262                    if !clean {
2263                        jt("push-outside-site");
2264                        return None;
2265                    }
2266                }
2267                // ★ AN ELEMENT STORE KEEPS THE VM'S VALUE SEMANTICS. Native code writes through the pinned
2268                // buffer; the VM writes in place only into a register it has proven is a mutable borrow
2269                // (`cow_exempt_regs`) and otherwise copies a shared list on its
2270                // first write. A store into a register that may hold a parameter's list or a self-call's
2271                // result (which may BE a parameter, passed through) — and is not exempt — would reach the
2272                // caller's list, which the VM never does (`walk` returning its param, the caller writing
2273                // item 1: the caller's `arr` changed under native code). So that store copies first.
2274                Op::SetIndex { collection, .. } | Op::SetIndexUnchecked { collection, .. } => {
2275                    let shared = taint_in[i].as_ref().is_some_and(|t| t[collection as usize]);
2276                    if shared && !cow_exempt_regs.contains(&collection) {
2277                        own_before.insert(i);
2278                    }
2279                }
2280                _ => {}
2281            }
2282        }
2283    }
2284    let list_regs: Vec<u16> = (0..nregs_pin as u16)
2285        .filter(|&r| is_list[r as usize])
2286        .collect();
2287    let total_pins = list_regs.len();
2288    if total_pins > 24 {
2289        jt("pins");
2290        return None;
2291    }
2292    let n_params = list_params.len();
2293    let _ = n_params;
2294    // pin id = index into list_regs; pin_of mirrors it per register.
2295    let mut pin_of: Vec<Option<u8>> = vec![None; nregs_pin];
2296    for (id, &r) in list_regs.iter().enumerate() {
2297        pin_of[r as usize] = Some(id as u8);
2298    }
2299    // Register numbers are reused: a slot that held a list earlier may
2300    // return a scalar. Verify each candidate against flow-sensitive returns.
2301    let assumed_set: Vec<Kind> = match declared_ret {
2302        Some(SlotKind::Int) => vec![Kind::Int],
2303        Some(SlotKind::Bool) => vec![Kind::Bool],
2304        Some(SlotKind::Float) => vec![Kind::Float],
2305        Some(SlotKind::CharText) => vec![Kind::CharText],
2306        Some(SlotKind::Word32) => vec![Kind::Word32],
2307        Some(SlotKind::Word64) => vec![Kind::Word64],
2308        None => {
2309            // An undeclared scalar return in a body that handles nodes is most likely a node.
2310            let mut kinds = if nodes {
2311                vec![Kind::Inductive, Kind::Int, Kind::Bool]
2312            } else {
2313                vec![Kind::Int, Kind::Bool]
2314            };
2315            if list_mode && list_params.iter().all(|(_, elem)| *elem == PinElem::Int) {
2316                kinds.push(Kind::IntList);
2317            }
2318            if list_mode && list_params.iter().all(|(_, elem)| *elem == PinElem::Word32) {
2319                kinds.push(Kind::Word32List);
2320            }
2321            kinds
2322        }
2323    };
2324    let binds = if nodes {
2325        inductive::bind_kinds(ops, constants, enums)
2326    } else {
2327        Vec::new()
2328    };
2329    let mut chosen: Option<(Vec<Option<Vec<Kind>>>, Kind)> = None;
2330    for assumed in assumed_set {
2331        let mut entry = vec![Kind::Unknown; register_count as usize + 2];
2332        entry[..param_count as usize].copy_from_slice(&param_entry);
2333        // Self-calls resolve against the assumed signature; calls to OTHER
2334        // functions against their DECLARED all-scalar signatures (the call
2335        // stencil dispatches through the published table; an uncompiled
2336        // callee deopts at the call until it tiers up on its own). This is
2337        // valid in list-owning mode B too: scalar helpers need no pin staging
2338        // and cannot move a caller list buffer.
2339        let resolver = |fi: u16| -> Option<(Kind, Vec<Kind>)> {
2340            if fi == self_fi {
2341                return Some((assumed, param_entry.clone()));
2342            }
2343            let sig = callees.get(fi as usize)?;
2344            let ret = match sig.ret? {
2345                SlotKind::Int => Kind::Int,
2346                SlotKind::Bool => Kind::Bool,
2347                SlotKind::Float => Kind::Float,
2348                SlotKind::CharText => Kind::CharText,
2349                SlotKind::Word32 => Kind::Word32,
2350                SlotKind::Word64 => Kind::Word64,
2351            };
2352            let params = sig
2353                .param_kinds
2354                .iter()
2355                .map(|k| match k {
2356                    Some(ParamKind::Scalar(SlotKind::Int)) => Some(Kind::Int),
2357                    Some(ParamKind::Scalar(SlotKind::Bool)) => Some(Kind::Bool),
2358                    Some(ParamKind::Scalar(SlotKind::Float)) => Some(Kind::Float),
2359                    Some(ParamKind::Scalar(SlotKind::CharText)) => Some(Kind::CharText),
2360                    Some(ParamKind::Scalar(SlotKind::Word32)) => Some(Kind::Word32),
2361                    Some(ParamKind::Scalar(SlotKind::Word64)) => Some(Kind::Word64),
2362                    _ => None,
2363                })
2364                .collect::<Option<Vec<Kind>>>()?;
2365            Some((ret, params))
2366        };
2367        let sites = if mode_b {
2368            fresh_list_kinds(
2369                ops,
2370                entry_pc,
2371                constants,
2372                entry.clone(),
2373                Some(&resolver),
2374                &binds,
2375            )
2376        } else {
2377            Some(FreshSites::Ints)
2378        };
2379        let Some(sites) = sites else {
2380            continue;
2381        };
2382        let Some(kin) = kind_flow_sited(
2383            ops,
2384            entry_pc,
2385            constants,
2386            entry,
2387            Some(&resolver),
2388            &binds,
2389            &sites,
2390        ) else {
2391            continue;
2392        };
2393        // A reachable ReturnNothing would return Nothing, which native code cannot represent. Mode B
2394        // resumes the VM precisely at it (the fall-through after an `Inspect` whose arms cover every
2395        // variant reaches it only on paper); mode A needs it to be dead code. All reachable returns
2396        // must agree on one kind.
2397        let mut ret_kind: Option<Kind> = None;
2398        let mut ok = true;
2399        for (i, op) in ops.iter().enumerate() {
2400            let Some(k) = &kin[i] else { continue };
2401            match *op {
2402                Op::ReturnNothing if mode_b => {}
2403                Op::ReturnNothing => {
2404                    ok = false;
2405                    break;
2406                }
2407                Op::Return { src } => {
2408                    if inout_params
2409                        .iter()
2410                        .any(|&r| k[r as usize] != param_entry[r as usize])
2411                    {
2412                        ok = false;
2413                        break;
2414                    }
2415                    let rk = k[src as usize];
2416                    match ret_kind {
2417                        None => ret_kind = Some(rk),
2418                        Some(prev) if prev == rk => {}
2419                        _ => {
2420                            ok = false;
2421                            break;
2422                        }
2423                    }
2424                }
2425                _ => {}
2426            }
2427        }
2428        if !ok {
2429            continue;
2430        }
2431        let Some(rk) = ret_kind else { continue };
2432        if rk == assumed {
2433            chosen = Some((kin, rk));
2434            break;
2435        }
2436    }
2437    if chosen.is_none() {
2438        jt("chosen");
2439    }
2440    let (kin, ret_kind) = chosen?;
2441    let fn_returns_lists = matches!(ret_kind, Kind::IntList | Kind::Word32List);
2442    let ret_elem = if ret_kind == Kind::Word32List {
2443        PinElem::Word32
2444    } else {
2445        PinElem::Int
2446    };
2447    let ret = if fn_returns_lists {
2448        NativeRet::ListByHandle
2449    } else if ret_kind == Kind::Inductive {
2450        NativeRet::Inductive
2451    } else {
2452        NativeRet::Scalar(ret_kind.slot_kind()?)
2453    };
2454
2455    // The enum lane's ownership plan: where counts are taken, handed over and released.
2456    let plan = if nodes {
2457        let node_params: Vec<bool> = param_entry.iter().map(|k| *k == Kind::Inductive).collect();
2458        let plan = inductive::ownership(
2459            ops,
2460            entry_pc,
2461            &kin,
2462            &live,
2463            &binds,
2464            &node_params,
2465            register_count as usize + 2,
2466            ret_kind == Kind::Inductive,
2467        );
2468        if plan.is_none() {
2469            jt("ownership");
2470        }
2471        Some(plan?)
2472    } else {
2473        None
2474    };
2475    // A native list-building function can run inside another native frame for
2476    // millions of calls. Without a per-call watermark, every scratch Vec stays
2477    // registered until the outermost VM boundary. Scope every list-allocating
2478    // function (not only recursion) so scratch lifetimes match Rust locals.
2479    let scope_exports = function_scope_export_slots(ops, param_count, nodes);
2480    let scoped_allocs = scope_exports != 0;
2481    if scoped_allocs {
2482        logicaffeine_compile::optimize::with_backend_lowering(|| {
2483            logicaffeine_compile::optimize::mark_fired(
2484                logicaffeine_compile::optimization::Opt::Unbox,
2485            )
2486        });
2487    }
2488    // Final mutable parameters are observable even when the return expression
2489    // does not read them. Keep those writes alive through local fusion.
2490    let jump_targets: std::collections::HashSet<usize> = ops
2491        .iter()
2492        .filter_map(|op| match *op {
2493            Op::Jump { target }
2494            | Op::JumpIfFalse { target, .. }
2495            | Op::JumpIfTrue { target, .. } => Some(target),
2496            _ => None,
2497        })
2498        .collect();
2499    let scratch_ok = |_: u16| true;
2500
2501    let conv = (register_count, register_count + 1);
2502    let rc = register_count as usize;
2503    // Frame layout (`function_frame_size`): the published table value is frame_size − 3 in every
2504    // mode, so the call stencil's bound math and limit planting hold unchanged.
2505    let npins = total_pins;
2506    let frame_size = function_frame_size(rc, mode_b, npins, nodes, scope_exports);
2507    if frame_size > u16::MAX as usize {
2508        return None;
2509    }
2510    let export_base = (frame_size - 1 - scope_exports) as u16;
2511    let plant_window = (rc + 2) as u16;
2512    let plant_resume = (rc + 3) as u16;
2513    let plant_dst = (rc + 4) as u16;
2514    let pins_start = rc + 5;
2515    let hold_slot = (pins_start + 3 * npins) as u16;
2516    let mut shapes = NodeShapes::default();
2517    // Ops whose micro range opens with releases emitted ahead of the op's own translation.
2518    let mut range_starts: Vec<(usize, usize)> = Vec::new();
2519    let mut micro: Vec<MicroOp> = Vec::with_capacity(ops.len());
2520    let mut pc_to_micro: Vec<usize> = Vec::with_capacity(ops.len());
2521    let mut fixups: Vec<usize> = Vec::new();
2522
2523    // Every pin-aliased register resolves to its pin's slot triple.
2524    let pin_elem = |j: usize| -> PinElem {
2525        let reg = list_regs[j];
2526        list_params
2527            .iter()
2528            .find(|(preg, _)| *preg == reg)
2529            .map(|(_, e)| *e)
2530            .unwrap_or(PinElem::Int)
2531    };
2532    let pin_slots_of = |j: usize| -> PinSlots {
2533        let base = pins_start + 3 * j;
2534        PinSlots {
2535            vec_slot: base as u16,
2536            ptr_slot: (base + 1) as u16,
2537            len_slot: (base + 2) as u16,
2538            elem: pin_elem(j),
2539        }
2540    };
2541    let mut pins: std::collections::HashMap<u16, PinSlots> = std::collections::HashMap::new();
2542    if mode_b {
2543        for (r, p) in pin_of.iter().enumerate() {
2544            if let Some(j) = p {
2545                pins.insert(r as u16, pin_slots_of(*j as usize));
2546            }
2547        }
2548        // Prologue: my plant is invalid until I make a call (the precise
2549        // walk stops at the first invalid plant).
2550        micro.push(MicroOp::LoadConst {
2551            dst: plant_window,
2552            value: -1,
2553        });
2554        if scoped_allocs {
2555            micro.push(host_call(conv.0, conv.0, 0, 0, logos_rt_alloc_scope_enter));
2556        }
2557        // ENTRY PIN REFRESH — a list PARAMETER's frame register holds its vec
2558        // HANDLE at entry (the VM boundary marshals it there; a region LEVER-B
2559        // cross-function call `Move`s it into the callee window). Derive each
2560        // param pin's vec/ptr/LEN triple FROM that handle so the body reads a
2561        // LIVE length even when reached through a region call — which stages
2562        // only the handle and never runs the `ChainFn::call` pin scatter. Absent
2563        // this, `length of xs` read a stale slot and a `length of`-bounded loop
2564        // never ran (firstGE/matchAt/indexOf returned 0/false once hot). This is
2565        // idempotent for the paths that DO scatter (VM boundary / self-call
2566        // staging re-derive the same values), and makes the callee self-
2567        // sufficient across the region seam. A list-param callee never
2568        // reallocates a param buffer under LEVER B, so the entry triple stays
2569        // valid for the whole body.
2570        for (preg, _) in list_params.iter() {
2571            if let Some(j) = pin_of[*preg as usize] {
2572                let slots = pin_slots_of(j as usize);
2573                micro.push(MicroOp::ListTriple {
2574                    handle_slot: *preg,
2575                    vec_slot: slots.vec_slot,
2576                    ptr_slot: slots.ptr_slot,
2577                    len_slot: slots.len_slot,
2578                    helper_addr: logos_rt_list_triple as usize as i64,
2579                });
2580            }
2581        }
2582        // Every register that ever holds a node starts empty, so a release on a path that never
2583        // wrote it releases nothing.
2584        if let Some(plan) = &plan {
2585            for &r in &plan.zero_at_entry {
2586                micro.push(MicroOp::LoadConst { dst: r, value: 0 });
2587            }
2588            for &r in &plan.retain_at_entry {
2589                micro.push(host_call(r, r, 1, 0, inductive::logos_rt_node_retain));
2590            }
2591        }
2592    }
2593
2594    // Per-pause-point register re-box kinds (deopt sites + call sites).
2595    // Param-pinned list registers re-box as their argument; NATIVE-OWNED
2596    // pins (sites, call results) record their vec-handle slot so the
2597    // deopt walk can detach-or-match them.
2598    let mut kinds_by_pc: std::collections::HashMap<usize, Vec<RegBox>> =
2599        std::collections::HashMap::new();
2600    let mut owned_by_pc: std::collections::HashMap<usize, Vec<(u16, u16, PinElem)>> =
2601        std::collections::HashMap::new();
2602    let mut capture =
2603        |i: usize, kin: &Vec<Option<Vec<Kind>>>, pin_of: &Vec<Option<u8>>| -> Option<()> {
2604            let k = kin[i].as_ref()?;
2605            let mut row = Vec::with_capacity(rc);
2606            let mut owned: Vec<(u16, u16, PinElem)> = Vec::new();
2607            for r in 0..rc {
2608                row.push(match k[r] {
2609                    Kind::Nothing => RegBox::Nothing,
2610                    Kind::Int => RegBox::Int,
2611                    Kind::Bool => RegBox::Bool,
2612                    Kind::Float => RegBox::Float,
2613                    Kind::Word32 => RegBox::Word32,
2614                    Kind::Word64 => RegBox::Word64,
2615                    // No re-box for a narrow word: a deopt with one live would lose it.
2616                    Kind::Word16 => return None,
2617                    Kind::CharText => RegBox::CharText,
2618                    Kind::IntList
2619                    | Kind::IntListI32
2620                    | Kind::Word32List
2621                    | Kind::FloatList
2622                    | Kind::BoolList => {
2623                        let j = pin_of[r]?;
2624                        let elem = if k[r] == Kind::Word32List {
2625                            PinElem::Word32
2626                        } else {
2627                            PinElem::Int
2628                        };
2629                        owned.push((r as u16, pin_slots_of(j as usize).vec_slot, elem));
2630                        RegBox::Resolved
2631                    }
2632                    _ => RegBox::Dead,
2633                });
2634            }
2635            kinds_by_pc.insert(entry_pc + i, row);
2636            owned_by_pc.insert(entry_pc + i, owned);
2637            Some(())
2638        };
2639
2640    // Ops whose releases the loop emitted, and the landing pads a branch's taken edge goes through
2641    // to release the counts that die on it: (branch micro, target op, registers).
2642    let mut placed = vec![false; ops.len()];
2643    let mut pads: Vec<(usize, usize, Vec<u16>)> = Vec::new();
2644    let mut i = 0usize;
2645    while i < ops.len() {
2646        if mode_b {
2647            // ★ EVERY REACHABLE PC IS A POSSIBLE RESUME POINT. A precise deopt resumes at the bytecode pc
2648            // that owns the side-exiting micro, and that set is wider than any list of "deoptable" ops:
2649            // Int `+`/`-`/`*` deopt on signed overflow (the VM re-runs them into a big integer), and a
2650            // fused pair (`Move R9 = R7; Mul R10 = R9 * R9`) attributes its exit to the FIRST op — a Move.
2651            // A missing row panicked the deopt walk (`missing kind capture for pc 53`) the first time an
2652            // overflow hit a list-param function. So the row is captured wherever the op is reachable.
2653            if kin[i].is_some() {
2654                if capture(i, &kin, &pin_of).is_none() {
2655                    jt("capture");
2656                    return None;
2657                }
2658            }
2659            // THE ENUM LANE. The releases the plan puts ahead of op i open its micro range; an op that
2660            // reads the register it overwrites parks the old node in the hold slot. Once the op is done,
2661            // the parked node and every count that died with the op are released (a side exit inside
2662            // the op still finds them all in place).
2663            let op_start = micro.len();
2664            let mut after: Vec<MicroOp> = Vec::new();
2665            if let Some(plan) = &plan {
2666                // A branch's edges are placed once it is translated.
2667                placed[i] = !matches!(ops[i], Op::JumpIfFalse { .. } | Op::JumpIfTrue { .. });
2668                for &r in &plan.release_before[i] {
2669                    micro.push(host_call(r, r, 1, 0, inductive::logos_rt_node_release));
2670                }
2671                if let Some(r) = plan.hold_old[i] {
2672                    micro.push(MicroOp::Move {
2673                        dst: hold_slot,
2674                        src: r,
2675                    });
2676                    after.push(host_call(
2677                        hold_slot,
2678                        hold_slot,
2679                        1,
2680                        0,
2681                        inductive::logos_rt_node_release,
2682                    ));
2683                }
2684                // The counts dying on the way out: a branch releases them on each of its two edges
2685                // (below, once the branch is translated), any other op after it. A jump has none: its
2686                // holds arrive live, and it reads nothing.
2687                if !matches!(ops[i], Op::JumpIfFalse { .. } | Op::JumpIfTrue { .. }) {
2688                    for (_, regs) in &plan.edges[i] {
2689                        for &r in regs {
2690                            after.push(host_call(r, r, 1, 0, inductive::logos_rt_node_release));
2691                        }
2692                    }
2693                }
2694                if micro.len() > op_start {
2695                    range_starts.push((i, op_start));
2696                }
2697                let emitted = match (ops[i], &plan.steps[i]) {
2698                    (Op::NewInductive { .. } | Op::TestArm { .. } | Op::BindArm { .. }, _)
2699                        if kin[i].is_none() =>
2700                    {
2701                        pc_to_micro.push(micro.len());
2702                        true
2703                    }
2704                    (Op::Move { dst, src }, inductive::Step::Move { take, retain }) => {
2705                        pc_to_micro.push(micro.len());
2706                        micro.push(MicroOp::Move { dst, src });
2707                        if *take {
2708                            micro.push(MicroOp::LoadConst { dst: src, value: 0 });
2709                        }
2710                        if *retain {
2711                            micro.push(host_call(dst, dst, 1, 0, inductive::logos_rt_node_retain));
2712                        }
2713                        true
2714                    }
2715                    (
2716                        Op::NewInductive {
2717                            dst,
2718                            type_name,
2719                            ctor,
2720                            args_start,
2721                            count,
2722                        },
2723                        inductive::Step::Construct(fields),
2724                    ) => {
2725                        let (Some(Constant::Text(type_name)), Some(Constant::Text(ctor))) = (
2726                            constants.get(type_name as usize),
2727                            constants.get(ctor as usize),
2728                        ) else {
2729                            jt("node-names");
2730                            return None;
2731                        };
2732                        let shape = Box::new(inductive::Construct {
2733                            type_name: type_name.clone(),
2734                            ctor: ctor.clone(),
2735                            fields: fields.clone(),
2736                        });
2737                        let imm = &*shape as *const inductive::Construct as i64;
2738                        shapes.constructs.push(shape);
2739                        pc_to_micro.push(micro.len());
2740                        micro.push(host_call(
2741                            dst,
2742                            args_start,
2743                            count,
2744                            imm,
2745                            inductive::logos_rt_node_new,
2746                        ));
2747                        // A field that took its register's count leaves the register empty.
2748                        for (k, field) in fields.iter().enumerate() {
2749                            let a = args_start + k as u16;
2750                            if *field == inductive::FieldIn::Take && a != dst {
2751                                micro.push(MicroOp::LoadConst { dst: a, value: 0 });
2752                            }
2753                        }
2754                        true
2755                    }
2756                    (
2757                        Op::TestArm {
2758                            dst,
2759                            target,
2760                            variant,
2761                        },
2762                        _,
2763                    ) => {
2764                        let Some(Constant::Text(name)) = constants.get(variant as usize) else {
2765                            jt("node-variant");
2766                            return None;
2767                        };
2768                        let name = Box::new(name.clone());
2769                        let imm = &*name as *const String as i64;
2770                        shapes.variants.push(name);
2771                        pc_to_micro.push(micro.len());
2772                        micro.push(host_call(
2773                            dst,
2774                            target,
2775                            1,
2776                            imm,
2777                            inductive::logos_rt_node_test,
2778                        ));
2779                        true
2780                    }
2781                    (
2782                        Op::BindArm {
2783                            dst, target, index, ..
2784                        },
2785                        inductive::Step::Field { kind, retain },
2786                    ) => {
2787                        let imm = inductive::field_operand(index, *kind, *retain)?;
2788                        pc_to_micro.push(micro.len());
2789                        micro.push(host_call(
2790                            dst,
2791                            target,
2792                            1,
2793                            imm,
2794                            inductive::logos_rt_node_field,
2795                        ));
2796                        true
2797                    }
2798                    (Op::Return { src }, inductive::Step::Return { retain }) => {
2799                        pc_to_micro.push(micro.len());
2800                        if *retain {
2801                            micro.push(host_call(src, src, 1, 0, inductive::logos_rt_node_retain));
2802                        }
2803                        micro.push(MicroOp::Return { src });
2804                        true
2805                    }
2806                    _ => false,
2807                };
2808                if emitted {
2809                    micro.append(&mut after);
2810                    i += 1;
2811                    continue;
2812                }
2813            }
2814            // A reachable ReturnNothing side-exits, and the VM returns Nothing from the same pc.
2815            if let (Op::ReturnNothing, Some(_)) = (ops[i], &kin[i]) {
2816                pc_to_micro.push(micro.len());
2817                micro.push(host_call(conv.0, conv.0, 0, 0, logos_rt_side_exit));
2818                micro.push(MicroOp::Return { src: conv.0 });
2819                i += 1;
2820                continue;
2821            }
2822            // Mode-B call: the callee windows at base + FRAME_SIZE —
2823            // fully DISJOINT from this frame, because the interpreter's
2824            // compact windowing (base + args_start) would let the callee's
2825            // registers overlap this frame's plant and pin slots and
2826            // clobber them. Arguments are copied into the fresh window,
2827            // self-call pins pass through, while cross-function scalar helpers
2828            // need no pins. The plant records the linkage for the precise walk,
2829            // and the post-return store invalidates it.
2830            if let Op::Call {
2831                dst,
2832                args_start,
2833                arg_count,
2834                func,
2835            } = ops[i]
2836            {
2837                let cross_sig = (func != self_fi)
2838                    .then(|| callees.get(func as usize))
2839                    .flatten();
2840                if func != self_fi
2841                    && !cross_sig.is_some_and(|sig| {
2842                        sig.ret.is_some()
2843                            && sig.inout_params.is_empty()
2844                            && sig
2845                                .param_kinds
2846                                .iter()
2847                                .all(|k| matches!(k, Some(ParamKind::Scalar(_))))
2848                    })
2849                {
2850                    jt("non-scalar-cross-call-mode-b");
2851                    return None;
2852                }
2853                pc_to_micro.push(micro.len());
2854                let window = frame_size as u16;
2855                micro.push(MicroOp::LoadConst {
2856                    dst: plant_window,
2857                    value: window as i64,
2858                });
2859                micro.push(MicroOp::LoadConst {
2860                    dst: plant_resume,
2861                    value: (entry_pc + i + 1) as i64,
2862                });
2863                micro.push(MicroOp::LoadConst {
2864                    dst: plant_dst,
2865                    value: dst as i64,
2866                });
2867                for j in 0..arg_count {
2868                    micro.push(MicroOp::Move {
2869                        dst: window + j,
2870                        src: args_start + j,
2871                    });
2872                }
2873                // Each callee list-param pin receives the triple of WHATEVER
2874                // pin the staged argument carries (a param passthrough, a
2875                // fresh site, or a previous call's result).
2876                if func == self_fi {
2877                    for (slot, (preg, pelem)) in list_params.iter().enumerate() {
2878                        if *pelem != PinElem::Int
2879                            && *pelem != PinElem::Word32
2880                            && *pelem != PinElem::Float
2881                            && *pelem != PinElem::Bool
2882                        {
2883                            return None;
2884                        }
2885                        let Some(arg_pin) = pin_of[(args_start + preg) as usize] else {
2886                            jt("staged-arg-unpinned");
2887                            return None;
2888                        };
2889                        let src_slots = pin_slots_of(arg_pin as usize);
2890                        let dst_base = window + (pins_start + 3 * slot) as u16;
2891                        micro.push(MicroOp::Move {
2892                            dst: dst_base,
2893                            src: src_slots.vec_slot,
2894                        });
2895                        micro.push(MicroOp::Move {
2896                            dst: dst_base + 1,
2897                            src: src_slots.ptr_slot,
2898                        });
2899                        micro.push(MicroOp::Move {
2900                            dst: dst_base + 2,
2901                            src: src_slots.len_slot,
2902                        });
2903                    }
2904                }
2905                let c = call_ctx_in;
2906                micro.push(MicroOp::Call {
2907                    dst,
2908                    args_start: window,
2909                    table_addr: if func == self_fi {
2910                        c.table_addr
2911                    } else {
2912                        c.table.slot_addr(func as usize)
2913                    },
2914                    depth_addr: c.depth_addr,
2915                    status_addr: c.status_addr,
2916                    limit_slot: c.limit_slot,
2917                    depth_limit: c.depth_limit,
2918                });
2919                let call_inouts = if func == self_fi {
2920                    inout_params
2921                } else {
2922                    &callees[func as usize].inout_params
2923                };
2924                for &j in call_inouts {
2925                    let arg = args_start + j;
2926                    micro.push(MicroOp::Move {
2927                        dst: arg,
2928                        src: window + j,
2929                    });
2930                    if let Some(pin) = pins.get(&arg) {
2931                        micro.push(MicroOp::ListTriple {
2932                            handle_slot: arg,
2933                            vec_slot: pin.vec_slot,
2934                            ptr_slot: pin.ptr_slot,
2935                            len_slot: pin.len_slot,
2936                            helper_addr: logos_rt_list_triple as usize as i64,
2937                        });
2938                    }
2939                }
2940                micro.push(MicroOp::LoadConst {
2941                    dst: plant_window,
2942                    value: -1,
2943                });
2944                // A list-returning self-call: plant the result's triple
2945                // from the returned handle.
2946                if func == self_fi && fn_returns_lists {
2947                    if let Some(j) = pin_of[dst as usize] {
2948                        let slots = pin_slots_of(j as usize);
2949                        micro.push(MicroOp::ListTriple {
2950                            handle_slot: dst,
2951                            vec_slot: slots.vec_slot,
2952                            ptr_slot: slots.ptr_slot,
2953                            len_slot: slots.len_slot,
2954                            helper_addr: logos_rt_list_triple as usize as i64,
2955                        });
2956                    }
2957                }
2958                micro.append(&mut after);
2959                i += 1;
2960                continue;
2961            }
2962            // Return through the allocation-scope helper so every invocation
2963            // frees its own scratch lists. A list returns its Vec handle; a
2964            // scalar returns its raw register word. Export final mutable lists
2965            // as well, so the caller can take ownership of their buffers.
2966            if scoped_allocs {
2967                if let Op::Return { src } = ops[i] {
2968                    pc_to_micro.push(micro.len());
2969                    let returned = if let Some(j) =
2970                        pin_of[src as usize].filter(|_| holds_list_at(&kin, i, src))
2971                    {
2972                        pin_slots_of(j as usize).vec_slot
2973                    } else {
2974                        src
2975                    };
2976                    micro.push(MicroOp::Move {
2977                        dst: export_base,
2978                        src: returned,
2979                    });
2980                    let mut exports = 1;
2981                    for &param in inout_params {
2982                        if holds_list_at(&kin, i, param) {
2983                            let pin = pin_of[param as usize]?;
2984                            micro.push(MicroOp::Move {
2985                                dst: export_base + exports,
2986                                src: pin_slots_of(pin as usize).vec_slot,
2987                            });
2988                            exports += 1;
2989                        }
2990                    }
2991                    micro.push(host_call(
2992                        conv.0,
2993                        export_base,
2994                        exports,
2995                        i64::from(!fn_returns_lists),
2996                        logos_rt_alloc_scope_leave,
2997                    ));
2998                    micro.push(MicroOp::Return { src: conv.0 });
2999                    i += 1;
3000                    continue;
3001                }
3002            }
3003            // Only the enum ops and a call read or write a register that owns a node, so no other op
3004            // has releases to place after it.
3005            if !after.is_empty() {
3006                jt("node-release-after");
3007                return None;
3008            }
3009            // Fresh-list allocation: registry-owned, triple planted.
3010            if let Op::NewEmptyList { dst }
3011            | Op::NewEmptyListWithCapacity { dst, .. }
3012            | Op::NewEmptyListFixed { dst, .. }
3013            | Op::NewList { dst, .. } = ops[i]
3014            {
3015                if let Op::NewList { start, count, .. } = ops[i] {
3016                    if !kin[i]
3017                        .as_ref()
3018                        .is_some_and(|k| (start..start + count).all(|r| k[r as usize] == Kind::Int))
3019                    {
3020                        return None;
3021                    }
3022                }
3023                pc_to_micro.push(micro.len());
3024                let j = pin_of[dst as usize].expect("site pins were assigned");
3025                let slots = pin_slots_of(j as usize);
3026                let helper_addr = match ops[i] {
3027                    Op::NewEmptyListFixed { capacity, .. } => {
3028                        micro.push(MicroOp::LoadConst {
3029                            dst: slots.len_slot,
3030                            value: capacity as i64,
3031                        });
3032                        logos_rt_alloc_list_i64_fixed as usize as i64
3033                    }
3034                    Op::NewEmptyListWithCapacity { capacity, .. } => {
3035                        micro.push(MicroOp::Move {
3036                            dst: slots.len_slot,
3037                            src: capacity,
3038                        });
3039                        logos_rt_alloc_list_i64_fixed as usize as i64
3040                    }
3041                    _ => logos_rt_alloc_list_i64 as usize as i64,
3042                };
3043                micro.push(MicroOp::NewList {
3044                    vec_slot: slots.vec_slot,
3045                    ptr_slot: slots.ptr_slot,
3046                    len_slot: slots.len_slot,
3047                    helper_addr,
3048                });
3049                // INVARIANT: a list register's frame slot mirrors its vec
3050                // handle (Moves, staging and returns all ride it).
3051                micro.push(MicroOp::Move {
3052                    dst,
3053                    src: slots.vec_slot,
3054                });
3055                if let Op::NewList { start, count, .. } = ops[i] {
3056                    for src in start..start + count {
3057                        micro.push(MicroOp::ArrPush {
3058                            src,
3059                            vec_slot: slots.vec_slot,
3060                            ptr_slot: slots.ptr_slot,
3061                            len_slot: slots.len_slot,
3062                            helper_addr: logos_rt_push_i64 as usize as i64,
3063                            byte: false,
3064                            narrow32: false,
3065                        });
3066                    }
3067                }
3068                i += 1;
3069                continue;
3070            }
3071            // A Move BETWEEN list registers transfers the handle and
3072            // refreshes the destination's own pin triple from the live
3073            // vector (per-register pins make reassignment conflict-free).
3074            //
3075            // ★ ASKED AT THIS PC, NOT OF THE REGISTER. A VM register is a slot the bytecode compiler
3076            // recycles — a block's bindings when the block closes, a statement's scratch when the
3077            // statement ends — so one register can hold a list here and an Int there. `is_list` says
3078            // only that it holds a list SOMEWHERE (it sizes the pins); treating that as "a list now"
3079            // planted a triple from an Int and dereferenced it as a `*mut Vec` (quicksort, SIGABRT).
3080            // `kin` is the flow-sensitive kind before this op, definite at every reachable Move.
3081            if let Op::Move { dst, src } = ops[i] {
3082                if holds_list_at(&kin, i, src) {
3083                    pc_to_micro.push(micro.len());
3084                    let j = pin_of[dst as usize].expect("list regs are pinned");
3085                    let slots = pin_slots_of(j as usize);
3086                    micro.push(MicroOp::Move { dst, src });
3087                    micro.push(MicroOp::ListTriple {
3088                        handle_slot: dst,
3089                        vec_slot: slots.vec_slot,
3090                        ptr_slot: slots.ptr_slot,
3091                        len_slot: slots.len_slot,
3092                        helper_addr: logos_rt_list_triple as usize as i64,
3093                    });
3094                    i += 1;
3095                    continue;
3096                }
3097            }
3098            // List return: the vec HANDLE rides the return value (the
3099            // boundary detaches registry-owned lists or matches a param).
3100            if let Op::Return { src } = ops[i] {
3101                if let Some(j) = pin_of[src as usize].filter(|_| holds_list_at(&kin, i, src)) {
3102                    pc_to_micro.push(micro.len());
3103                    let slots = pin_slots_of(j as usize);
3104                    micro.push(MicroOp::Move {
3105                        dst: conv.0,
3106                        src: slots.vec_slot,
3107                    });
3108                    micro.push(MicroOp::Return { src: conv.0 });
3109                    i += 1;
3110                    continue;
3111                }
3112            }
3113            // OPERATION FUSION (nbody's hot lever): collapse
3114            //   `t1 = item I of A; t2 = item J of A; D = t1 <op> t2`
3115            // — two loads from the SAME pinned 8-byte float array feeding one
3116            // float add/sub/mul — into a single ArrLoad2F so the two loaded
3117            // f64s never round-trip through the frame. Both scratch loads must
3118            // be single-use (dead after the binop, read only by it), the two
3119            // collapsed ops must not be jump targets (no entry lands between),
3120            // and a bounds failure side-exits to the FIRST Index's bytecode pc
3121            // (captured above, since Index is deoptable) — resuming there
3122            // re-runs all three pure ops, every effect still confined.
3123            if let Some(fused) =
3124                fuse_index2_fbinop(ops, i, entry_pc, &kin, &live, &jump_targets, &pins)
3125            {
3126                if std::env::var_os("LOGOS_JIT_TRACE").is_some() {
3127                    eprintln!(
3128                        "jit-trace: FUSED arrld2 at pc {} -> {:?}",
3129                        entry_pc + i,
3130                        fused
3131                    );
3132                }
3133                pc_to_micro.push(micro.len());
3134                micro.push(fused);
3135                // The j-Index (i+1) and the binop (i+2) map PAST the fused
3136                // micro, so the first Index's deopt range covers exactly it.
3137                pc_to_micro.push(micro.len());
3138                pc_to_micro.push(micro.len());
3139                i += 3;
3140                continue;
3141            }
3142        }
3143        // NATIVE COPY-ON-WRITE: the copy is the first micro of the store's own pc range, so a jump to
3144        // the store runs it and a deopt inside the store resumes AT the store (which the VM re-runs,
3145        // copying the still-unwritten original exactly as the copy did).
3146        let copy_at = if own_before.contains(&i) {
3147            let (Op::SetIndex { collection, .. } | Op::SetIndexUnchecked { collection, .. }) =
3148                ops[i]
3149            else {
3150                unreachable!("own_before holds only element stores")
3151            };
3152            // Allocation sites are Int-lane; a copy of any other element width has no registry form.
3153            if !kin[i]
3154                .as_ref()
3155                .is_some_and(|k| k[collection as usize] == Kind::IntList)
3156            {
3157                jt("copy-on-write-non-int-list");
3158                return None;
3159            }
3160            let slots = pin_slots_of(pin_of[collection as usize]? as usize);
3161            let at = micro.len();
3162            micro.push(MicroOp::ListTriple {
3163                handle_slot: collection,
3164                vec_slot: slots.vec_slot,
3165                ptr_slot: slots.ptr_slot,
3166                len_slot: slots.len_slot,
3167                helper_addr: logos_rt_list_own as usize as i64,
3168            });
3169            Some(at)
3170        } else {
3171            None
3172        };
3173        let step = translate_op(
3174            ops,
3175            i,
3176            entry_pc,
3177            constants,
3178            &kin,
3179            &live,
3180            None,
3181            &jump_targets,
3182            &scratch_ok,
3183            conv,
3184            &pins,
3185            Some(call_ctx_in),
3186            None,
3187            true,
3188            false,
3189            &mut micro,
3190            &mut pc_to_micro,
3191            &mut fixups,
3192        );
3193        if let (Some(at), Some(_)) = (copy_at, step) {
3194            pc_to_micro[i] = at;
3195        }
3196        if step.is_none() {
3197            jt("translate");
3198            if std::env::var_os("LOGOS_JIT_TRACE").is_some() {
3199                eprintln!("jit-trace:   op {:?}", ops[i]);
3200            }
3201        }
3202        let step = step?;
3203        // A branch (alone or fused with its compare) releases what dies on its fall-through edge right
3204        // after the branch micro, and what dies on its taken edge in a landing pad.
3205        if let Some(plan) = &plan {
3206            let b = i + step - 1;
3207            if let Op::JumpIfFalse { .. } | Op::JumpIfTrue { .. } = ops[b] {
3208                let branch = micro.len() - 1;
3209                for (s, regs) in &plan.edges[b] {
3210                    if *s == b + 1 {
3211                        for &r in regs {
3212                            micro.push(host_call(r, r, 1, 0, inductive::logos_rt_node_release));
3213                        }
3214                    } else {
3215                        pads.push((branch, *s, regs.clone()));
3216                    }
3217                }
3218                placed[b] = true;
3219            }
3220        }
3221        i += step;
3222    }
3223    // A jump to an op lands on the releases that open its range.
3224    for &(op, start) in &range_starts {
3225        pc_to_micro[op] = start;
3226    }
3227    // An op folded into its predecessor's translation never emitted its own releases.
3228    if let Some(plan) = &plan {
3229        let unplaced = (0..ops.len()).any(|j| {
3230            !placed[j]
3231                && (!plan.release_before[j].is_empty()
3232                    || plan.hold_old[j].is_some()
3233                    || !plan.edges[j].is_empty())
3234        });
3235        if unplaced {
3236            jt("node-release-fused");
3237            return None;
3238        }
3239    }
3240    // Landing pads: the branch jumps to its pad, the pad releases and jumps on to the target.
3241    for (branch, target, regs) in pads {
3242        let pad = micro.len();
3243        for r in regs {
3244            micro.push(host_call(r, r, 1, 0, inductive::logos_rt_node_release));
3245        }
3246        fixups.push(micro.len());
3247        micro.push(MicroOp::Jump {
3248            target: entry_pc + target,
3249        });
3250        fixups.retain(|&f| f != branch);
3251        match &mut micro[branch] {
3252            MicroOp::JumpIfFalse { target, .. }
3253            | MicroOp::JumpIfTrue { target, .. }
3254            | MicroOp::Branch { target, .. }
3255            | MicroOp::BranchF { target, .. } => *target = pad,
3256            _ => {
3257                jt("node-pad-branch");
3258                return None;
3259            }
3260        }
3261    }
3262    for &fi in &fixups {
3263        match &mut micro[fi] {
3264            MicroOp::Jump { target }
3265            | MicroOp::JumpIfFalse { target, .. }
3266            | MicroOp::JumpIfTrue { target, .. }
3267            | MicroOp::Branch { target, .. }
3268            | MicroOp::BranchF { target, .. } => {
3269                let rebased = target.checked_sub(entry_pc)?;
3270                *target = *pc_to_micro.get(rebased)?;
3271            }
3272            _ => unreachable!(),
3273        }
3274    }
3275    // Function bodies may end on a Return-less path only if the VM never
3276    // reaches it; the chain compiler requires structural termination.
3277    if !matches!(
3278        micro.last(),
3279        Some(MicroOp::Return { .. }) | Some(MicroOp::Jump { .. })
3280    ) {
3281        return None;
3282    }
3283    // Mode B: every micro of bytecode op i carries that op's encoded pc
3284    // so its side exit resumes precisely.
3285    let deopt_codes = if mode_b {
3286        let mut codes = vec![1i64; micro.len()];
3287        for opi in 0..ops.len() {
3288            let lo = pc_to_micro[opi];
3289            let hi = pc_to_micro.get(opi + 1).copied().unwrap_or(micro.len());
3290            let code = (((entry_pc + opi) as i64) << 2) | 3;
3291            for c in codes.iter_mut().take(hi).skip(lo) {
3292                *c = code;
3293            }
3294        }
3295        Some(codes)
3296    } else {
3297        None
3298    };
3299    let param_pin_scatter: Vec<u16> = list_params
3300        .iter()
3301        .map(|(preg, _)| pin_slots_of(pin_of[*preg as usize].unwrap() as usize).vec_slot)
3302        .collect();
3303    let mut nodes_by_pc: std::collections::HashMap<usize, Vec<(u16, inductive::Hold)>> =
3304        std::collections::HashMap::new();
3305    if let Some(plan) = &plan {
3306        for (i, pause) in plan.pause.iter().enumerate() {
3307            let Some(pause) = pause else { continue };
3308            let nodes: Vec<(u16, inductive::Hold)> = pause[..rc]
3309                .iter()
3310                .enumerate()
3311                .filter(|(_, h)| h.is_node())
3312                .map(|(r, h)| (r as u16, *h))
3313                .collect();
3314            nodes_by_pc.insert(entry_pc + i, nodes);
3315        }
3316    }
3317    let precise = if mode_b {
3318        Some(PreciseInfo {
3319            register_count: rc,
3320            kinds_by_pc,
3321            owned_by_pc,
3322            param_pin_scatter,
3323            nodes_by_pc,
3324        })
3325    } else {
3326        None
3327    };
3328    Some(AdaptedFn {
3329        micro,
3330        frame_size,
3331        ret,
3332        ret_elem,
3333        deopt_codes,
3334        precise,
3335        shapes,
3336    })
3337}
3338
3339/// A `Host` micro calling `helper` over the frame.
3340fn host_call(
3341    dst: u16,
3342    src: u16,
3343    count: u16,
3344    imm: i64,
3345    helper: unsafe extern "C" fn(*mut i64, i64, i64, i64, i64) -> i64,
3346) -> MicroOp {
3347    MicroOp::Host {
3348        dst,
3349        src,
3350        count,
3351        imm,
3352        helper_addr: helper as usize as i64,
3353    }
3354}
3355
3356/// If slot `rhs` is a region-constant power of two — its ONLY writer in `ops`
3357/// is a `LoadConst` of `2^k` with `1 <= k <= 62` — return `k`, so an integer
3358/// `x / rhs` can lower to the side-exit-free [`MicroOp::DivPow2`] shift instead
3359/// of an `idiv`. Sound: a single constant writer means `rhs` holds exactly
3360/// `2^k` at every `Div`, in every loop iteration. Any other writer (or an op
3361/// whose defs we cannot determine) disqualifies it.
3362/// The constant `Int` value of `slot` if it is defined EXACTLY ONCE across the region by a `LoadConst` of
3363/// an `Int` — else `None`. SOUND: a variable, multiply-defined, or non-`Int`-defined slot declines (so a
3364/// caller that only handles a compile-time constant, e.g. `pow`'s exponent, falls back to the VM).
3365fn const_int_operand(ops: &[Op], slot: u16, constants: &[Constant]) -> Option<i64> {
3366    let mut found: Option<i64> = None;
3367    for op in ops {
3368        let defs = region_use_def(op)?.1;
3369        if !defs.contains(&slot) {
3370            continue;
3371        }
3372        match op {
3373            Op::LoadConst { dst, idx } if *dst == slot => match constants.get(*idx as usize) {
3374                Some(Constant::Int(v)) if found.is_none() => found = Some(*v),
3375                _ => return None,
3376            },
3377            _ => return None,
3378        }
3379    }
3380    found
3381}
3382
3383fn const_pow2_div(ops: &[Op], rhs: u16, constants: &[Constant]) -> Option<u32> {
3384    let mut k_found: Option<u32> = None;
3385    for op in ops {
3386        let defs = region_use_def(op)?.1;
3387        if !defs.contains(&rhs) {
3388            continue;
3389        }
3390        match op {
3391            Op::LoadConst { dst, idx } if *dst == rhs => match constants.get(*idx as usize) {
3392                Some(Constant::Int(d)) if *d >= 2 && (*d & (*d - 1)) == 0 => {
3393                    let k = d.trailing_zeros();
3394                    if !(1..=62).contains(&k) || k_found.is_some() {
3395                        return None;
3396                    }
3397                    k_found = Some(k);
3398                }
3399                _ => return None,
3400            },
3401            _ => return None,
3402        }
3403    }
3404    k_found
3405}
3406
3407/// The use/def sets of one op from the adaptable subset, or None when the op
3408/// is outside it. `AddAssign` reads AND writes its dst.
3409fn region_use_def(op: &Op) -> Option<(Vec<u16>, Vec<u16>)> {
3410    Some(match *op {
3411        Op::Return { src } => (vec![src], vec![]),
3412        Op::ReturnNothing => (vec![], vec![]),
3413        Op::LoadConst { dst, .. } => (vec![], vec![dst]),
3414        Op::DivPow2 { dst, lhs, .. } => (vec![lhs], vec![dst]),
3415        Op::MagicDivU { dst, lhs, .. } => (vec![lhs], vec![dst]),
3416        Op::Move { dst, src } => (vec![src], vec![dst]),
3417        Op::RevSwap { a, b } => (vec![a, b], vec![a, b]),
3418        // Interpreter-only call-site COW barrier: a no-op in a native region (the
3419        // pinned-buffer / list-param mechanism already governs value semantics here,
3420        // exactly as it did before the barrier existed). Reads `reg` to keep it live.
3421        Op::EnsureOwned { reg } => (vec![reg], vec![]),
3422        Op::BitXor { dst, lhs, rhs }
3423        | Op::BitAnd { dst, lhs, rhs }
3424        | Op::BitOr { dst, lhs, rhs }
3425        | Op::Shl { dst, lhs, rhs }
3426        | Op::Shr { dst, lhs, rhs } => (vec![lhs, rhs], vec![dst]),
3427        Op::Not { dst, src } => (vec![src], vec![dst]),
3428        Op::Index {
3429            dst,
3430            collection,
3431            index,
3432        }
3433        | Op::IndexUnchecked {
3434            dst,
3435            collection,
3436            index,
3437        } => (vec![collection, index], vec![dst]),
3438        Op::Contains {
3439            dst,
3440            collection,
3441            value,
3442        } => (vec![collection, value], vec![dst]),
3443        Op::NewEmptyList { dst } | Op::NewEmptyListFixed { dst, .. } => (vec![], vec![dst]),
3444        Op::NewEmptyListWithCapacity { dst, capacity } => (vec![capacity], vec![dst]),
3445        Op::NewList { dst, start, count } => ((start..start + count).collect(), vec![dst]),
3446        Op::SetIndex {
3447            collection,
3448            index,
3449            value,
3450        }
3451        | Op::SetIndexUnchecked {
3452            collection,
3453            index,
3454            value,
3455        } => (vec![collection, index, value], vec![]),
3456        Op::Length { dst, collection } => (vec![collection], vec![dst]),
3457        Op::ListPush { list, value } => (vec![list, value], vec![]),
3458        Op::NewInductive {
3459            dst,
3460            args_start,
3461            count,
3462            ..
3463        } => ((args_start..args_start + count).collect(), vec![dst]),
3464        Op::TestArm { dst, target, .. } | Op::BindArm { dst, target, .. } => {
3465            (vec![target], vec![dst])
3466        }
3467        Op::Call {
3468            dst,
3469            args_start,
3470            arg_count,
3471            ..
3472        } => ((args_start..args_start + arg_count).collect(), vec![dst]),
3473        Op::CallBuiltin {
3474            dst,
3475            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Sqrt,
3476            args_start,
3477            arg_count,
3478        } if arg_count == 1 => (vec![args_start], vec![dst]),
3479        Op::CallBuiltin {
3480            dst,
3481            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Abs,
3482            args_start,
3483            arg_count,
3484        } if arg_count == 1 => (vec![args_start], vec![dst]),
3485        Op::CallBuiltin {
3486            dst,
3487            builtin:
3488                logicaffeine_compile::semantics::builtins::BuiltinId::Min
3489                | logicaffeine_compile::semantics::builtins::BuiltinId::Max
3490                | logicaffeine_compile::semantics::builtins::BuiltinId::Pow
3491                | logicaffeine_compile::semantics::builtins::BuiltinId::Wand
3492                | logicaffeine_compile::semantics::builtins::BuiltinId::Wor
3493                | logicaffeine_compile::semantics::builtins::BuiltinId::Word64And
3494                | logicaffeine_compile::semantics::builtins::BuiltinId::Word64Shl
3495                | logicaffeine_compile::semantics::builtins::BuiltinId::Word32Shr
3496                | logicaffeine_compile::semantics::builtins::BuiltinId::Word64Shr
3497                | logicaffeine_compile::semantics::builtins::BuiltinId::Rotl
3498                | logicaffeine_compile::semantics::builtins::BuiltinId::Rotr,
3499            args_start,
3500            arg_count,
3501        } if arg_count == 2 => (vec![args_start, args_start + 1], vec![dst]),
3502        Op::CallBuiltin {
3503            dst,
3504            builtin:
3505                logicaffeine_compile::semantics::builtins::BuiltinId::CountOnes
3506                | logicaffeine_compile::semantics::builtins::BuiltinId::LeadingZeros
3507                | logicaffeine_compile::semantics::builtins::BuiltinId::TrailingZeros
3508                | logicaffeine_compile::semantics::builtins::BuiltinId::Floor
3509                | logicaffeine_compile::semantics::builtins::BuiltinId::Ceil
3510                | logicaffeine_compile::semantics::builtins::BuiltinId::Round
3511                | logicaffeine_compile::semantics::builtins::BuiltinId::Word32
3512                | logicaffeine_compile::semantics::builtins::BuiltinId::Word64
3513                | logicaffeine_compile::semantics::builtins::BuiltinId::Word16Make
3514                | logicaffeine_compile::semantics::builtins::BuiltinId::IntOfWord32
3515                | logicaffeine_compile::semantics::builtins::BuiltinId::IntOfWord64
3516                | logicaffeine_compile::semantics::builtins::BuiltinId::IntOfWord16
3517                | logicaffeine_compile::semantics::builtins::BuiltinId::Wnot
3518                | logicaffeine_compile::semantics::builtins::BuiltinId::Chr,
3519            args_start,
3520            arg_count,
3521        } if arg_count == 1 => (vec![args_start], vec![dst]),
3522        Op::Add { dst, lhs, rhs }
3523        | Op::Sub { dst, lhs, rhs }
3524        | Op::Mul { dst, lhs, rhs }
3525        | Op::Div { dst, lhs, rhs }
3526        | Op::Mod { dst, lhs, rhs }
3527        | Op::Lt { dst, lhs, rhs }
3528        | Op::Gt { dst, lhs, rhs }
3529        | Op::LtEq { dst, lhs, rhs }
3530        | Op::GtEq { dst, lhs, rhs }
3531        | Op::Eq { dst, lhs, rhs }
3532        | Op::NotEq { dst, lhs, rhs } => (vec![lhs, rhs], vec![dst]),
3533        Op::AddAssign { dst, src } => (vec![dst, src], vec![dst]),
3534        Op::JumpIfFalse { cond, .. } | Op::JumpIfTrue { cond, .. } => (vec![cond], vec![]),
3535        Op::Jump { .. } => (vec![], vec![]),
3536        // Region-entry metadata: emits no native code (the VM verifies it at
3537        // entry from its own registers + the pinned length). No frame use/def.
3538        Op::RegionBoundsGuard { .. } => (vec![], vec![]),
3539        _ => return None,
3540    })
3541}
3542
3543/// Backward liveness over a bytecode slice to a fixpoint: per-op LIVE-IN
3544/// vectors. Successors are the fall-through and the in-slice jump target;
3545/// out-of-slice targets are exits with empty live-out (exit-observable slots
3546/// flow through the caller's write-back, never the native frame), and
3547/// `Return`/`ReturnNothing` are terminals. None when the slice contains an
3548/// op outside the adaptable subset.
3549fn liveness(ops: &[Op], base_pc: usize, nregs: usize) -> Option<Vec<Vec<bool>>> {
3550    liveness_with_outputs(ops, base_pc, nregs, &[])
3551}
3552
3553fn liveness_with_outputs(
3554    ops: &[Op],
3555    base_pc: usize,
3556    nregs: usize,
3557    outputs: &[u16],
3558) -> Option<Vec<Vec<bool>>> {
3559    let in_slice = |t: usize| (base_pc..base_pc + ops.len()).contains(&t);
3560    fn merge_into(out: &mut [bool], row: &[bool]) {
3561        for (o, &l) in out.iter_mut().zip(row) {
3562            *o |= l;
3563        }
3564    }
3565    let mut live: Vec<Vec<bool>> = vec![vec![false; nregs]; ops.len()];
3566    loop {
3567        let mut changed = false;
3568        for i in (0..ops.len()).rev() {
3569            let Some((uses, defs)) = region_use_def(&ops[i]) else {
3570                if std::env::var_os("LOGOS_RDIAG").is_some() {
3571                    eprintln!("RDIAG-BAIL liveness use_def-unsupported op={:?}", ops[i]);
3572                }
3573                return None;
3574            };
3575            let mut out = vec![false; nregs];
3576            match ops[i] {
3577                Op::Jump { target } => {
3578                    if in_slice(target) {
3579                        merge_into(&mut out, &live[target - base_pc]);
3580                    }
3581                }
3582                Op::JumpIfFalse { target, .. } | Op::JumpIfTrue { target, .. } => {
3583                    if i + 1 < ops.len() {
3584                        merge_into(&mut out, &live[i + 1]);
3585                    }
3586                    if in_slice(target) {
3587                        merge_into(&mut out, &live[target - base_pc]);
3588                    }
3589                }
3590                Op::Return { .. } | Op::ReturnNothing => {
3591                    for &r in outputs {
3592                        out[r as usize] = true;
3593                    }
3594                }
3595                _ => {
3596                    if i + 1 < ops.len() {
3597                        merge_into(&mut out, &live[i + 1]);
3598                    }
3599                }
3600            }
3601            for &d in &defs {
3602                out[d as usize] = false;
3603            }
3604            for &u in &uses {
3605                out[u as usize] = true;
3606            }
3607            if out != live[i] {
3608                live[i] = out;
3609                changed = true;
3610            }
3611        }
3612        if !changed {
3613            break;
3614        }
3615    }
3616    Some(live)
3617}
3618
3619/// The [`Cmp`] a comparison op computes, if it is one.
3620fn cmp_of(op: &Op) -> Option<(Cmp, u16, u16, u16)> {
3621    Some(match *op {
3622        Op::Lt { dst, lhs, rhs } => (Cmp::Lt, dst, lhs, rhs),
3623        Op::Gt { dst, lhs, rhs } => (Cmp::Gt, dst, lhs, rhs),
3624        Op::LtEq { dst, lhs, rhs } => (Cmp::LtEq, dst, lhs, rhs),
3625        Op::GtEq { dst, lhs, rhs } => (Cmp::GtEq, dst, lhs, rhs),
3626        Op::Eq { dst, lhs, rhs } => (Cmp::Eq, dst, lhs, rhs),
3627        Op::NotEq { dst, lhs, rhs } => (Cmp::NotEq, dst, lhs, rhs),
3628        _ => return None,
3629    })
3630}
3631
3632/// When `ops[i]` is a comparison whose dst feeds ONLY the immediately
3633/// following conditional jump, return the fused [`MicroOp::Branch`]
3634/// parameters `(cmp, lhs, rhs, vm_target)` — `cmp` already negated for the
3635/// JumpIfTrue polarity (Branch jumps when its cmp is FALSE). Conditions:
3636/// the dst is dead after the jump (per `live`), no jump lands BETWEEN the
3637/// pair, and `scratch_ok(dst)` (regions: the dst must be an unobservable
3638/// scratch — its value write disappears under fusion).
3639fn fuse_cmp_branch(
3640    ops: &[Op],
3641    i: usize,
3642    base_pc: usize,
3643    live: &[Vec<bool>],
3644    jump_targets: &std::collections::HashSet<usize>,
3645    scratch_ok: &dyn Fn(u16) -> bool,
3646) -> Option<(Cmp, u16, u16, usize)> {
3647    let (cmp, dst, lhs, rhs) = cmp_of(&ops[i])?;
3648    if i + 1 >= ops.len() || jump_targets.contains(&(base_pc + i + 1)) {
3649        return None;
3650    }
3651    let (fused_cmp, target) = match ops[i + 1] {
3652        Op::JumpIfFalse { cond, target } if cond == dst => (cmp, target),
3653        Op::JumpIfTrue { cond, target } if cond == dst => (cmp.negated(), target),
3654        _ => return None,
3655    };
3656    if !scratch_ok(dst) {
3657        return None;
3658    }
3659    // Dead after the jump: not live-in at the fall-through nor at an
3660    // in-slice target (out-of-slice exits are covered by scratch_ok).
3661    let in_slice = |t: usize| (base_pc..base_pc + ops.len()).contains(&t);
3662    if i + 2 < ops.len() && live[i + 2][dst as usize] {
3663        return None;
3664    }
3665    if in_slice(target) && live[target - base_pc][dst as usize] {
3666        return None;
3667    }
3668    Some((fused_cmp, lhs, rhs, target))
3669}
3670
3671/// Detect the fusable triple at `ops[i]`:
3672///   `t1 = item I of A; t2 = item J of A; D = t1 <op> t2`
3673/// — two loads from the SAME pinned 8-byte float array (`A`), both feeding a
3674/// single float add/sub/mul. Returns the collapsed [`MicroOp::ArrLoad2F`].
3675///
3676/// Conditions (all required for soundness/no-loss):
3677/// - the two `item` reads target the SAME pinned collection, which is a
3678///   list of 8-byte FLOAT elements (not a map, not a byte/Bool buffer);
3679/// - both loaded values are FLOATS at the binop (no Int→Float promotion is
3680///   folded — the fused stencil reads raw f64 bits straight from the buffer);
3681/// - the binop's operands are exactly the two scratch loads (for the
3682///   commutative Add/Mul either order; for Sub only `t1 - t2`);
3683/// - both scratches are SINGLE-USE: distinct, dead after the binop, and read
3684///   by nothing between (the three ops are adjacent and i+1/i+2 are not jump
3685///   targets, so no other reader can sneak in);
3686/// - the destination is not one of the scratch slots (the binop overwrites
3687///   its inputs only after both are read — the fused stencil does the same,
3688///   but keeping them distinct avoids any aliasing surprise).
3689fn fuse_index2_fbinop(
3690    ops: &[Op],
3691    i: usize,
3692    base_pc: usize,
3693    kin: &[Option<Vec<Kind>>],
3694    live: &[Vec<bool>],
3695    jump_targets: &std::collections::HashSet<usize>,
3696    pins: &std::collections::HashMap<u16, PinSlots>,
3697) -> Option<MicroOp> {
3698    if i + 3 > ops.len() {
3699        return None;
3700    }
3701    // No fresh entry may land on the second load or the binop, or a jump
3702    // target would skip the first load's effects.
3703    if jump_targets.contains(&(base_pc + i + 1)) || jump_targets.contains(&(base_pc + i + 2)) {
3704        return None;
3705    }
3706    // The first load is the deopt resume point; its kind capture must exist
3707    // (the mode-B loop captures every deoptable op with a known kind row).
3708    if kin.get(i)?.is_none() {
3709        return None;
3710    }
3711    let (t1, coll_a, ix) = match ops[i] {
3712        Op::Index {
3713            dst,
3714            collection,
3715            index,
3716        }
3717        | Op::IndexUnchecked {
3718            dst,
3719            collection,
3720            index,
3721        } => (dst, collection, index),
3722        _ => return None,
3723    };
3724    let (t2, coll_b, jx) = match ops[i + 1] {
3725        Op::Index {
3726            dst,
3727            collection,
3728            index,
3729        }
3730        | Op::IndexUnchecked {
3731            dst,
3732            collection,
3733            index,
3734        } => (dst, collection, index),
3735        _ => return None,
3736    };
3737    if coll_a != coll_b || t1 == t2 {
3738        return None;
3739    }
3740    let (op, dst, lhs, rhs) = match ops[i + 2] {
3741        Op::Add { dst, lhs, rhs } => (FOp::Add, dst, lhs, rhs),
3742        Op::Sub { dst, lhs, rhs } => (FOp::Sub, dst, lhs, rhs),
3743        Op::Mul { dst, lhs, rhs } => (FOp::Mul, dst, lhs, rhs),
3744        _ => return None,
3745    };
3746    // The binop must consume exactly the two scratch loads, mapping i→j so
3747    // the result equals `f(A[I]) <op> f(A[J])`. Add/Mul commute; Sub does not.
3748    let (load_i, load_j) = if lhs == t1 && rhs == t2 {
3749        (ix, jx)
3750    } else if (op == FOp::Add || op == FOp::Mul) && lhs == t2 && rhs == t1 {
3751        (jx, ix)
3752    } else {
3753        return None;
3754    };
3755    if dst == t1 || dst == t2 {
3756        return None;
3757    }
3758    // The collection is a pinned list of 8-byte float elements.
3759    let p = pins.get(&coll_a)?;
3760    if p.elem != PinElem::Float {
3761        return None;
3762    }
3763    // Both loaded values are floats at the binop (the fused stencil reads raw
3764    // f64 bits — an Int element would need a promotion the stencil omits).
3765    let k = kin.get(i + 2)?.as_ref()?;
3766    if k[t1 as usize] != Kind::Float || k[t2 as usize] != Kind::Float {
3767        return None;
3768    }
3769    // Single-use: both scratches dead entering the op after the binop, so the
3770    // collapse drops their frame writes with no observable loss.
3771    let after = live.get(i + 3)?;
3772    if after[t1 as usize] || after[t2 as usize] {
3773        return None;
3774    }
3775    Some(MicroOp::ArrLoad2F {
3776        dst,
3777        i: load_i,
3778        j: load_j,
3779        ptr_slot: p.ptr_slot,
3780        len_slot: p.len_slot,
3781        op,
3782    })
3783}
3784
3785/// Translate the VM op at `i` (or a fused cmp+branch pair) into micro-ops,
3786/// choosing Int or Float forms from the kinds holding at that point and
3787/// inserting the kernel's Int→Float promotion through the two conversion
3788/// scratch slots. Jump-family micro targets keep their RAW VM pcs — the
3789/// caller remaps them (and routes out-of-slice exits). Pushes the pc→micro
3790/// map entries for every VM op it consumes; returns how many it consumed,
3791/// or None when the op (or its kind shape) is outside the subset.
3792#[allow(clippy::too_many_arguments)]
3793fn translate_op(
3794    ops: &[Op],
3795    i: usize,
3796    base_pc: usize,
3797    constants: &[Constant],
3798    kin: &[Option<Vec<Kind>>],
3799    live: &[Vec<bool>],
3800    safe_list_stages: Option<&std::collections::HashSet<(usize, u16)>>,
3801    jump_targets: &std::collections::HashSet<usize>,
3802    scratch_ok: &dyn Fn(u16) -> bool,
3803    conv: (u16, u16),
3804    pins: &std::collections::HashMap<u16, PinSlots>,
3805    call_ctx: Option<&CallCtx>,
3806    region_return: Option<(u16, u16)>,
3807    allow_return: bool,
3808    region: bool,
3809    micro: &mut Vec<MicroOp>,
3810    pc_to_micro: &mut Vec<usize>,
3811    fixups: &mut Vec<usize>,
3812) -> Option<usize> {
3813    pc_to_micro.push(micro.len());
3814    let k = kin[i].as_ref();
3815    // Unreachable ops never execute — emit a placeholder of valid shape so
3816    // pc mapping and structural termination hold.
3817    let kind_of = |r: u16| k.map(|kk| kk[r as usize]).unwrap_or(Kind::Int);
3818    // Resolve a numeric operand to (slot, is_float), inserting a conversion
3819    // into `cslot` when the other side forces a Float promotion.
3820    let promote =
3821        |micro: &mut Vec<MicroOp>, slot: u16, kind: Kind, want_float: bool, cslot: u16| -> u16 {
3822            if want_float && kind == Kind::Int {
3823                micro.push(MicroOp::IntToFloat {
3824                    dst: cslot,
3825                    src: slot,
3826                });
3827                cslot
3828            } else {
3829                slot
3830            }
3831        };
3832
3833    // Fused compare-and-branch first.
3834    if let Some((cmp, lhs, rhs, target)) =
3835        fuse_cmp_branch(ops, i, base_pc, live, jump_targets, scratch_ok)
3836    {
3837        let (lk, rk) = (kind_of(lhs), kind_of(rhs));
3838        let bools = lk == Kind::Bool && rk == Kind::Bool;
3839        if bools && matches!(cmp, Cmp::Eq | Cmp::NotEq) {
3840            pc_to_micro.push(micro.len());
3841            fixups.push(micro.len());
3842            micro.push(MicroOp::Branch {
3843                cmp,
3844                lhs,
3845                rhs,
3846                target,
3847            });
3848            return Some(2);
3849        }
3850        let want_float = lk == Kind::Float || rk == Kind::Float;
3851        if want_float {
3852            let l = promote(micro, lhs, lk, true, conv.0);
3853            let r = promote(micro, rhs, rk, true, conv.1);
3854            pc_to_micro.push(micro.len());
3855            fixups.push(micro.len());
3856            micro.push(MicroOp::BranchF {
3857                cmp,
3858                lhs: l,
3859                rhs: r,
3860                target,
3861            });
3862        } else {
3863            pc_to_micro.push(micro.len());
3864            fixups.push(micro.len());
3865            micro.push(MicroOp::Branch {
3866                cmp,
3867                lhs,
3868                rhs,
3869                target,
3870            });
3871        }
3872        return Some(2);
3873    }
3874
3875    match ops[i] {
3876        Op::LoadConst { dst, idx } => match constants.get(idx as usize)? {
3877            // A loan leaves Nothing until its final argument is copied back.
3878            // Kind gates keep this placeholder out of numeric/list operations.
3879            Constant::Nothing => micro.push(MicroOp::LoadConst { dst, value: 0 }),
3880            Constant::Int(v) => micro.push(MicroOp::LoadConst { dst, value: *v }),
3881            Constant::Float(f) => micro.push(MicroOp::LoadConst {
3882                dst,
3883                value: f.to_bits() as i64,
3884            }),
3885            Constant::Bool(b) => micro.push(MicroOp::LoadConst {
3886                dst,
3887                value: *b as i64,
3888            }),
3889            // A 1-char ASCII text/char literal lowers to its single byte so a
3890            // `Kind::TextByte` comparison against it is an integer compare (the
3891            // strings benchmark's `item i of result equals " "`).
3892            Constant::Char(c) if c.is_ascii() => micro.push(MicroOp::LoadConst {
3893                dst,
3894                value: *c as i64,
3895            }),
3896            Constant::Text(s) if text_const_byte(s).is_some() => micro.push(MicroOp::LoadConst {
3897                dst,
3898                value: text_const_byte(s).unwrap() as i64,
3899            }),
3900            // A MULTI-char ASCII text constant (`text + "XXXXX"`) is consumed ONLY
3901            // as a `StrAppend` source (`Kind::TextConst`, rejected by every other
3902            // gate), which bakes the literal's bytes directly — its frame slot is
3903            // never read as a value. Emit a harmless placeholder so the pc→micro
3904            // mapping stays 1:1 without materializing the (non-scalar) string.
3905            Constant::Text(s) if s.is_ascii() && !s.is_empty() => {
3906                micro.push(MicroOp::LoadConst { dst, value: 0 })
3907            }
3908            _ => return None,
3909        },
3910        Op::Move { dst, src } => micro.push(MicroOp::Move { dst, src }),
3911        Op::RevSwap { a, b } => {
3912            if a != b {
3913                let list = |kind: Kind| {
3914                    matches!(
3915                        kind,
3916                        Kind::IntList
3917                            | Kind::IntListI32
3918                            | Kind::Word32List
3919                            | Kind::FloatList
3920                            | Kind::BoolList
3921                    )
3922                };
3923                if list(kind_of(a)) {
3924                    // List values ride three pinned slots rather than their
3925                    // scalar register slot. Swap the dynamic vector identity,
3926                    // data pointer and length together; also mirror the handle
3927                    // in the register slots for a later list-parameter call.
3928                    // The VM boundary uses `ArrayPin::rebound` to map the final
3929                    // handles back to their original `Rc`s without copying a
3930                    // buffer or adding work to the inner loop.
3931                    let pa = pins.get(&a)?;
3932                    let pb = pins.get(&b)?;
3933                    if pa.elem != pb.elem {
3934                        return None;
3935                    }
3936                    for (left, right) in [
3937                        (pa.vec_slot, pb.vec_slot),
3938                        (pa.ptr_slot, pb.ptr_slot),
3939                        (pa.len_slot, pb.len_slot),
3940                        (a, b),
3941                    ] {
3942                        micro.push(MicroOp::Move {
3943                            dst: conv.0,
3944                            src: left,
3945                        });
3946                        micro.push(MicroOp::Move {
3947                            dst: left,
3948                            src: right,
3949                        });
3950                        micro.push(MicroOp::Move {
3951                            dst: right,
3952                            src: conv.0,
3953                        });
3954                    }
3955                } else {
3956                    micro.push(MicroOp::Move {
3957                        dst: conv.0,
3958                        src: a,
3959                    });
3960                    micro.push(MicroOp::Move { dst: a, src: b });
3961                    micro.push(MicroOp::Move {
3962                        dst: b,
3963                        src: conv.0,
3964                    });
3965                }
3966            }
3967        }
3968        Op::EnsureOwned { .. } => {} // interpreter-only COW barrier — no-op in a native region
3969        Op::DivPow2 { dst, lhs, k } => micro.push(MicroOp::DivPow2 {
3970            dst,
3971            lhs,
3972            k: k as u32,
3973        }),
3974        Op::MagicDivU {
3975            dst,
3976            lhs,
3977            magic,
3978            more,
3979            mul_back,
3980            divisor: _,
3981            wrap: _,
3982        } => micro.push(MicroOp::MagicDivU {
3983            dst,
3984            lhs,
3985            magic,
3986            more,
3987            mul_back,
3988        }),
3989        Op::Add { dst, lhs, rhs }
3990        | Op::Sub { dst, lhs, rhs }
3991        | Op::Mul { dst, lhs, rhs }
3992        | Op::Div { dst, lhs, rhs } => {
3993            let (lk, rk) = (kind_of(lhs), kind_of(rhs));
3994            let word_w = match (lk, rk) {
3995                (Kind::Word32, Kind::Word32) => Some(Kind::Word32),
3996                (Kind::Word64, Kind::Word64) => Some(Kind::Word64),
3997                _ => None,
3998            };
3999            if let Some(wk) = word_w {
4000                // Modular Word `+`/`-`/`*`: the i64 op is WRAPPING, so it is the modular result outright;
4001                // its checked form still deopts on a rare signed overflow, and the VM then re-runs the op on
4002                // the boxed Words — which is ALSO the modular result — so correctness holds either way. A
4003                // Word32 then masks to 2³² (`Word32` operands are `< 2³²`, so add/sub never overflow i64 and
4004                // always mask; a `*` product ≥ 2⁶³ deopts→VM before the mask). A Word64 needs no mask (the
4005                // i64 slot IS the 2⁶⁴ pattern). `Div` on a Word never reaches here (the gate rejects it).
4006                micro.push(match ops[i] {
4007                    Op::Add { .. } => MicroOp::Add { dst, lhs, rhs },
4008                    Op::Sub { .. } => MicroOp::Sub { dst, lhs, rhs },
4009                    Op::Mul { .. } => MicroOp::Mul { dst, lhs, rhs },
4010                    _ => return None,
4011                });
4012                if wk == Kind::Word32 {
4013                    micro.push(MicroOp::LoadConst {
4014                        dst: conv.0,
4015                        value: 0xFFFF_FFFF,
4016                    });
4017                    micro.push(MicroOp::BitAnd {
4018                        dst,
4019                        lhs: dst,
4020                        rhs: conv.0,
4021                    });
4022                }
4023            } else if lk == Kind::Float || rk == Kind::Float {
4024                let l = promote(micro, lhs, lk, true, conv.0);
4025                let r = promote(micro, rhs, rk, true, conv.1);
4026                micro.push(match ops[i] {
4027                    Op::Add { .. } => MicroOp::AddF {
4028                        dst,
4029                        lhs: l,
4030                        rhs: r,
4031                    },
4032                    Op::Sub { .. } => MicroOp::SubF {
4033                        dst,
4034                        lhs: l,
4035                        rhs: r,
4036                    },
4037                    Op::Mul { .. } => MicroOp::MulF {
4038                        dst,
4039                        lhs: l,
4040                        rhs: r,
4041                    },
4042                    _ => MicroOp::DivF {
4043                        dst,
4044                        lhs: l,
4045                        rhs: r,
4046                    },
4047                });
4048            } else {
4049                micro.push(match ops[i] {
4050                    Op::Add { .. } => MicroOp::Add { dst, lhs, rhs },
4051                    Op::Sub { .. } => MicroOp::Sub { dst, lhs, rhs },
4052                    Op::Mul { .. } => MicroOp::Mul { dst, lhs, rhs },
4053                    // integer `x / 2^k` → side-exit-free shift when the divisor
4054                    // is a region-constant power of two (collatz, heap_sort i/2,
4055                    // mergesort (lo+hi)/2).
4056                    _ => match const_pow2_div(ops, rhs, constants) {
4057                        Some(k) => MicroOp::DivPow2 { dst, lhs, k },
4058                        None => MicroOp::Div { dst, lhs, rhs },
4059                    },
4060                });
4061            }
4062        }
4063        Op::AddAssign { dst, src } => {
4064            let (dk, sk) = (kind_of(dst), kind_of(src));
4065            if dk == Kind::TextMut {
4066                // A pinned mutable-Text accumulator grows through the `StrAppend`
4067                // helper. The handle is the pin's vec slot (a `*mut Value`). The
4068                // source is a 1-char runtime byte (`TextByte` — the byte VALUE
4069                // rides its frame slot), an `Int` (its decimal text, as the VM's
4070                // `Text + Int` writes it) or a multi-char ASCII constant
4071                // (`TextConst` — recover the literal's bytes and bake a `'static`
4072                // slice). The handle slot is force-frame-resident so a non-frame
4073                // (register-resident) handle is impossible here.
4074                let p = pins.get(&dst)?;
4075                let strsrc = match sk {
4076                    Kind::TextByte => logicaffeine_forge::jit::StrSrc::Byte(src),
4077                    Kind::Int => logicaffeine_forge::jit::StrSrc::Int(src),
4078                    Kind::TextConst => {
4079                        let (ptr, len) = const_text_slice(ops, i, base_pc, src, constants)?;
4080                        logicaffeine_forge::jit::StrSrc::Const { ptr, len }
4081                    }
4082                    _ => return None,
4083                };
4084                micro.push(MicroOp::StrAppend {
4085                    text_handle_slot: p.vec_slot,
4086                    src: strsrc,
4087                    helper_addr: crate::logos_rt_str_append as usize as i64,
4088                });
4089            } else if matches!(
4090                (dk, sk),
4091                (Kind::Word32, Kind::Word32) | (Kind::Word64, Kind::Word64)
4092            ) {
4093                // Modular Word `acc += x` — the checked-i64 add is the wrapping result (a rare overflow
4094                // deopts→VM, also modular); a Word32 then re-masks to 2³², a Word64 needs none. Mirrors the
4095                // `Op::Add` Word branch.
4096                micro.push(MicroOp::Add {
4097                    dst,
4098                    lhs: dst,
4099                    rhs: src,
4100                });
4101                if dk == Kind::Word32 {
4102                    micro.push(MicroOp::LoadConst {
4103                        dst: conv.0,
4104                        value: 0xFFFF_FFFF,
4105                    });
4106                    micro.push(MicroOp::BitAnd {
4107                        dst,
4108                        lhs: dst,
4109                        rhs: conv.0,
4110                    });
4111                }
4112            } else if dk == Kind::Float || sk == Kind::Float {
4113                let l = promote(micro, dst, dk, true, conv.0);
4114                let r = promote(micro, src, sk, true, conv.1);
4115                micro.push(MicroOp::AddF {
4116                    dst,
4117                    lhs: l,
4118                    rhs: r,
4119                });
4120            } else {
4121                micro.push(MicroOp::Add {
4122                    dst,
4123                    lhs: dst,
4124                    rhs: src,
4125                });
4126            }
4127        }
4128        Op::Mod { dst, lhs, rhs } => micro.push(MicroOp::Mod { dst, lhs, rhs }),
4129        Op::BitXor { dst, lhs, rhs } => micro.push(MicroOp::BitXor { dst, lhs, rhs }),
4130        Op::Shl { dst, lhs, rhs } => micro.push(MicroOp::Shl { dst, lhs, rhs }),
4131        Op::Shr { dst, lhs, rhs } => micro.push(MicroOp::Shr { dst, lhs, rhs }),
4132        Op::BitAnd { dst, lhs, rhs } => micro.push(MicroOp::BitAnd { dst, lhs, rhs }),
4133        Op::BitOr { dst, lhs, rhs } => micro.push(MicroOp::BitOr { dst, lhs, rhs }),
4134        Op::Not { dst, src } => match kind_of(src) {
4135            Kind::Bool => micro.push(MicroOp::NotBool { dst, src }),
4136            // The region guard admits `Not` only on Bool; a bitwise NotInt
4137            // here would silently miscompile the logical `not` — fail closed.
4138            _ => return None,
4139        },
4140        Op::Lt { dst, lhs, rhs }
4141        | Op::Gt { dst, lhs, rhs }
4142        | Op::LtEq { dst, lhs, rhs }
4143        | Op::GtEq { dst, lhs, rhs }
4144        | Op::Eq { dst, lhs, rhs }
4145        | Op::NotEq { dst, lhs, rhs } => {
4146            let (lk, rk) = (kind_of(lhs), kind_of(rhs));
4147            if lk == Kind::Float || rk == Kind::Float {
4148                let l = promote(micro, lhs, lk, true, conv.0);
4149                let r = promote(micro, rhs, rk, true, conv.1);
4150                micro.push(match ops[i] {
4151                    Op::Lt { .. } => MicroOp::LtF {
4152                        dst,
4153                        lhs: l,
4154                        rhs: r,
4155                    },
4156                    Op::Gt { .. } => MicroOp::GtF {
4157                        dst,
4158                        lhs: l,
4159                        rhs: r,
4160                    },
4161                    Op::LtEq { .. } => MicroOp::LtEqF {
4162                        dst,
4163                        lhs: l,
4164                        rhs: r,
4165                    },
4166                    Op::GtEq { .. } => MicroOp::GtEqF {
4167                        dst,
4168                        lhs: l,
4169                        rhs: r,
4170                    },
4171                    Op::Eq { .. } => MicroOp::EqF {
4172                        dst,
4173                        lhs: l,
4174                        rhs: r,
4175                    },
4176                    _ => MicroOp::NeqF {
4177                        dst,
4178                        lhs: l,
4179                        rhs: r,
4180                    },
4181                });
4182            } else {
4183                micro.push(match ops[i] {
4184                    Op::Lt { .. } => MicroOp::Lt { dst, lhs, rhs },
4185                    Op::Gt { .. } => MicroOp::Gt { dst, lhs, rhs },
4186                    Op::LtEq { .. } => MicroOp::LtEq { dst, lhs, rhs },
4187                    Op::GtEq { .. } => MicroOp::GtEq { dst, lhs, rhs },
4188                    Op::Eq { .. } => MicroOp::Eq { dst, lhs, rhs },
4189                    _ => MicroOp::Neq { dst, lhs, rhs },
4190                });
4191            }
4192        }
4193        Op::Jump { target } => {
4194            fixups.push(micro.len());
4195            micro.push(MicroOp::Jump { target });
4196        }
4197        Op::JumpIfFalse { cond, target } => {
4198            fixups.push(micro.len());
4199            micro.push(MicroOp::JumpIfFalse { cond, target });
4200        }
4201        Op::JumpIfTrue { cond, target } => {
4202            fixups.push(micro.len());
4203            micro.push(MicroOp::JumpIfTrue { cond, target });
4204        }
4205        // `IndexUnchecked` carries the Oracle's in-bounds proof (M9 range
4206        // analysis): its array load drops the bounds branch entirely
4207        // (V8/LLVM-style bounds-check elimination). Maps always check
4208        // through their helper, so the proof only affects the list lane.
4209        Op::Index {
4210            dst,
4211            collection,
4212            index,
4213        }
4214        | Op::IndexUnchecked {
4215            dst,
4216            collection,
4217            index,
4218        } => {
4219            // Elision is region-only: the function tier has no per-loop entry
4220            // guard, so it keeps every access checked (a speculative
4221            // `IndexUnchecked` there would be unguarded). Static proofs lose
4222            // nothing measurable in functions.
4223            let p = pins.get(&collection)?;
4224            if p.elem == PinElem::Map {
4225                micro.push(MicroOp::MapGet {
4226                    dst,
4227                    key: index,
4228                    map_slot: p.vec_slot,
4229                    helper_addr: logos_rt_map_get_ii as usize as i64,
4230                });
4231            } else {
4232                // A Text-as-bytes pin loads ONE byte (the ASCII char codepoint)
4233                // and is ALWAYS bounds-checked: indexing past an ASCII text must
4234                // raise the same error at the same point as the tree-walker's
4235                // per-char path (`IndexUnchecked` elision is never applied to a
4236                // text — no RegionBoundsGuard is emitted for it). Bool buffers
4237                // are 1-byte too; Int/Float are 8-byte.
4238                let text = p.elem == PinElem::TextBytes;
4239                let byte = text || p.elem == PinElem::Bool;
4240                let narrow32 = p.elem == PinElem::IntI32;
4241                let checked = text || !region || matches!(ops[i], Op::Index { .. });
4242                micro.push(MicroOp::ArrLoad {
4243                    dst,
4244                    idx: index,
4245                    ptr_slot: p.ptr_slot,
4246                    len_slot: p.len_slot,
4247                    byte,
4248                    narrow32,
4249                    checked,
4250                });
4251            }
4252        }
4253        Op::SetIndex {
4254            collection,
4255            index,
4256            value,
4257        }
4258        | Op::SetIndexUnchecked {
4259            collection,
4260            index,
4261            value,
4262        } => {
4263            // Region-only elision (see `Index`); maps always check.
4264            let checked = !region || matches!(ops[i], Op::SetIndex { .. });
4265            let p = pins.get(&collection)?;
4266            // A Text pin is read-only — `Set item i of text` never tiers (the
4267            // kind gate already rejects it; bail defensively too).
4268            if p.elem == PinElem::TextBytes {
4269                return None;
4270            }
4271            if p.elem == PinElem::Map {
4272                micro.push(MicroOp::MapSet {
4273                    src: value,
4274                    key: index,
4275                    map_slot: p.vec_slot,
4276                    helper_addr: logos_rt_map_set_ii as usize as i64,
4277                });
4278            } else {
4279                let byte = p.elem == PinElem::Bool;
4280                let narrow32 = p.elem == PinElem::IntI32;
4281                micro.push(MicroOp::ArrStore {
4282                    src: value,
4283                    idx: index,
4284                    ptr_slot: p.ptr_slot,
4285                    len_slot: p.len_slot,
4286                    byte,
4287                    narrow32,
4288                    checked,
4289                });
4290            }
4291        }
4292        Op::Contains {
4293            dst,
4294            collection,
4295            value,
4296        } => {
4297            let p = pins.get(&collection)?;
4298            if p.elem != PinElem::Map {
4299                return None;
4300            }
4301            micro.push(MicroOp::MapHas {
4302                dst,
4303                key: value,
4304                map_slot: p.vec_slot,
4305                helper_addr: logos_rt_map_has_i as usize as i64,
4306            });
4307        }
4308        Op::Length { dst, collection } => {
4309            // `length of chr(code)` — a `CharText` is carried unboxed as its code point, and its `Length`
4310            // is the UTF-8 BYTE length of that scalar (1..4 bytes, never a constant 1), matching the
4311            // tree-walker's byte-count `Length` over the boxed 1-char `Text`. `Utf8Len` computes it from
4312            // the code register (this is how a CharText is consumed to a scalar so `chr` tiers without a
4313            // boxed region output). Any other length rides the pinned collection's length slot.
4314            if matches!(kind_of(collection), Kind::CharText) {
4315                micro.push(MicroOp::Utf8Len {
4316                    dst,
4317                    src: collection,
4318                });
4319            } else {
4320                let p = pins.get(&collection)?;
4321                micro.push(MicroOp::Move {
4322                    dst,
4323                    src: p.len_slot,
4324                });
4325            }
4326        }
4327        Op::ListPush { list, value } => {
4328            let p = pins.get(&list)?;
4329            let helper_addr = match p.elem {
4330                PinElem::Int => crate::logos_rt_push_i64 as usize as i64,
4331                // A `Words32` buffer is `Vec<i64>`; the pushed Word32 rides its masked value → the i64 push.
4332                PinElem::Word32 => crate::logos_rt_push_i64 as usize as i64,
4333                PinElem::IntI32 => crate::logos_rt_push_i32 as usize as i64,
4334                PinElem::Float => crate::logos_rt_push_f64 as usize as i64,
4335                PinElem::Bool => crate::logos_rt_push_bool as usize as i64,
4336                // No push onto a map or a text accumulator.
4337                PinElem::Map | PinElem::TextBytes | PinElem::TextMut => return None,
4338            };
4339            micro.push(MicroOp::ArrPush {
4340                src: value,
4341                vec_slot: p.vec_slot,
4342                ptr_slot: p.ptr_slot,
4343                len_slot: p.len_slot,
4344                helper_addr,
4345                // A `Seq of Bool` buffer is 1-byte; the inline fast-path store
4346                // writes the boolean normalization. Int/Float are 8-byte raw;
4347                // a narrowed `IntsI32` buffer is 4-byte (truncating push).
4348                byte: p.elem == PinElem::Bool,
4349                narrow32: p.elem == PinElem::IntI32,
4350            });
4351        }
4352        Op::NewEmptyList { dst } | Op::NewEmptyListFixed { dst, .. } => {
4353            // In-region `Let x be a new Seq` on a PINNED array: clear it in place
4354            // (truncate + reset the pinned length, keep the buffer) and reuse it,
4355            // rather than allocating fresh. An in-place mutation — the precise
4356            // region resumes over it soundly. Bails (`?`) for a non-pinned dst:
4357            // such a fresh list has no pin channel to clear here.
4358            let Some(p) = pins.get(&dst) else {
4359                if std::env::var_os("LOGOS_RDIAG").is_some() {
4360                    eprintln!("RDIAG-BAIL list-clear-unpinned dst={dst}");
4361                }
4362                return None;
4363            };
4364            // SOUNDNESS: reusing the buffer is only valid if the old contents
4365            // are dead. A `Move { src: dst }` that copies THIS list's handle to
4366            // another register ALIASES the buffer past the clear — reusing it
4367            // would wipe the alias's live data (knapsack's `Set prev to curr`,
4368            // where the cleared row is the one `prev` now points at). But the
4369            // compiler reuses register slots, so `dst` may also be a Move source
4370            // while it transiently holds an UNRELATED scalar (fannkuch's `perm`
4371            // slot is a `Sub` result moved out one op before the `NewEmptyList`
4372            // re-binds it to the list). Such a move reads the scalar, not the
4373            // list, and is irrelevant to buffer reuse. The kind flow already
4374            // resolves which value `dst` holds at each op: a move aliases the
4375            // list iff `dst` holds a LIST kind there (Mixed = a list joined with
4376            // a scalar across paths ⇒ conservatively an alias). A scalar kind
4377            // (or an unreachable/`Unknown` op) provably does not observe the
4378            // list, so clear-reuse stays sound. This is the same alias test the
4379            // VM makes dynamically (sole-ownership), lifted to the static kind
4380            // flow.
4381            let list_handle_escapes = ops.iter().enumerate().any(|(j, o)| {
4382                matches!(o, Op::Move { src, .. } if *src == dst)
4383                    && matches!(
4384                        kin[j].as_ref().map(|kk| kk[dst as usize]),
4385                        Some(
4386                            Kind::IntList
4387                                | Kind::IntListI32
4388                                | Kind::Word32List
4389                                | Kind::FloatList
4390                                | Kind::BoolList
4391                                | Kind::IntMap
4392                                | Kind::Mixed
4393                        )
4394                    )
4395                    && !safe_list_stages.is_some_and(|safe| safe.contains(&(j, dst)))
4396            });
4397            if list_handle_escapes {
4398                if std::env::var_os("LOGOS_RDIAG").is_some() {
4399                    let aliases: Vec<(usize, Op)> = ops
4400                        .iter()
4401                        .enumerate()
4402                        .filter_map(|(j, op)| {
4403                            matches!(op, Op::Move { src, .. } if *src == dst)
4404                                .then_some((base_pc + j, op.clone()))
4405                        })
4406                        .collect();
4407                    eprintln!("RDIAG-BAIL list-clear-alias dst={dst} aliases={aliases:?}");
4408                }
4409                return None;
4410            }
4411            let helper_addr = match p.elem {
4412                PinElem::Int => crate::logos_rt_clear_i64 as usize as i64,
4413                PinElem::Word32 => crate::logos_rt_clear_i64 as usize as i64,
4414                PinElem::IntI32 => crate::logos_rt_clear_i32 as usize as i64,
4415                PinElem::Float => crate::logos_rt_clear_f64 as usize as i64,
4416                PinElem::Bool => crate::logos_rt_clear_bool as usize as i64,
4417                // No empty-list clear for a map or text pin.
4418                PinElem::Map | PinElem::TextBytes | PinElem::TextMut => return None,
4419            };
4420            micro.push(MicroOp::ListClear {
4421                vec_slot: p.vec_slot,
4422                ptr_slot: p.ptr_slot,
4423                len_slot: p.len_slot,
4424                helper_addr,
4425            });
4426            // The pin triple is the region's authoritative list storage, but
4427            // a compiled callee receives list arguments through ordinary
4428            // frame registers. Rebinding `dst` to a fresh list therefore
4429            // must also materialize the raw Vec handle into that register;
4430            // otherwise a later compiler-generated argument-stage Move would
4431            // copy the stale boxed/zero VM slot into the callee.
4432            micro.push(MicroOp::Move {
4433                dst,
4434                src: p.vec_slot,
4435            });
4436        }
4437        // A dynamic reserve cannot be represented by the region clear/reuse micro-op yet. Decline the
4438        // region explicitly so the function adapter can still compile the same operation with the
4439        // capacity-preserving allocator above.
4440        Op::NewEmptyListWithCapacity { .. } => {
4441            jt("region-list-capacity");
4442            return None;
4443        }
4444        Op::CallBuiltin {
4445            dst,
4446            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Abs,
4447            args_start,
4448            arg_count,
4449        } => {
4450            // Int `abs`, branchless — NO new stencil, only existing integer MicroOps: with
4451            //   mask = x >>ᵃ 63   (arithmetic shift: 0 when x≥0, all-ones when x<0)
4452            //   dst  = (x ^ mask) − mask
4453            // For x≥0: mask=0 ⇒ dst = x. For x<0: mask=−1 ⇒ dst = (~x) − (−1) = −x. Exactly `abs`.
4454            // Float abs (an XMM sign-bit clear) has no stencil yet, so it declines and stays on the VM.
4455            if arg_count != 1 || kind_of(args_start) != Kind::Int {
4456                return None;
4457            }
4458            micro.push(MicroOp::LoadConst {
4459                dst: conv.0,
4460                value: 63,
4461            });
4462            micro.push(MicroOp::Shr {
4463                dst: conv.1,
4464                lhs: args_start,
4465                rhs: conv.0,
4466            });
4467            micro.push(MicroOp::BitXor {
4468                dst: conv.0,
4469                lhs: args_start,
4470                rhs: conv.1,
4471            });
4472            micro.push(MicroOp::Sub {
4473                dst,
4474                lhs: conv.0,
4475                rhs: conv.1,
4476            });
4477        }
4478        Op::CallBuiltin {
4479            dst,
4480            builtin:
4481                bid @ (logicaffeine_compile::semantics::builtins::BuiltinId::Min
4482                | logicaffeine_compile::semantics::builtins::BuiltinId::Max),
4483            args_start,
4484            arg_count,
4485        } => {
4486            // Int min/max, branchless, NO new stencil — only existing integer MicroOps. With
4487            //   mask = 0 − (a < b)          (0 when a≥b, all-ones when a<b)
4488            //   min  = b ^ ((a ^ b) & mask)   max = a ^ ((a ^ b) & mask)
4489            // For a<b (mask=−1): min = b^(a^b)=a, max = a^(a^b)=b. For a≥b (mask=0): min=b, max=a.
4490            // Float min/max (minsd/maxsd) has no stencil yet, so it declines and stays on the VM.
4491            let a = args_start;
4492            let b2 = args_start + 1;
4493            if arg_count != 2 || kind_of(a) != Kind::Int || kind_of(b2) != Kind::Int {
4494                return None;
4495            }
4496            let is_min = matches!(
4497                bid,
4498                logicaffeine_compile::semantics::builtins::BuiltinId::Min
4499            );
4500            micro.push(MicroOp::Lt {
4501                dst: conv.0,
4502                lhs: a,
4503                rhs: b2,
4504            }); // lt = (a<b) as 0/1
4505            micro.push(MicroOp::LoadConst {
4506                dst: conv.1,
4507                value: 0,
4508            });
4509            micro.push(MicroOp::Sub {
4510                dst: conv.0,
4511                lhs: conv.1,
4512                rhs: conv.0,
4513            }); // mask = 0 − lt
4514            micro.push(MicroOp::BitXor {
4515                dst: conv.1,
4516                lhs: a,
4517                rhs: b2,
4518            }); // a ^ b
4519            micro.push(MicroOp::BitAnd {
4520                dst: conv.1,
4521                lhs: conv.1,
4522                rhs: conv.0,
4523            }); // (a^b) & mask
4524            let base = if is_min { b2 } else { a };
4525            micro.push(MicroOp::BitXor {
4526                dst,
4527                lhs: base,
4528                rhs: conv.1,
4529            });
4530        }
4531        Op::CallBuiltin {
4532            dst,
4533            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::CountOnes,
4534            args_start,
4535            arg_count,
4536        } => {
4537            // Int popcount → the native `popcnt` instruction. Its src is `gp_blocked` from register
4538            // pinning (see the pin selector) so the frame-reading stencil never reads a stale slot.
4539            if arg_count != 1 || kind_of(args_start) != Kind::Int {
4540                return None;
4541            }
4542            // `popcnt` #UDs on a pre-SSE4.2 CPU; decline to the VM there so the JIT never faults.
4543            #[cfg(target_arch = "x86_64")]
4544            if !std::arch::is_x86_feature_detected!("popcnt") {
4545                return None;
4546            }
4547            micro.push(MicroOp::Popcnt {
4548                dst,
4549                src: args_start,
4550            });
4551        }
4552        Op::CallBuiltin {
4553            dst,
4554            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::LeadingZeros,
4555            args_start,
4556            arg_count,
4557        } => {
4558            // Int leading-zero count → the native `lzcnt` instruction (64 for 0). Like popcnt its src is
4559            // `gp_blocked` so a register-pinned source is read from the pin, never a stale frame slot.
4560            if arg_count != 1 || kind_of(args_start) != Kind::Int {
4561                return None;
4562            }
4563            // `lzcnt` needs ABM; without it the encoding SILENTLY decodes as `bsr` (undefined for 0), so
4564            // decline to the VM on any CPU lacking the feature — correctness holds everywhere.
4565            #[cfg(target_arch = "x86_64")]
4566            if !std::arch::is_x86_feature_detected!("lzcnt") {
4567                return None;
4568            }
4569            micro.push(MicroOp::Lzcnt {
4570                dst,
4571                src: args_start,
4572            });
4573        }
4574        Op::CallBuiltin {
4575            dst,
4576            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::TrailingZeros,
4577            args_start,
4578            arg_count,
4579        } => {
4580            // Int trailing-zero count → the native `tzcnt` instruction (64 for 0). Like popcnt its src is
4581            // `gp_blocked` so a register-pinned source is read from the pin, never a stale frame slot.
4582            if arg_count != 1 || kind_of(args_start) != Kind::Int {
4583                return None;
4584            }
4585            // `tzcnt` needs BMI1; without it the encoding SILENTLY decodes as `bsf` (undefined for 0), so
4586            // decline to the VM on any CPU lacking the feature — correctness holds everywhere.
4587            #[cfg(target_arch = "x86_64")]
4588            if !std::arch::is_x86_feature_detected!("bmi1") {
4589                return None;
4590            }
4591            micro.push(MicroOp::Tzcnt {
4592                dst,
4593                src: args_start,
4594            });
4595        }
4596        Op::CallBuiltin {
4597            dst,
4598            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Floor,
4599            args_start,
4600            arg_count,
4601        } => {
4602            // `floor(f: Float) -> Int` → `roundsd …,1` + saturating `cvttsd2si`. Only the FLOAT arg tiers
4603            // (an Int/Rational/Decimal `floor` is a different, boxed path the VM keeps).
4604            if arg_count != 1 || kind_of(args_start) != Kind::Float {
4605                return None;
4606            }
4607            // `roundsd` needs SSE4.1; without it the instruction #UDs, so decline to the VM there.
4608            #[cfg(target_arch = "x86_64")]
4609            if !std::arch::is_x86_feature_detected!("sse4.1") {
4610                return None;
4611            }
4612            micro.push(MicroOp::FloorToInt {
4613                dst,
4614                src: args_start,
4615            });
4616        }
4617        Op::CallBuiltin {
4618            dst,
4619            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Ceil,
4620            args_start,
4621            arg_count,
4622        } => {
4623            if arg_count != 1 || kind_of(args_start) != Kind::Float {
4624                return None;
4625            }
4626            #[cfg(target_arch = "x86_64")]
4627            if !std::arch::is_x86_feature_detected!("sse4.1") {
4628                return None;
4629            }
4630            micro.push(MicroOp::CeilToInt {
4631                dst,
4632                src: args_start,
4633            });
4634        }
4635        Op::CallBuiltin {
4636            dst,
4637            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Round,
4638            args_start,
4639            arg_count,
4640        } => {
4641            // `round(f: Float) -> Int`, ties AWAY from zero → `roundsd …,3` (trunc) + ties-away adjust +
4642            // saturating `cvttsd2si` (roundsd's nearest mode ties to EVEN, which LOGOS `round` is not).
4643            if arg_count != 1 || kind_of(args_start) != Kind::Float {
4644                return None;
4645            }
4646            #[cfg(target_arch = "x86_64")]
4647            if !std::arch::is_x86_feature_detected!("sse4.1") {
4648                return None;
4649            }
4650            micro.push(MicroOp::RoundToInt {
4651                dst,
4652                src: args_start,
4653            });
4654        }
4655        Op::CallBuiltin {
4656            dst,
4657            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Pow,
4658            args_start,
4659            arg_count,
4660        } if arg_count == 2 => {
4661            // `pow(base: Int, e)` with a small non-negative CONSTANT `e` → UNROLLED checked Muls. Each Mul
4662            // deopts to a BigInt recompute on overflow, so the result matches the VM's `checked_pow` →
4663            // BigInt exactly. A Float base, or a variable / negative / too-large exponent, declines to VM.
4664            // (A variable exponent would need a runtime loop, which one builtin lowering cannot emit.)
4665            if kind_of(args_start) != Kind::Int {
4666                return None;
4667            }
4668            let e = const_int_operand(ops, args_start + 1, constants)?;
4669            // Cap the unroll so a huge constant exponent doesn't explode the code; larger → VM.
4670            if !(0..=32).contains(&e) {
4671                return None;
4672            }
4673            if e == 0 {
4674                micro.push(MicroOp::LoadConst { dst, value: 1 });
4675            } else if e == 1 {
4676                micro.push(MicroOp::Move {
4677                    dst,
4678                    src: args_start,
4679                });
4680            } else {
4681                // acc = base²; acc *= base another (e−2) times; then dst = acc. Accumulating in the scratch
4682                // `conv.0` leaves `dst` UNWRITTEN until success, so a mid-chain overflow deopt (which
4683                // reconstructs at this pow PC and lets the VM recompute) never sees a partial `dst`.
4684                micro.push(MicroOp::Mul {
4685                    dst: conv.0,
4686                    lhs: args_start,
4687                    rhs: args_start,
4688                });
4689                for _ in 2..e {
4690                    micro.push(MicroOp::Mul {
4691                        dst: conv.0,
4692                        lhs: conv.0,
4693                        rhs: args_start,
4694                    });
4695                }
4696                micro.push(MicroOp::Move { dst, src: conv.0 });
4697            }
4698        }
4699        // WORD lane (crypto substrate) — a Word rides UNBOXED as a masked i64 (Word32/16 zero-extended,
4700        // Word64 = full bits) and re-boxes to `RuntimeValue::Word` at a deopt/exit via `RegBox::Word{32,64}`.
4701        // Every op preserves or re-establishes the width invariant. A boxed/Float arg → decline to VM.
4702        Op::CallBuiltin {
4703            dst,
4704            builtin:
4705                bid @ (logicaffeine_compile::semantics::builtins::BuiltinId::Word32
4706                | logicaffeine_compile::semantics::builtins::BuiltinId::Word16Make),
4707            args_start,
4708            arg_count,
4709        } if arg_count == 1 => {
4710            if kind_of(args_start) != Kind::Int {
4711                return None;
4712            }
4713            let mask = if matches!(
4714                bid,
4715                logicaffeine_compile::semantics::builtins::BuiltinId::Word32
4716            ) {
4717                0xFFFF_FFFF
4718            } else {
4719                0xFFFF
4720            };
4721            micro.push(MicroOp::LoadConst {
4722                dst: conv.0,
4723                value: mask,
4724            });
4725            micro.push(MicroOp::BitAnd {
4726                dst,
4727                lhs: args_start,
4728                rhs: conv.0,
4729            });
4730        }
4731        Op::CallBuiltin {
4732            dst,
4733            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word64,
4734            args_start,
4735            arg_count,
4736        } if arg_count == 1 => {
4737            // Word64 = the full 64-bit pattern; the i64 bits ARE the u64 bits.
4738            if kind_of(args_start) != Kind::Int {
4739                return None;
4740            }
4741            micro.push(MicroOp::Move {
4742                dst,
4743                src: args_start,
4744            });
4745        }
4746        Op::CallBuiltin {
4747            dst,
4748            builtin:
4749                logicaffeine_compile::semantics::builtins::BuiltinId::IntOfWord32
4750                | logicaffeine_compile::semantics::builtins::BuiltinId::IntOfWord64,
4751            args_start,
4752            arg_count,
4753        } if arg_count == 1 => {
4754            // `to_u64() as i64`: a Word32 (0..2³²) and a Word64's bit pattern both ARE their i64 value.
4755            if !matches!(kind_of(args_start), Kind::Word32 | Kind::Word64) {
4756                return None;
4757            }
4758            micro.push(MicroOp::Move {
4759                dst,
4760                src: args_start,
4761            });
4762        }
4763        Op::CallBuiltin {
4764            dst,
4765            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::IntOfWord16,
4766            args_start,
4767            arg_count,
4768        } if arg_count == 1 => {
4769            // A Word16 slot already holds its value in [0, 2¹⁶); an Int argument takes its low 16 bits.
4770            match kind_of(args_start) {
4771                Kind::Word16 => micro.push(MicroOp::Move {
4772                    dst,
4773                    src: args_start,
4774                }),
4775                Kind::Int => {
4776                    micro.push(MicroOp::LoadConst {
4777                        dst: conv.0,
4778                        value: 0xFFFF,
4779                    });
4780                    micro.push(MicroOp::BitAnd {
4781                        dst,
4782                        lhs: args_start,
4783                        rhs: conv.0,
4784                    });
4785                }
4786                _ => return None,
4787            }
4788        }
4789        Op::CallBuiltin {
4790            dst,
4791            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Chr,
4792            args_start,
4793            arg_count,
4794        } if arg_count == 1 => {
4795            // `chr(code)` → a `ChrGuard`: validates the code and DEOPTS to the VM (which re-runs chr and
4796            // TRAPS) if it is not a valid Unicode scalar, else carries the code to a `Kind::CharText` dst
4797            // that re-boxes to a 1-char Text at exit. The arg must be an Int (a Word/Float code declines).
4798            if kind_of(args_start) != Kind::Int {
4799                return None;
4800            }
4801            micro.push(MicroOp::ChrGuard {
4802                dst,
4803                src: args_start,
4804            });
4805        }
4806        Op::CallBuiltin {
4807            dst,
4808            builtin:
4809                bid @ (logicaffeine_compile::semantics::builtins::BuiltinId::Wand
4810                | logicaffeine_compile::semantics::builtins::BuiltinId::Wor),
4811            args_start,
4812            arg_count,
4813        } if arg_count == 2 => {
4814            // Same-width Word AND/OR — preserves the mask (AND/OR of two masked values stays masked). Both
4815            // operands must be the SAME Word width (the VM errors on a mismatch); an Int operand declines.
4816            let ka = kind_of(args_start);
4817            if !matches!(ka, Kind::Word32 | Kind::Word64) || kind_of(args_start + 1) != ka {
4818                return None;
4819            }
4820            if matches!(
4821                bid,
4822                logicaffeine_compile::semantics::builtins::BuiltinId::Wand
4823            ) {
4824                micro.push(MicroOp::BitAnd {
4825                    dst,
4826                    lhs: args_start,
4827                    rhs: args_start + 1,
4828                });
4829            } else {
4830                micro.push(MicroOp::BitOr {
4831                    dst,
4832                    lhs: args_start,
4833                    rhs: args_start + 1,
4834                });
4835            }
4836        }
4837        Op::CallBuiltin {
4838            dst,
4839            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word64And,
4840            args_start,
4841            arg_count,
4842        } if arg_count == 2 => {
4843            // Word64 AND (both operands the full 64-bit pattern). An Int operand declines for now.
4844            if kind_of(args_start) != Kind::Word64 || kind_of(args_start + 1) != Kind::Word64 {
4845                return None;
4846            }
4847            micro.push(MicroOp::BitAnd {
4848                dst,
4849                lhs: args_start,
4850                rhs: args_start + 1,
4851            });
4852        }
4853        Op::CallBuiltin {
4854            dst,
4855            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word64Shl,
4856            args_start,
4857            arg_count,
4858        } if arg_count == 2 => {
4859            // `w << n` (u64 wrapping). i64 `Shl` already masks the count to `& 63` == u64's wrapping_shl.
4860            if kind_of(args_start) != Kind::Word64 || kind_of(args_start + 1) != Kind::Int {
4861                return None;
4862            }
4863            micro.push(MicroOp::Shl {
4864                dst,
4865                lhs: args_start,
4866                rhs: args_start + 1,
4867            });
4868        }
4869        Op::CallBuiltin {
4870            dst,
4871            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word32Shr,
4872            args_start,
4873            arg_count,
4874        } if arg_count == 2 => {
4875            // u32 LOGICAL `>>`: mask the count to `& 31` (u32's wrapping_shr) then arithmetic `Shr` — which
4876            // IS logical for a masked (non-negative, < 2³²) Word32, and the result stays `< 2³²`.
4877            if kind_of(args_start) != Kind::Word32 || kind_of(args_start + 1) != Kind::Int {
4878                return None;
4879            }
4880            micro.push(MicroOp::LoadConst {
4881                dst: conv.0,
4882                value: 31,
4883            });
4884            micro.push(MicroOp::BitAnd {
4885                dst: conv.1,
4886                lhs: args_start + 1,
4887                rhs: conv.0,
4888            });
4889            micro.push(MicroOp::Shr {
4890                dst,
4891                lhs: args_start,
4892                rhs: conv.1,
4893            });
4894        }
4895        Op::CallBuiltin {
4896            dst,
4897            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Word64Shr,
4898            args_start,
4899            arg_count,
4900        } if arg_count == 2 => {
4901            // u64 LOGICAL `>>` on a Word64 whose high bit may be set — a single `Ushr` (zero-fill), which
4902            // masks the count `& 63` exactly like `WordVal::shr`'s `wrapping_shr`. Handles a CONSTANT and a
4903            // VARIABLE count uniformly (the old arithmetic-`Shr`+top-bit-mask lane only did constants).
4904            if kind_of(args_start) != Kind::Word64 || kind_of(args_start + 1) != Kind::Int {
4905                return None;
4906            }
4907            micro.push(MicroOp::Ushr {
4908                dst,
4909                lhs: args_start,
4910                rhs: args_start + 1,
4911            });
4912        }
4913        Op::CallBuiltin {
4914            dst,
4915            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Wnot,
4916            args_start,
4917            arg_count,
4918        } if arg_count == 1 => {
4919            // Bitwise complement, width-preserving. Word32: `w ^ 0xFFFFFFFF` (flips only the low 32 bits,
4920            // keeping the mask). Word64: flip all 64 bits (`NotInt`).
4921            match kind_of(args_start) {
4922                Kind::Word32 => {
4923                    micro.push(MicroOp::LoadConst {
4924                        dst: conv.0,
4925                        value: 0xFFFF_FFFF,
4926                    });
4927                    micro.push(MicroOp::BitXor {
4928                        dst,
4929                        lhs: args_start,
4930                        rhs: conv.0,
4931                    });
4932                }
4933                Kind::Word64 => micro.push(MicroOp::NotInt {
4934                    dst,
4935                    src: args_start,
4936                }),
4937                _ => return None,
4938            }
4939        }
4940        Op::CallBuiltin {
4941            dst,
4942            builtin:
4943                bid @ (logicaffeine_compile::semantics::builtins::BuiltinId::Rotl
4944                | logicaffeine_compile::semantics::builtins::BuiltinId::Rotr),
4945            args_start,
4946            arg_count,
4947        } if arg_count == 2 => {
4948            // Keep rotate as one semantic micro-op. Every native backend has a
4949            // direct `rol`/`ror` lowering; the old shift/subtract/or expansion
4950            // cost 7–9 micro-ops per SHA round and obscured this missing opt.
4951            let width32 = match kind_of(args_start) {
4952                Kind::Word32 => true,
4953                Kind::Word64 => false,
4954                _ => return None,
4955            };
4956            if kind_of(args_start + 1) != Kind::Int {
4957                return None;
4958            }
4959            micro.push(MicroOp::Rotate {
4960                dst,
4961                lhs: args_start,
4962                rhs: args_start + 1,
4963                width32,
4964                left: matches!(
4965                    bid,
4966                    logicaffeine_compile::semantics::builtins::BuiltinId::Rotl
4967                ),
4968            });
4969        }
4970        Op::CallBuiltin {
4971            dst,
4972            builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Sqrt,
4973            args_start,
4974            arg_count,
4975        } => {
4976            if arg_count != 1 {
4977                return None;
4978            }
4979            let src = match kind_of(args_start) {
4980                Kind::Float => args_start,
4981                Kind::Int => {
4982                    micro.push(MicroOp::IntToFloat {
4983                        dst: conv.0,
4984                        src: args_start,
4985                    });
4986                    conv.0
4987                }
4988                _ => return None,
4989            };
4990            micro.push(MicroOp::SqrtF { dst, src });
4991        }
4992        Op::Call {
4993            dst,
4994            args_start,
4995            arg_count,
4996            func,
4997        } => {
4998            let c = call_ctx?;
4999            // The callee windows at a DISJOINT offset past the limit slot —
5000            // the interpreter's overlapping windowing (callee base = caller
5001            // base + args_start) would let the callee's registers land on
5002            // the caller's conversion scratches and arena-limit slot, so
5003            // the caller's NEXT call would read a clobbered bound and
5004            // deopt. Args are staged across with explicit moves.
5005            let window = c.limit_slot + 1;
5006            // LEVER A — the pinned-argument self-call ABI. A DIRECT self-call
5007            // whose arguments are a contiguous all-scalar block lying wholly
5008            // below the callee window stages them inside ONE fused stencil
5009            // (`CallSelfCopy`) instead of `arg_count` separate frame-to-frame
5010            // `Move` pieces — the dispatch-reduction win on this piece-bound
5011            // engine. The copy is bit-identical to the Moves: the same callee
5012            // slots receive the same 8-byte values (Int/Bool/Float alike),
5013            // and the depth/deopt machinery is untouched. The disjointness
5014            // guard (`args_start + arg_count <= window`) is always true for
5015            // the function tier (`window = limit_slot + 1` sits past every
5016            // register), but is checked so the fallback is provably safe; any
5017            // list/map-kinded argument (which the all-scalar mode-A signature
5018            // never produces, but is guarded for soundness) keeps the Moves.
5019            let scalar_args = (0..arg_count).all(|j| {
5020                matches!(
5021                    kind_of(args_start + j),
5022                    Kind::Int | Kind::Bool | Kind::Float
5023                )
5024            });
5025            let fuse_self = func == c.self_fi
5026                && arg_count >= 1
5027                && args_start + arg_count <= window
5028                && scalar_args
5029                && std::env::var_os("LOGOS_NO_PINNED_ARGS").is_none();
5030            if fuse_self {
5031                // DIRECT self-call with the fused argument copy: the entry
5032                // pool word is patched with this chain's own base after
5033                // layout; the frame bound is static (self-recursion: the
5034                // callee frame is OUR OWN size).
5035                micro.push(MicroOp::CallSelfCopy {
5036                    dst,
5037                    args_start: window,
5038                    src_start: args_start,
5039                    arg_count,
5040                    depth_addr: c.depth_addr,
5041                    status_addr: c.status_addr,
5042                    limit_slot: c.limit_slot,
5043                    frame_size: (c.limit_slot as i64) + 1,
5044                });
5045                if let Some(sig) = c.callees.get(func as usize) {
5046                    for &j in &sig.inout_params {
5047                        micro.push(MicroOp::Move {
5048                            dst: args_start + j,
5049                            src: window + j,
5050                        });
5051                    }
5052                }
5053                return Some(1);
5054            }
5055            for j in 0..arg_count {
5056                micro.push(MicroOp::Move {
5057                    dst: window + j,
5058                    src: args_start + j,
5059                });
5060            }
5061            if func == c.self_fi {
5062                // DIRECT self-call: the entry pool word is patched with
5063                // this chain's own base after layout; the frame bound is
5064                // static (self-recursion: the callee frame is OUR OWN
5065                // size).
5066                micro.push(MicroOp::CallSelf {
5067                    dst,
5068                    args_start: window,
5069                    depth_addr: c.depth_addr,
5070                    status_addr: c.status_addr,
5071                    limit_slot: c.limit_slot,
5072                    frame_size: (c.limit_slot as i64) + 1,
5073                });
5074            } else {
5075                // Cross-function call: table dispatch through the CALLEE's
5076                // slot pair (the kind fixpoint already validated its
5077                // all-scalar signature); an unpublished entry deopts and
5078                // the boundary replay stays exact.
5079                micro.push(MicroOp::Call {
5080                    dst,
5081                    args_start: window,
5082                    table_addr: c.table.slot_addr(func as usize),
5083                    depth_addr: c.depth_addr,
5084                    status_addr: c.status_addr,
5085                    limit_slot: c.limit_slot,
5086                    depth_limit: c.depth_limit,
5087                });
5088            }
5089            if let Some(sig) = c.callees.get(func as usize) {
5090                for &j in &sig.inout_params {
5091                    micro.push(MicroOp::Move {
5092                        dst: args_start + j,
5093                        src: window + j,
5094                    });
5095                }
5096            }
5097        }
5098        // In-region Return: set the flag, stash the value, leave via the
5099        // synthetic exit (usize::MAX is the out-of-region marker the remap
5100        // routes there).
5101        Op::Return { src } if region_return.is_some() => {
5102            let (flag_slot, value_slot) = region_return.unwrap();
5103            micro.push(MicroOp::LoadConst {
5104                dst: flag_slot,
5105                value: 1,
5106            });
5107            if matches!(
5108                kind_of(src),
5109                Kind::IntList | Kind::FloatList | Kind::BoolList
5110            ) {
5111                // Lists return BY REGISTER: stash the register number; the
5112                // VM returns that register's current value.
5113                micro.push(MicroOp::LoadConst {
5114                    dst: value_slot,
5115                    value: src as i64,
5116                });
5117            } else {
5118                micro.push(MicroOp::Move {
5119                    dst: value_slot,
5120                    src,
5121                });
5122            }
5123            fixups.push(micro.len());
5124            micro.push(MicroOp::Jump { target: usize::MAX });
5125        }
5126        Op::Return { src } if allow_return => micro.push(MicroOp::Return { src }),
5127        // Statically dead (gated by the caller); valid-shape placeholder.
5128        Op::ReturnNothing if allow_return => micro.push(MicroOp::Return { src: 0 }),
5129        // Region-entry length hoist: pure metadata, no native code. The VM
5130        // verifies it once at region entry; `adapt_region` collects it.
5131        Op::RegionBoundsGuard { .. } => {}
5132        // Map values do not yet have a native pin/allocator lane. Make the unsupported optimization
5133        // visible in the trace instead of silently falling through the generic translator refusal.
5134        Op::NewEmptyMapWithCapacity { .. } => {
5135            jt(if region {
5136                "region-map-capacity"
5137            } else {
5138                "function-map-capacity"
5139            });
5140            return None;
5141        }
5142        _ => return None,
5143    }
5144    Some(1)
5145}
5146
5147/// Translate a MAIN-LOOP REGION into the J2 subset.
5148///
5149/// The register roles of a recognized naive substring-search nest (the
5150/// string_search benchmark idiom): the count of OVERLAPPING `needle`
5151/// occurrences in `text` over the outer index range.
5152struct MemMemShape {
5153    text_reg: u16,
5154    needle_reg: u16,
5155    needle_len_reg: u16,
5156    i_reg: u16,
5157    count_reg: u16,
5158}
5159
5160/// Recognize the EXACT naive substring-search nest the LOGOS compiler lowers
5161/// for `string_search`'s count loop, so the JIT can collapse the per-byte
5162/// nested-loop region to one [`MicroOp::MemMem`] call.
5163///
5164/// The matched outer-loop region (head at `ops[0]`) is, in bytecode:
5165///
5166/// ```text
5167///   Sub(t1 = textLen - needleLen); LoadConst(c=1); Add(bound = t1 + c)
5168///   LtEq(cmp = i <= bound); JumpIfFalse(cmp -> EXIT)
5169///   LoadConst(c=1); Move(match = c); LoadConst(c=0); Move(j = c)
5170///   Lt(cj = j < needleLen); JumpIfFalse(cj -> after_inner)
5171///     Add(t3 = i + j); IndexUnchecked(ch1 = text[t3])
5172///     LoadConst(c=1); Add(t4 = j + c); Index(ch2 = needle[t4])     // checked
5173///     NotEq(ne = ch1 != ch2); JumpIfFalse(ne -> cont)
5174///       LoadConst(c=0); Move(match = c); Move(t5 = needleLen); Move(j = t5)
5175///   cont:   LoadConst(c=1); AddAssign(j += c); Jump(-> inner head)
5176///   after_inner: LoadConst(c=1); Eq(eq = match == c); JumpIfFalse(eq -> skip)
5177///     LoadConst(c=1); AddAssign(count += c)
5178///   skip:   LoadConst(c=1); AddAssign(i += c); Jump(-> outer head)
5179/// ```
5180///
5181/// Recognition is STRICT — the shape, the operand wiring (`i`/`j`/`needleLen`/
5182/// `count`/`text`/`needle` register threading), the two `Index` collections, the
5183/// jump topology, and the `1`/`0` constants are all checked — so the helper is
5184/// only ever substituted when it is bit-identical to this nest. Any deviation
5185/// returns `None` and the region falls back to the per-byte tiered loop.
5186/// `LOGOS_MEMMEM=0` disables the recognizer entirely.
5187fn match_memmem_nest(
5188    ops: &[Op],
5189    head_pc: usize,
5190    exit_pc: usize,
5191    constants: &[Constant],
5192) -> Option<MemMemShape> {
5193    if std::env::var("LOGOS_MEMMEM").as_deref() == Ok("0") {
5194        return None;
5195    }
5196    // The template is exactly 33 ops (the outer back-edge is the last).
5197    if ops.len() != 33 {
5198        return None;
5199    }
5200    let is_const = |i: usize, want: i64| -> bool {
5201        matches!(ops.get(i), Some(Op::LoadConst { idx, .. })
5202            if matches!(constants.get(*idx as usize), Some(Constant::Int(v)) if *v == want))
5203    };
5204    let const_dst = |i: usize| -> Option<u16> {
5205        match ops.get(i) {
5206            Some(Op::LoadConst { dst, .. }) => Some(*dst),
5207            _ => None,
5208        }
5209    };
5210    // The region-relative targets the jumps must hit.
5211    let inner_head = head_pc + 9; // op [38] Lt(j < needleLen)
5212    let after_inner = head_pc + 25; // op [54]
5213    let cont = head_pc + 22; // op [51]
5214    let skip = head_pc + 30; // op [59]
5215
5216    // [0] Sub(t1 = textLen - needleLen)
5217    let Op::Sub {
5218        dst: t1,
5219        lhs: text_len,
5220        rhs: needle_len,
5221    } = ops[0]
5222    else {
5223        return None;
5224    };
5225    // [1] LoadConst(c1 = 1); [2] Add(bound = t1 + c1)
5226    if !is_const(1, 1) {
5227        return None;
5228    }
5229    let c1 = const_dst(1)?;
5230    let Op::Add {
5231        dst: bound,
5232        lhs,
5233        rhs,
5234    } = ops[2]
5235    else {
5236        return None;
5237    };
5238    if lhs != t1 || rhs != c1 {
5239        return None;
5240    }
5241    // [3] LtEq(cmp = i <= bound); [4] JumpIfFalse(cmp -> EXIT)
5242    let Op::LtEq {
5243        dst: cmp,
5244        lhs: i_reg,
5245        rhs,
5246    } = ops[3]
5247    else {
5248        return None;
5249    };
5250    if rhs != bound {
5251        return None;
5252    }
5253    let Op::JumpIfFalse { cond, target } = ops[4] else {
5254        return None;
5255    };
5256    if cond != cmp || target != exit_pc {
5257        return None;
5258    }
5259    // [5] LoadConst(=1); [6] Move(match = it)
5260    if !is_const(5, 1) {
5261        return None;
5262    }
5263    let c5 = const_dst(5)?;
5264    let Op::Move {
5265        dst: match_reg,
5266        src,
5267    } = ops[6]
5268    else {
5269        return None;
5270    };
5271    if src != c5 {
5272        return None;
5273    }
5274    // [7] LoadConst(=0); [8] Move(j = it)
5275    if !is_const(7, 0) {
5276        return None;
5277    }
5278    let c7 = const_dst(7)?;
5279    let Op::Move { dst: j_reg, src } = ops[8] else {
5280        return None;
5281    };
5282    if src != c7 {
5283        return None;
5284    }
5285    // [9] Lt(cj = j < needleLen); [10] JumpIfFalse(cj -> after_inner)
5286    let Op::Lt { dst: cj, lhs, rhs } = ops[9] else {
5287        return None;
5288    };
5289    if lhs != j_reg || rhs != needle_len {
5290        return None;
5291    }
5292    let Op::JumpIfFalse { cond, target } = ops[10] else {
5293        return None;
5294    };
5295    if cond != cj || target != after_inner {
5296        return None;
5297    }
5298    // [11] Add(t3 = i + j); [12] IndexUnchecked(ch1 = text[t3])
5299    let Op::Add { dst: t3, lhs, rhs } = ops[11] else {
5300        return None;
5301    };
5302    if lhs != i_reg || rhs != j_reg {
5303        return None;
5304    }
5305    let Op::IndexUnchecked {
5306        dst: ch1,
5307        collection: text_reg,
5308        index,
5309    } = ops[12]
5310    else {
5311        return None;
5312    };
5313    if index != t3 {
5314        return None;
5315    }
5316    // [13] LoadConst(=1); [14] Add(t4 = j + it); [15] Index(ch2 = needle[t4])
5317    if !is_const(13, 1) {
5318        return None;
5319    }
5320    let c13 = const_dst(13)?;
5321    let Op::Add { dst: t4, lhs, rhs } = ops[14] else {
5322        return None;
5323    };
5324    if lhs != j_reg || rhs != c13 {
5325        return None;
5326    }
5327    let Op::Index {
5328        dst: ch2,
5329        collection: needle_reg,
5330        index,
5331    } = ops[15]
5332    else {
5333        return None;
5334    };
5335    if index != t4 {
5336        return None;
5337    }
5338    // [16] NotEq(ne = ch1 != ch2); [17] JumpIfFalse(ne -> cont)
5339    let Op::NotEq { dst: ne, lhs, rhs } = ops[16] else {
5340        return None;
5341    };
5342    if !((lhs == ch1 && rhs == ch2) || (lhs == ch2 && rhs == ch1)) {
5343        return None;
5344    }
5345    let Op::JumpIfFalse { cond, target } = ops[17] else {
5346        return None;
5347    };
5348    if cond != ne || target != cont {
5349        return None;
5350    }
5351    // [18] LoadConst(=0); [19] Move(match = it)
5352    if !is_const(18, 0) {
5353        return None;
5354    }
5355    let c18 = const_dst(18)?;
5356    let Op::Move { dst, src } = ops[19] else {
5357        return None;
5358    };
5359    if dst != match_reg || src != c18 {
5360        return None;
5361    }
5362    // [20] Move(t5 = needleLen); [21] Move(j = t5)
5363    let Op::Move { dst: t5, src } = ops[20] else {
5364        return None;
5365    };
5366    if src != needle_len {
5367        return None;
5368    }
5369    let Op::Move { dst, src } = ops[21] else {
5370        return None;
5371    };
5372    if dst != j_reg || src != t5 {
5373        return None;
5374    }
5375    // [22] cont: LoadConst(=1); [23] AddAssign(j += it); [24] Jump(-> inner head)
5376    if !is_const(22, 1) {
5377        return None;
5378    }
5379    let c22 = const_dst(22)?;
5380    let Op::AddAssign { dst, src } = ops[23] else {
5381        return None;
5382    };
5383    if dst != j_reg || src != c22 {
5384        return None;
5385    }
5386    let Op::Jump { target } = ops[24] else {
5387        return None;
5388    };
5389    if target != inner_head {
5390        return None;
5391    }
5392    // [25] after_inner: LoadConst(=1); [26] Eq(eq = match == it); [27] JumpIfFalse(eq -> skip)
5393    if !is_const(25, 1) {
5394        return None;
5395    }
5396    let c25 = const_dst(25)?;
5397    let Op::Eq { dst: eq, lhs, rhs } = ops[26] else {
5398        return None;
5399    };
5400    if !((lhs == match_reg && rhs == c25) || (lhs == c25 && rhs == match_reg)) {
5401        return None;
5402    }
5403    let Op::JumpIfFalse { cond, target } = ops[27] else {
5404        return None;
5405    };
5406    if cond != eq || target != skip {
5407        return None;
5408    }
5409    // [28] LoadConst(=1); [29] AddAssign(count += it)
5410    if !is_const(28, 1) {
5411        return None;
5412    }
5413    let c28 = const_dst(28)?;
5414    let Op::AddAssign {
5415        dst: count_reg,
5416        src,
5417    } = ops[29]
5418    else {
5419        return None;
5420    };
5421    if src != c28 {
5422        return None;
5423    }
5424    // [30] skip: LoadConst(=1); [31] AddAssign(i += it); [32] Jump(-> outer head)
5425    if !is_const(30, 1) {
5426        return None;
5427    }
5428    let c30 = const_dst(30)?;
5429    let Op::AddAssign { dst, src } = ops[31] else {
5430        return None;
5431    };
5432    if dst != i_reg || src != c30 {
5433        return None;
5434    }
5435    let Op::Jump { target } = ops[32] else {
5436        return None;
5437    };
5438    if target != head_pc {
5439        return None;
5440    }
5441    // text and needle must be DISTINCT collections; the count accumulator must
5442    // be distinct from the loop induction `i`.
5443    let _ = text_len;
5444    if text_reg == needle_reg || count_reg == i_reg {
5445        return None;
5446    }
5447    Some(MemMemShape {
5448        text_reg,
5449        needle_reg,
5450        needle_len_reg: needle_len,
5451        i_reg,
5452        count_reg,
5453    })
5454}
5455
5456/// Region contract: `ops[0]` is the loop head; the slice ends at the
5457/// back-edge; every jump out targets `exit_pc` (mapped to a synthetic
5458/// terminal). The guard set is the LIVE-IN set at the head — computed by
5459/// textbook backward liveness over the region's CFG — so any slot whose
5460/// incoming value can be observed is Int-guarded and copied in, while
5461/// incoming-dead slots (loop scratches, comparison temporaries anywhere in
5462/// the body) need no guard. Writes are re-boxed by inferred kind.
5463#[allow(clippy::type_complexity)]
5464fn adapt_region(
5465    ops: &[Op],
5466    head_pc: usize,
5467    exit_pc: usize,
5468    constants: &[Constant],
5469    register_count: u16,
5470    named: &[bool],
5471    observed: &[ObservedKind],
5472    ctx: &NativeCtx,
5473    callees: &[logicaffeine_compile::vm::CalleeSig],
5474) -> Option<(
5475    Vec<MicroOp>,
5476    usize,
5477    Vec<(u16, SlotKind)>,
5478    Vec<u16>,
5479    Vec<(u16, SlotKind)>,
5480    Vec<ArrayPin>,
5481    Option<logicaffeine_compile::vm::RegionReturn>,
5482    Vec<HoistGuard>,
5483    // Precise-deopt tables (Some ⇒ this region resumes AT the faulting op on a
5484    // side exit, re-boxing each register by kind, instead of replaying from the
5485    // head — required for a sound push+SetIndex region).
5486    Option<RegionPrecise>,
5487)> {
5488    // SOUNDNESS (Bug Report #1, BUG-001): a region runs under a
5489    // discard-and-replay-from-head deopt contract that is sound only for
5490    // replay-idempotent effects. `ListPush` APPENDS — not idempotent on its own
5491    // — but the VM's region deopt path now rolls every pinned buffer back to its
5492    // entry length before replaying (see machine.rs), so a push followed by a
5493    // PURE side-exit (Div/Mod div-by-zero, Index/Contains out-of-bounds or
5494    // fast-lane miss — all read-only or arithmetic) replays cleanly. What stays
5495    // unsound is push coexisting with another NON-idempotent effect whose replay
5496    // the truncate cannot undo: an in-place `SetIndex`/`SetIndexUnchecked` write
5497    // (a read-modify-write would double-apply). Calls admitted below are native,
5498    // typed and replay-safe; list results are adopted into snapshotted pins.
5499    if std::env::var("LOGOS_DUMP_REGION")
5500        .ok()
5501        .and_then(|v| v.parse::<usize>().ok())
5502        == Some(head_pc)
5503    {
5504        eprintln!("=== REGION head_pc={head_pc} ops ({}) ===", ops.len());
5505        for (i, op) in ops.iter().enumerate() {
5506            eprintln!("  [{}] {op:?}", head_pc + i);
5507        }
5508    }
5509    let has_list_push = ops.iter().any(|op| matches!(op, Op::ListPush { .. }));
5510    let has_setindex = ops
5511        .iter()
5512        .any(|op| matches!(op, Op::SetIndex { .. } | Op::SetIndexUnchecked { .. }));
5513    let has_call_op = ops.iter().any(|op| matches!(op, Op::Call { .. }));
5514    // A `ListPush` coexisting with an in-place `SetIndex` or a `Call` is NOT
5515    // replay-safe under the classic discard-replay-from-head deopt (truncate
5516    // rolls the pushes back but the in-place write persists, so a self-gated
5517    // re-push is skipped — the BFS lost-node bug). It can still tier up with
5518    // PRECISE region deopt (resume AT the faulting op, no replay): sound for any
5519    // pattern. A push beside a SetIndex is admitted here and re-checked for
5520    // all-int after lowering (where the precise `deopt_codes` are built).
5521    let needs_precise = has_list_push && has_setindex;
5522    if needs_precise && has_call_op {
5523        return None;
5524    }
5525
5526    // Backward liveness: out-of-region exits contribute empty live-out —
5527    // exit-observable slots flow through the WRITE-BACK, never the frame.
5528    let nregs = register_count as usize + 2;
5529    let in_region = |t: usize| (head_pc..head_pc + ops.len()).contains(&t);
5530    // SOUNDNESS BAIL — a list-element read (`Op::Index`) on a path that SIDE-EXITS the region (an
5531    // early `Return`/`Break` OUT of the loop, i.e. a jump neither back into the region nor to the
5532    // loop's normal `exit_pc`) is miscompiled: the read's speculated unboxed list handle goes stale
5533    // across the discard-and-replay side exit, so the element comes back wrong (a hot substring/search
5534    // scan then returns the wrong index — `matchAt`, `indexOf`). Decline such a region to the correct
5535    // VM bytecode rather than emit a silently-wrong native loop. A list read in a loop with only
5536    // in-region control flow (sum/map/dot-product) is unaffected. Locked by
5537    // `jit_list_search_differential_lock`.
5538    {
5539        let has_index_read = ops.iter().any(|op| matches!(op, Op::Index { .. }));
5540        if has_index_read {
5541            // The miscompiled shape is an early `Return` OUT OF THE FUNCTION from inside the loop
5542            // (matchAt's `Return false`): its frame materializes from stale slots. A checked-index
5543            // BOUNDS BAIL (a jump to the deopt/trap handler) is NOT this — it replays correctly on the
5544            // VM — so a jump-target heuristic wrongly declines every checked list-read loop (e.g. the
5545            // `energy` float reader, which has no early return at all). Detect ONLY an `Op::Return`
5546            // inside the region.
5547            let _ = exit_pc;
5548            let _ = &in_region;
5549            let has_side_exit = ops
5550                .iter()
5551                .any(|op| matches!(op, Op::Return { .. } | Op::ReturnNothing));
5552            if has_side_exit {
5553                if std::env::var_os("LOGOS_RDIAG").is_some() {
5554                    eprintln!("RDIAG-BAIL head_pc={head_pc} list-index read + side-exit");
5555                }
5556                return None;
5557            }
5558        }
5559    }
5560    let Some(live) = liveness(ops, head_pc, nregs) else {
5561        if std::env::var_os("LOGOS_RDIAG").is_some() {
5562            eprintln!("RDIAG-BAIL head_pc={head_pc} liveness");
5563        }
5564        return None;
5565    };
5566    // A compiler-generated `Move` that stages a list into a call argument is
5567    // not an escaping alias when the callee keeps list-parameter handles stable,
5568    // cannot return one of those parameters, and the staging register has no
5569    // other list-valued use. Keep the proof as a set of `(op index, source)`
5570    // pairs so both the allocation-lifetime gate and list-clear lowering apply
5571    // exactly the same exception; every other list-handle copy stays an escape.
5572    let mut safe_list_stages = std::collections::HashSet::<(usize, u16)>::new();
5573    for (call_i, op) in ops.iter().enumerate() {
5574        let Op::Call {
5575            args_start,
5576            arg_count,
5577            func,
5578            ..
5579        } = *op
5580        else {
5581            continue;
5582        };
5583        let Some(sig) = callees.get(func as usize) else {
5584            continue;
5585        };
5586        if !sig.list_params_stable || sig.returns_list_param {
5587            continue;
5588        }
5589        for j in 0..arg_count {
5590            if !matches!(
5591                sig.param_kinds.get(j as usize),
5592                Some(Some(ParamKind::List(_)))
5593            ) {
5594                continue;
5595            }
5596            let arg = args_start + j;
5597            for move_i in (0..call_i).rev() {
5598                let Some((_, defs)) = region_use_def(&ops[move_i]) else {
5599                    break;
5600                };
5601                if !defs.contains(&arg) {
5602                    continue;
5603                }
5604                if let Op::Move { dst, src } = ops[move_i] {
5605                    // The argument register must die with THIS call. The
5606                    // fixpoint liveness row after it includes every later use,
5607                    // including uses reached around the region backedge, so a
5608                    // false bit proves that no observable alias survives.
5609                    let dies_with_call = live.get(call_i + 1).is_none_or(|row| !row[arg as usize]);
5610                    let staged_only_for_this_call = dst == arg && dies_with_call;
5611                    if staged_only_for_this_call {
5612                        safe_list_stages.insert((move_i, src));
5613                    }
5614                }
5615                break;
5616            }
5617        }
5618    }
5619
5620    // Allocation sites whose registers are dead at the backedge are ordinary
5621    // per-iteration locals (SHA's `m` and `h0`). Reclaim the previous
5622    // iteration's registry entries at the next head instead of retaining O(n)
5623    // Vec boxes until the region exits. A copied or swapped handle could remain
5624    // live under another name, so those shapes stay on the conservative path.
5625    let iteration_alloc_regs: std::collections::HashSet<u16> = ops
5626        .iter()
5627        .filter_map(|op| match *op {
5628            Op::NewEmptyList { dst }
5629            | Op::NewEmptyListWithCapacity { dst, .. }
5630            | Op::NewEmptyListFixed { dst, .. }
5631            | Op::NewList { dst, .. } => Some(dst),
5632            _ => None,
5633        })
5634        .collect();
5635    let iteration_alloc_reset = !iteration_alloc_regs.is_empty()
5636        && iteration_alloc_regs
5637            .iter()
5638            .all(|&r| !live[0].get(r as usize).copied().unwrap_or(true))
5639        && !ops.iter().enumerate().any(|(op_i, op)| match *op {
5640            Op::Move { dst, src } => {
5641                (iteration_alloc_regs.contains(&dst) || iteration_alloc_regs.contains(&src))
5642                    && !safe_list_stages.contains(&(op_i, src))
5643            }
5644            Op::RevSwap { a, b } => {
5645                iteration_alloc_regs.contains(&a) || iteration_alloc_regs.contains(&b)
5646            }
5647            Op::Return { src } => iteration_alloc_regs.contains(&src),
5648            _ => false,
5649        });
5650    if iteration_alloc_reset {
5651        logicaffeine_compile::optimize::with_backend_lowering(|| {
5652            logicaffeine_compile::optimize::mark_fired(
5653                logicaffeine_compile::optimization::Opt::Unbox,
5654            )
5655        });
5656    }
5657
5658    // Guard = live-in at the head; touched = every use or def; free =
5659    // touched − guard; writes = every def (re-boxed by kind on completion).
5660    let mut guard: Vec<u16> = Vec::new();
5661    let mut free: Vec<u16> = Vec::new();
5662    let mut writes: Vec<u16> = Vec::new();
5663    let mut touched: Vec<u16> = Vec::new();
5664    for op in ops {
5665        let Some((uses, defs)) = region_use_def(op) else {
5666            if std::env::var_os("LOGOS_RDIAG").is_some() {
5667                eprintln!("RDIAG-BAIL head_pc={head_pc} use_def-unsupported op={op:?}");
5668            }
5669            return None;
5670        };
5671        for d in defs {
5672            if !writes.contains(&d) {
5673                writes.push(d);
5674            }
5675            if !touched.contains(&d) {
5676                touched.push(d);
5677            }
5678        }
5679        for u in uses {
5680            if !touched.contains(&u) {
5681                touched.push(u);
5682            }
5683        }
5684    }
5685    // Array pins: every register used as an Index/SetIndex/Length collection
5686    // must hold an UNBOXED list right now (the speculation the entry guard
5687    // re-checks); each gets a pinned (pointer, length) slot pair past the
5688    // conversion scratches.
5689    let mut pin_regs: Vec<(u16, PinElem)> = Vec::new();
5690    for op in ops {
5691        let coll = match *op {
5692            Op::Index { collection, .. }
5693            | Op::IndexUnchecked { collection, .. }
5694            | Op::SetIndex { collection, .. }
5695            | Op::SetIndexUnchecked { collection, .. }
5696            | Op::Length { collection, .. }
5697            | Op::Contains { collection, .. } => Some(collection),
5698            Op::ListPush { list, .. } => Some(list),
5699            _ => None,
5700        };
5701        if let Some(c) = coll {
5702            // A `chr(code)` result used as a "collection" (by `length of chr(k)`) is a CharText, NOT a real
5703            // Text byte-buffer: its length is the constant 1 (handled in translate_op), so it needs no pin.
5704            // Skip it so the TextBytes-pin machinery doesn't grab it and bail on its per-iteration rebind.
5705            if ops.iter().any(|o| {
5706                matches!(o,
5707                    Op::CallBuiltin { dst, builtin: logicaffeine_compile::semantics::builtins::BuiltinId::Chr, .. }
5708                    if *dst == c)
5709            }) {
5710                continue;
5711            }
5712            let elem = match observed.get(c as usize)? {
5713                ObservedKind::IntList => PinElem::Int,
5714                ObservedKind::IntListI32 => PinElem::IntI32,
5715                ObservedKind::Word32List => PinElem::Word32,
5716                ObservedKind::FloatList => PinElem::Float,
5717                ObservedKind::BoolList => PinElem::Bool,
5718                ObservedKind::Map => PinElem::Map,
5719                ObservedKind::TextBytes => {
5720                    // A Text-as-bytes pin is read-only: the byte buffer pointer
5721                    // is captured at entry and the `Rc<String>` is never written
5722                    // in place. A region that REASSIGNS the pinned register (a
5723                    // `Move`/rebind into `c`, or string growth via `Op::Concat`
5724                    // — already out of `region_use_def` so it bails on its own)
5725                    // would leave a stale buffer pointer. Bail if the pinned
5726                    // register is ever a def in this region.
5727                    if writes.contains(&c) {
5728                        if std::env::var_os("LOGOS_RDIAG").is_some() {
5729                            eprintln!(
5730                                "RDIAG-BAIL head_pc={head_pc} textbytes-pin-reassigned reg={c}"
5731                            );
5732                        }
5733                        return None;
5734                    }
5735                    PinElem::TextBytes
5736                }
5737                _ => {
5738                    if std::env::var_os("LOGOS_RDIAG").is_some() {
5739                        eprintln!("RDIAG-BAIL head_pc={head_pc} non-list-collection reg={c}");
5740                    }
5741                    return None;
5742                }
5743            };
5744            if !pin_regs.iter().any(|&(r, _)| r == c) {
5745                pin_regs.push((c, elem));
5746            }
5747        }
5748    }
5749    // MUTABLE-TEXT accumulator (`Set text to text + ch`): a register that is the
5750    // `dst` of an `AddAssign` and is OBSERVED as an ASCII Text rides the
5751    // `TextMut` pin channel (a `*mut Value` handle to its VM register cell), so
5752    // the append lowers to a `StrAppend` helper call instead of bailing the
5753    // region on a non-numeric `AddAssign`. Emitted ONLY for the contiguous
5754    // regalloc backend (the per-piece stencil tier has no `StrAppend` lowering
5755    // and declines it); when regalloc is off, a `text + ch` region falls back to
5756    // bytecode exactly as before. A register that is ALSO used as a collection
5757    // (already pinned above) is not re-pinned as TextMut.
5758    let strappend_on = logicaffeine_forge::regalloc::regalloc_enabled();
5759    if strappend_on {
5760        for op in ops {
5761            if let Op::AddAssign { dst, .. } = *op {
5762                if matches!(observed.get(dst as usize), Some(ObservedKind::TextBytes))
5763                    && !pin_regs.iter().any(|&(r, _)| r == dst)
5764                {
5765                    pin_regs.push((dst, PinElem::TextMut));
5766                }
5767            }
5768        }
5769    }
5770    // List-param calls (on by default; kill-switch `LOGOS_LEVERB=0`): a list that flows
5771    // into a list-parameter CALL but is never directly Indexed here (e.g.
5772    // `arr = siftDown(arr, …)`) is still a pinnable array — pin every touched
5773    // slot observed as a list, so it rides the array channel rather than the
5774    // scalar guard set (which has no `slot_kind` for a list and would bail).
5775    // Validated across ~2180 tests (878 JIT + 1301 e2e) + the deopt-rollback
5776    // RED/GREEN; regions calling list-param functions now tier (heap_sort,
5777    // mergesort, any worklist-via-helper) with discard-replay soundness from
5778    // the array snapshot/rollback.
5779    let leverb_on = std::env::var("LOGOS_LEVERB").as_deref() != Ok("0");
5780    // Fresh list-returning calls are lowered as an in-place adoption into the
5781    // destination's pinned Vec. Keep the transformation deliberately narrow:
5782    // the destination must already be a same-element list at region entry and
5783    // may not be copied/rebound by any other op in the region. Entry COW in the
5784    // VM then makes the stable-handle implementation observationally identical
5785    // to the source-level fresh-value rebind.
5786    let mut adopted_call_dsts = std::collections::HashMap::<u16, PinElem>::new();
5787    if leverb_on {
5788        for op in ops {
5789            let Op::Call { dst, func, .. } = *op else {
5790                continue;
5791            };
5792            let Some(sig) = callees.get(func as usize) else {
5793                continue;
5794            };
5795            if std::env::var_os("LOGOS_RDIAG").is_some() {
5796                eprintln!(
5797                    "RDIAG-ADOPT candidate dst={dst} func={func} list_ret={:?} ret={:?} returns_param={} stable={} inout={:?}",
5798                    sig.list_ret,
5799                    sig.ret,
5800                    sig.returns_list_param,
5801                    sig.list_params_stable,
5802                    sig.inout_params
5803                );
5804            }
5805            let Some(elem) = sig.list_ret else { continue };
5806            if sig.ret.is_some() || sig.returns_list_param || !sig.list_params_stable {
5807                if std::env::var_os("LOGOS_RDIAG").is_some() {
5808                    eprintln!(
5809                        "RDIAG-ADOPT reject dst={dst} func={func} ret={:?} returns_param={} stable={}",
5810                        sig.ret, sig.returns_list_param, sig.list_params_stable
5811                    );
5812                }
5813                continue;
5814            }
5815            if sig.inout_params.iter().any(|&r| {
5816                matches!(
5817                    sig.param_kinds.get(r as usize),
5818                    Some(Some(ParamKind::List(_)))
5819                )
5820            }) {
5821                continue;
5822            }
5823            let observed_matches = matches!(
5824                (elem, observed.get(dst as usize)),
5825                (PinElem::Int, Some(ObservedKind::IntList))
5826                    | (PinElem::Word32, Some(ObservedKind::Word32List))
5827            );
5828            if !observed_matches {
5829                if std::env::var_os("LOGOS_RDIAG").is_some() {
5830                    eprintln!(
5831                        "RDIAG-ADOPT observed-mismatch dst={dst} elem={elem:?} observed={:?}",
5832                        observed.get(dst as usize)
5833                    );
5834                }
5835                continue;
5836            }
5837            match adopted_call_dsts.get(&dst) {
5838                Some(previous) if *previous != elem => return None,
5839                _ => {
5840                    adopted_call_dsts.insert(dst, elem);
5841                }
5842            }
5843        }
5844        for (&dst, &elem) in &adopted_call_dsts {
5845            let unsafe_flow = ops.iter().enumerate().any(|(op_i, op)| {
5846                if let Op::Move { dst: d, src: s } = *op {
5847                    if d == dst || s == dst {
5848                        // A proven one-call staging copy dies at the call and
5849                        // cannot observe the adopted in-place replacement.
5850                        return !safe_list_stages.contains(&(op_i, s));
5851                    }
5852                }
5853                if matches!(*op, Op::RevSwap { a, b } if a == dst || b == dst) {
5854                    return true;
5855                }
5856                let Some((_, defs)) = region_use_def(op) else { return true };
5857                if !defs.contains(&dst) {
5858                    return false;
5859                }
5860                matches!(*op, Op::Call { dst: d, func, .. } if d == dst && callees.get(func as usize).is_some_and(|sig| sig.list_ret == Some(elem) && !sig.returns_list_param)) == false
5861            });
5862            if unsafe_flow {
5863                if std::env::var_os("LOGOS_RDIAG").is_some() {
5864                    eprintln!("RDIAG-ADOPT unsafe-flow dst={dst}");
5865                }
5866                return None;
5867            }
5868        }
5869        if !adopted_call_dsts.is_empty() {
5870            logicaffeine_compile::optimize::with_backend_lowering(|| {
5871                logicaffeine_compile::optimize::mark_fired(
5872                    logicaffeine_compile::optimization::Opt::Unbox,
5873                )
5874            });
5875        }
5876    }
5877    // Does this region CALL a list-parameter function? Only then must a list
5878    // that's merely passed through (not Indexed here) be pinned. Pinning EVERY
5879    // touched list would spuriously re-pin lists in SCALAR-call regions and
5880    // reintroduce the float-pin / mem-form clobber (spectral_norm), so this is
5881    // strictly scoped to list-param-call regions.
5882    let has_list_param_call = leverb_on
5883        && ops.iter().any(|op| match *op {
5884            Op::Call { func, .. } => callees.get(func as usize).is_some_and(|s| {
5885                s.param_kinds
5886                    .iter()
5887                    .any(|p| matches!(p, Some(ParamKind::List(_))))
5888            }),
5889            _ => false,
5890        });
5891    if has_list_param_call {
5892        for &r in &touched {
5893            if pin_regs.iter().any(|&(p, _)| p == r) {
5894                continue;
5895            }
5896            let elem = match observed.get(r as usize) {
5897                Some(ObservedKind::IntList) => Some(PinElem::Int),
5898                Some(ObservedKind::IntListI32) => Some(PinElem::IntI32),
5899                Some(ObservedKind::Word32List) => Some(PinElem::Word32),
5900                Some(ObservedKind::FloatList) => Some(PinElem::Float),
5901                Some(ObservedKind::BoolList) => Some(PinElem::Bool),
5902                _ => None,
5903            };
5904            if let Some(e) = elem {
5905                pin_regs.push((r, e));
5906            }
5907        }
5908    }
5909    for (&reg, &elem) in &adopted_call_dsts {
5910        if !pin_regs.iter().any(|&(r, _)| r == reg) {
5911            pin_regs.push((reg, elem));
5912        }
5913    }
5914    // In-region Returns: the value's kind must agree across every return
5915    // site (re-boxed by SlotKind at the boundary).
5916    let has_return = ops.iter().any(|op| matches!(op, Op::Return { .. }));
5917    if ops.iter().any(|op| matches!(op, Op::ReturnNothing)) {
5918        if std::env::var_os("LOGOS_RDIAG").is_some() {
5919            eprintln!("RDIAG-BAIL head_pc={head_pc} return-nothing");
5920        }
5921        return None;
5922    }
5923    // An in-place `SetIndex` write is NOT replay-idempotent (a read-modify-write
5924    // or swap double-applies), so a buffer it targets must be snapshotted on
5925    // region entry and restored on a classic replay-from-head `Deopt`. That cost
5926    // is only owed when the region can ACTUALLY take a recoverable side exit:
5927    // a checked list `Index` (bounds), ANY map `Index`/`Contains` (int-lane
5928    // miss), `Div`/`Mod` (div-by-zero), or a `Call` (callee deopt). Unchecked
5929    // list reads, pure arithmetic, and control flow never side-exit — so a
5930    // deopt-free swap loop (bubble/quick sort) pays nothing. A PRECISE region
5931    // resumes AT the faulting op (no replay), so it never needs the snapshot.
5932    let is_map = |c: u16| matches!(observed.get(c as usize), Some(ObservedKind::Map));
5933    let region_has_deopt_source = ops.iter().any(|op| match *op {
5934        Op::Div { .. } | Op::Mod { .. } | Op::Call { .. } | Op::Index { .. } => true,
5935        Op::IndexUnchecked { collection, .. } | Op::Contains { collection, .. } => {
5936            is_map(collection)
5937        }
5938        _ => false,
5939    });
5940    let is_setindexed = |reg: u16| {
5941        ops.iter().any(|op| {
5942            matches!(*op,
5943                Op::SetIndex { collection, .. } | Op::SetIndexUnchecked { collection, .. }
5944                    if collection == reg)
5945        })
5946    };
5947    // A pinned mutable-Text accumulator is grown directly in its VM register cell
5948    // by the `StrAppend` helper — like an in-place `SetIndex`, that growth is NOT
5949    // replay-idempotent (a classic replay-from-head would double-append), so its
5950    // entry `Value` must be snapshotted and restored on a classic deopt.
5951    let is_text_mut = |reg: u16| {
5952        pin_regs
5953            .iter()
5954            .any(|&(r, e)| r == reg && e == PinElem::TextMut)
5955    };
5956    // LEVER B: a region that CALLS a list-parameter function (`has_list_param_call`,
5957    // computed above) lets the callee mutate the passed buffer IN PLACE. The
5958    // region can't see which pinned array flows into the call (it's staged through
5959    // Moves into the arg window), so conservatively snapshot EVERY pinned array in
5960    // such a region — its contents must roll back on a classic deopt like a SetIndex.
5961    let needs_snapshot = !needs_precise && region_has_deopt_source;
5962    let pin_base = register_count + 2;
5963    let array_pins: Vec<ArrayPin> = pin_regs
5964        .iter()
5965        .enumerate()
5966        .map(|(k, &(reg, elem))| ArrayPin {
5967            reg,
5968            vec_slot: pin_base + 3 * k as u16,
5969            ptr_slot: pin_base + 3 * k as u16 + 1,
5970            len_slot: pin_base + 3 * k as u16 + 2,
5971            elem,
5972            rebound: ops
5973                .iter()
5974                .any(|op| matches!(*op, Op::RevSwap { a, b } if a == reg || b == reg)),
5975            mutated: needs_snapshot
5976                && (is_setindexed(reg)
5977                    || has_list_param_call
5978                    || is_text_mut(reg)
5979                    || adopted_call_dsts.contains_key(&reg)),
5980        })
5981        .collect();
5982    // Collect the loop's region-entry bounds hoists, resolving each guarded
5983    // array to its pinned length slot. The guarded array MUST be pinned (it is
5984    // — the compiler only emits a guard for an array it also accesses); a
5985    // guard whose array is not pinned is dropped (its accesses then stay
5986    // checked, which is safe).
5987    let mut hoist_guards: Vec<HoistGuard> = Vec::new();
5988    for op in ops {
5989        if let Op::RegionBoundsGuard {
5990            array,
5991            bound,
5992            iv,
5993            add_max,
5994            add_min,
5995        } = *op
5996        {
5997            // The guarded array must be pinned (so its length is available to
5998            // check). If not, bail the region entirely — never run the
5999            // speculative accesses without their guard.
6000            let Some(pin) = array_pins.iter().find(|p| p.reg == array) else {
6001                if std::env::var_os("LOGOS_RDIAG").is_some() {
6002                    eprintln!("RDIAG-BAIL head_pc={head_pc} bounds-guard-array-not-pinned");
6003                }
6004                return None;
6005            };
6006            hoist_guards.push(HoistGuard {
6007                len_slot: pin.len_slot,
6008                bound_reg: bound,
6009                iv_reg: iv,
6010                add_max,
6011                add_min,
6012            });
6013        }
6014    }
6015    let pins: std::collections::HashMap<u16, PinSlots> = array_pins
6016        .iter()
6017        .map(|p| {
6018            (
6019                p.reg,
6020                PinSlots {
6021                    vec_slot: p.vec_slot,
6022                    ptr_slot: p.ptr_slot,
6023                    len_slot: p.len_slot,
6024                    elem: p.elem,
6025                },
6026            )
6027        })
6028        .collect();
6029
6030    // Must-write: slots DEFINITELY written on every path from the head to
6031    // op i (state holding before i executes). Forward dataflow with
6032    // intersection at merges. A written slot that is not must-written at
6033    // some exit edge is only written on SOME completing paths — bytecode
6034    // would leave its old value on the others, so the region must copy the
6035    // old value IN (guard it) for write-back to restore when the taken path
6036    // skipped the write. (The primes `isPrime`-flag shape.)
6037    let mut mw: Vec<Option<Vec<bool>>> = vec![None; ops.len()];
6038    mw[0] = Some(vec![false; nregs]);
6039    let mut work: Vec<usize> = vec![0];
6040    while let Some(i) = work.pop() {
6041        let Some(cur) = mw[i].clone() else { continue };
6042        let mut out = cur;
6043        let Some((_, defs)) = region_use_def(&ops[i]) else {
6044            if std::env::var_os("LOGOS_RDIAG").is_some() {
6045                eprintln!(
6046                    "RDIAG-BAIL head_pc={head_pc} mw-use_def-unsupported op={:?}",
6047                    ops[i]
6048                );
6049            }
6050            return None;
6051        };
6052        for d in defs {
6053            out[d as usize] = true;
6054        }
6055        let mut succs: Vec<usize> = Vec::with_capacity(2);
6056        match ops[i] {
6057            Op::Jump { target } => {
6058                if in_region(target) {
6059                    succs.push(target - head_pc);
6060                }
6061            }
6062            Op::JumpIfFalse { target, .. } | Op::JumpIfTrue { target, .. } => {
6063                if i + 1 < ops.len() {
6064                    succs.push(i + 1);
6065                }
6066                if in_region(target) {
6067                    succs.push(target - head_pc);
6068                }
6069            }
6070            _ => {
6071                if i + 1 < ops.len() {
6072                    succs.push(i + 1);
6073                }
6074            }
6075        }
6076        for s in succs {
6077            match &mut mw[s] {
6078                slot @ None => {
6079                    *slot = Some(out.clone());
6080                    work.push(s);
6081                }
6082                Some(prev) => {
6083                    let mut changed = false;
6084                    for (a, &b) in prev.iter_mut().zip(&out) {
6085                        if *a && !b {
6086                            *a = false;
6087                            changed = true;
6088                        }
6089                    }
6090                    if changed {
6091                        work.push(s);
6092                    }
6093                }
6094            }
6095        }
6096    }
6097    // Intersection of must-write across every reachable exit edge.
6098    let mut exit_must: Vec<bool> = vec![true; nregs];
6099    let mut saw_exit = false;
6100    for (i, op) in ops.iter().enumerate() {
6101        let Some(m) = &mw[i] else { continue };
6102        let exits_here = match *op {
6103            Op::Jump { target }
6104            | Op::JumpIfFalse { target, .. }
6105            | Op::JumpIfTrue { target, .. } => !in_region(target),
6106            Op::Return { .. } => true,
6107            _ => false,
6108        };
6109        if exits_here {
6110            saw_exit = true;
6111            for (e, &b) in exit_must.iter_mut().zip(m) {
6112                *e &= b;
6113            }
6114        }
6115    }
6116    if !saw_exit {
6117        exit_must.iter_mut().for_each(|e| *e = false);
6118    }
6119
6120    // Observability policy: only NAMED slots can be read after the region
6121    // (scratches are statement-local and dead at every statement boundary by
6122    // the compiler's allocation discipline). A named slot written only on
6123    // SOME completing paths is also copied IN, so write-back restores the
6124    // pre-region value when the taken path skipped the write.
6125    let is_named = |r: u16| named.get(r as usize).copied().unwrap_or(false);
6126    for &r in &touched {
6127        if pins.contains_key(&r) {
6128            continue; // pinned arrays ride their own channel
6129        }
6130        let conditionally_written = is_named(r) && writes.contains(&r) && !exit_must[r as usize];
6131        if live[0][r as usize] || conditionally_written {
6132            guard.push(r);
6133        } else {
6134            free.push(r);
6135        }
6136    }
6137
6138    // Flow-sensitive kinds: guarded (live-in or conditionally-written) slots
6139    // enter with the kind the VM OBSERVED at this hot crossing — exactly what
6140    // the runtime guard will re-check on every entry — free slots as Unknown.
6141    // A guard slot holding something the frame can't carry kills the region.
6142    let mut entry = vec![Kind::Unknown; nregs];
6143    let mut guard_kinds: Vec<(u16, SlotKind)> = Vec::with_capacity(guard.len());
6144    for &g in &guard {
6145        let k = observed_kind(*observed.get(g as usize)?);
6146        // `CharText` is a WRITE-BACK-only kind (it re-boxes to a Text on exit); it has no entry
6147        // marshalling (a Text → code-point read), so a `chr` result flowing IN as a live-in guard declines.
6148        if matches!(k, Kind::CharText) {
6149            if std::env::var_os("LOGOS_RDIAG").is_some() {
6150                eprintln!("RDIAG-BAIL head_pc={head_pc} chartext-live-in g={g}");
6151            }
6152            return None;
6153        }
6154        let Some(sk) = k.slot_kind() else {
6155            if std::env::var_os("LOGOS_RDIAG").is_some() {
6156                eprintln!("RDIAG-BAIL head_pc={head_pc} guard-slot-no-slotkind g={g} kind={k:?}");
6157            }
6158            return None;
6159        };
6160        entry[g as usize] = k;
6161        guard_kinds.push((g, sk));
6162    }
6163    for &(reg, elem) in &pin_regs {
6164        entry[reg as usize] = match elem {
6165            PinElem::Int => Kind::IntList,
6166            PinElem::IntI32 => Kind::IntListI32,
6167            PinElem::Word32 => Kind::Word32List,
6168            PinElem::Float => Kind::FloatList,
6169            PinElem::Bool => Kind::BoolList,
6170            PinElem::Map => Kind::IntMap,
6171            PinElem::TextBytes => Kind::TextBytes,
6172            PinElem::TextMut => Kind::TextMut,
6173        };
6174    }
6175    // Admit a region that calls a list-parameter function. Sound only for a
6176    // region-safe callee (never reallocs a list param) whose list args are
6177    // pinned arrays the region snapshots; the region also releases its array
6178    // borrows around the call so the callee can borrow them. On by default;
6179    // `LOGOS_LEVERB=0` rejects such regions. `leverb_on` is bound above (at the
6180    // pin-regs stage).
6181    let resolve = |fi: u16| -> Option<(Kind, Vec<Kind>)> {
6182        let sig = callees.get(fi as usize)?;
6183        if sig.inout_params.iter().any(|&r| {
6184            matches!(
6185                sig.param_kinds.get(r as usize),
6186                Some(Some(ParamKind::List(_)))
6187            )
6188        }) {
6189            return None;
6190        }
6191        let list_kind = |e: PinElem| -> Option<Kind> {
6192            match e {
6193                PinElem::Int => Some(Kind::IntList),
6194                PinElem::Word32 => Some(Kind::Word32List),
6195                PinElem::Float => Some(Kind::FloatList),
6196                PinElem::Bool => Some(Kind::BoolList),
6197                // A half-width buffer is never a declared list-param.
6198                PinElem::IntI32 => None,
6199                PinElem::Map | PinElem::TextBytes | PinElem::TextMut => None,
6200            }
6201        };
6202        let ret = match sig.ret {
6203            Some(SlotKind::Int) => Kind::Int,
6204            Some(SlotKind::Bool) => Kind::Bool,
6205            Some(SlotKind::Float) => Kind::Float,
6206            Some(SlotKind::CharText) => Kind::CharText,
6207            Some(SlotKind::Word32) => Kind::Word32,
6208            Some(SlotKind::Word64) => Kind::Word64,
6209            // A LIST (or void) return: a parameter-passthrough keeps the
6210            // existing pin identity; a declared Int/Word32 list return is
6211            // adopted into the destination pin immediately after the call.
6212            None => {
6213                if !leverb_on || !sig.list_params_stable {
6214                    if std::env::var_os("LOGOS_RDIAG").is_some() {
6215                        eprintln!("RDIAG-BAIL head_pc={head_pc} list-return-call");
6216                    }
6217                    return None;
6218                }
6219                let elem = if sig.returns_list_param {
6220                    sig.param_kinds.iter().find_map(|pk| match pk {
6221                        Some(ParamKind::List(e)) => Some(*e),
6222                        _ => None,
6223                    })?
6224                } else {
6225                    sig.list_ret?
6226                };
6227                list_kind(elem)?
6228            }
6229        };
6230        let mut ps = Vec::with_capacity(sig.param_kinds.len());
6231        for pk in &sig.param_kinds {
6232            match (*pk)? {
6233                ParamKind::Scalar(SlotKind::Int) => ps.push(Kind::Int),
6234                ParamKind::Scalar(SlotKind::Bool) => ps.push(Kind::Bool),
6235                ParamKind::Scalar(SlotKind::Float) => ps.push(Kind::Float),
6236                ParamKind::Scalar(SlotKind::CharText) => ps.push(Kind::CharText),
6237                ParamKind::Scalar(SlotKind::Word32) => ps.push(Kind::Word32),
6238                ParamKind::Scalar(SlotKind::Word64) => ps.push(Kind::Word64),
6239                // A list param: the callee mutates the shared buffer in place.
6240                // Sound iff the callee is stable (no realloc) — the pinned arg's
6241                // contents ride the deopt snapshot/rollback, and the region
6242                // releases its borrow so the callee can access it.
6243                ParamKind::List(elem) => {
6244                    if !leverb_on || !sig.list_params_stable {
6245                        if std::env::var_os("LOGOS_RDIAG").is_some() {
6246                            eprintln!("RDIAG-BAIL head_pc={head_pc} list-param-call");
6247                        }
6248                        return None;
6249                    }
6250                    ps.push(list_kind(elem)?);
6251                }
6252                // A region carries no nodes.
6253                ParamKind::Inductive => return None,
6254            }
6255        }
6256        Some((ret, ps))
6257    };
6258    let Some(kin) = kind_flow(ops, head_pc, constants, entry, Some(&resolve), &[]) else {
6259        if std::env::var_os("LOGOS_RDIAG").is_some() {
6260            eprintln!("RDIAG-BAIL head_pc={head_pc} kind_flow");
6261        }
6262        return None;
6263    };
6264
6265    // Write-back kinds come from the EXIT EDGES: for each written slot, join
6266    // its kind at every reachable out-of-region jump. Mixed (exits disagree)
6267    // bails; Unknown means no completing path writes it — leave the VM
6268    // register untouched (exactly what bytecode reaching the exit would do).
6269    let mut exit_kind: Vec<Kind> = vec![Kind::Unknown; nregs];
6270    for (i, op) in ops.iter().enumerate() {
6271        let Some(k) = &kin[i] else { continue };
6272        let exits_here = match *op {
6273            Op::Jump { target } => !in_region(target),
6274            Op::JumpIfFalse { target, .. } | Op::JumpIfTrue { target, .. } => !in_region(target),
6275            // An in-region Return leaves the loop too — its named writes
6276            // flow through the same write-back.
6277            Op::Return { .. } => true,
6278            _ => false,
6279        };
6280        if exits_here {
6281            for (e, kk) in exit_kind.iter_mut().zip(k) {
6282                *e = join(*e, *kk);
6283            }
6284        }
6285    }
6286    // Exit edges can carry different scalar types after an exchange.
6287    // Materialize at the taken edge, then execute its jump or return once.
6288    let typed_exits = writes
6289        .iter()
6290        .any(|&r| is_named(r) && live[0][r as usize] && exit_kind[r as usize] == Kind::Mixed);
6291    if typed_exits {
6292        // Calls and rebound collections need their own precise ownership
6293        // protocol; scalar materialization cannot reconstruct those.
6294        if has_call_op || array_pins.iter().any(|p| p.rebound) {
6295            return None;
6296        }
6297        for &r in &writes {
6298            if is_named(r) && exit_kind[r as usize] == Kind::Mixed {
6299                for k in kin.iter().flatten() {
6300                    if !matches!(k[r as usize], Kind::Unknown)
6301                        && k[r as usize].slot_kind().is_none()
6302                    {
6303                        return None;
6304                    }
6305                }
6306            }
6307        }
6308    }
6309    // A fresh-list-return adoption is also a precise-resume shape. Before the
6310    // call, pinned list effects already live in their VM buffers; if the native
6311    // callee side-exits, resuming at the Call observes those exact buffers. On
6312    // success the following Host adopts into the stable destination handle.
6313    // Selecting precise mode lets the contiguous backend compile Call + Host
6314    // instead of falling back to the per-piece stencil tier.
6315    let needs_precise = needs_precise || typed_exits || !adopted_call_dsts.is_empty();
6316    let mut write_set: Vec<(u16, SlotKind)> = Vec::new();
6317    for &r in &writes {
6318        // Scratches are unobservable after the region — never written back,
6319        // and their exit kind (often Mixed: the compiler reuses them across
6320        // Int and Bool statements) is irrelevant.
6321        if !is_named(r) {
6322            continue;
6323        }
6324        // LEVER B: a pinned array REBOUND to a return-aliased call result
6325        // (`arr = siftDown(arr, …)`) carries a list exit-kind, but it rides the
6326        // pin channel, not the scalar write-back: the callee returns its own
6327        // argument (`returns_list_param`), so the VM register already holds the
6328        // correct Rc and no write-back is owed. Skip it (else `slot_kind()` on a
6329        // list kind below would bail the region).
6330        if leverb_on && array_pins.iter().any(|a| a.reg == r) {
6331            continue;
6332        }
6333        match exit_kind[r as usize] {
6334            Kind::Unknown => {}
6335            // A Mixed exit-kind means the compiler REUSED this register across
6336            // an Int and a Float on different paths — it is never a single
6337            // typed observable variable. If it is NOT loop-carried (not live-in
6338            // at the region head, per the region's own backward liveness) it is
6339            // a per-iteration scratch, dead at the region boundary: skip its
6340            // write-back rather than decline the whole region (the VM's stale
6341            // register value is unobservable — the scratch is recomputed every
6342            // iteration). A genuinely loop-carried Mixed slot still bails.
6343            Kind::Mixed => {
6344                if live[0][r as usize] && !typed_exits {
6345                    if std::env::var_os("LOGOS_RDIAG").is_some() {
6346                        eprintln!("RDIAG-BAIL head_pc={head_pc} mixed-write-set slot={r}");
6347                    }
6348                    return None;
6349                }
6350            }
6351            // A text kind has no scalar write-back representation. The pinned
6352            // `TextMut` accumulator already rode the `array_pins` skip above; a
6353            // `TextByte`/`TextConst` here is a per-iteration char/const scratch
6354            // (the `ch` selection, a literal load) — dead at the region boundary
6355            // when NOT loop-carried, so skip its write-back exactly like a
6356            // non-loop-carried Mixed scratch. A genuinely loop-carried text
6357            // (live-in at the head, e.g. an unpinned Text variable) still bails.
6358            Kind::TextByte | Kind::TextConst | Kind::TextMut => {
6359                if live[0][r as usize] {
6360                    if std::env::var_os("LOGOS_RDIAG").is_some() {
6361                        eprintln!("RDIAG-BAIL head_pc={head_pc} text-write-set-loop-carried slot={r} kind={:?}", exit_kind[r as usize]);
6362                    }
6363                    return None;
6364                }
6365            }
6366            k => {
6367                let Some(sk) = k.slot_kind() else {
6368                    if std::env::var_os("LOGOS_RDIAG").is_some() {
6369                        eprintln!(
6370                            "RDIAG-BAIL head_pc={head_pc} write-set-no-slotkind r={r} kind={k:?}"
6371                        );
6372                    }
6373                    return None;
6374                };
6375                write_set.push((r, sk));
6376            }
6377        }
6378    }
6379
6380    let ret_base = pin_base + 3 * array_pins.len() as u16;
6381    let region_return_slots = has_return.then_some((ret_base, ret_base + 1));
6382
6383    // The agreed return kind across every reachable Return site.
6384    use logicaffeine_compile::vm::RegionReturnKind;
6385    let mut ret_kind: Option<RegionReturnKind> = None;
6386    if has_return {
6387        for (i, op) in ops.iter().enumerate() {
6388            let Some(k) = &kin[i] else { continue };
6389            if let Op::Return { src } = *op {
6390                let rk = match k[src as usize] {
6391                    Kind::IntList | Kind::FloatList | Kind::BoolList => RegionReturnKind::Register,
6392                    other => RegionReturnKind::Slot(other.slot_kind()?),
6393                };
6394                match ret_kind {
6395                    None => ret_kind = Some(rk),
6396                    Some(prev) if prev == rk => {}
6397                    _ => return None,
6398                }
6399            }
6400        }
6401        // A region whose every Return is unreachable: treat as returnless.
6402        if ret_kind.is_none() {
6403            return None;
6404        }
6405    }
6406    let region_return = match (region_return_slots, ret_kind) {
6407        (Some((flag, val)), Some(kind)) => Some(logicaffeine_compile::vm::RegionReturn {
6408            flag_slot: flag,
6409            value_slot: val,
6410            kind,
6411        }),
6412        _ => None,
6413    };
6414
6415    // Emit: out-of-region jumps go to the synthetic exit terminal. Adjacent
6416    // cmp + conditional-jump pairs whose scratch is dead FUSE into one
6417    // Branch micro-op (both VM pcs map to it). Two scratch slots past the
6418    // register file carry Int→Float promotions; two more per pinned array
6419    // carry its buffer pointer and length.
6420    let has_calls = ops.iter().any(|op| matches!(op, Op::Call { .. }));
6421    let frame_size = register_count as usize
6422        + 2
6423        + 3 * array_pins.len()
6424        + if has_return { 2 } else { 0 }
6425        + if has_calls { 2 } else { 0 };
6426    // The arena-limit slot is LAST; callees window immediately past the
6427    // frame (region frames get real arena headroom when they call).
6428    let limit_slot = (frame_size - 1) as u16;
6429    let mut jump_targets: std::collections::HashSet<usize> = ops
6430        .iter()
6431        .filter_map(|op| match *op {
6432            Op::Jump { target }
6433            | Op::JumpIfFalse { target, .. }
6434            | Op::JumpIfTrue { target, .. } => Some(target),
6435            _ => None,
6436        })
6437        .collect();
6438    if typed_exits {
6439        // A resumed conditional edge needs its condition register populated;
6440        // prevent comparison/jump fusion from removing that assignment.
6441        jump_targets.extend(head_pc..head_pc + ops.len());
6442    }
6443    let scratch_ok = |r: u16| !is_named(r);
6444    let conv = (register_count, register_count + 1);
6445    let mut micro: Vec<MicroOp> = Vec::with_capacity(ops.len());
6446    let mut pc_to_micro: Vec<usize> = Vec::with_capacity(ops.len());
6447    let mut fixups: Vec<usize> = Vec::new();
6448
6449    // NAIVE SUBSTRING-SEARCH COLLAPSE (string_search): if the WHOLE outer-loop
6450    // region is the exact naive-search nest over two pinned ASCII `TextBytes`
6451    // buffers (text + needle), replace the per-byte nested loop with ONE
6452    // `MemMem` helper call. The helper counts overlapping matches, adds them to
6453    // `count`, and advances `i` to the loop's exit value — bit-identical to the
6454    // nest, with a deopt exit for the one recoverable disagreement (a checked
6455    // needle index past the needle buffer). Gated on: no return, no precise
6456    // requirement, both `text` and `needle` pinned as `TextBytes`, and `count`/
6457    // `i`/`needleLen` carried as plain Int write-back/guard slots.
6458    if !has_return && !needs_precise {
6459        if let Some(shape) = match_memmem_nest(ops, head_pc, exit_pc, constants) {
6460            let text_pin = pins.get(&shape.text_reg);
6461            let needle_pin = pins.get(&shape.needle_reg);
6462            if let (Some(tp), Some(np)) = (text_pin, needle_pin) {
6463                let both_text = tp.elem == PinElem::TextBytes && np.elem == PinElem::TextBytes;
6464                // The accumulators must be plain Int write-back slots (the nest's
6465                // `count`/`i`); `needleLen` must be a guarded Int input. If the
6466                // shape's registers don't line up as Int the recognizer declines.
6467                let count_int = write_set
6468                    .iter()
6469                    .any(|&(r, k)| r == shape.count_reg && k == SlotKind::Int);
6470                let i_int = write_set
6471                    .iter()
6472                    .any(|&(r, k)| r == shape.i_reg && k == SlotKind::Int);
6473                let needle_len_int = guard_kinds
6474                    .iter()
6475                    .any(|&(r, k)| r == shape.needle_len_reg && k == SlotKind::Int);
6476                if both_text && count_int && i_int && needle_len_int {
6477                    let mut mm: Vec<MicroOp> = Vec::with_capacity(2);
6478                    mm.push(MicroOp::MemMem {
6479                        h_ptr_slot: tp.ptr_slot,
6480                        h_len_slot: tp.len_slot,
6481                        n_ptr_slot: np.ptr_slot,
6482                        n_len_slot: np.len_slot,
6483                        needle_len_slot: shape.needle_len_reg,
6484                        i_slot: shape.i_reg,
6485                        count_slot: shape.count_reg,
6486                        helper_addr: logos_rt_memmem_frame as usize as i64,
6487                    });
6488                    mm.push(MicroOp::Return { src: 0 });
6489                    // Only `count` and `i` are observable after the loop (they are
6490                    // the nest's loop-carried write-back); restrict the write-set
6491                    // to them so nothing stale is copied back.
6492                    let mm_write_set: Vec<(u16, SlotKind)> = write_set
6493                        .iter()
6494                        .copied()
6495                        .filter(|&(r, _)| r == shape.count_reg || r == shape.i_reg)
6496                        .collect();
6497                    return Some((
6498                        mm,
6499                        frame_size,
6500                        guard_kinds,
6501                        free,
6502                        mm_write_set,
6503                        array_pins,
6504                        None,
6505                        hoist_guards,
6506                        None,
6507                    ));
6508                }
6509            }
6510        }
6511    }
6512
6513    // The frame buffer is reused across entries — the return flag must be
6514    // explicitly cleared at the head of every run.
6515    if let Some((flag, _)) = region_return_slots {
6516        micro.push(MicroOp::LoadConst {
6517            dst: flag,
6518            value: 0,
6519        });
6520    }
6521    // The pending call survives unwinding through native code. Clear it
6522    // after a completed call so later region exits use the region's own PC.
6523    let call_site_slot = has_calls.then(|| (frame_size - 2) as u16);
6524    if let Some(dst) = call_site_slot {
6525        micro.push(MicroOp::LoadConst { dst, value: -1 });
6526    }
6527    let iteration_reset_micro = iteration_alloc_reset.then(|| {
6528        let at = micro.len();
6529        micro.push(host_call(conv.0, conv.0, 0, 0, logos_rt_region_alloc_reset));
6530        at
6531    });
6532
6533    let mut i = 0usize;
6534    while i < ops.len() {
6535        // Region call: the callee windows at base + frame_size (disjoint
6536        // from registers, pins, return and limit slots), arguments copied
6537        // into the fresh window. Entry deopt (callee not yet compiled,
6538        // depth, arena) writes the PLAIN marker — region replay is sound
6539        // because the resolver admitted only scalar-pure callees.
6540        if let Op::Call {
6541            dst,
6542            args_start,
6543            arg_count,
6544            func,
6545        } = ops[i]
6546        {
6547            if kin[i].is_some() {
6548                if resolve(func).is_none() {
6549                    if std::env::var_os("LOGOS_RDIAG").is_some() {
6550                        let s = callees.get(func as usize);
6551                        eprintln!(
6552                            "RDIAG-BAIL head_pc={head_pc} lowering-resolve func={func} stable={:?} retparam={:?} ret={:?}",
6553                            s.map(|x| x.list_params_stable),
6554                            s.map(|x| x.returns_list_param),
6555                            s.map(|x| x.ret),
6556                        );
6557                    }
6558                    return None;
6559                }
6560                pc_to_micro.push(micro.len());
6561                micro.push(MicroOp::LoadConst {
6562                    dst: call_site_slot?,
6563                    value: (head_pc + i) as i64,
6564                });
6565                let window = frame_size as u16;
6566                for j in 0..arg_count {
6567                    micro.push(MicroOp::Move {
6568                        dst: window + j,
6569                        src: args_start + j,
6570                    });
6571                }
6572                micro.push(MicroOp::Call {
6573                    dst,
6574                    args_start: window,
6575                    table_addr: ctx.table.slot_addr(func as usize),
6576                    depth_addr: std::sync::Arc::as_ptr(&ctx.depth) as i64,
6577                    status_addr: std::sync::Arc::as_ptr(&ctx.status) as i64,
6578                    limit_slot,
6579                    depth_limit: logicaffeine_compile::semantics::MAX_CALL_DEPTH as i64,
6580                });
6581                micro.push(MicroOp::LoadConst {
6582                    dst: call_site_slot?,
6583                    value: -1,
6584                });
6585                if let Some(&elem) = adopted_call_dsts.get(&dst) {
6586                    let pin = pins.get(&dst)?;
6587                    if pin.elem != elem {
6588                        return None;
6589                    }
6590                    micro.push(MicroOp::Move {
6591                        dst: conv.0,
6592                        src: dst,
6593                    });
6594                    micro.push(MicroOp::Move {
6595                        dst: conv.1,
6596                        src: pin.vec_slot,
6597                    });
6598                    micro.push(host_call(dst, conv.0, 2, 0, logos_rt_adopt_list_i64));
6599                    micro.push(MicroOp::ListTriple {
6600                        handle_slot: dst,
6601                        vec_slot: pin.vec_slot,
6602                        ptr_slot: pin.ptr_slot,
6603                        len_slot: pin.len_slot,
6604                        helper_addr: logos_rt_list_triple as usize as i64,
6605                    });
6606                }
6607                for &j in &callees[func as usize].inout_params {
6608                    micro.push(MicroOp::Move {
6609                        dst: args_start + j,
6610                        src: window + j,
6611                    });
6612                }
6613            } else {
6614                pc_to_micro.push(micro.len());
6615            }
6616            i += 1;
6617            continue;
6618        }
6619        let Some(advance) = translate_op(
6620            ops,
6621            i,
6622            head_pc,
6623            constants,
6624            &kin,
6625            &live,
6626            Some(&safe_list_stages),
6627            &jump_targets,
6628            &scratch_ok,
6629            conv,
6630            &pins,
6631            None,
6632            region_return_slots,
6633            false,
6634            true,
6635            &mut micro,
6636            &mut pc_to_micro,
6637            &mut fixups,
6638        ) else {
6639            if std::env::var_os("LOGOS_RDIAG").is_some() {
6640                eprintln!(
6641                    "RDIAG-BAIL head_pc={head_pc} translate_op-failed op={:?}",
6642                    ops[i]
6643                );
6644            }
6645            return None;
6646        };
6647        i += advance;
6648    }
6649    if let (Some(at), Some(first)) = (iteration_reset_micro, pc_to_micro.first_mut()) {
6650        // Every backedge to the VM loop head must run the lifetime boundary;
6651        // the one-time frame prologue remains before it and is intentionally
6652        // skipped on internal iterations.
6653        *first = at;
6654    }
6655    // Out-of-region jumps route to the synthetic exit terminal.
6656    let exit_micro = micro.len();
6657    micro.push(MicroOp::Return { src: 0 });
6658    let _ = exit_pc;
6659    for &fi in &fixups {
6660        let vm_target = match micro[fi] {
6661            MicroOp::Jump { target }
6662            | MicroOp::JumpIfFalse { target, .. }
6663            | MicroOp::JumpIfTrue { target, .. }
6664            | MicroOp::Branch { target, .. }
6665            | MicroOp::BranchF { target, .. } => target,
6666            _ => unreachable!(),
6667        };
6668        let target_micro = if in_region(vm_target) {
6669            *pc_to_micro.get(vm_target - head_pc)?
6670        } else if typed_exits {
6671            let opi = pc_to_micro.iter().rposition(|&start| start <= fi)?;
6672            let resume_pc = head_pc + opi;
6673            let terminal = micro.len();
6674            micro.push(MicroOp::LoadConst {
6675                dst: conv.0,
6676                value: resume_pc as i64,
6677            });
6678            micro.push(MicroOp::Return { src: conv.0 });
6679            terminal
6680        } else {
6681            exit_micro
6682        };
6683        match &mut micro[fi] {
6684            MicroOp::Jump { target }
6685            | MicroOp::JumpIfFalse { target, .. }
6686            | MicroOp::JumpIfTrue { target, .. }
6687            | MicroOp::Branch { target, .. }
6688            | MicroOp::BranchF { target, .. } => *target = target_micro,
6689            _ => unreachable!(),
6690        }
6691    }
6692    // A push+SetIndex region is admitted ONLY with PRECISE deopt: on a side
6693    // exit the VM materializes the frame's scalars back into the VM registers
6694    // and resumes AT the faulting op. Materialization re-boxes each register by
6695    // its kind at that op (from the kind flow) — Int/Bool/Float by value;
6696    // LIST/MAP and read-only/unknown registers are KEPT (the VM register holds
6697    // the live value: a pinned array is mutated in place through its pins, and a
6698    // read-only slot still holds its entry value). The ONE thing that breaks
6699    // "keep" is a list/map REBIND — a def whose value is a collection, which
6700    // would leave the VM register holding the stale Rc. In-place array
6701    // mutations (`ListPush`/`SetIndex`) are USES of the handle, never defs, so
6702    // they never appear in `writes`; a genuine rebind does, and disqualifies.
6703    let array_reg_set: std::collections::HashSet<u16> = array_pins.iter().map(|a| a.reg).collect();
6704    let rebinds_collection = writes.iter().any(|&r| {
6705        !array_reg_set.contains(&r)
6706            && matches!(
6707                exit_kind[r as usize],
6708                Kind::IntList | Kind::FloatList | Kind::BoolList | Kind::IntMap
6709            )
6710    });
6711    let precise_region = needs_precise && !rebinds_collection;
6712    if needs_precise && !precise_region {
6713        if std::env::var_os("LOGOS_RDIAG").is_some() {
6714            eprintln!("RDIAG-BAIL head_pc={head_pc} needs-precise-but-rebinds-collection");
6715        }
6716        return None;
6717    }
6718    // Per-op resume codes + per-op materialization kinds. Each micro of bytecode
6719    // op `opi` carries `((head_pc+opi) << 2) | 3`; the matching `kinds_by_pc`
6720    // row says how to re-box every register when the VM resumes there.
6721    let precise = if precise_region {
6722        let mut codes = vec![1i64; micro.len()];
6723        let mut kinds_by_pc: std::collections::HashMap<usize, Vec<Option<SlotKind>>> =
6724            std::collections::HashMap::new();
6725        for opi in 0..ops.len() {
6726            let lo = pc_to_micro[opi];
6727            let hi = pc_to_micro.get(opi + 1).copied().unwrap_or(micro.len());
6728            let resume_pc = head_pc + opi;
6729            let code = ((resume_pc as i64) << 2) | 3;
6730            for c in codes.iter_mut().take(hi).skip(lo) {
6731                *c = code;
6732            }
6733            if let Some(k) = kin.get(opi).and_then(|x| x.as_ref()) {
6734                let row: Vec<Option<SlotKind>> = (0..register_count as usize)
6735                    .map(|r| {
6736                        if array_reg_set.contains(&(r as u16)) {
6737                            return None; // pinned array — keep its live Rc
6738                        }
6739                        match k.get(r) {
6740                            Some(Kind::Int) => Some(SlotKind::Int),
6741                            Some(Kind::Bool) => Some(SlotKind::Bool),
6742                            Some(Kind::Float) => Some(SlotKind::Float),
6743                            // A `chr` result re-boxes to a Text on write-back (never "keep VM value").
6744                            Some(Kind::CharText) => Some(SlotKind::CharText),
6745                            // A loop-carried Word re-boxes to a `RuntimeValue::Word` on write-back.
6746                            Some(Kind::Word32) => Some(SlotKind::Word32),
6747                            Some(Kind::Word64) => Some(SlotKind::Word64),
6748                            // list/map/unknown/mixed read-only → keep VM value
6749                            _ => None,
6750                        }
6751                    })
6752                    .collect();
6753                kinds_by_pc.insert(resume_pc, row);
6754            }
6755        }
6756        Some(RegionPrecise {
6757            resume_on_return: typed_exits,
6758            deopt_codes: codes,
6759            kinds_by_pc,
6760        })
6761    } else {
6762        None
6763    };
6764    Some((
6765        micro,
6766        frame_size,
6767        guard_kinds,
6768        free,
6769        write_set,
6770        array_pins,
6771        region_return,
6772        hoist_guards,
6773        precise,
6774    ))
6775}
6776
6777/// Maximum slots in a per-thread native call arena. Each compiled function
6778/// allocates only its proven `frame_size * (MAX_CALL_DEPTH + 1)` requirement;
6779/// this 16 MiB ceiling remains the compile-time capability limit for unusually
6780/// large frames. The call stencil's arena-limit check deopts before overflow.
6781const ARENA_SLOTS: usize = 1 << 21;
6782
6783struct ChainFn {
6784    chain: CompiledChain,
6785    /// Bytecode function-table index, retained for runtime trace attribution.
6786    function_index: u16,
6787    limit_slot: usize,
6788    /// Exact recursive arena bound proved at compile time. Right-sizing avoids
6789    /// zero-filling the 16 MiB capability ceiling on every fresh JIT process.
6790    arena_slots: usize,
6791    depth: std::sync::Arc<std::sync::atomic::AtomicI64>,
6792    ret: NativeRet,
6793    /// The elements of a fresh list it returns, which decide the VM representation it re-boxes into.
6794    ret_elem: PinElem,
6795    /// frame_size − 3: what the call stencil's bound math expects in the
6796    /// table's regcount slot (mode A: the plain register count).
6797    published_regc: i64,
6798    precise: Option<PreciseInfo>,
6799    stats: std::sync::Arc<RuntimeStats>,
6800    /// The constructor and variant shapes the chain's enum-lane helpers point at.
6801    _shapes: NodeShapes,
6802    param_kinds: Vec<Option<ParamKind>>,
6803}
6804
6805impl NativeFn for ChainFn {
6806    fn call(&self, args: &[i64], pins: &[i64], depth: usize) -> NativeOutcome {
6807        self.call_with_writeback(args, pins, depth, &[], &mut Vec::new())
6808    }
6809    fn call_with_writeback(
6810        &self,
6811        args: &[i64],
6812        pins: &[i64],
6813        depth: usize,
6814        slots: &[u16],
6815        writeback: &mut Vec<(u16, logicaffeine_compile::vm::NativeWriteback)>,
6816    ) -> NativeOutcome {
6817        // One arena per thread: the outermost native call owns it for the
6818        // whole (possibly deeply recursive) run. Kind gates prove no slot is
6819        // read before it is written, so stale contents are unobservable.
6820        thread_local! {
6821            static ARENA: std::cell::RefCell<Vec<i64>> = const { std::cell::RefCell::new(Vec::new()) };
6822        }
6823        self.stats
6824            .entries
6825            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6826        ARENA.with(|f| {
6827            let mut frame = f.borrow_mut();
6828            if frame.len() < self.arena_slots {
6829                // A fresh zero-filled allocation lets the system allocator
6830                // provide untouched pages lazily. `resize` would explicitly
6831                // write the entire recursive safety ceiling up front even
6832                // when execution reaches only a handful of frames.
6833                *frame = vec![0; self.arena_slots];
6834            }
6835            frame[..args.len()].copy_from_slice(args);
6836            if let Some(p) = &self.precise {
6837                for (k, chunk) in pins.chunks(3).enumerate() {
6838                    let base = p.param_pin_scatter[k] as usize;
6839                    frame[base..base + 3].copy_from_slice(chunk);
6840                }
6841            }
6842            let arena_end = unsafe { frame.as_ptr().add(self.arena_slots) } as i64;
6843            frame[self.limit_slot] = arena_end;
6844            self.depth
6845                .store(depth as i64, std::sync::atomic::Ordering::Relaxed);
6846            match self.chain.run_with_frame(&mut frame) {
6847                ChainOutcome::Return(v) => {
6848                    self.stats
6849                        .completions
6850                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6851                    // Detach each owned buffer once, sharing that value between
6852                    // output arguments and the return when their handles alias.
6853                    let mut detached =
6854                        std::collections::HashMap::<i64, logicaffeine_compile::vm::Value>::new();
6855                    for &slot in slots {
6856                        let raw = frame[slot as usize];
6857                        let boxed = if let Some(Some(ParamKind::List(elem))) =
6858                            self.param_kinds.get(slot as usize)
6859                        {
6860                            detached.get(&raw).cloned().or_else(|| {
6861                                alloc_registry_detach(raw).map(|vec| {
6862                                    let value = list_value(vec, *elem);
6863                                    detached.insert(raw, value.clone());
6864                                    value
6865                                })
6866                            })
6867                        } else {
6868                            None
6869                        };
6870                        let value = match boxed {
6871                            Some(value) => logicaffeine_compile::vm::NativeWriteback::Value(value),
6872                            None => logicaffeine_compile::vm::NativeWriteback::Raw(raw),
6873                        };
6874                        writeback.push((slot, value));
6875                    }
6876                    let out = if matches!(self.ret, NativeRet::ListByHandle) {
6877                        if let Some(value) = detached.get(&v) {
6878                            NativeOutcome::ReturnValue(value.clone())
6879                        } else {
6880                            match alloc_registry_detach(v) {
6881                                // A fresh, registry-owned list: re-box here.
6882                                Some(vec) => {
6883                                    NativeOutcome::ReturnValue(list_value(vec, self.ret_elem))
6884                                }
6885                                // A param passthrough: the VM matches the
6886                                // handle against its pin arguments.
6887                                None => NativeOutcome::Return(v),
6888                            }
6889                        }
6890                    } else {
6891                        NativeOutcome::Return(v)
6892                    };
6893                    alloc_registry_drain();
6894                    out
6895                }
6896                ChainOutcome::Deopt(raw) => {
6897                    if std::env::var_os("LOGOS_JIT_TRACE").is_some() {
6898                        let arena_end = unsafe { frame.as_ptr().add(self.arena_slots) } as i64;
6899                        eprintln!(
6900                            "jit-trace: fn={} deopt raw={raw:#x} depth={depth} limit_slot={} \
6901                             frame[limit]={:#x} arena_end={:#x} delta={}",
6902                            self.function_index,
6903                            self.limit_slot,
6904                            frame[self.limit_slot],
6905                            arena_end,
6906                            arena_end - frame[self.limit_slot],
6907                        );
6908                    }
6909                    let out = if raw & 3 == 3 {
6910                        self.stats
6911                            .deopt_ats
6912                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6913                        let pc = ((raw & 0xFFFF_FFFF) >> 2) as usize;
6914                        let frame_count = ((raw >> 32) - depth as i64 + 1) as usize;
6915                        self.materialize(pc, frame_count, &frame, pins)
6916                    } else {
6917                        self.stats
6918                            .deopts
6919                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6920                        NativeOutcome::Deopt
6921                    };
6922                    alloc_registry_drain();
6923                    out
6924                }
6925            }
6926        })
6927    }
6928    fn materialize_side_exit(
6929        &self,
6930        status: i64,
6931        entry_depth: usize,
6932        frame: &[i64],
6933        pins: &[i64],
6934    ) -> Option<NativeOutcome> {
6935        self.precise.as_ref()?;
6936        if status & 3 != 3 {
6937            return None;
6938        }
6939        let exit_depth = (status >> 32) as usize;
6940        let frame_count = exit_depth.checked_sub(entry_depth)? + 1;
6941        let pc = ((status & 0xFFFF_FFFF) >> 2) as usize;
6942        self.stats.deopt_ats.fetch_add(1, Ordering::Relaxed);
6943        Some(self.materialize(pc, frame_count, frame, pins))
6944    }
6945
6946    fn ret(&self) -> NativeRet {
6947        self.ret
6948    }
6949    fn entry_ptr(&self) -> i64 {
6950        self.chain.base() as i64
6951    }
6952    fn published_regc(&self) -> i64 {
6953        self.published_regc
6954    }
6955    fn code_extents(&self) -> Vec<(usize, usize)> {
6956        let code = self.chain.bytes();
6957        vec![(code.as_ptr() as usize, code.len())]
6958    }
6959}
6960
6961impl ChainFn {
6962    /// Precise deopt: walk the active plant chain (every frame's window
6963    /// plant is −1 unless a call is in flight) and package each native
6964    /// frame with its pause-point re-box kinds — the innermost pauses at
6965    /// the faulting pc, every ancestor at its own Call op.
6966    fn materialize(
6967        &self,
6968        pc: usize,
6969        frame_count: usize,
6970        frame: &[i64],
6971        pins: &[i64],
6972    ) -> NativeOutcome {
6973        let p = self
6974            .precise
6975            .as_ref()
6976            .expect("precise deopt status from a mode-A chain");
6977        let rc = p.register_count;
6978        // Exactly `frame_count` frames are live (the depth rode the status
6979        // value): a call-entry deopt leaves the innermost frame's plant
6980        // freshly written with a callee that never materialized, so the
6981        // plant chain alone cannot terminate the walk.
6982        let mut raw: Vec<(usize, i64, usize, u16)> = Vec::with_capacity(frame_count);
6983        let mut base = 0usize;
6984        for k in 0..frame_count {
6985            let window = frame[base + rc + 2];
6986            raw.push((
6987                base,
6988                window,
6989                frame[base + rc + 3] as usize,
6990                frame[base + rc + 4] as u16,
6991            ));
6992            if k + 1 < frame_count {
6993                assert!(
6994                    window > 0,
6995                    "corrupt plant chain: window {window} at depth {k} (pc {pc})"
6996                );
6997                base += window as usize;
6998            }
6999        }
7000        let last = raw.len() - 1;
7001        let mut frames = Vec::with_capacity(raw.len());
7002        // ★ ONE LIST, ONE VALUE. Registers alias a native-owned list freely (a Move, a call returning its
7003        // argument) — within a frame and across frames. Detaching removes the buffer from the registry, so
7004        // a second alias used to miss it and re-box as Dead (`Cannot index into Nothing` after an overflow
7005        // deopt). Each handle detaches ONCE; every alias gets a clone of that one value — a shared list,
7006        // exactly the aliasing the VM itself holds (and copy-on-writes) at this point.
7007        let mut detached: std::collections::HashMap<i64, logicaffeine_compile::vm::Value> =
7008            std::collections::HashMap::new();
7009        for (k, &(b, _, my_resume, _)) in raw.iter().enumerate() {
7010            let pause_pc = if k == last { pc } else { my_resume - 1 };
7011            let mut kinds = p
7012                .kinds_by_pc
7013                .get(&pause_pc)
7014                .unwrap_or_else(|| panic!("missing kind capture for pc {pause_pc}"))
7015                .clone();
7016            // Native-owned lists survive the deopt: detach fresh ones into
7017            // real values; param passthroughs rewrite to their argument.
7018            let mut resolved: Vec<(u16, logicaffeine_compile::vm::Value)> = Vec::new();
7019            if let Some(owned) = p.owned_by_pc.get(&pause_pc) {
7020                for &(reg, vslot, elem) in owned {
7021                    let handle = frame[b + vslot as usize];
7022                    let owned_value = match detached.get(&handle) {
7023                        Some(v) => Some(v.clone()),
7024                        None => alloc_registry_detach(handle).map(|vec| {
7025                            let v = list_value(vec, elem);
7026                            detached.insert(handle, v.clone());
7027                            v
7028                        }),
7029                    };
7030                    if let Some(v) = owned_value {
7031                        kinds[reg as usize] = RegBox::Resolved;
7032                        resolved.push((reg, v));
7033                    } else {
7034                        // A param's vec: match the boundary pin handles.
7035                        let mut hit = false;
7036                        for (j, chunk) in pins.chunks(3).enumerate() {
7037                            if chunk.first() == Some(&handle) {
7038                                kinds[reg as usize] = RegBox::ListParam(j as u8);
7039                                hit = true;
7040                                break;
7041                            }
7042                        }
7043                        if !hit {
7044                            kinds[reg as usize] = RegBox::Dead;
7045                        }
7046                    }
7047                }
7048            }
7049            // Nodes go back to the VM: an owned one transfers its count, a borrowed one is shared.
7050            if let Some(nodes) = p.nodes_by_pc.get(&pause_pc) {
7051                for &(reg, hold) in nodes {
7052                    // SAFETY: the plan says what `reg` holds at this pause point, and this frame is
7053                    // abandoned after the walk, so each owned count is handed over exactly once.
7054                    match unsafe { inductive::rebox(frame[b + reg as usize], hold) } {
7055                        Some(v) => {
7056                            kinds[reg as usize] = RegBox::Resolved;
7057                            resolved.push((reg, v));
7058                        }
7059                        None => kinds[reg as usize] = RegBox::Dead,
7060                    }
7061                }
7062            }
7063            let (offset, return_pc, return_reg) = if k == 0 {
7064                (0, 0, 0)
7065            } else {
7066                let prev = raw[k - 1];
7067                (prev.1 as usize, prev.2, prev.3)
7068            };
7069            frames.push(NativeFrame {
7070                offset,
7071                return_pc,
7072                return_reg,
7073                regs: frame[b..b + rc].to_vec(),
7074                kinds,
7075                resolved,
7076            });
7077        }
7078        NativeOutcome::DeoptAt {
7079            resume_pc: pc,
7080            frames,
7081        }
7082    }
7083}
7084
7085pub static REGION_RUNS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
7086pub static REGION_DEOPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
7087
7088struct RegionChain {
7089    chain: CompiledChain,
7090    frame_size: usize,
7091    /// Set when the region CALLS functions: arena headroom for callee
7092    /// windows, the limit slot to plant, and the live depth cell.
7093    call_support: Option<(usize, u16, std::sync::Arc<std::sync::atomic::AtomicI64>)>,
7094    call_sites: std::collections::HashMap<usize, u16>,
7095    guard: Vec<(u16, SlotKind)>,
7096    free: Vec<u16>,
7097    writes: Vec<(u16, SlotKind)>,
7098    arrays: Vec<ArrayPin>,
7099    region_return: Option<logicaffeine_compile::vm::RegionReturn>,
7100    hoist_guards: Vec<HoistGuard>,
7101    /// PRECISE region deopt: when `Some`, the chain was compiled with per-op
7102    /// `deopt_codes`, so a side exit stores `(resume_pc << 2) | 3` (low 32 bits)
7103    /// in the status cell — decode it to a precise `DeoptAt` and look the
7104    /// per-register re-box kinds up here by resume pc. `None` ⇒ the classic
7105    /// plain-replay region.
7106    precise_kinds: Option<std::collections::HashMap<usize, Vec<Option<SlotKind>>>>,
7107    stats: std::sync::Arc<RuntimeStats>,
7108    resume_on_return: bool,
7109}
7110
7111impl RegionFn for RegionChain {
7112    fn guard_set(&self) -> &[(u16, SlotKind)] {
7113        &self.guard
7114    }
7115    fn free_set(&self) -> &[u16] {
7116        &self.free
7117    }
7118    fn write_set(&self) -> &[(u16, SlotKind)] {
7119        &self.writes
7120    }
7121    fn array_set(&self) -> &[ArrayPin] {
7122        &self.arrays
7123    }
7124    fn region_return(&self) -> Option<logicaffeine_compile::vm::RegionReturn> {
7125        self.region_return
7126    }
7127    fn hoist_guards(&self) -> &[HoistGuard] {
7128        &self.hoist_guards
7129    }
7130    fn frame_size(&self) -> usize {
7131        self.frame_size
7132    }
7133    fn arena_slots(&self) -> usize {
7134        self.call_support.as_ref().map(|(a, _, _)| *a).unwrap_or(0)
7135    }
7136    fn precise_kinds(&self, resume_pc: usize) -> Option<&[Option<SlotKind>]> {
7137        self.precise_kinds
7138            .as_ref()
7139            .and_then(|m| m.get(&resume_pc))
7140            .map(|v| v.as_slice())
7141    }
7142    fn code_extents(&self) -> Vec<(usize, usize)> {
7143        let code = self.chain.bytes();
7144        vec![(code.as_ptr() as usize, code.len())]
7145    }
7146    fn run(&self, frame: &mut [i64], depth: usize) -> RegionOutcome {
7147        self.run_with_callees(frame, depth, &|_| None)
7148    }
7149    fn run_with_callees<'a>(
7150        &self,
7151        frame: &mut [i64],
7152        depth: usize,
7153        callees: &dyn Fn(u16) -> Option<&'a dyn NativeFn>,
7154    ) -> RegionOutcome {
7155        self.stats
7156            .region_entries
7157            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7158        if let Some((_, limit_slot, depth_cell)) = &self.call_support {
7159            let arena_end = unsafe { frame.as_ptr().add(frame.len()) } as i64;
7160            frame[*limit_slot as usize] = arena_end;
7161            depth_cell.store(depth as i64, std::sync::atomic::Ordering::Relaxed);
7162        }
7163        let outcome = match self.chain.run_with_frame(frame) {
7164            ChainOutcome::Return(pc) => {
7165                REGION_RUNS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7166                self.stats
7167                    .region_completions
7168                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7169                if self.resume_on_return {
7170                    RegionOutcome::DeoptAt {
7171                        resume_pc: pc as usize,
7172                    }
7173                } else {
7174                    RegionOutcome::Completed
7175                }
7176            }
7177            ChainOutcome::Deopt(raw) => {
7178                REGION_DEOPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7179                self.stats
7180                    .region_deopts
7181                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7182                // Precise chains tag every side exit with `(resume_pc << 2) | 3`
7183                // in the low 32 bits; a plain chain's terminal stores a value
7184                // whose low 2 bits are not 3. Resume precisely when tagged.
7185                let pending_call = self
7186                    .call_support
7187                    .as_ref()
7188                    .map(|_| frame[self.frame_size - 2])
7189                    .filter(|pc| *pc >= 0);
7190                if self.precise_kinds.is_some() && pending_call.is_some() {
7191                    let call_pc = pending_call.unwrap() as usize;
7192                    if raw & 3 == 3 && (raw >> 32) as usize > depth {
7193                        let fi = self.call_sites[&call_pc];
7194                        let callee =
7195                            callees(fi).expect("published callee has no frame materializer");
7196                        let pins: Vec<i64> = self
7197                            .arrays
7198                            .iter()
7199                            .flat_map(|pin| {
7200                                [
7201                                    frame[pin.vec_slot as usize],
7202                                    frame[pin.ptr_slot as usize],
7203                                    frame[pin.len_slot as usize],
7204                                ]
7205                            })
7206                            .collect();
7207                        let materialized = callee
7208                            .materialize_side_exit(raw, depth + 1, &frame[self.frame_size..], &pins)
7209                            .expect("precise callee exit has no frame description");
7210                        let NativeOutcome::DeoptAt { resume_pc, frames } = materialized else {
7211                            panic!("callee materializer returned a non-precise outcome");
7212                        };
7213                        RegionOutcome::DeoptCall {
7214                            call_pc,
7215                            resume_pc,
7216                            frames,
7217                        }
7218                    } else {
7219                        // The callee did not enter, or a scalar-only callee
7220                        // exited without effects. Preserve the region prefix
7221                        // and interpret this call once.
7222                        RegionOutcome::DeoptAt { resume_pc: call_pc }
7223                    }
7224                } else if self.precise_kinds.is_some() && (raw & 0b11) == 0b11 {
7225                    let resume_pc = ((raw & 0xFFFF_FFFF) >> 2) as usize;
7226                    RegionOutcome::DeoptAt { resume_pc }
7227                } else {
7228                    RegionOutcome::Deopt
7229                }
7230            }
7231        };
7232        // Region-owned allocation sites are never part of scalar write-back;
7233        // successful list results have already been adopted into VM pins.
7234        // Clear remaining scratch buffers on both completion and deopt.
7235        alloc_registry_drain();
7236        outcome
7237    }
7238}
7239
7240/// Runtime boundary counters shared by every ChainFn a tier produces.
7241/// Compilation is not execution: these count what the native code actually
7242/// DID — entries across the VM boundary, completed returns, and side exits.
7243#[derive(Default)]
7244struct RuntimeStats {
7245    entries: std::sync::atomic::AtomicU64,
7246    completions: std::sync::atomic::AtomicU64,
7247    deopts: std::sync::atomic::AtomicU64,
7248    deopt_ats: std::sync::atomic::AtomicU64,
7249    region_entries: std::sync::atomic::AtomicU64,
7250    region_completions: std::sync::atomic::AtomicU64,
7251    region_deopts: std::sync::atomic::AtomicU64,
7252}
7253
7254/// Native-only JIT optimizations which run after LOGOS bytecode has been
7255/// produced. These cannot honestly share an [`Opt`](logicaffeine_compile::optimization::Opt)
7256/// bit with the Rust emitter: they transform JIT micro-ops, so they have their
7257/// own named trace and are reported alongside the shared compiler trace.
7258#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
7259pub enum JitOptimization {
7260    /// Micro-op copy propagation and constant CSE.
7261    CopyPropagation,
7262    /// Array load/ALU/store collapsed to one read-modify-write operation.
7263    ArrayReadModifyWrite,
7264    /// Two array loads plus an integer operation collapsed to one operation.
7265    TwoBufferLoad,
7266    /// Floating multiply plus add collapsed to FMA.
7267    FusedMultiplyAdd,
7268    /// A branchy compare-and-swap collapsed to one operation.
7269    ConditionalSwap,
7270    /// An unconditional array exchange collapsed to one operation.
7271    Swap,
7272    /// Affine index arithmetic folded into an array load.
7273    AffineIndex,
7274    /// Mutable `Text += Int` lowered to allocation-free decimal append.
7275    StringAppendInt,
7276    /// A function emitted by the contiguous register allocator.
7277    RegisterAllocatedFunction,
7278    /// A loop region emitted by the contiguous register allocator.
7279    RegisterAllocatedRegion,
7280    /// A precise-deopt region emitted by the contiguous register allocator.
7281    RegisterAllocatedPreciseRegion,
7282    /// A successful stencil compile with hot values pinned in registers.
7283    PinnedRegisters,
7284    /// Self-call argument moves fused into one contiguous copy.
7285    FusedSelfCall,
7286    /// Word rotate lowered to one native `rol`/`ror` instruction.
7287    RotateInstruction,
7288}
7289
7290impl JitOptimization {
7291    /// Every native optimization, in stable report order.
7292    pub const ALL: [Self; 14] = [
7293        Self::CopyPropagation,
7294        Self::ArrayReadModifyWrite,
7295        Self::TwoBufferLoad,
7296        Self::FusedMultiplyAdd,
7297        Self::ConditionalSwap,
7298        Self::Swap,
7299        Self::AffineIndex,
7300        Self::StringAppendInt,
7301        Self::RegisterAllocatedFunction,
7302        Self::RegisterAllocatedRegion,
7303        Self::RegisterAllocatedPreciseRegion,
7304        Self::PinnedRegisters,
7305        Self::FusedSelfCall,
7306        Self::RotateInstruction,
7307    ];
7308
7309    /// Stable machine-readable report name.
7310    pub const fn keyword(self) -> &'static str {
7311        match self {
7312            Self::CopyPropagation => "copyprop",
7313            Self::ArrayReadModifyWrite => "array_rmw",
7314            Self::TwoBufferLoad => "array_load2",
7315            Self::FusedMultiplyAdd => "fma",
7316            Self::ConditionalSwap => "conditional_swap",
7317            Self::Swap => "swap",
7318            Self::AffineIndex => "affine_index",
7319            Self::StringAppendInt => "stringappendint",
7320            Self::RegisterAllocatedFunction => "regalloc_function",
7321            Self::RegisterAllocatedRegion => "regalloc_region",
7322            Self::RegisterAllocatedPreciseRegion => "regalloc_precise_region",
7323            Self::PinnedRegisters => "pinned_registers",
7324            Self::FusedSelfCall => "fused_self_call",
7325            Self::RotateInstruction => "rotate_instruction",
7326        }
7327    }
7328}
7329
7330/// Monotonic firing counts. Snapshot before and after one benchmark run and
7331/// subtract to obtain that program's exact native-JIT optimization trace.
7332#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
7333pub struct JitOptimizationTrace {
7334    counts: [u32; 14],
7335}
7336
7337impl JitOptimizationTrace {
7338    /// Number of successful compilations in which `opt` fired.
7339    pub fn count(self, opt: JitOptimization) -> u32 {
7340        self.counts[opt as usize]
7341    }
7342
7343    /// Native optimizations with nonzero firing counts.
7344    pub fn fired(self) -> Vec<JitOptimization> {
7345        JitOptimization::ALL
7346            .into_iter()
7347            .filter(|opt| self.count(*opt) != 0)
7348            .collect()
7349    }
7350
7351    /// Stable names of native optimizations with nonzero firing counts.
7352    pub fn keywords(self) -> Vec<&'static str> {
7353        self.fired()
7354            .into_iter()
7355            .map(JitOptimization::keyword)
7356            .collect()
7357    }
7358
7359    /// Saturating per-optimization delta from an earlier snapshot.
7360    pub fn since(self, earlier: Self) -> Self {
7361        let mut counts = [0; 14];
7362        for (i, count) in counts.iter_mut().enumerate() {
7363            *count = self.counts[i].saturating_sub(earlier.counts[i]);
7364        }
7365        Self { counts }
7366    }
7367}
7368
7369/// The forge-backed native tier, with compile observability.
7370#[derive(Default)]
7371pub struct ForgeTier {
7372    compiles: AtomicU32,
7373    successes: AtomicU32,
7374    region_compiles: AtomicU32,
7375    region_successes: AtomicU32,
7376    /// Region compiles whose chain came from the CONTIGUOUS register-allocating
7377    /// backend (`compile_region_regalloc`) rather than a per-piece stencil tier
7378    /// — the observable that this backend actually fired on a region.
7379    regalloc_regions: AtomicU32,
7380    /// PRECISE region compiles whose chain came from the contiguous register-
7381    /// allocating backend (`compile_region_regalloc_precise`) rather than the
7382    /// per-piece precise stencil tier (`compile_straightline_coded`). A precise
7383    /// region is the in-place-mutation + reallocating-push shape (the fannkuch /
7384    /// graph_bfs worklist). Nonzero proves the Wave 21 precise-region regalloc
7385    /// path fired — distinct from `regalloc_regions`, which counts a program's
7386    /// non-precise loops too.
7387    regalloc_precise_regions: AtomicU32,
7388    /// FUNCTION compiles whose chain came from the contiguous register-allocating
7389    /// backend (`compile_function_regalloc`) — the observable that the recursion
7390    /// cluster (self-calls) now goes through the regalloc backend instead of the
7391    /// per-piece stencil tier.
7392    regalloc_functions: AtomicU32,
7393    /// Fused pinned-argument self-calls (`CallSelfCopy`) emitted across all
7394    /// function compiles — the observable that Lever A fired.
7395    pinned_self_calls: AtomicU32,
7396    copy_propagations: AtomicU32,
7397    array_rmw_fusions: AtomicU32,
7398    two_buffer_load_fusions: AtomicU32,
7399    fma_fusions: AtomicU32,
7400    conditional_swap_fusions: AtomicU32,
7401    swap_fusions: AtomicU32,
7402    affine_index_fusions: AtomicU32,
7403    /// Regions that lowered a mutable `Text += Int` to the allocation-free
7404    /// decimal append helper instead of leaving the loop on VM bytecode.
7405    string_append_ints: AtomicU32,
7406    pinned_register_compiles: AtomicU32,
7407    /// Native rotate instruction sites emitted by successful compilations.
7408    native_rotate_instructions: AtomicU32,
7409    /// Stable, benchmark-visible explanations for every native compile that
7410    /// returned `None`.  A failed-attempt total on its own permits optimization
7411    /// drift to hide behind an undifferentiated fallback.
7412    function_declines: std::sync::Mutex<std::collections::BTreeMap<&'static str, u32>>,
7413    region_declines: std::sync::Mutex<std::collections::BTreeMap<&'static str, u32>>,
7414    runtime: std::sync::Arc<RuntimeStats>,
7415}
7416
7417impl ForgeTier {
7418    /// A fresh tier with zeroed counters.
7419    pub fn new() -> Self {
7420        ForgeTier::default()
7421    }
7422
7423    fn note_function_decline(&self, reason: &'static str) {
7424        let mut counts = self
7425            .function_declines
7426            .lock()
7427            .unwrap_or_else(|e| e.into_inner());
7428        *counts.entry(reason).or_insert(0) += 1;
7429    }
7430
7431    fn note_region_decline(&self, reason: &'static str) {
7432        let mut counts = self
7433            .region_declines
7434            .lock()
7435            .unwrap_or_else(|e| e.into_inner());
7436        *counts.entry(reason).or_insert(0) += 1;
7437    }
7438
7439    /// (attempts, successes) for FUNCTION compiles.
7440    pub fn function_counts(&self) -> (u32, u32) {
7441        (
7442            self.compiles.load(Ordering::SeqCst),
7443            self.successes.load(Ordering::SeqCst),
7444        )
7445    }
7446
7447    /// The number of fused pinned-argument self-calls (`CallSelfCopy`)
7448    /// emitted across every function compile — Lever A's observable. A
7449    /// nonzero value proves a scalar self-call took the fused ABI rather
7450    /// than per-argument frame `Move` staging.
7451    pub fn pinned_self_call_count(&self) -> u32 {
7452        self.pinned_self_calls.load(Ordering::SeqCst)
7453    }
7454
7455    /// Snapshot every native-JIT optimization that actually changed/lowered a
7456    /// compiled region. Counters are monotonic so callers can take a cheap
7457    /// before/after delta around one benchmark invocation.
7458    pub fn optimization_trace(&self) -> JitOptimizationTrace {
7459        let mut counts = [0; 14];
7460        counts[JitOptimization::CopyPropagation as usize] =
7461            self.copy_propagations.load(Ordering::Relaxed);
7462        counts[JitOptimization::ArrayReadModifyWrite as usize] =
7463            self.array_rmw_fusions.load(Ordering::Relaxed);
7464        counts[JitOptimization::TwoBufferLoad as usize] =
7465            self.two_buffer_load_fusions.load(Ordering::Relaxed);
7466        counts[JitOptimization::FusedMultiplyAdd as usize] =
7467            self.fma_fusions.load(Ordering::Relaxed);
7468        counts[JitOptimization::ConditionalSwap as usize] =
7469            self.conditional_swap_fusions.load(Ordering::Relaxed);
7470        counts[JitOptimization::Swap as usize] = self.swap_fusions.load(Ordering::Relaxed);
7471        counts[JitOptimization::AffineIndex as usize] =
7472            self.affine_index_fusions.load(Ordering::Relaxed);
7473        counts[JitOptimization::StringAppendInt as usize] =
7474            self.string_append_ints.load(Ordering::Relaxed);
7475        counts[JitOptimization::RegisterAllocatedFunction as usize] =
7476            self.regalloc_functions.load(Ordering::Relaxed);
7477        counts[JitOptimization::RegisterAllocatedRegion as usize] =
7478            self.regalloc_regions.load(Ordering::Relaxed);
7479        counts[JitOptimization::RegisterAllocatedPreciseRegion as usize] =
7480            self.regalloc_precise_regions.load(Ordering::Relaxed);
7481        counts[JitOptimization::PinnedRegisters as usize] =
7482            self.pinned_register_compiles.load(Ordering::Relaxed);
7483        counts[JitOptimization::FusedSelfCall as usize] =
7484            self.pinned_self_calls.load(Ordering::Relaxed);
7485        counts[JitOptimization::RotateInstruction as usize] =
7486            self.native_rotate_instructions.load(Ordering::Relaxed);
7487        JitOptimizationTrace { counts }
7488    }
7489
7490    /// (attempts, successes) for Main-loop REGION compiles.
7491    pub fn region_counts(&self) -> (u32, u32) {
7492        (
7493            self.region_compiles.load(Ordering::SeqCst),
7494            self.region_successes.load(Ordering::SeqCst),
7495        )
7496    }
7497
7498    /// How many region compiles used the CONTIGUOUS register-allocating backend
7499    /// (`compile_region_regalloc`) rather than a per-piece stencil tier.
7500    /// Nonzero proves the regalloc backend fired on a real program's hot loop.
7501    pub fn regalloc_region_count(&self) -> u32 {
7502        self.regalloc_regions.load(Ordering::SeqCst)
7503    }
7504
7505    /// How many PRECISE region compiles used the contiguous register-allocating
7506    /// backend (`compile_region_regalloc_precise`) rather than the per-piece
7507    /// precise stencil tier. Nonzero proves the in-place-mutation + reallocating-
7508    /// push shape (fannkuch / graph_bfs worklist) tiered through the regalloc
7509    /// backend — Wave 21's lever.
7510    pub fn regalloc_precise_region_count(&self) -> u32 {
7511        self.regalloc_precise_regions.load(Ordering::SeqCst)
7512    }
7513
7514    /// How many FUNCTION compiles used the contiguous register-allocating backend
7515    /// (`compile_function_regalloc`) rather than the per-piece stencil tier.
7516    /// Nonzero proves a recursive (self-calling) function tiered through the
7517    /// regalloc backend — the recursion cluster's lever.
7518    pub fn regalloc_function_count(&self) -> u32 {
7519        self.regalloc_functions.load(Ordering::SeqCst)
7520    }
7521
7522    /// Executed region entries, completions, and side exits for this tier.
7523    pub fn region_runtime_stats(&self) -> (u64, u64, u64) {
7524        (
7525            self.runtime.region_entries.load(Ordering::SeqCst),
7526            self.runtime.region_completions.load(Ordering::SeqCst),
7527            self.runtime.region_deopts.load(Ordering::SeqCst),
7528        )
7529    }
7530
7531    /// Function entries, completions, plain deopts, and precise deopts.
7532    pub fn runtime_stats(&self) -> (u64, u64, u64, u64) {
7533        (
7534            self.runtime.entries.load(Ordering::SeqCst),
7535            self.runtime.completions.load(Ordering::SeqCst),
7536            self.runtime.deopts.load(Ordering::SeqCst),
7537            self.runtime.deopt_ats.load(Ordering::SeqCst),
7538        )
7539    }
7540}
7541
7542/// Loop-nesting depth of each micro op, from its enclosing back-edges (a
7543/// jump/branch whose target is at or before it opens a loop over
7544/// `[target, here]`). Depth is how many such loops contain an op — the
7545/// frequency proxy for region pin selection.
7546fn loop_depths(ops: &[MicroOp]) -> Vec<u32> {
7547    let n = ops.len();
7548    let mut depth = vec![0u32; n];
7549    for (i, op) in ops.iter().enumerate() {
7550        let target = match *op {
7551            MicroOp::Jump { target }
7552            | MicroOp::JumpIfFalse { target, .. }
7553            | MicroOp::JumpIfTrue { target, .. }
7554            | MicroOp::Branch { target, .. }
7555            | MicroOp::BranchF { target, .. } => Some(target),
7556            _ => None,
7557        };
7558        if let Some(t) = target {
7559            if t <= i && t < n {
7560                for d in depth.iter_mut().take(i + 1).skip(t) {
7561                    *d += 1;
7562                }
7563            }
7564        }
7565    }
7566    depth
7567}
7568
7569/// Linear-scan pin selection. Each slot's profit sums its per-op deltas —
7570/// variant-family uses save a memory access (positive), mem-form uses force
7571/// a frame spill (negative).
7572///
7573/// `region` switches the FREQUENCY MODEL. A FUNCTION body is itself the hot
7574/// loop (recursion is a Call, not a back-edge), so every op counts equally
7575/// (the historical flat model — preserved exactly). A REGION's depth-0 ops
7576/// run once per entry while its INNER loops dominate, so each op is weighted
7577/// by `BASE^loop_depth` — a slot wins only when its register-resident
7578/// variant uses outweigh its spill costs AT THE FREQUENCY THEY EXECUTE.
7579/// (Without this, a counter feeding an inner-loop array INDEX — mem-form,
7580/// spills every iteration — looks neutral statically but is a net loss; see
7581/// histogram vs sieve.) Conversion scratches and beyond-register slots
7582/// never pin; the four most profitable net-positive slots win.
7583///
7584/// The slots a micro-op READS, by value (for read-counting). Call/CallSelf are
7585/// handled by the caller (copy-prop bails on any region containing one), so
7586/// their frame-window arg reads need no accounting here.
7587fn micro_read_slots(op: &MicroOp) -> Vec<u16> {
7588    use MicroOp::*;
7589    match *op {
7590        LoadConst { .. } | Jump { .. } | NewList { .. } => vec![],
7591        Move { src, .. }
7592        | DivPow2 { lhs: src, .. }
7593        | MagicDivU { lhs: src, .. }
7594        | NotInt { src, .. }
7595        | NotBool { src, .. }
7596        | Popcnt { src, .. }
7597        | Lzcnt { src, .. }
7598        | Tzcnt { src, .. }
7599        | ChrGuard { src, .. }
7600        | Utf8Len { src, .. }
7601        | FloorToInt { src, .. }
7602        | CeilToInt { src, .. }
7603        | RoundToInt { src, .. }
7604        | IntToFloat { src, .. }
7605        | SqrtF { src, .. }
7606        | Return { src }
7607        | ListTriple {
7608            handle_slot: src, ..
7609        } => vec![src],
7610        JumpIfFalse { cond, .. } | JumpIfTrue { cond, .. } => vec![cond],
7611        Add { lhs, rhs, .. }
7612        | Sub { lhs, rhs, .. }
7613        | Mul { lhs, rhs, .. }
7614        | Div { lhs, rhs, .. }
7615        | Mod { lhs, rhs, .. }
7616        | Lt { lhs, rhs, .. }
7617        | Gt { lhs, rhs, .. }
7618        | Eq { lhs, rhs, .. }
7619        | LtEq { lhs, rhs, .. }
7620        | GtEq { lhs, rhs, .. }
7621        | Neq { lhs, rhs, .. }
7622        | BitAnd { lhs, rhs, .. }
7623        | BitOr { lhs, rhs, .. }
7624        | BitXor { lhs, rhs, .. }
7625        | Shl { lhs, rhs, .. }
7626        | Shr { lhs, rhs, .. }
7627        | Ushr { lhs, rhs, .. }
7628        | Rotate { lhs, rhs, .. }
7629        | Branch { lhs, rhs, .. }
7630        | AddF { lhs, rhs, .. }
7631        | SubF { lhs, rhs, .. }
7632        | MulF { lhs, rhs, .. }
7633        | DivF { lhs, rhs, .. }
7634        | LtF { lhs, rhs, .. }
7635        | GtF { lhs, rhs, .. }
7636        | LtEqF { lhs, rhs, .. }
7637        | GtEqF { lhs, rhs, .. }
7638        | EqF { lhs, rhs, .. }
7639        | NeqF { lhs, rhs, .. }
7640        | BranchF { lhs, rhs, .. } => vec![lhs, rhs],
7641        Host { src, count, .. } => (src..src + count).collect(),
7642        MapGet { key, map_slot, .. } | MapHas { key, map_slot, .. } => vec![key, map_slot],
7643        MapSet {
7644            src, key, map_slot, ..
7645        } => vec![src, key, map_slot],
7646        ArrLoad {
7647            idx,
7648            ptr_slot,
7649            len_slot,
7650            ..
7651        } => vec![idx, ptr_slot, len_slot],
7652        ArrLoadAffine {
7653            a,
7654            op,
7655            b,
7656            ptr_slot,
7657            len_slot,
7658            ..
7659        } => {
7660            if op == logicaffeine_forge::jit::AffOp::None {
7661                vec![a, ptr_slot, len_slot]
7662            } else {
7663                vec![a, b, ptr_slot, len_slot]
7664            }
7665        }
7666        ArrLoad2F {
7667            i,
7668            j,
7669            ptr_slot,
7670            len_slot,
7671            ..
7672        } => vec![i, j, ptr_slot, len_slot],
7673        ArrLoad2 {
7674            i,
7675            j,
7676            ptr_a,
7677            len_a,
7678            ptr_b,
7679            len_b,
7680            ..
7681        } => vec![i, j, ptr_a, len_a, ptr_b, len_b],
7682        ArrStore {
7683            src,
7684            idx,
7685            ptr_slot,
7686            len_slot,
7687            ..
7688        } => vec![src, idx, ptr_slot, len_slot],
7689        ArrRMW {
7690            idx,
7691            operand,
7692            ptr_slot,
7693            len_slot,
7694            ..
7695        } => vec![idx, operand, ptr_slot, len_slot],
7696        ArrCondSwap {
7697            idx1,
7698            idx2,
7699            ptr_slot,
7700            len_slot,
7701            ..
7702        } => vec![idx1, idx2, ptr_slot, len_slot],
7703        ArrSwap {
7704            idx1,
7705            idx2,
7706            ptr_slot,
7707            len_slot,
7708            ..
7709        } => vec![idx1, idx2, ptr_slot, len_slot],
7710        FmaF { a, b, c, .. } => vec![a, b, c],
7711        ArrPush {
7712            src,
7713            vec_slot,
7714            ptr_slot,
7715            len_slot,
7716            ..
7717        } => vec![src, vec_slot, ptr_slot, len_slot],
7718        ListClear {
7719            vec_slot,
7720            ptr_slot,
7721            len_slot,
7722            ..
7723        } => vec![vec_slot, ptr_slot, len_slot],
7724        StrAppend {
7725            text_handle_slot,
7726            src,
7727            ..
7728        } => std::iter::once(text_handle_slot)
7729            .chain(src.slot())
7730            .collect(),
7731        MemMem {
7732            h_ptr_slot,
7733            h_len_slot,
7734            n_ptr_slot,
7735            n_len_slot,
7736            needle_len_slot,
7737            i_slot,
7738            count_slot,
7739            ..
7740        } => vec![
7741            h_ptr_slot,
7742            h_len_slot,
7743            n_ptr_slot,
7744            n_len_slot,
7745            needle_len_slot,
7746            i_slot,
7747            count_slot,
7748        ],
7749        Call { .. } | CallSelf { .. } | CallSelfCopy { .. } => vec![],
7750    }
7751}
7752
7753/// Mutable references to a micro-op's READ operands (for in-place copy
7754/// substitution). Mirrors [`micro_read_slots`].
7755fn micro_reads_mut(op: &mut MicroOp) -> Vec<&mut u16> {
7756    use MicroOp::*;
7757    match op {
7758        // A host call reads a contiguous window: its slots are not renamed one by one.
7759        LoadConst { .. }
7760        | Jump { .. }
7761        | NewList { .. }
7762        | Call { .. }
7763        | CallSelf { .. }
7764        | CallSelfCopy { .. }
7765        | Host { .. } => vec![],
7766        Move { src, .. }
7767        | DivPow2 { lhs: src, .. }
7768        | MagicDivU { lhs: src, .. }
7769        | NotInt { src, .. }
7770        | NotBool { src, .. }
7771        | Popcnt { src, .. }
7772        | Lzcnt { src, .. }
7773        | Tzcnt { src, .. }
7774        | ChrGuard { src, .. }
7775        | Utf8Len { src, .. }
7776        | FloorToInt { src, .. }
7777        | CeilToInt { src, .. }
7778        | RoundToInt { src, .. }
7779        | IntToFloat { src, .. }
7780        | SqrtF { src, .. }
7781        | Return { src }
7782        | ListTriple {
7783            handle_slot: src, ..
7784        } => vec![src],
7785        JumpIfFalse { cond, .. } | JumpIfTrue { cond, .. } => vec![cond],
7786        Add { lhs, rhs, .. }
7787        | Sub { lhs, rhs, .. }
7788        | Mul { lhs, rhs, .. }
7789        | Div { lhs, rhs, .. }
7790        | Mod { lhs, rhs, .. }
7791        | Lt { lhs, rhs, .. }
7792        | Gt { lhs, rhs, .. }
7793        | Eq { lhs, rhs, .. }
7794        | LtEq { lhs, rhs, .. }
7795        | GtEq { lhs, rhs, .. }
7796        | Neq { lhs, rhs, .. }
7797        | BitAnd { lhs, rhs, .. }
7798        | BitOr { lhs, rhs, .. }
7799        | BitXor { lhs, rhs, .. }
7800        | Shl { lhs, rhs, .. }
7801        | Shr { lhs, rhs, .. }
7802        | Ushr { lhs, rhs, .. }
7803        | Rotate { lhs, rhs, .. }
7804        | Branch { lhs, rhs, .. }
7805        | AddF { lhs, rhs, .. }
7806        | SubF { lhs, rhs, .. }
7807        | MulF { lhs, rhs, .. }
7808        | DivF { lhs, rhs, .. }
7809        | LtF { lhs, rhs, .. }
7810        | GtF { lhs, rhs, .. }
7811        | LtEqF { lhs, rhs, .. }
7812        | GtEqF { lhs, rhs, .. }
7813        | EqF { lhs, rhs, .. }
7814        | NeqF { lhs, rhs, .. }
7815        | BranchF { lhs, rhs, .. } => vec![lhs, rhs],
7816        MapGet { key, map_slot, .. } | MapHas { key, map_slot, .. } => vec![key, map_slot],
7817        MapSet {
7818            src, key, map_slot, ..
7819        } => vec![src, key, map_slot],
7820        ArrLoad {
7821            idx,
7822            ptr_slot,
7823            len_slot,
7824            ..
7825        } => vec![idx, ptr_slot, len_slot],
7826        ArrLoadAffine {
7827            a,
7828            b,
7829            ptr_slot,
7830            len_slot,
7831            ..
7832        } => vec![a, b, ptr_slot, len_slot],
7833        ArrLoad2F {
7834            i,
7835            j,
7836            ptr_slot,
7837            len_slot,
7838            ..
7839        } => vec![i, j, ptr_slot, len_slot],
7840        ArrLoad2 {
7841            i,
7842            j,
7843            ptr_a,
7844            len_a,
7845            ptr_b,
7846            len_b,
7847            ..
7848        } => vec![i, j, ptr_a, len_a, ptr_b, len_b],
7849        ArrStore {
7850            src,
7851            idx,
7852            ptr_slot,
7853            len_slot,
7854            ..
7855        } => vec![src, idx, ptr_slot, len_slot],
7856        ArrRMW {
7857            idx,
7858            operand,
7859            ptr_slot,
7860            len_slot,
7861            ..
7862        } => vec![idx, operand, ptr_slot, len_slot],
7863        ArrCondSwap {
7864            idx1,
7865            idx2,
7866            ptr_slot,
7867            len_slot,
7868            ..
7869        } => vec![idx1, idx2, ptr_slot, len_slot],
7870        ArrSwap {
7871            idx1,
7872            idx2,
7873            ptr_slot,
7874            len_slot,
7875            ..
7876        } => vec![idx1, idx2, ptr_slot, len_slot],
7877        FmaF { a, b, c, .. } => vec![a, b, c],
7878        ArrPush {
7879            src,
7880            vec_slot,
7881            ptr_slot,
7882            len_slot,
7883            ..
7884        } => vec![src, vec_slot, ptr_slot, len_slot],
7885        ListClear {
7886            vec_slot,
7887            ptr_slot,
7888            len_slot,
7889            ..
7890        } => vec![vec_slot, ptr_slot, len_slot],
7891        StrAppend {
7892            text_handle_slot,
7893            src,
7894            ..
7895        } => std::iter::once(text_handle_slot)
7896            .chain(src.slot_mut())
7897            .collect(),
7898        MemMem {
7899            h_ptr_slot,
7900            h_len_slot,
7901            n_ptr_slot,
7902            n_len_slot,
7903            needle_len_slot,
7904            i_slot,
7905            count_slot,
7906            ..
7907        } => vec![
7908            h_ptr_slot,
7909            h_len_slot,
7910            n_ptr_slot,
7911            n_len_slot,
7912            needle_len_slot,
7913            i_slot,
7914            count_slot,
7915        ],
7916    }
7917}
7918
7919/// The slots a micro-op DEFINES (writes).
7920fn micro_defs(op: &MicroOp) -> Vec<u16> {
7921    use MicroOp::*;
7922    match *op {
7923        LoadConst { dst, .. } | Move { dst, .. } | Add { dst, .. } | Sub { dst, .. } | Mul { dst, .. }
7924        | Div { dst, .. } | DivPow2 { dst, .. } | MagicDivU { dst, .. } | Mod { dst, .. } | Lt { dst, .. } | Gt { dst, .. }
7925        | Eq { dst, .. } | LtEq { dst, .. } | GtEq { dst, .. } | Neq { dst, .. } | BitAnd { dst, .. }
7926        | BitOr { dst, .. } | BitXor { dst, .. } | Shl { dst, .. } | Shr { dst, .. } | Ushr { dst, .. } | Rotate { dst, .. } | NotInt { dst, .. }
7927        | Popcnt { dst, .. } | Lzcnt { dst, .. } | Tzcnt { dst, .. } | ChrGuard { dst, .. } | Utf8Len { dst, .. }
7928        | FloorToInt { dst, .. } | CeilToInt { dst, .. } | RoundToInt { dst, .. }
7929        | NotBool { dst, .. } | AddF { dst, .. } | SubF { dst, .. } | MulF { dst, .. } | DivF { dst, .. }
7930        | LtF { dst, .. } | GtF { dst, .. } | LtEqF { dst, .. } | GtEqF { dst, .. } | EqF { dst, .. }
7931        | NeqF { dst, .. } | IntToFloat { dst, .. } | SqrtF { dst, .. } | ArrLoad { dst, .. }
7932        | ArrLoadAffine { dst, .. }
7933        | ArrLoad2F { dst, .. } | ArrLoad2 { dst, .. } | FmaF { dst, .. } | MapGet { dst, .. } | MapHas { dst, .. }
7934        | Call { dst, .. } | CallSelf { dst, .. } | CallSelfCopy { dst, .. } | Host { dst, .. } => vec![dst],
7935        ArrPush { ptr_slot, len_slot, .. } => vec![ptr_slot, len_slot],
7936        ListClear { ptr_slot, len_slot, .. } => vec![ptr_slot, len_slot],
7937        NewList { vec_slot, ptr_slot, len_slot, .. } => vec![vec_slot, ptr_slot, len_slot],
7938        ListTriple { vec_slot, ptr_slot, len_slot, .. } => vec![vec_slot, ptr_slot, len_slot],
7939        MemMem { i_slot, count_slot, .. } => vec![i_slot, count_slot],
7940        Branch { .. } | BranchF { .. } | Jump { .. } | JumpIfFalse { .. } | JumpIfTrue { .. }
7941        | MapSet { .. } | ArrStore { .. } | ArrRMW { .. } | ArrCondSwap { .. } | ArrSwap { .. } | Return { .. }
7942        // The mutable-Text append writes the off-frame VM register cell (through
7943        // the planted `*mut Value`), not a frame slot — it defines NO frame slot.
7944        | StrAppend { .. } => vec![],
7945    }
7946}
7947
7948/// A mutable reference to a micro-op's branch/jump TARGET (a micro index), if any.
7949fn micro_target_mut(op: &mut MicroOp) -> Option<&mut usize> {
7950    use MicroOp::*;
7951    match op {
7952        Jump { target }
7953        | Branch { target, .. }
7954        | BranchF { target, .. }
7955        | JumpIfFalse { target, .. }
7956        | JumpIfTrue { target, .. } => Some(target),
7957        _ => None,
7958    }
7959}
7960
7961/// COPY PROPAGATION + dead-Move elimination over a region's micro stream — kills
7962/// the redundant copy chains the bytecode lowering leaves in hot loops (e.g.
7963/// mandelbrot's `t40←t36; t46←t40; zr←t46`, three Moves to land one value),
7964/// each of which is a wasted stencil dispatch every iteration. SOUNDNESS: it
7965/// only ever (1) rewrites a READ to a value provably equal to it within the
7966/// same basic block (copies are cleared at every jump target and across every
7967/// branch/jump), and (2) removes a `Move` whose destination is an UN-NAMED
7968/// scratch temp (never written back to a VM register — `named[d]` is false) and
7969/// has zero remaining reads. Named slots (loop-carried / observable) are never
7970/// touched. The caller restricts this to NON-PRECISE, CALL-FREE regions, so the
7971/// only index-bearing references that survive removal are jump targets, which
7972/// are remapped here; `deopt` is replay-from-head (no per-micro resume).
7973fn copy_propagate(
7974    micro: &mut Vec<MicroOp>,
7975    named: &[bool],
7976    register_count: u16,
7977    pinned: &std::collections::HashSet<u16>,
7978) {
7979    if micro.iter().any(|op| {
7980        matches!(
7981            op,
7982            MicroOp::Call { .. } | MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. }
7983        )
7984    }) {
7985        return;
7986    }
7987    // A slot is REMOVABLE only if it is an un-named, un-PINNED scratch temp: its
7988    // value is never written back to a VM register (not named) and it is not
7989    // held live in a register by the pin allocator. This lets the pass run AFTER
7990    // pin selection without disturbing the chosen pins (named/pinned defining ops
7991    // and their reads are left intact).
7992    let removable = |slot: u16| -> bool {
7993        slot < register_count
7994            && !named.get(slot as usize).copied().unwrap_or(true)
7995            && !pinned.contains(&slot)
7996    };
7997    let n = micro.len();
7998    let mut leader = vec![false; n];
7999    for op in micro.iter() {
8000        if let Some(t) = micro_target_const(op) {
8001            if t < n {
8002                leader[t] = true;
8003            }
8004        }
8005    }
8006    // Phase 1: forward block-local value propagation. `root[d] = s` means slot d
8007    // currently holds an unmodified copy of slot s; reads of d are rewritten to
8008    // s. `const_holder[v] = slot` tracks the live slot holding integer-bits
8009    // constant `v`, so a re-`LoadConst` of the same value aliases the existing
8010    // holder (CONSTANT CSE — hot loops re-load the same small constants every
8011    // iteration). Both maps clear at block boundaries and invalidate when a
8012    // tracked slot is redefined.
8013    let mut root: std::collections::HashMap<u16, u16> = std::collections::HashMap::new();
8014    let mut const_holder: std::collections::HashMap<i64, u16> = std::collections::HashMap::new();
8015    // `value_holder[(tag, a, b)] = slot` — the live slot already holding the
8016    // result of that pure op over those operands. A redundant recomputation
8017    // (e.g. `v + 1` evaluated for both the load index and the store index of an
8018    // array RMW) aliases the existing holder, which (a) cuts a stencil dispatch
8019    // and (b) makes the two indices the SAME slot, letting `fuse_array_rmw`
8020    // collapse the load/store. Local value numbering: cleared at block
8021    // boundaries, invalidated the instant any operand or the holder is redefined.
8022    let mut value_holder: std::collections::HashMap<(u8, u16, u16), u16> =
8023        std::collections::HashMap::new();
8024    for i in 0..n {
8025        if leader[i] {
8026            root.clear();
8027            const_holder.clear();
8028            value_holder.clear();
8029        }
8030        for r in micro_reads_mut(&mut micro[i]) {
8031            if let Some(&s) = root.get(r) {
8032                *r = s;
8033            }
8034        }
8035        // Value key + prior holder, captured from the operands AS SUBSTITUTED
8036        // above and BEFORE this op's own def invalidates the table.
8037        let value_key = micro_pure_value_key(&micro[i]);
8038        let cse_hit = value_key.and_then(|(k, _)| value_holder.get(&k).copied());
8039        let defs = micro_defs(&micro[i]);
8040        for &d in &defs {
8041            root.retain(|k, v| *k != d && *v != d);
8042            const_holder.retain(|_, s| *s != d);
8043            value_holder.retain(|k, s| k.1 != d && k.2 != d && *s != d);
8044        }
8045        match micro[i] {
8046            MicroOp::Move { dst, src } if dst != src => {
8047                let sroot = root.get(&src).copied().unwrap_or(src);
8048                if sroot != dst {
8049                    root.insert(dst, sroot);
8050                }
8051            }
8052            MicroOp::LoadConst { dst, value } => match const_holder.get(&value) {
8053                Some(&d2) if d2 != dst => {
8054                    root.insert(dst, d2);
8055                }
8056                Some(_) => {}
8057                None => {
8058                    const_holder.insert(value, dst);
8059                }
8060            },
8061            _ => {}
8062        }
8063        if let Some((k, dst)) = value_key {
8064            match cse_hit {
8065                Some(h) if h != dst => {
8066                    root.insert(dst, h);
8067                }
8068                _ => {
8069                    value_holder.insert(k, dst);
8070                }
8071            }
8072        }
8073        // NB: copies/CSE are NOT cleared after a branch. A branch defines no
8074        // slot, so its fall-through (a single-predecessor block) validly inherits
8075        // them; the only multi-predecessor blocks are JUMP TARGETS, which the
8076        // leader-clear at the top of the loop already resets. (Clearing here too
8077        // was overly conservative — it dropped copies that hold across the
8078        // compare-branch into a loop's conditional body, e.g. a sort's swap.)
8079    }
8080    // Phase 2: remove dead scratch Moves / LoadConsts / pure binops (0 remaining
8081    // reads after propagation), remapping jump targets after each removal.
8082    loop {
8083        let mut reads: std::collections::HashMap<u16, usize> = std::collections::HashMap::new();
8084        for op in micro.iter() {
8085            for s in micro_read_slots(op) {
8086                *reads.entry(s).or_insert(0) += 1;
8087            }
8088        }
8089        let dead = |dst: u16| removable(dst) && reads.get(&dst).copied().unwrap_or(0) == 0;
8090        let victim = micro.iter().position(|op| match *op {
8091            MicroOp::Move { dst, src } => dst != src && dead(dst),
8092            MicroOp::LoadConst { dst, .. } => dead(dst),
8093            _ => micro_pure_value_key(op).is_some_and(|(_, dst)| dead(dst)),
8094        });
8095        let Some(idx) = victim else { break };
8096        micro.remove(idx);
8097        for op in micro.iter_mut() {
8098            if let Some(t) = micro_target_mut(op) {
8099                if *t > idx {
8100                    *t -= 1;
8101                }
8102            }
8103        }
8104    }
8105    // Phase 3: DEAD-STORE elimination — a pure def whose dst is REDEFINED before
8106    // it is ever read is dead even if the dst is read LATER (register reuse, e.g.
8107    // a sort's recomputed `j+1` index whose slot is reused for the loop-increment
8108    // constant). Global read-counting (phase 2) keeps these; a forward straight-
8109    // line scan removes them. Conservative: stop the scan at any control-flow op
8110    // or jump target (the value could be live on another path → keep). Only
8111    // un-named/un-pinned scratch (the `removable` slots) is eligible.
8112    loop {
8113        let mut victim = None;
8114        'scan: for i in 0..micro.len() {
8115            let d = match micro[i] {
8116                MicroOp::Move { dst, src } if dst != src => dst,
8117                MicroOp::LoadConst { dst, .. } => dst,
8118                ref other => match micro_pure_value_key(other) {
8119                    Some((_, dst)) => dst,
8120                    None => continue,
8121                },
8122            };
8123            if !removable(d) {
8124                continue;
8125            }
8126            // Walk forward: `d` is dead at `i` iff it is REDEFINED before any
8127            // read. We stop at a control-flow SOURCE op (a branch/jump could
8128            // carry `d`'s value to a taken path that reads it) — but NOT at a
8129            // mere jump TARGET: a leader that redefines `d` as its first action
8130            // kills every incoming `d`, so checking it is sound.
8131            for op in micro.iter().skip(i + 1) {
8132                if micro_read_slots(op).contains(&d) {
8133                    break; // read before redef — live; keep.
8134                }
8135                if micro_defs(op).contains(&d) {
8136                    victim = Some(i); // redefined before any read — op `i` is dead.
8137                    break 'scan;
8138                }
8139                if micro_target_const(op).is_some() {
8140                    break; // control transfers away — be conservative; keep.
8141                }
8142            }
8143        }
8144        let Some(idx) = victim else { break };
8145        micro.remove(idx);
8146        for op in micro.iter_mut() {
8147            if let Some(t) = micro_target_mut(op) {
8148                if *t > idx {
8149                    *t -= 1;
8150                }
8151            }
8152        }
8153    }
8154}
8155
8156/// ARRAY READ-MODIFY-WRITE FUSION — collapses the `ArrLoad(t = arr[i]) ;
8157/// <int ALU>(t2 = t OP operand) ; ArrStore(arr[i] = t2)` idiom (histogram's
8158/// `counts[x] += 1`, counting sort, bitset marks) into ONE [`MicroOp::ArrRMW`]:
8159/// one stencil dispatch + one bounds check instead of three, and the element
8160/// never round-trips the frame. The JIT is per-op DISPATCH-bound, so collapsing
8161/// three hot ops into one is a direct win on the indexed-RMW loops that lose
8162/// worst to V8.
8163///
8164/// SOUNDNESS: the load and store hit the SAME pinned 8-byte array and the SAME
8165/// index slot (unchanged between them — the ALU only writes the scratch `t2`),
8166/// so the read cell and the written cell coincide. A single pre-write bounds
8167/// check (`checked = c1 || c2`) is bit-identical to the original pair because
8168/// both tested that same index. The fused op side-exits BEFORE any effect and,
8169/// occupying the ArrLoad's micro slot, replays all three ops from that bytecode
8170/// pc (region deopt is replay-from-head). The loaded value `t` and the result
8171/// `t2` must be single-use, un-named, un-pinned scratch (read only by the ALU /
8172/// the store) — exactly the staleness contract `copy_propagate` already relies
8173/// on, so a dead frame cell is never observably written back. None of the three
8174/// ops may be a jump target (no entry lands mid-idiom). Caller restricts this to
8175/// NON-PRECISE regions (removing micro ops renumbers jump targets — remapped
8176/// here — but would break per-op precise resume codes).
8177fn fuse_array_rmw(
8178    micro: &mut Vec<MicroOp>,
8179    named: &[bool],
8180    register_count: u16,
8181    pinned: &std::collections::HashSet<u16>,
8182) {
8183    if micro.iter().any(|op| {
8184        matches!(
8185            op,
8186            MicroOp::Call { .. } | MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. }
8187        )
8188    }) {
8189        return;
8190    }
8191    let removable = |slot: u16, reads: &std::collections::HashMap<u16, usize>| -> bool {
8192        slot < register_count
8193            && !named.get(slot as usize).copied().unwrap_or(true)
8194            && !pinned.contains(&slot)
8195            && reads.get(&slot).copied().unwrap_or(0) == 1
8196    };
8197    loop {
8198        let n = micro.len();
8199        // Block leaders: an op any branch/jump lands on. Recomputed each round
8200        // (a fusion renumbers the stream).
8201        let mut is_target = vec![false; n];
8202        for op in micro.iter() {
8203            if let Some(t) = micro_target_const(op) {
8204                if t < n {
8205                    is_target[t] = true;
8206                }
8207            }
8208        }
8209        let mut reads: std::collections::HashMap<u16, usize> = std::collections::HashMap::new();
8210        for op in micro.iter() {
8211            for s in micro_read_slots(op) {
8212                *reads.entry(s).or_insert(0) += 1;
8213            }
8214        }
8215        let mut hit: Option<(usize, MicroOp)> = None;
8216        for k in 0..n.saturating_sub(2) {
8217            // The ALU and the store must not be block leaders.
8218            if is_target[k + 1] || is_target[k + 2] {
8219                continue;
8220            }
8221            let MicroOp::ArrLoad {
8222                dst: t,
8223                idx: i,
8224                ptr_slot: p,
8225                len_slot: l,
8226                byte: false,
8227                narrow32: false,
8228                checked: c1,
8229            } = micro[k]
8230            else {
8231                continue;
8232            };
8233            // The ALU op: the loaded value `t` is one operand; the OTHER is the
8234            // RMW operand. Sub is non-commutative — fuse only when `t` is on the
8235            // left (`buf[i] - operand`).
8236            let (t2, op, operand) = match micro[k + 1] {
8237                MicroOp::Add { dst, lhs, rhs } if lhs == t => (dst, RmwOp::Add, rhs),
8238                MicroOp::Add { dst, lhs, rhs } if rhs == t => (dst, RmwOp::Add, lhs),
8239                MicroOp::Sub { dst, lhs, rhs } if lhs == t => (dst, RmwOp::Sub, rhs),
8240                MicroOp::Mul { dst, lhs, rhs } if lhs == t => (dst, RmwOp::Mul, rhs),
8241                MicroOp::Mul { dst, lhs, rhs } if rhs == t => (dst, RmwOp::Mul, lhs),
8242                MicroOp::BitAnd { dst, lhs, rhs } if lhs == t => (dst, RmwOp::And, rhs),
8243                MicroOp::BitAnd { dst, lhs, rhs } if rhs == t => (dst, RmwOp::And, lhs),
8244                MicroOp::BitOr { dst, lhs, rhs } if lhs == t => (dst, RmwOp::Or, rhs),
8245                MicroOp::BitOr { dst, lhs, rhs } if rhs == t => (dst, RmwOp::Or, lhs),
8246                MicroOp::BitXor { dst, lhs, rhs } if lhs == t => (dst, RmwOp::Xor, rhs),
8247                MicroOp::BitXor { dst, lhs, rhs } if rhs == t => (dst, RmwOp::Xor, lhs),
8248                // Float RMW (nbody's `v[i] = v[i] + dx*mag`): the array holds
8249                // f64 bits; the fused op reinterprets. Same commutativity rules.
8250                MicroOp::AddF { dst, lhs, rhs } if lhs == t => (dst, RmwOp::AddF, rhs),
8251                MicroOp::AddF { dst, lhs, rhs } if rhs == t => (dst, RmwOp::AddF, lhs),
8252                MicroOp::SubF { dst, lhs, rhs } if lhs == t => (dst, RmwOp::SubF, rhs),
8253                MicroOp::MulF { dst, lhs, rhs } if lhs == t => (dst, RmwOp::MulF, rhs),
8254                MicroOp::MulF { dst, lhs, rhs } if rhs == t => (dst, RmwOp::MulF, lhs),
8255                _ => continue,
8256            };
8257            let MicroOp::ArrStore {
8258                src,
8259                idx: i2,
8260                ptr_slot: p2,
8261                len_slot: l2,
8262                byte: false,
8263                narrow32: false,
8264                checked: c2,
8265            } = micro[k + 2]
8266            else {
8267                continue;
8268            };
8269            // Same array + index, and the store consumes exactly the ALU result.
8270            if src != t2 || i2 != i || p2 != p || l2 != l {
8271                continue;
8272            }
8273            // `t` and `t2` are single-use scratch we can erase; `operand` is
8274            // re-read by the fused op (so it must NOT be one of them), and the
8275            // index `i` likewise stays live.
8276            if !removable(t, &reads) || !removable(t2, &reads) || operand == t || operand == t2 {
8277                continue;
8278            }
8279            hit = Some((
8280                k,
8281                MicroOp::ArrRMW {
8282                    idx: i,
8283                    operand,
8284                    ptr_slot: p,
8285                    len_slot: l,
8286                    op,
8287                    checked: c1 || c2,
8288                },
8289            ));
8290            break;
8291        }
8292        let Some((k, rmw)) = hit else { break };
8293        if std::env::var_os("LOGOS_FUSE_TRACE").is_some() {
8294            eprintln!("fuse-trace: ARRRMW {rmw:?}");
8295        }
8296        micro[k] = rmw;
8297        micro.remove(k + 2);
8298        micro.remove(k + 1);
8299        // Two ops vanished at k+1, k+2 (neither a jump target). Shift targets
8300        // above them down; a jump to the fused op (k) stays put.
8301        for op in micro.iter_mut() {
8302            if let Some(t) = micro_target_mut(op) {
8303                if *t > k + 2 {
8304                    *t -= 2;
8305                } else if *t > k {
8306                    *t -= 1;
8307                }
8308            }
8309        }
8310    }
8311}
8312
8313/// TWO-BUFFER INTEGER LOAD+BINOP FUSION — collapses `ArrLoad(t1 = a[i]); …;
8314/// ArrLoad(t2 = b[j]); …; {Add,Sub,Mul}(dst = t1 OP t2)` (the matrix-multiply /
8315/// dot-product idiom `c += a[..] * b[..]`) into one [`MicroOp::ArrLoad2`] placed
8316/// at the binop: ONE stencil dispatch + ONE combined bounds gate instead of
8317/// three ops, and the two loaded i64s never round-trip the frame. The JIT is
8318/// per-op DISPATCH-bound, so folding three hot inner-loop ops into one is a
8319/// direct win on the indexed arithmetic loops (matrix_mult) that lose worst to
8320/// V8. The two loads need NOT be adjacent (matmul computes `b`'s index between
8321/// them) — only their values, indices, and buffers must reach the binop
8322/// unchanged. The two buffers may be distinct (`a`, `b`) or the same (a self dot
8323/// product); each must be a pinned 8-byte INT buffer.
8324///
8325/// SOUNDNESS — the fused op evaluates `a[i-1] OP b[j-1]` with the kernel's
8326/// wrapping i64 semantics, bit-identical to the original ArrLoad+ArrLoad+ALU,
8327/// provided the two loaded values are exactly the ones the binop consumed:
8328/// - both loaded scratch values `t1`/`t2` are SINGLE-USE (read only by the
8329///   binop), distinct, un-named, un-pinned — so erasing their frame writes
8330///   loses no observable value (the `copy_propagate` staleness contract);
8331/// - between the EARLIER load and the binop, NOTHING redefines either index
8332///   (`i`/`j`) or either pointer/length slot, and NOTHING writes memory (no
8333///   array store/RMW/swap/push, map set, or list rebuild) — so neither buffer
8334///   nor index can change under the loads being hoisted to the binop site;
8335/// - no block leader (jump target) lands strictly AFTER the earlier load up to
8336///   and including the binop — otherwise an entry would skip a load.
8337/// The combined `checked = c1 || c2` is at least as safe as the pair (an
8338/// unchecked load proven in-bounds is in range by hypothesis, so re-checking it
8339/// never fires). The fused op side-exits BEFORE any effect on out-of-bounds and,
8340/// in a replay-from-head region, the deopt re-runs the whole region from its
8341/// entry — so moving the bounds gates to the binop site changes no observable
8342/// result (the only intervening ops are pure arithmetic on dead scratch).
8343/// Add/Mul commute (`t1`/`t2` in either order); Sub fuses only `a[i] - b[j]`
8344/// (the first load on the left). BYTE (Bool) buffers never fuse — the fused
8345/// stencil reads raw i64s. Caller restricts this to NON-PRECISE regions (it
8346/// renumbers micro indices).
8347fn fuse_array_ld2(
8348    micro: &mut Vec<MicroOp>,
8349    named: &[bool],
8350    register_count: u16,
8351    pinned: &std::collections::HashSet<u16>,
8352) {
8353    if micro.iter().any(|op| {
8354        matches!(
8355            op,
8356            MicroOp::Call { .. } | MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. }
8357        )
8358    }) {
8359        return;
8360    }
8361    let removable = |slot: u16, reads: &std::collections::HashMap<u16, usize>| -> bool {
8362        slot < register_count
8363            && !named.get(slot as usize).copied().unwrap_or(true)
8364            && !pinned.contains(&slot)
8365            && reads.get(&slot).copied().unwrap_or(0) == 1
8366    };
8367    // An op that writes anywhere in memory (any pinned array / map / list) —
8368    // we cannot statically tell which buffer it aliases, so any such op between
8369    // a load and the binop blocks the hoist conservatively.
8370    let writes_memory = |op: &MicroOp| -> bool {
8371        matches!(
8372            op,
8373            MicroOp::ArrStore { .. }
8374                | MicroOp::ArrRMW { .. }
8375                | MicroOp::ArrSwap { .. }
8376                | MicroOp::ArrCondSwap { .. }
8377                | MicroOp::ArrPush { .. }
8378                | MicroOp::MapSet { .. }
8379                | MicroOp::NewList { .. }
8380                | MicroOp::ListClear { .. }
8381                | MicroOp::ListTriple { .. }
8382        )
8383    };
8384    loop {
8385        let n = micro.len();
8386        let mut is_target = vec![false; n];
8387        for op in micro.iter() {
8388            if let Some(t) = micro_target_const(op) {
8389                if t < n {
8390                    is_target[t] = true;
8391                }
8392            }
8393        }
8394        let mut reads: std::collections::HashMap<u16, usize> = std::collections::HashMap::new();
8395        for op in micro.iter() {
8396            for s in micro_read_slots(op) {
8397                *reads.entry(s).or_insert(0) += 1;
8398            }
8399        }
8400        // Anchor on the binop; locate the two ArrLoads that define its operands.
8401        let mut hit: Option<(usize, usize, usize, MicroOp)> = None;
8402        'anchor: for m in 0..n {
8403            let (binop_kind, dst, lhs, rhs) = match micro[m] {
8404                MicroOp::Add { dst, lhs, rhs } => (IOp::Add, dst, lhs, rhs),
8405                MicroOp::Sub { dst, lhs, rhs } => (IOp::Sub, dst, lhs, rhs),
8406                MicroOp::Mul { dst, lhs, rhs } => (IOp::Mul, dst, lhs, rhs),
8407                _ => continue,
8408            };
8409            if lhs == rhs || dst == lhs || dst == rhs {
8410                continue;
8411            }
8412            // The most-recent ArrLoad defining a slot strictly before m, if its
8413            // value provably still holds at m (single-use scratch, and the load
8414            // is not itself re-defined in between — guaranteed by single-use of
8415            // its dst plus the no-rebind interval check below).
8416            let find_load = |slot: u16| -> Option<usize> {
8417                (0..m)
8418                    .rev()
8419                    .find(|&k| micro_defs(&micro[k]).contains(&slot))
8420            };
8421            let (Some(ka), Some(kb)) = (find_load(lhs), find_load(rhs)) else {
8422                continue;
8423            };
8424            if ka == kb {
8425                continue;
8426            }
8427            let MicroOp::ArrLoad {
8428                dst: _,
8429                idx: ia,
8430                ptr_slot: pa,
8431                len_slot: lena,
8432                byte: false,
8433                narrow32: false,
8434                checked: ca,
8435            } = micro[ka]
8436            else {
8437                continue;
8438            };
8439            let MicroOp::ArrLoad {
8440                dst: _,
8441                idx: ib,
8442                ptr_slot: pb,
8443                len_slot: lenb,
8444                byte: false,
8445                narrow32: false,
8446                checked: cb,
8447            } = micro[kb]
8448            else {
8449                continue;
8450            };
8451            // For Sub the order is fixed: lhs must be `a[ia]` (the load at ka).
8452            // Add/Mul commute. We always store the operand that came from ka as
8453            // `a`/`i` and from kb as `b`/`j` so `eval` reproduces lhs OP rhs.
8454            // (Sub: lhs == a[ia], rhs == b[ib] ⇒ a - b. Correct by construction.)
8455            // Both scratch loads must be single-use removable; dst already
8456            // checked distinct from both above.
8457            if !removable(lhs, &reads) || !removable(rhs, &reads) {
8458                continue;
8459            }
8460            // Interval soundness. The fused op sits at the binop and reads each
8461            // index + pointer/length from the frame at THAT point, so each
8462            // load's index/buffer must reach the binop unchanged FROM ITS OWN
8463            // LOAD onward (the index is naturally produced just before the load
8464            // — that write is fine). Concretely:
8465            //  - NO jump target in `[lo, m]` (the loads are removed and the fused
8466            //    op moves to the binop, so any entry there would skip a load);
8467            //  - `ia`,`pa`,`lena` not redefined in `(ka, m)`; `ib`,`pb`,`lenb`
8468            //    not redefined in `(kb, m)`;
8469            //  - NO memory write in `[lo, m)` (could mutate either buffer).
8470            let lo = ka.min(kb);
8471            let guard_a: [u16; 3] = [ia, pa, lena];
8472            let guard_b: [u16; 3] = [ib, pb, lenb];
8473            for p in lo..m {
8474                if p < n && is_target[p] {
8475                    continue 'anchor;
8476                }
8477                if p == ka || p == kb {
8478                    continue;
8479                }
8480                if writes_memory(&micro[p]) {
8481                    continue 'anchor;
8482                }
8483                let defs = micro_defs(&micro[p]);
8484                if p > ka && defs.iter().any(|d| guard_a.contains(d)) {
8485                    continue 'anchor;
8486                }
8487                if p > kb && defs.iter().any(|d| guard_b.contains(d)) {
8488                    continue 'anchor;
8489                }
8490            }
8491            // A jump target landing exactly on the binop would skip both loads.
8492            if m < n && is_target[m] {
8493                continue 'anchor;
8494            }
8495            hit = Some((
8496                ka,
8497                kb,
8498                m,
8499                MicroOp::ArrLoad2 {
8500                    dst,
8501                    i: ia,
8502                    j: ib,
8503                    ptr_a: pa,
8504                    len_a: lena,
8505                    ptr_b: pb,
8506                    len_b: lenb,
8507                    op: binop_kind,
8508                    checked: ca || cb,
8509                },
8510            ));
8511            break;
8512        }
8513        let Some((ka, kb, m, ld2)) = hit else { break };
8514        if std::env::var_os("LOGOS_FUSE_TRACE").is_some() {
8515            eprintln!("fuse-trace: ARRLD2 {ld2:?}");
8516        }
8517        // Place the fused op at the binop, then remove the two loads (higher
8518        // index first so the lower index stays valid).
8519        micro[m] = ld2;
8520        let (hi, low) = if ka > kb { (ka, kb) } else { (kb, ka) };
8521        micro.remove(hi);
8522        micro.remove(low);
8523        // Two ops vanished at `low` and `hi` (neither a jump target — the
8524        // interval check forbids targets after the earlier load). Shift later
8525        // targets down by however many removed ops precede them. The fused op
8526        // at `m` is itself shifted by the removals below it.
8527        for op in micro.iter_mut() {
8528            if let Some(t) = micro_target_mut(op) {
8529                let shift = (*t > low) as usize + (*t > hi) as usize;
8530                *t -= shift;
8531            }
8532        }
8533    }
8534}
8535
8536/// AFFINE-INDEX LOAD FUSION — folds the index-arithmetic chain that builds a
8537/// read-only array index INTO the load, so `<binop>(t = a OP b); Add(t2 = t +
8538/// Kc); ArrLoad(arr[t2])` (the `w - wi + 1`, `i*n + j + 1` shape) — or the
8539/// shorter `Add(t = a + Kc); ArrLoad(arr[t])` (`w + 1`) and the bare
8540/// `<binop>(t = a OP b); ArrLoad(arr[t])` (`i*n + j`) — collapse into one
8541/// [`MicroOp::ArrLoadAffine`] stencil that computes the 1-based index and loads
8542/// in a single dispatch. The JIT is per-op DISPATCH-bound, so removing the 1-2
8543/// index-arithmetic ops per access is a direct win on the indexed inner loops
8544/// (knapsack `prev[w - wi + 1]`, the heap-sift read region, graph adjacency
8545/// reads) that lose worst to V8.
8546///
8547/// SOUNDNESS — the fused stencil recomputes `idx = (frame[a] OP frame[b])
8548/// .wrapping_add(const_offset)` (or `frame[a] + const_offset` for the no-`b`
8549/// shape) with the kernel's EXACT i64 wrapping semantics, bit-identical to the
8550/// chain it replaces, PROVIDED the surviving operands reach the load unchanged:
8551/// - the load's index slot is SINGLE-USE scratch (read only by this load), so
8552///   erasing the index-producing op loses no observable value;
8553/// - the trailing-const `Add`'s product `t` (the two-slot binop's dst) is also
8554///   single-use scratch, so the inner binop is removable too;
8555/// - the constant offset is a LoadConst VALUE whose source slot is NOT redefined
8556///   between its load and the index `Add` (the LoadConst itself is KEPT — it is
8557///   usually reused — only its value is folded);
8558/// - between each removed op and the load NOTHING redefines a surviving operand
8559///   (`a`, `b`) and NO jump target lands in the removed span (an entry there
8560///   would skip a removed op).
8561/// The fused op SIDE-EXITS before any effect on out-of-bounds, identical to the
8562/// plain [`MicroOp::ArrLoad`] it replaces (replay-from-head recomputes the same
8563/// index). BYTE (Bool) buffers never fuse (the affine stencils read raw i64s).
8564/// Runs AFTER `fuse_array_ld2` so the matmul `a[..] * b[..]` two-buffer loads
8565/// keep fusing into `ArrLoad2` (which consumes the raw `ArrLoad`s) — this pass
8566/// only claims the plain read-only `ArrLoad`s that `ArrLoad2`/swap fusion left
8567/// behind. Caller restricts to NON-PRECISE regions (it renumbers micro indices).
8568/// `LOGOS_AFFINE=0` is the kill-switch.
8569fn fuse_index_affine(
8570    micro: &mut Vec<MicroOp>,
8571    named: &[bool],
8572    register_count: u16,
8573    pinned: &std::collections::HashSet<u16>,
8574) {
8575    use logicaffeine_forge::jit::AffOp;
8576    if micro.iter().any(|op| {
8577        matches!(
8578            op,
8579            MicroOp::Call { .. } | MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. }
8580        )
8581    }) {
8582        return;
8583    }
8584    // A scratch temp removable iff it is in-range, un-named, un-pinned, and
8585    // read EXACTLY once (its only reader is the op we erase or replace).
8586    let single_use_scratch = |slot: u16, reads: &std::collections::HashMap<u16, usize>| -> bool {
8587        (slot as usize) < register_count as usize
8588            && !named.get(slot as usize).copied().unwrap_or(true)
8589            && !pinned.contains(&slot)
8590            && reads.get(&slot).copied().unwrap_or(0) == 1
8591    };
8592    // The integer binop family that can build an affine index.
8593    let as_iop = |op: &MicroOp| -> Option<(IOp, u16, u16, u16)> {
8594        match *op {
8595            MicroOp::Add { dst, lhs, rhs } => Some((IOp::Add, dst, lhs, rhs)),
8596            MicroOp::Sub { dst, lhs, rhs } => Some((IOp::Sub, dst, lhs, rhs)),
8597            MicroOp::Mul { dst, lhs, rhs } => Some((IOp::Mul, dst, lhs, rhs)),
8598            _ => None,
8599        }
8600    };
8601    let iop_to_aff = |op: IOp| match op {
8602        IOp::Add => AffOp::Add,
8603        IOp::Sub => AffOp::Sub,
8604        IOp::Mul => AffOp::Mul,
8605    };
8606    loop {
8607        let n = micro.len();
8608        let mut is_target = vec![false; n];
8609        for op in micro.iter() {
8610            if let Some(t) = micro_target_const(op) {
8611                if t < n {
8612                    is_target[t] = true;
8613                }
8614            }
8615        }
8616        let mut reads: std::collections::HashMap<u16, usize> = std::collections::HashMap::new();
8617        for op in micro.iter() {
8618            for s in micro_read_slots(op) {
8619                *reads.entry(s).or_insert(0) += 1;
8620            }
8621        }
8622        // The reaching constant value of a slot at position `m`, if it is a
8623        // LoadConst not redefined in `(def, m)`. Returns (value, def_index).
8624        let reaching_const = |slot: u16, m: usize| -> Option<(i64, usize)> {
8625            let k = (0..m)
8626                .rev()
8627                .find(|&p| micro_defs(&micro[p]).contains(&slot))?;
8628            if let MicroOp::LoadConst { value, .. } = micro[k] {
8629                Some((value, k))
8630            } else {
8631                None
8632            }
8633        };
8634        // The reaching def index of a slot strictly before `m`.
8635        let reaching_def = |slot: u16, m: usize| -> Option<usize> {
8636            (0..m)
8637                .rev()
8638                .find(|&p| micro_defs(&micro[p]).contains(&slot))
8639        };
8640        // No jump target lands in [lo, m]; no surviving operand redefined in the
8641        // open spans after each removed op up to the load.
8642        let mut hit: Option<(Vec<usize>, usize, MicroOp)> = None;
8643        'anchor: for m in 0..n {
8644            let MicroOp::ArrLoad {
8645                dst,
8646                idx,
8647                ptr_slot,
8648                len_slot,
8649                byte: false,
8650                narrow32: false,
8651                checked,
8652            } = micro[m]
8653            else {
8654                continue;
8655            };
8656            // The index must be single-use scratch defined by an integer binop.
8657            if !single_use_scratch(idx, &reads) {
8658                continue;
8659            }
8660            let Some(kidx) = reaching_def(idx, m) else {
8661                continue;
8662            };
8663            let Some((idx_op, _idst, ilhs, irhs)) = as_iop(&micro[kidx]) else {
8664                continue;
8665            };
8666
8667            // Decompose into (a, op, b, const_offset) + the chain ops to remove.
8668            // Three shapes, tried in order of specificity.
8669            let mut removed: Vec<usize> = Vec::new();
8670            let (a, aff_op, b, coff): (u16, AffOp, u16, i64);
8671
8672            // Does either operand of the index binop come from an inner two-slot
8673            // binop whose dst is single-use (the `t` of `t + Kc`)? If the OTHER
8674            // operand is a reaching const, this is the trailing-const shape.
8675            let inner_of = |slot: u16| -> Option<(usize, IOp, u16, u16)> {
8676                if !single_use_scratch(slot, &reads) {
8677                    return None;
8678                }
8679                let k = reaching_def(slot, kidx)?;
8680                let (op, d, l, r) = as_iop(&micro[k])?;
8681                Some((k, op, l, r)).filter(|_| d == slot)
8682            };
8683
8684            if idx_op == IOp::Add {
8685                // `Add(idx = LHS + RHS)`: classify each side.
8686                let lconst = reaching_const(ilhs, kidx);
8687                let rconst = reaching_const(irhs, kidx);
8688                let linner = inner_of(ilhs);
8689                let rinner = inner_of(irhs);
8690                if let (Some((kc, _)), Some((kin, iop, l, r))) = (rconst, linner) {
8691                    // `(l OP r) + Kc` — Kc on the right.
8692                    let _ = kc;
8693                    a = l;
8694                    b = r;
8695                    aff_op = iop_to_aff(iop);
8696                    coff = rconst.unwrap().0;
8697                    removed.push(kin);
8698                    removed.push(kidx);
8699                } else if let (Some((kc, _)), Some((kin, iop, l, r))) = (lconst, rinner) {
8700                    // `Kc + (l OP r)` — Kc on the left.
8701                    let _ = kc;
8702                    a = l;
8703                    b = r;
8704                    aff_op = iop_to_aff(iop);
8705                    coff = lconst.unwrap().0;
8706                    removed.push(kin);
8707                    removed.push(kidx);
8708                } else if let Some((_, _)) = rconst {
8709                    // `a + Kc` (the `w + 1` shape): single slot + const.
8710                    a = ilhs;
8711                    b = ilhs;
8712                    aff_op = AffOp::None;
8713                    coff = rconst.unwrap().0;
8714                    removed.push(kidx);
8715                } else if let Some((_, _)) = lconst {
8716                    a = irhs;
8717                    b = irhs;
8718                    aff_op = AffOp::None;
8719                    coff = lconst.unwrap().0;
8720                    removed.push(kidx);
8721                } else {
8722                    // `a + b` (no const): a bare two-slot add.
8723                    a = ilhs;
8724                    b = irhs;
8725                    aff_op = AffOp::Add;
8726                    coff = 0;
8727                    removed.push(kidx);
8728                }
8729            } else {
8730                // `Sub`/`Mul(idx = a OP b)` with no trailing const (the const,
8731                // when present, is always the OUTER `+ Kc` Add handled above; a
8732                // bare Sub/Mul index folds with const_offset = 0).
8733                a = ilhs;
8734                b = irhs;
8735                aff_op = iop_to_aff(idx_op);
8736                coff = 0;
8737                removed.push(kidx);
8738            }
8739
8740            // Interval soundness over the union of removed ops and the load.
8741            let lo = *removed.iter().min().unwrap();
8742            let survivors: [u16; 2] = [a, b];
8743            for p in lo..m {
8744                if p < n && is_target[p] {
8745                    continue 'anchor;
8746                }
8747                if removed.contains(&p) {
8748                    continue;
8749                }
8750                let defs = micro_defs(&micro[p]);
8751                if defs.iter().any(|d| survivors.contains(d)) {
8752                    continue 'anchor;
8753                }
8754            }
8755            // A jump target landing exactly on the load would skip the removed
8756            // index ops.
8757            if m < n && is_target[m] {
8758                continue 'anchor;
8759            }
8760            removed.sort_unstable();
8761            hit = Some((
8762                removed,
8763                m,
8764                MicroOp::ArrLoadAffine {
8765                    dst,
8766                    a,
8767                    op: aff_op,
8768                    b,
8769                    const_offset: coff,
8770                    ptr_slot,
8771                    len_slot,
8772                    checked,
8773                },
8774            ));
8775            break;
8776        }
8777        let Some((removed, m, affine)) = hit else {
8778            break;
8779        };
8780        if std::env::var_os("LOGOS_FUSE_TRACE").is_some() {
8781            eprintln!("fuse-trace: AFFINE {affine:?}");
8782        }
8783        // Place the fused op at the load, then remove the index-chain ops
8784        // (highest index first so lower indices stay valid). None of the removed
8785        // ops is a jump target (the interval check forbids targets in [lo, m]).
8786        micro[m] = affine;
8787        for &r in removed.iter().rev() {
8788            micro.remove(r);
8789        }
8790        for op in micro.iter_mut() {
8791            if let Some(t) = micro_target_mut(op) {
8792                let shift = removed.iter().filter(|&&r| r < *t).count();
8793                *t -= shift;
8794            }
8795        }
8796    }
8797}
8798
8799/// FLOAT MULTIPLY-ADD FUSION — collapses `MulF(t = a*b); AddF(d = t + c)` (the
8800/// product `t` single-use, AddF commutative so `t` may be either operand) into
8801/// one [`MicroOp::FmaF`] computing `(a*b) + c`. The JIT is per-op DISPATCH-bound,
8802/// and the float arithmetic chains that dominate the float cluster (nbody's
8803/// `dz*dz + sum`, dot products) are a stream of two-input AddF/MulF; merging a
8804/// product into its consuming add removes a stencil dispatch per occurrence.
8805///
8806/// SOUNDNESS: FmaF rounds the product and the add SEPARATELY (`(a*b)+c`, two
8807/// roundings — NOT a hardware single-rounding FMA), bit-identical to MulF+AddF.
8808/// It is mem-form (all operands read from the frame), so it never disturbs the
8809/// threaded XMM pins. To keep it a SPILL-FREE win on its INPUTS, fuse only when
8810/// the surviving inputs (`a`, `b`, the addend `c`) are FRAME-RESIDENT (not
8811/// pinned) — a pinned input would be spilled BEFORE the mem-form op, possibly
8812/// costing more than the saved dispatch. The RESULT `d` MAY be pinned (Lever
8813/// 1a): the pinned compiler's mem-form path reloads a pinned `d` from the frame
8814/// after the FmaF, exactly as the unfused register-form `AddF` would settle it,
8815/// so a pinned `d` adds no input spill (the nbody distance-sum's `dz*dz +
8816/// partial`, whose `d` is the float-pinned running sum). The product `t` must be
8817/// single-use, un-named, un-pinned scratch (its only reader, the AddF, is
8818/// removed). Caller restricts to NON-PRECISE regions (renumbering).
8819fn fuse_fma(
8820    micro: &mut Vec<MicroOp>,
8821    named: &[bool],
8822    register_count: u16,
8823    pinned: &std::collections::HashSet<u16>,
8824) {
8825    if micro.iter().any(|op| {
8826        matches!(
8827            op,
8828            MicroOp::Call { .. } | MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. }
8829        )
8830    }) {
8831        return;
8832    }
8833    let frame_resident = |slot: u16| -> bool { !pinned.contains(&slot) };
8834    loop {
8835        let n = micro.len();
8836        let mut is_target = vec![false; n];
8837        for op in micro.iter() {
8838            if let Some(t) = micro_target_const(op) {
8839                if t < n {
8840                    is_target[t] = true;
8841                }
8842            }
8843        }
8844        let mut reads: std::collections::HashMap<u16, usize> = std::collections::HashMap::new();
8845        for op in micro.iter() {
8846            for s in micro_read_slots(op) {
8847                *reads.entry(s).or_insert(0) += 1;
8848            }
8849        }
8850        let mut hit: Option<(usize, MicroOp)> = None;
8851        for k in 0..n.saturating_sub(1) {
8852            if is_target[k + 1] {
8853                continue;
8854            }
8855            let MicroOp::MulF {
8856                dst: t,
8857                lhs: a,
8858                rhs: b,
8859            } = micro[k]
8860            else {
8861                continue;
8862            };
8863            // The AddF consumes the product `t` (either operand) plus the addend.
8864            let (d, c) = match micro[k + 1] {
8865                MicroOp::AddF { dst, lhs, rhs } if lhs == t => (dst, rhs),
8866                MicroOp::AddF { dst, lhs, rhs } if rhs == t => (dst, lhs),
8867                _ => continue,
8868            };
8869            // `t` is single-use, un-named, un-pinned scratch we can erase.
8870            let t_dead = (t as usize) < register_count as usize
8871                && !named.get(t as usize).copied().unwrap_or(true)
8872                && !pinned.contains(&t)
8873                && reads.get(&t).copied().unwrap_or(0) == 1;
8874            // INPUT-spill-free (Lever 1a): require only the surviving INPUTS
8875            // (`a`, `b`, the addend `c`) frame-resident. `FmaF` is mem-form, so a
8876            // pinned RESULT `d` is spilled/reloaded by the pinned compiler's
8877            // mem-form path exactly as the unfused `AddF`'s register-form write
8878            // would settle it — fusing a pinned `d` adds no INPUT spill, removing
8879            // the `MulF` dispatch (the nbody distance-sum's `dz*dz + partial`,
8880            // whose `d` is the float-pinned sum). The addend `c` must NOT be
8881            // pinned: in the `s = s + a*b` accumulator shape `c == d == s`, a
8882            // pinned `c` would be spilled BEFORE the FmaF (a real extra spill),
8883            // costing more pieces than the register-form `AddF` it replaces.
8884            if !t_dead || !frame_resident(a) || !frame_resident(b) || !frame_resident(c) {
8885                continue;
8886            }
8887            hit = Some((k, MicroOp::FmaF { dst: d, a, b, c }));
8888            break;
8889        }
8890        let Some((k, fma)) = hit else { break };
8891        if std::env::var_os("LOGOS_FUSE_TRACE").is_some() {
8892            eprintln!("fuse-trace: FMAF {fma:?}");
8893        }
8894        micro[k] = fma;
8895        micro.remove(k + 1);
8896        for op in micro.iter_mut() {
8897            if let Some(t) = micro_target_mut(op) {
8898                if *t > k {
8899                    *t -= 1;
8900                }
8901            }
8902        }
8903    }
8904}
8905
8906/// CONDITIONAL-SWAP FUSION — collapses the sort inner-loop idiom
8907/// `ArrLoad(a, i1); [pure index ops]; ArrLoad(b, i2); Branch(cmp, a, b, skip);
8908/// ArrStore(i1, b); ArrStore(i2, a)` into one [`MicroOp::ArrCondSwap`] — the
8909/// biggest per-iteration dispatch sink for bubble/insertion/quick sort. Unlocked
8910/// by the precise-region-live-out keystone: the loaded values flow through
8911/// loop-local `Let a`/`Let b`, which are now dropped from write-back, so
8912/// copy_propagate erases their Moves and the loaded temps become single-use.
8913///
8914/// SOUNDNESS: `ArrCondSwap` re-reads `buf[i1]`/`buf[i2]` and swaps atomically
8915/// (both writes or neither) — bit-identical to the load/compare/cross-store it
8916/// replaces because NOTHING writes the array between the original loads and the
8917/// stores (only the pure index ops and the branch sit there). One pre-write
8918/// bounds check covers both indices. The loaded `a`, `b` must be single-use
8919/// scratch (read only by the branch + their cross-store — exactly two reads
8920/// each — un-named, un-pinned), the branch must target precisely past both
8921/// stores, the comparison must be an ordering (Gt/Lt/GtEq/LtEq), and up to two
8922/// PURE ops (a const + the `i+1` add) may sit between the loads. No fused op may
8923/// be a jump target. Non-precise regions only.
8924fn fuse_cond_swap(
8925    micro: &mut Vec<MicroOp>,
8926    named: &[bool],
8927    register_count: u16,
8928    pinned: &std::collections::HashSet<u16>,
8929) {
8930    if micro.iter().any(|op| {
8931        matches!(
8932            op,
8933            MicroOp::Call { .. } | MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. }
8934        )
8935    }) {
8936        return;
8937    }
8938    let dead_scratch = |slot: u16, reads: &std::collections::HashMap<u16, usize>| -> bool {
8939        (slot as usize) < register_count as usize
8940            && !named.get(slot as usize).copied().unwrap_or(true)
8941            && !pinned.contains(&slot)
8942            && reads.get(&slot).copied().unwrap_or(0) == 2 // the branch + its cross-store
8943    };
8944    loop {
8945        let n = micro.len();
8946        let mut is_target = vec![false; n];
8947        for op in micro.iter() {
8948            if let Some(t) = micro_target_const(op) {
8949                if t < n {
8950                    is_target[t] = true;
8951                }
8952            }
8953        }
8954        let mut reads: std::collections::HashMap<u16, usize> = std::collections::HashMap::new();
8955        for op in micro.iter() {
8956            for s in micro_read_slots(op) {
8957                *reads.entry(s).or_insert(0) += 1;
8958            }
8959        }
8960        let mut hit: Option<(usize, usize, MicroOp)> = None; // (k, gap, condswap)
8961                                                             // The compare's SECOND index can be a multi-op affine computation
8962                                                             // (`2*root+2` = LoadConst + Mul + Add, or `i*n + j + 1`) sitting between
8963                                                             // the two loads. The `between_ok` purity guard below — not this window —
8964                                                             // is what proves the gap ops cannot perturb the swap (pure, and they
8965                                                             // redefine none of the first loaded value / first index / pointer /
8966                                                             // length); the window only bounds the linear search, so it must be wide
8967                                                             // enough to span a realistic index expression.
8968        const MAXGAP: usize = 5;
8969        'outer: for k in 0..n {
8970            let MicroOp::ArrLoad {
8971                dst: a,
8972                idx: i1,
8973                ptr_slot: p,
8974                len_slot: l,
8975                byte: false,
8976                narrow32: false,
8977                checked: c1,
8978            } = micro[k]
8979            else {
8980                continue;
8981            };
8982            for gap in 0..=MAXGAP {
8983                let lb = k + 1 + gap;
8984                if lb + 3 >= n {
8985                    break;
8986                }
8987                let between_ok = (k + 1..lb).all(|x| {
8988                    let pure = micro_pure_value_key(&micro[x]).is_some()
8989                        || matches!(micro[x], MicroOp::LoadConst { .. });
8990                    let defs = micro_defs(&micro[x]);
8991                    pure && !defs.contains(&a)
8992                        && !defs.contains(&i1)
8993                        && !defs.contains(&p)
8994                        && !defs.contains(&l)
8995                });
8996                if !between_ok {
8997                    continue;
8998                }
8999                let MicroOp::ArrLoad {
9000                    dst: b,
9001                    idx: i2,
9002                    ptr_slot: p2,
9003                    len_slot: l2,
9004                    byte: false,
9005                    narrow32: false,
9006                    checked: c2,
9007                } = micro[lb]
9008                else {
9009                    continue;
9010                };
9011                if p2 != p || l2 != l {
9012                    continue;
9013                }
9014                let MicroOp::Branch {
9015                    cmp,
9016                    lhs,
9017                    rhs,
9018                    target,
9019                } = micro[lb + 1]
9020                else {
9021                    continue;
9022                };
9023                if !matches!(cmp, Cmp::Lt | Cmp::Gt | Cmp::LtEq | Cmp::GtEq) || lhs != a || rhs != b
9024                {
9025                    continue;
9026                }
9027                let MicroOp::ArrStore {
9028                    src: s1,
9029                    idx: si1,
9030                    ptr_slot: sp1,
9031                    len_slot: sl1,
9032                    byte: false,
9033                    narrow32: false,
9034                    checked: c3,
9035                } = micro[lb + 2]
9036                else {
9037                    continue;
9038                };
9039                let MicroOp::ArrStore {
9040                    src: s2,
9041                    idx: si2,
9042                    ptr_slot: sp2,
9043                    len_slot: sl2,
9044                    byte: false,
9045                    narrow32: false,
9046                    checked: c4,
9047                } = micro[lb + 3]
9048                else {
9049                    continue;
9050                };
9051                if si1 != i1
9052                    || si2 != i2
9053                    || s1 != b
9054                    || s2 != a
9055                    || sp1 != p
9056                    || sp2 != p
9057                    || sl1 != l
9058                    || sl2 != l
9059                {
9060                    continue;
9061                }
9062                if target != lb + 4 {
9063                    continue;
9064                }
9065                if (k..=lb + 3).any(|x| is_target.get(x).copied().unwrap_or(false)) {
9066                    continue;
9067                }
9068                if !dead_scratch(a, &reads) || !dead_scratch(b, &reads) {
9069                    continue;
9070                }
9071                hit = Some((
9072                    k,
9073                    gap,
9074                    MicroOp::ArrCondSwap {
9075                        idx1: i1,
9076                        idx2: i2,
9077                        ptr_slot: p,
9078                        len_slot: l,
9079                        cmp,
9080                        checked: c1 || c2 || c3 || c4,
9081                    },
9082                ));
9083                break 'outer;
9084            }
9085        }
9086        let Some((k, gap, swap)) = hit else { break };
9087        if std::env::var_os("LOGOS_FUSE_TRACE").is_some() {
9088            eprintln!("fuse-trace: CONDSWAP {swap:?}");
9089        }
9090        // Span k ..= k+4+gap. Keep the between ops, turn the b-load slot into the
9091        // swap, drop a-load + branch + both stores (4 removed). First op after the
9092        // span (old k+gap+5) lands at k+gap+1.
9093        micro[k + gap + 1] = swap;
9094        micro.drain(k + gap + 2..=k + gap + 4);
9095        micro.remove(k);
9096        for op in micro.iter_mut() {
9097            if let Some(t) = micro_target_mut(op) {
9098                if *t >= k + gap + 5 {
9099                    *t -= 4;
9100                }
9101            }
9102        }
9103    }
9104}
9105
9106/// UNCONDITIONAL-SWAP FUSION — collapses the `Let tmp = arr[i]; arr[i] = arr[j];
9107/// arr[j] = tmp` exchange (quicksort/heap_sort/mergesort) — micro
9108/// `ArrLoad(a, i1); ArrLoad(b, i2); ArrStore(i1, b); ArrStore(i2, a)` — into one
9109/// [`MicroOp::ArrSwap`] (4 ops → 1). The conditionality (`if arr[j] <= pivot`)
9110/// is a SEPARATE branch before the loads and stays.
9111///
9112/// SOUNDNESS: `ArrSwap` re-reads `buf[i1]`/`buf[i2]` and swaps atomically —
9113/// bit-identical because nothing writes the array between the loads and stores.
9114/// `a`, `b` must be LOCALLY single-use (each read only by its cross-store before
9115/// its next redefinition — a slot may be REUSED later, so global read-counting
9116/// is too coarse here), un-named, un-pinned. No control flow between the four
9117/// ops; none a jump target. Non-precise regions only.
9118fn fuse_swap(
9119    micro: &mut Vec<MicroOp>,
9120    named: &[bool],
9121    register_count: u16,
9122    pinned: &std::collections::HashSet<u16>,
9123) {
9124    if micro.iter().any(|op| {
9125        matches!(
9126            op,
9127            MicroOp::Call { .. } | MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. }
9128        )
9129    }) {
9130        return;
9131    }
9132    let erasable = |slot: u16| -> bool {
9133        (slot as usize) < register_count as usize
9134            && !named.get(slot as usize).copied().unwrap_or(true)
9135            && !pinned.contains(&slot)
9136    };
9137    loop {
9138        let n = micro.len();
9139        let mut is_target = vec![false; n];
9140        for op in micro.iter() {
9141            if let Some(t) = micro_target_const(op) {
9142                if t < n {
9143                    is_target[t] = true;
9144                }
9145            }
9146        }
9147        // `slot` (defined at def_i) is read ONLY at `want` before its next redef.
9148        let local_single_use = |slot: u16, def_i: usize, want: usize| -> bool {
9149            let mut seen = false;
9150            for j in def_i + 1..micro.len() {
9151                if micro_read_slots(&micro[j]).contains(&slot) {
9152                    if j != want {
9153                        return false;
9154                    }
9155                    seen = true;
9156                }
9157                if micro_defs(&micro[j]).contains(&slot) {
9158                    break; // next redefinition — a separate live range
9159                }
9160            }
9161            seen
9162        };
9163        let mut hit: Option<(usize, MicroOp)> = None;
9164        for k in 0..n.saturating_sub(3) {
9165            let MicroOp::ArrLoad {
9166                dst: a,
9167                idx: i1,
9168                ptr_slot: p,
9169                len_slot: l,
9170                byte: false,
9171                narrow32: false,
9172                checked: c1,
9173            } = micro[k]
9174            else {
9175                continue;
9176            };
9177            let MicroOp::ArrLoad {
9178                dst: b,
9179                idx: i2,
9180                ptr_slot: p2,
9181                len_slot: l2,
9182                byte: false,
9183                narrow32: false,
9184                checked: c2,
9185            } = micro[k + 1]
9186            else {
9187                continue;
9188            };
9189            if p2 != p || l2 != l || a == b {
9190                continue;
9191            }
9192            let MicroOp::ArrStore {
9193                src: s1,
9194                idx: si1,
9195                ptr_slot: sp1,
9196                len_slot: sl1,
9197                byte: false,
9198                narrow32: false,
9199                checked: c3,
9200            } = micro[k + 2]
9201            else {
9202                continue;
9203            };
9204            let MicroOp::ArrStore {
9205                src: s2,
9206                idx: si2,
9207                ptr_slot: sp2,
9208                len_slot: sl2,
9209                byte: false,
9210                narrow32: false,
9211                checked: c4,
9212            } = micro[k + 3]
9213            else {
9214                continue;
9215            };
9216            // Cross-store swap to the SAME array+indices: buf[i1]=b, buf[i2]=a.
9217            if si1 != i1
9218                || si2 != i2
9219                || s1 != b
9220                || s2 != a
9221                || sp1 != p
9222                || sp2 != p
9223                || sl1 != l
9224                || sl2 != l
9225            {
9226                continue;
9227            }
9228            if is_target[k + 1] || is_target[k + 2] || is_target[k + 3] {
9229                continue;
9230            }
9231            // `a` consumed only by the store at k+3, `b` only by the store at k+2.
9232            if !erasable(a)
9233                || !erasable(b)
9234                || !local_single_use(a, k, k + 3)
9235                || !local_single_use(b, k + 1, k + 2)
9236            {
9237                continue;
9238            }
9239            hit = Some((
9240                k,
9241                MicroOp::ArrSwap {
9242                    idx1: i1,
9243                    idx2: i2,
9244                    ptr_slot: p,
9245                    len_slot: l,
9246                    checked: c1 || c2 || c3 || c4,
9247                },
9248            ));
9249            break;
9250        }
9251        let Some((k, swap)) = hit else { break };
9252        if std::env::var_os("LOGOS_FUSE_TRACE").is_some() {
9253            eprintln!("fuse-trace: ARRSWAP {swap:?}");
9254        }
9255        micro[k] = swap;
9256        micro.drain(k + 1..=k + 3); // remove the 2nd load + both stores
9257        for op in micro.iter_mut() {
9258            if let Some(t) = micro_target_mut(op) {
9259                if *t >= k + 4 {
9260                    *t -= 3;
9261                }
9262            }
9263        }
9264    }
9265}
9266
9267/// A canonical value key for a PURE, side-effect-free, deterministic micro-op —
9268/// the basis for local value numbering (CSE) in [`copy_propagate`]. Returns
9269/// `((tag, a, b), dst)`: a unique op tag, the two operand slots (commutative ops
9270/// sort them so `v + 1` and `1 + v` share a key), and the result slot. Returns
9271/// None for anything that loads memory, calls, side-exits (Div/Mod, whose
9272/// duplicate could diverge on a zero divisor), branches, or carries hidden
9273/// state — those must never be deduplicated. Every operand position is a real
9274/// frame slot (never an immediate), so the invalidation in `copy_propagate` can
9275/// drop a key the moment any slot it names is redefined.
9276fn micro_pure_value_key(op: &MicroOp) -> Option<((u8, u16, u16), u16)> {
9277    use MicroOp::*;
9278    let comm = |t: u8, a: u16, b: u16, d: u16| Some(((t, a.min(b), a.max(b)), d));
9279    let ord = |t: u8, a: u16, b: u16, d: u16| Some(((t, a, b), d));
9280    match *op {
9281        Add { dst, lhs, rhs } => comm(1, lhs, rhs, dst),
9282        Mul { dst, lhs, rhs } => comm(2, lhs, rhs, dst),
9283        BitAnd { dst, lhs, rhs } => comm(3, lhs, rhs, dst),
9284        BitOr { dst, lhs, rhs } => comm(4, lhs, rhs, dst),
9285        BitXor { dst, lhs, rhs } => comm(5, lhs, rhs, dst),
9286        Eq { dst, lhs, rhs } => comm(6, lhs, rhs, dst),
9287        Neq { dst, lhs, rhs } => comm(7, lhs, rhs, dst),
9288        Sub { dst, lhs, rhs } => ord(8, lhs, rhs, dst),
9289        Shl { dst, lhs, rhs } => ord(9, lhs, rhs, dst),
9290        Shr { dst, lhs, rhs } => ord(10, lhs, rhs, dst),
9291        Rotate {
9292            dst,
9293            lhs,
9294            rhs,
9295            width32,
9296            left,
9297        } => ord(17 + (width32 as u8) * 2 + left as u8, lhs, rhs, dst),
9298        Lt { dst, lhs, rhs } => ord(11, lhs, rhs, dst),
9299        Gt { dst, lhs, rhs } => ord(12, lhs, rhs, dst),
9300        LtEq { dst, lhs, rhs } => ord(13, lhs, rhs, dst),
9301        GtEq { dst, lhs, rhs } => ord(14, lhs, rhs, dst),
9302        NotInt { dst, src } => ord(15, src, src, dst),
9303        NotBool { dst, src } => ord(16, src, src, dst),
9304        _ => None,
9305    }
9306}
9307
9308/// The branch/jump TARGET of a micro-op (a micro index), if any — by value.
9309fn micro_target_const(op: &MicroOp) -> Option<usize> {
9310    use MicroOp::*;
9311    match *op {
9312        Jump { target }
9313        | Branch { target, .. }
9314        | BranchF { target, .. }
9315        | JumpIfFalse { target, .. }
9316        | JumpIfTrue { target, .. } => Some(target),
9317        _ => None,
9318    }
9319}
9320
9321/// Returns TWO disjoint pin sets: `(gp_pins, float_pins)`. A slot that ever
9322/// holds an f64 VALUE (used by any float-arithmetic / float-compare op) is a
9323/// FLOAT slot — it can only ride an XMM register (f0..f3), so it goes into
9324/// `float_pins` and is NEVER put in the GP set, which threads i64s through
9325/// r0..r3. The two budgets are independent (the threaded ABI passes both
9326/// r0..r3 and f0..f3), so each is ranked and capped at four on its own.
9327fn select_pins(ops: &[MicroOp], register_count: u16, region: bool) -> (Vec<u16>, Vec<u16>) {
9328    const BASE: i64 = 16;
9329    const CAP: u32 = 4;
9330    let depth = if region { loop_depths(ops) } else { Vec::new() };
9331    let weight = |i: usize| -> i64 {
9332        if region {
9333            BASE.pow(depth[i].min(CAP))
9334        } else {
9335            1
9336        }
9337    };
9338    // Every REAL call saves/restores each live pinned register (SysV makes
9339    // them caller-saved): call-heavy bodies (fib) lose to pinning while
9340    // loop-heavy bodies (gcd, nqueens' solver) win — charge each slot a
9341    // per-call penalty, frequency-weighted in regions (a call inside an
9342    // inner loop is far costlier than one at top level).
9343    let call_penalty: i64 = ops
9344        .iter()
9345        .enumerate()
9346        .filter(|(_, op)| {
9347            matches!(
9348                op,
9349                MicroOp::Call { .. } | MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. }
9350            )
9351        })
9352        .map(|(i, _)| 3 * weight(i))
9353        .sum();
9354    // FLOAT-slot set: every slot that ever holds an f64 VALUE. The float
9355    // arithmetic ops (AddF/SubF/MulF/DivF) carry floats in all three slots;
9356    // the float comparisons/branch carry floats only in the OPERANDS (their
9357    // dst is the Int 0/1 result); IntToFloat produces a float in dst from an
9358    // Int src; SqrtF and the fused float load produce/consume floats. A float
9359    // slot can only live in an XMM register, NEVER a GP one (the GP stencils
9360    // store raw i64 bits and the float arith reads `fN` directly), so EVERY
9361    // float slot is excluded from the GP budget below.
9362    //
9363    // A float slot is XMM-PINNABLE only when every op that touches it as a
9364    // float is XMM-aware: the V_FBINOP arith threads it through `fN`, and the
9365    // mem-form float ops (DivF, the float compares/branch, IntToFloat, SqrtF,
9366    // the fused load) spill/reload it around their frame-form stencils. The
9367    // register-form ops that resolve operands through the GP location only —
9368    // `LoadConst`, `Move`, and the function `Return` value — have NO XMM form,
9369    // so a float slot they touch must stay FRAME-resident (blocked from the
9370    // float-pin budget); the float arith then reads it from the frame (floc 0)
9371    // correctly. (`main_float_loop`: the `0.25` constant slot is a LoadConst
9372    // dst AND an AddF operand — float-valued but pin-blocked.)
9373    let mut float_slots: std::collections::HashSet<u16> = std::collections::HashSet::new();
9374    let mut float_blocked: std::collections::HashSet<u16> = std::collections::HashSet::new();
9375    let mark_float = |slot: u16, set: &mut std::collections::HashSet<u16>| {
9376        if slot < register_count {
9377            set.insert(slot);
9378        }
9379    };
9380    for op in ops {
9381        match *op {
9382            MicroOp::AddF { dst, lhs, rhs }
9383            | MicroOp::SubF { dst, lhs, rhs }
9384            | MicroOp::MulF { dst, lhs, rhs }
9385            | MicroOp::DivF { dst, lhs, rhs } => {
9386                for s in [dst, lhs, rhs] {
9387                    mark_float(s, &mut float_slots);
9388                }
9389            }
9390            MicroOp::LtF { lhs, rhs, .. }
9391            | MicroOp::GtF { lhs, rhs, .. }
9392            | MicroOp::LtEqF { lhs, rhs, .. }
9393            | MicroOp::GtEqF { lhs, rhs, .. }
9394            | MicroOp::EqF { lhs, rhs, .. }
9395            | MicroOp::NeqF { lhs, rhs, .. }
9396            | MicroOp::BranchF { lhs, rhs, .. } => {
9397                for s in [lhs, rhs] {
9398                    mark_float(s, &mut float_slots);
9399                }
9400            }
9401            MicroOp::IntToFloat { dst, .. } => mark_float(dst, &mut float_slots),
9402            MicroOp::SqrtF { dst, src } => {
9403                for s in [dst, src] {
9404                    mark_float(s, &mut float_slots);
9405                }
9406            }
9407            // FloorToInt/CeilToInt/RoundToInt: the SRC is a float (dst is an Int) — only the src wants an XMM pin.
9408            MicroOp::FloorToInt { src, .. }
9409            | MicroOp::CeilToInt { src, .. }
9410            | MicroOp::RoundToInt { src, .. } => mark_float(src, &mut float_slots),
9411            MicroOp::ArrLoad2F { dst, .. } => mark_float(dst, &mut float_slots),
9412            // A float value loaded from / stored to an array stays FRAME-RESIDENT
9413            // (block it from the XMM pin budget): the array access itself is
9414            // mem-form, so a pinned value would round-trip the frame anyway, and
9415            // the float-pin + mem-form-array interaction is not yet correct
9416            // (spectral_norm SIGSEGV). The array load/store still works mem-form.
9417            MicroOp::ArrLoad { dst, .. } => mark_float(dst, &mut float_blocked),
9418            MicroOp::ArrStore { src, .. } => mark_float(src, &mut float_blocked),
9419            // Register-form ops with no XMM lowering: a float slot they touch
9420            // is pin-blocked (it must read/write through the frame). `Move` is
9421            // NOT here — it threads XMM pins through V_FMOV (f→f, or frame↔f when
9422            // one end is unpinned), so a loop-carried float reassigned via `Set
9423            // acc to next` keeps its register (mandelbrot's `Set zr to zr2`).
9424            MicroOp::LoadConst { dst, .. } => mark_float(dst, &mut float_blocked),
9425            MicroOp::Return { src } => mark_float(src, &mut float_blocked),
9426            _ => {}
9427        }
9428    }
9429    // INTEGER-role slots: any slot read/written as an i64 by a non-float op —
9430    // int arithmetic, a branch/jump condition, an array index/pointer/length/
9431    // handle, an `IntToFloat` SOURCE, a map key/handle. A slot that is BOTH
9432    // float-valued (above) AND integer-role is a TYPE-REUSED scratch cell, and
9433    // must stay FRAME-resident (never float-pinned): the int stencil writes raw
9434    // i64 bits to its frame cell while a float pin would keep an f64 in an XMM
9435    // register, and the mem-form spill of the float pin clobbers the integer
9436    // the int op wrote. (spectral_norm SIGSEGV: a `MulF` result slot was reused
9437    // as an `ArrStore` index; the float-pin spill wrote f64 bits over the
9438    // integer index, so the store indexed through a garbage pointer.) Marking
9439    // the integer role into `float_blocked` blocks the pin; a pure-integer slot
9440    // is never in `float_slots`, so this is a no-op for it — only genuinely
9441    // mixed slots are forced frame-resident.
9442    for op in ops {
9443        match *op {
9444            MicroOp::Add { dst, lhs, rhs }
9445            | MicroOp::Sub { dst, lhs, rhs }
9446            | MicroOp::Mul { dst, lhs, rhs }
9447            | MicroOp::BitAnd { dst, lhs, rhs }
9448            | MicroOp::BitOr { dst, lhs, rhs }
9449            | MicroOp::BitXor { dst, lhs, rhs }
9450            | MicroOp::Shl { dst, lhs, rhs }
9451            | MicroOp::Shr { dst, lhs, rhs }
9452            | MicroOp::Ushr { dst, lhs, rhs }
9453            | MicroOp::Rotate { dst, lhs, rhs, .. }
9454            | MicroOp::Lt { dst, lhs, rhs }
9455            | MicroOp::Gt { dst, lhs, rhs }
9456            | MicroOp::LtEq { dst, lhs, rhs }
9457            | MicroOp::GtEq { dst, lhs, rhs }
9458            | MicroOp::Eq { dst, lhs, rhs }
9459            | MicroOp::Neq { dst, lhs, rhs }
9460            | MicroOp::Div { dst, lhs, rhs }
9461            | MicroOp::Mod { dst, lhs, rhs } => {
9462                for s in [dst, lhs, rhs] {
9463                    mark_float(s, &mut float_blocked);
9464                }
9465            }
9466            MicroOp::DivPow2 { dst, lhs, .. } | MicroOp::MagicDivU { dst, lhs, .. } => {
9467                for s in [dst, lhs] {
9468                    mark_float(s, &mut float_blocked);
9469                }
9470            }
9471            MicroOp::NotInt { dst, src } | MicroOp::NotBool { dst, src } => {
9472                for s in [dst, src] {
9473                    mark_float(s, &mut float_blocked);
9474                }
9475            }
9476            MicroOp::Branch { lhs, rhs, .. } => {
9477                for s in [lhs, rhs] {
9478                    mark_float(s, &mut float_blocked);
9479                }
9480            }
9481            MicroOp::JumpIfFalse { cond, .. } | MicroOp::JumpIfTrue { cond, .. } => {
9482                mark_float(cond, &mut float_blocked);
9483            }
9484            MicroOp::IntToFloat { src, .. } => mark_float(src, &mut float_blocked),
9485            // FloorToInt/CeilToInt/RoundToInt: the DST is an Int (mirror of IntToFloat's Int src) — block it
9486            // from float-pinning. The Float src is left free to live in an XMM pin (read there via `floc`).
9487            MicroOp::FloorToInt { dst, .. }
9488            | MicroOp::CeilToInt { dst, .. }
9489            | MicroOp::RoundToInt { dst, .. } => mark_float(dst, &mut float_blocked),
9490            MicroOp::ArrLoad {
9491                idx,
9492                ptr_slot,
9493                len_slot,
9494                ..
9495            } => {
9496                for s in [idx, ptr_slot, len_slot] {
9497                    mark_float(s, &mut float_blocked);
9498                }
9499            }
9500            MicroOp::ArrStore {
9501                idx,
9502                ptr_slot,
9503                len_slot,
9504                ..
9505            } => {
9506                for s in [idx, ptr_slot, len_slot] {
9507                    mark_float(s, &mut float_blocked);
9508                }
9509            }
9510            MicroOp::ArrRMW {
9511                idx,
9512                operand,
9513                ptr_slot,
9514                len_slot,
9515                ..
9516            } => {
9517                for s in [idx, operand, ptr_slot, len_slot] {
9518                    mark_float(s, &mut float_blocked);
9519                }
9520            }
9521            MicroOp::ArrCondSwap {
9522                idx1,
9523                idx2,
9524                ptr_slot,
9525                len_slot,
9526                ..
9527            } => {
9528                for s in [idx1, idx2, ptr_slot, len_slot] {
9529                    mark_float(s, &mut float_blocked);
9530                }
9531            }
9532            MicroOp::ArrSwap {
9533                idx1,
9534                idx2,
9535                ptr_slot,
9536                len_slot,
9537                ..
9538            } => {
9539                for s in [idx1, idx2, ptr_slot, len_slot] {
9540                    mark_float(s, &mut float_blocked);
9541                }
9542            }
9543            MicroOp::ArrLoad2F {
9544                i: ix,
9545                j: jx,
9546                ptr_slot,
9547                len_slot,
9548                ..
9549            } => {
9550                for s in [ix, jx, ptr_slot, len_slot] {
9551                    mark_float(s, &mut float_blocked);
9552                }
9553            }
9554            // The fused int two-load result is an i64; every operand and slot
9555            // is integer-role (block them from the float-pin budget, exactly
9556            // like the mem-form array ops).
9557            MicroOp::ArrLoad2 {
9558                dst,
9559                i: ix,
9560                j: jx,
9561                ptr_a,
9562                len_a,
9563                ptr_b,
9564                len_b,
9565                ..
9566            } => {
9567                for s in [dst, ix, jx, ptr_a, len_a, ptr_b, len_b] {
9568                    mark_float(s, &mut float_blocked);
9569                }
9570            }
9571            MicroOp::ArrPush {
9572                vec_slot,
9573                ptr_slot,
9574                len_slot,
9575                ..
9576            } => {
9577                for s in [vec_slot, ptr_slot, len_slot] {
9578                    mark_float(s, &mut float_blocked);
9579                }
9580            }
9581            MicroOp::NewList {
9582                vec_slot,
9583                ptr_slot,
9584                len_slot,
9585                ..
9586            } => {
9587                for s in [vec_slot, ptr_slot, len_slot] {
9588                    mark_float(s, &mut float_blocked);
9589                }
9590            }
9591            MicroOp::ListTriple {
9592                handle_slot,
9593                vec_slot,
9594                ptr_slot,
9595                len_slot,
9596                ..
9597            } => {
9598                for s in [handle_slot, vec_slot, ptr_slot, len_slot] {
9599                    mark_float(s, &mut float_blocked);
9600                }
9601            }
9602            MicroOp::MapGet { key, map_slot, .. } => {
9603                for s in [key, map_slot] {
9604                    mark_float(s, &mut float_blocked);
9605                }
9606            }
9607            MicroOp::MapSet { key, map_slot, .. } => {
9608                for s in [key, map_slot] {
9609                    mark_float(s, &mut float_blocked);
9610                }
9611            }
9612            MicroOp::MapHas {
9613                dst, key, map_slot, ..
9614            } => {
9615                for s in [dst, key, map_slot] {
9616                    mark_float(s, &mut float_blocked);
9617                }
9618            }
9619            // A host call's helper reads and writes integer frame slots.
9620            MicroOp::Host {
9621                dst, src, count, ..
9622            } => {
9623                for s in std::iter::once(dst).chain(src..src + count) {
9624                    mark_float(s, &mut float_blocked);
9625                }
9626            }
9627            _ => {}
9628        }
9629    }
9630    let mut profit: std::collections::HashMap<u16, i64> = std::collections::HashMap::new();
9631    let bump = |slot: u16, delta: i64, profit: &mut std::collections::HashMap<u16, i64>| {
9632        if slot < register_count {
9633            *profit.entry(slot).or_insert(0) += delta;
9634        }
9635    };
9636    for (i, op) in ops.iter().enumerate() {
9637        // Variant uses save a memory access (+); mem-form uses force a
9638        // spill (−). Each scaled by execution frequency (loop depth).
9639        let v = 2 * weight(i);
9640        let mv = 1 * weight(i);
9641        let m = -4 * weight(i);
9642        match *op {
9643            MicroOp::Add { dst, lhs, rhs }
9644            | MicroOp::Sub { dst, lhs, rhs }
9645            | MicroOp::Mul { dst, lhs, rhs }
9646            | MicroOp::BitAnd { dst, lhs, rhs }
9647            | MicroOp::BitOr { dst, lhs, rhs }
9648            | MicroOp::BitXor { dst, lhs, rhs }
9649            | MicroOp::Shl { dst, lhs, rhs }
9650            | MicroOp::Shr { dst, lhs, rhs }
9651            | MicroOp::Ushr { dst, lhs, rhs }
9652            | MicroOp::Rotate { dst, lhs, rhs, .. }
9653            | MicroOp::Lt { dst, lhs, rhs }
9654            | MicroOp::Gt { dst, lhs, rhs }
9655            | MicroOp::LtEq { dst, lhs, rhs }
9656            | MicroOp::GtEq { dst, lhs, rhs }
9657            | MicroOp::Eq { dst, lhs, rhs }
9658            | MicroOp::Neq { dst, lhs, rhs } => {
9659                for s in [dst, lhs, rhs] {
9660                    bump(s, v, &mut profit);
9661                }
9662            }
9663            MicroOp::Branch { lhs, rhs, .. } => {
9664                for s in [lhs, rhs] {
9665                    bump(s, v, &mut profit);
9666                }
9667            }
9668            MicroOp::Move { dst, src } => {
9669                for s in [dst, src] {
9670                    bump(s, mv, &mut profit);
9671                }
9672            }
9673            MicroOp::LoadConst { dst, .. } => bump(dst, mv, &mut profit),
9674            MicroOp::Return { src } => bump(src, mv, &mut profit),
9675            MicroOp::JumpIfFalse { cond, .. } | MicroOp::JumpIfTrue { cond, .. } => {
9676                bump(cond, -3 * weight(i), &mut profit);
9677            }
9678            MicroOp::Div { dst, lhs, rhs } | MicroOp::Mod { dst, lhs, rhs } => {
9679                for s in [dst, lhs, rhs] {
9680                    bump(s, m, &mut profit);
9681                }
9682            }
9683            // DivPow2 is a single mem-form stencil (reads lhs, writes dst).
9684            // MagicDivU bails the pinned/function tier (no stencil), but its
9685            // operands still profit from residency on the regalloc path.
9686            MicroOp::DivPow2 { dst, lhs, .. } | MicroOp::MagicDivU { dst, lhs, .. } => {
9687                for s in [dst, lhs] {
9688                    bump(s, m, &mut profit);
9689                }
9690            }
9691            // Float add/sub/mul are register-threaded now (V_FBINOP) → variant.
9692            MicroOp::AddF { dst, lhs, rhs }
9693            | MicroOp::SubF { dst, lhs, rhs }
9694            | MicroOp::MulF { dst, lhs, rhs } => {
9695                for s in [dst, lhs, rhs] {
9696                    bump(s, v, &mut profit);
9697                }
9698            }
9699            // DivF is register-threaded now (V_DIVF) → variant. The float
9700            // comparisons have no XMM variant yet → mem-form.
9701            MicroOp::DivF { dst, lhs, rhs } => {
9702                for s in [dst, lhs, rhs] {
9703                    bump(s, v, &mut profit);
9704                }
9705            }
9706            MicroOp::LtF { dst, lhs, rhs }
9707            | MicroOp::GtF { dst, lhs, rhs }
9708            | MicroOp::LtEqF { dst, lhs, rhs }
9709            | MicroOp::GtEqF { dst, lhs, rhs }
9710            | MicroOp::EqF { dst, lhs, rhs }
9711            | MicroOp::NeqF { dst, lhs, rhs } => {
9712                for s in [dst, lhs, rhs] {
9713                    bump(s, m, &mut profit);
9714                }
9715            }
9716            // BranchF is register-threaded now (V_BRANCHF) → variant.
9717            MicroOp::BranchF { lhs, rhs, .. } => {
9718                for s in [lhs, rhs] {
9719                    bump(s, v, &mut profit);
9720                }
9721            }
9722            // SqrtF is register-threaded now (V_SQRTF) → variant.
9723            MicroOp::SqrtF { dst, src } => {
9724                for s in [dst, src] {
9725                    bump(s, v, &mut profit);
9726                }
9727            }
9728            // IntToFloat is register-threaded now (V_I2F) → variant.
9729            MicroOp::IntToFloat { dst, src } => {
9730                for s in [dst, src] {
9731                    bump(s, v, &mut profit);
9732                }
9733            }
9734            // FloorToInt/CeilToInt/RoundToInt are register-threaded (V_FLOORF/V_CEILF/V_ROUNDF): float src, int dst.
9735            MicroOp::FloorToInt { dst, src }
9736            | MicroOp::CeilToInt { dst, src }
9737            | MicroOp::RoundToInt { dst, src } => {
9738                for s in [dst, src] {
9739                    bump(s, v, &mut profit);
9740                }
9741            }
9742            MicroOp::NotInt { dst, src }
9743            | MicroOp::NotBool { dst, src }
9744            | MicroOp::Popcnt { dst, src }
9745            | MicroOp::Lzcnt { dst, src }
9746            | MicroOp::Tzcnt { dst, src }
9747            | MicroOp::ChrGuard { dst, src }
9748            | MicroOp::Utf8Len { dst, src } => {
9749                for s in [dst, src] {
9750                    bump(s, m, &mut profit);
9751                }
9752            }
9753            MicroOp::ArrLoad {
9754                dst,
9755                idx,
9756                ptr_slot,
9757                len_slot,
9758                ..
9759            } => {
9760                for s in [dst, idx, ptr_slot, len_slot] {
9761                    bump(s, m, &mut profit);
9762                }
9763            }
9764            MicroOp::ArrLoadAffine {
9765                dst,
9766                a,
9767                b,
9768                ptr_slot,
9769                len_slot,
9770                ..
9771            } => {
9772                for s in [dst, a, b, ptr_slot, len_slot] {
9773                    bump(s, m, &mut profit);
9774                }
9775            }
9776            MicroOp::ArrLoad2F {
9777                dst,
9778                i: ix,
9779                j: jx,
9780                ptr_slot,
9781                len_slot,
9782                ..
9783            } => {
9784                for s in [dst, ix, jx, ptr_slot, len_slot] {
9785                    bump(s, m, &mut profit);
9786                }
9787            }
9788            MicroOp::ArrLoad2 {
9789                dst,
9790                i: ix,
9791                j: jx,
9792                ptr_a,
9793                len_a,
9794                ptr_b,
9795                len_b,
9796                ..
9797            } => {
9798                for s in [dst, ix, jx, ptr_a, len_a, ptr_b, len_b] {
9799                    bump(s, m, &mut profit);
9800                }
9801            }
9802            MicroOp::ArrStore {
9803                src,
9804                idx,
9805                ptr_slot,
9806                len_slot,
9807                ..
9808            } => {
9809                for s in [src, idx, ptr_slot, len_slot] {
9810                    bump(s, m, &mut profit);
9811                }
9812            }
9813            MicroOp::ArrRMW {
9814                idx,
9815                operand,
9816                ptr_slot,
9817                len_slot,
9818                ..
9819            } => {
9820                for s in [idx, operand, ptr_slot, len_slot] {
9821                    bump(s, m, &mut profit);
9822                }
9823            }
9824            MicroOp::ArrCondSwap {
9825                idx1,
9826                idx2,
9827                ptr_slot,
9828                len_slot,
9829                ..
9830            } => {
9831                for s in [idx1, idx2, ptr_slot, len_slot] {
9832                    bump(s, m, &mut profit);
9833                }
9834            }
9835            MicroOp::ArrSwap {
9836                idx1,
9837                idx2,
9838                ptr_slot,
9839                len_slot,
9840                ..
9841            } => {
9842                for s in [idx1, idx2, ptr_slot, len_slot] {
9843                    bump(s, m, &mut profit);
9844                }
9845            }
9846            // FmaF is introduced AFTER pin selection, so this arm never executes
9847            // at runtime — it exists only to keep the match exhaustive. Treat it
9848            // as a mem-form op for completeness.
9849            MicroOp::FmaF { dst, a, b, c } => {
9850                for s in [dst, a, b, c] {
9851                    bump(s, m, &mut profit);
9852                }
9853            }
9854            MicroOp::ArrPush {
9855                src,
9856                vec_slot,
9857                ptr_slot,
9858                len_slot,
9859                ..
9860            } => {
9861                for s in [src, vec_slot, ptr_slot, len_slot] {
9862                    bump(s, m, &mut profit);
9863                }
9864            }
9865            MicroOp::ListClear {
9866                vec_slot,
9867                ptr_slot,
9868                len_slot,
9869                ..
9870            } => {
9871                for s in [vec_slot, ptr_slot, len_slot] {
9872                    bump(s, m, &mut profit);
9873                }
9874            }
9875            // The str-append's byte or Int source is read across a SysV call (mem-form);
9876            // the handle slot is forced frame-resident, so count both as mem-form.
9877            MicroOp::StrAppend {
9878                text_handle_slot,
9879                src,
9880                ..
9881            } => {
9882                bump(text_handle_slot, m, &mut profit);
9883                if let Some(s) = src.slot() {
9884                    bump(s, m, &mut profit);
9885                }
9886            }
9887            MicroOp::Call { dst, .. } | MicroOp::CallSelf { dst, .. } => bump(dst, m, &mut profit),
9888            MicroOp::CallSelfCopy {
9889                dst,
9890                src_start,
9891                arg_count,
9892                ..
9893            } => {
9894                bump(dst, m, &mut profit);
9895                for s in src_start..src_start + arg_count {
9896                    bump(s, m, &mut profit);
9897                }
9898            }
9899            MicroOp::MapGet {
9900                dst, key, map_slot, ..
9901            } => {
9902                for s in [dst, key, map_slot] {
9903                    bump(s, m, &mut profit);
9904                }
9905            }
9906            MicroOp::MapSet {
9907                src, key, map_slot, ..
9908            } => {
9909                for s in [src, key, map_slot] {
9910                    bump(s, m, &mut profit);
9911                }
9912            }
9913            MicroOp::MapHas {
9914                dst, key, map_slot, ..
9915            } => {
9916                for s in [dst, key, map_slot] {
9917                    bump(s, m, &mut profit);
9918                }
9919            }
9920            MicroOp::Host {
9921                dst, src, count, ..
9922            } => {
9923                for s in std::iter::once(dst).chain(src..src + count) {
9924                    bump(s, m, &mut profit);
9925                }
9926            }
9927            MicroOp::NewList {
9928                vec_slot,
9929                ptr_slot,
9930                len_slot,
9931                ..
9932            } => {
9933                for s in [vec_slot, ptr_slot, len_slot] {
9934                    bump(s, m, &mut profit);
9935                }
9936            }
9937            MicroOp::ListTriple {
9938                handle_slot,
9939                vec_slot,
9940                ptr_slot,
9941                len_slot,
9942                ..
9943            } => {
9944                for s in [handle_slot, vec_slot, ptr_slot, len_slot] {
9945                    bump(s, m, &mut profit);
9946                }
9947            }
9948            // A MemMem region runs UNPINNED (it reads/writes every slot through
9949            // the frame in the helper); count every touched slot as mem-form so
9950            // none would be selected even if the no-pin gate were ever lifted.
9951            MicroOp::MemMem {
9952                h_ptr_slot,
9953                h_len_slot,
9954                n_ptr_slot,
9955                n_len_slot,
9956                needle_len_slot,
9957                i_slot,
9958                count_slot,
9959                ..
9960            } => {
9961                for s in [
9962                    h_ptr_slot,
9963                    h_len_slot,
9964                    n_ptr_slot,
9965                    n_len_slot,
9966                    needle_len_slot,
9967                    i_slot,
9968                    count_slot,
9969                ] {
9970                    bump(s, m, &mut profit);
9971                }
9972            }
9973            MicroOp::Jump { .. } => {}
9974        }
9975    }
9976    // Threshold: flat model wants any net win (>2, historical); the region
9977    // model wants at least one depth-1 net benefit (>BASE) so cold depth-0
9978    // slots never pin.
9979    let threshold = if region { BASE } else { 2 };
9980    let ranked: Vec<(u16, i64)> = {
9981        let mut r: Vec<(u16, i64)> = profit
9982            .into_iter()
9983            .map(|(s, p)| (s, p - call_penalty))
9984            .filter(|&(_, p)| p > threshold)
9985            .collect();
9986        r.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
9987        r
9988    };
9989    // Split by budget: a float slot can only ride an XMM register, an int/bool
9990    // slot only a GP register; each budget independently takes its four best. A
9991    // float slot that is pin-blocked (touched by a register-form op with no XMM
9992    // lowering) gets NO pin — it stays frame-resident — but is still kept out
9993    // of the GP budget (its value is f64 bits the GP stencils would mishandle).
9994    let mut gp_pins: Vec<u16> = Vec::new();
9995    let mut float_pins: Vec<u16> = Vec::new();
9996    // A float pin lives in a caller-saved XMM register, threaded through the
9997    // stencil chain by the register-form float ops (AddF/SubF/MulF). It is only
9998    // sound in a REGION when EVERY op on its live range provably leaves the
9999    // other live XMM pins alone behind the chain's back — otherwise a pin is
10000    // clobbered and memory corrupts (spectral_norm SIGSEGV'd at tier-up: its
10001    // inner loop kept the float product in a pinned XMM across both the `aVal`
10002    // CALL, when un-inlined, and the inlined `1.0/denom` DivF + IntToFloat).
10003    // Rather than blocklist the clobbering ops — which silently misses any new
10004    // one — WHITELIST the ops proven NOT to disturb a live float pin:
10005    // register-form float arith (AddF/SubF/MulF and the fused float load), the
10006    // array load/store stencils, the mem-form float stencils that spill/reload
10007    // only the slot THEY touch (DivF/SqrtF/IntToFloat/BranchF and — Lever 2a —
10008    // the float ORDERING compares LtF/LtEqF/GtF/GtEqF), and the pure integer/
10009    // pointer/control ops (no XMM at all). ANYTHING else blocks: a call or
10010    // helper-call (Call/CallSelf/Map*/NewList/ListTriple/ArrPush — all wipe the
10011    // caller-saved xmm0–15). Float EQUALITY (EqF/NeqF) is NOT whitelisted here —
10012    // it stays on its (epsilon-correct) mem-form path but a region carrying it
10013    // still drops its float pins, a pre-existing limitation outside Lever 2a's
10014    // ordering-only scope. A MicroOp variant added later is unmatched and so
10015    // blocks by default: sound until it is classified. GP pins and the function
10016    // tier are unaffected.
10017    let xmm_pin_safe = |op: &MicroOp| {
10018        matches!(
10019            op,
10020            MicroOp::LoadConst { .. }
10021                | MicroOp::Move { .. }
10022                | MicroOp::Add { .. }
10023                | MicroOp::Sub { .. }
10024                | MicroOp::Mul { .. }
10025                | MicroOp::Div { .. }
10026                | MicroOp::DivPow2 { .. }
10027                | MicroOp::MagicDivU { .. }
10028                | MicroOp::Mod { .. }
10029                | MicroOp::Lt { .. }
10030                | MicroOp::Gt { .. }
10031                | MicroOp::Eq { .. }
10032                | MicroOp::LtEq { .. }
10033                | MicroOp::GtEq { .. }
10034                | MicroOp::Neq { .. }
10035                | MicroOp::Branch { .. }
10036                | MicroOp::BitAnd { .. }
10037                | MicroOp::BitOr { .. }
10038                | MicroOp::BitXor { .. }
10039                | MicroOp::Shl { .. }
10040                | MicroOp::Shr { .. }
10041                | MicroOp::Ushr { .. }
10042                | MicroOp::Rotate { .. }
10043                | MicroOp::NotInt { .. }
10044                | MicroOp::NotBool { .. }
10045                | MicroOp::AddF { .. }
10046                | MicroOp::SubF { .. }
10047                | MicroOp::MulF { .. }
10048                | MicroOp::DivF { .. }
10049                | MicroOp::SqrtF { .. }
10050                | MicroOp::IntToFloat { .. }
10051                | MicroOp::FloorToInt { .. }
10052                | MicroOp::CeilToInt { .. }
10053                | MicroOp::RoundToInt { .. }
10054                | MicroOp::BranchF { .. }
10055                | MicroOp::LtF { .. }
10056                | MicroOp::LtEqF { .. }
10057                | MicroOp::GtF { .. }
10058                | MicroOp::GtEqF { .. }
10059                | MicroOp::ArrLoad { .. }
10060                | MicroOp::ArrLoad2F { .. }
10061                | MicroOp::ArrLoad2 { .. }
10062                | MicroOp::ArrStore { .. }
10063                | MicroOp::ArrRMW { .. }
10064                | MicroOp::ArrCondSwap { .. }
10065                | MicroOp::ArrSwap { .. }
10066                | MicroOp::FmaF { .. }
10067                | MicroOp::Jump { .. }
10068                | MicroOp::JumpIfFalse { .. }
10069                | MicroOp::JumpIfTrue { .. }
10070                | MicroOp::Return { .. }
10071        )
10072    };
10073    // LEVER 3 (fusion-aware pin selection): a float slot that is the RESULT `d`
10074    // of an `AddF` which `fuse_fma` will collapse into an `FmaF` — its product
10075    // operand is the single-use, un-named result of an immediately-preceding
10076    // `MulF` — is KEPT OUT of the float-pin budget. `fuse_fma` runs after pin
10077    // selection; a mem-form `FmaF` writing a PINNED `d` must reload that pin from
10078    // the frame afterwards (one extra piece), which exactly cancels the dispatch
10079    // the fusion saved. Leaving `d` frame-resident lets the `FmaF` write the
10080    // frame directly with NO reload — a true 2-pieces-to-1 win (the nbody
10081    // distance-sum's `dz*dz + partial`, whose single-use partial-sum was
10082    // wastefully pinned). Frame traffic on this temp is L1-free next to the
10083    // saved dispatch (the engine is per-op DISPATCH-bound). Excluding a slot
10084    // that turns out NOT to fuse is at worst neutral (one un-pinned float temp).
10085    // The product `t` is read by the AddF being removed; if `t` were pinned the
10086    // fusion would not fire, so it is left to its own pin eligibility.
10087    let mut fma_result_temps: std::collections::HashSet<u16> = std::collections::HashSet::new();
10088    {
10089        let mut read_counts: std::collections::HashMap<u16, usize> =
10090            std::collections::HashMap::new();
10091        for op in ops {
10092            for s in micro_read_slots(op) {
10093                *read_counts.entry(s).or_insert(0) += 1;
10094            }
10095        }
10096        for k in 0..ops.len().saturating_sub(1) {
10097            let MicroOp::MulF { dst: t, .. } = ops[k] else {
10098                continue;
10099            };
10100            // The addend `c` is the AddF operand that is NOT the product `t`.
10101            let (d, c) = match ops[k + 1] {
10102                MicroOp::AddF { dst, lhs, rhs } if lhs == t => (dst, rhs),
10103                MicroOp::AddF { dst, lhs, rhs } if rhs == t => (dst, lhs),
10104                _ => continue,
10105            };
10106            // The ACCUMULATOR shape `s = s + a*b` (`c == d`) is NOT a Lever-3
10107            // candidate: there `d` is a loop-carried float that must stay pinned,
10108            // and Lever 1a deliberately refuses to fuse it (a pinned addend `c`
10109            // would have to be spilled). Only a result `d` DISTINCT from its
10110            // addend is the genuine throwaway partial-sum the FmaF absorbs.
10111            if d == c {
10112                continue;
10113            }
10114            // `t` is single-use scratch (only the AddF reads it) — `fuse_fma`'s
10115            // removability precondition for the product (named `t`s are rejected
10116            // there too, but excluding their `d` here is at worst neutral: one
10117            // un-pinned float temp, free next to the per-op dispatch).
10118            let t_dead = (t as usize) < register_count as usize
10119                && read_counts.get(&t).copied().unwrap_or(0) == 1;
10120            if t_dead {
10121                fma_result_temps.insert(d);
10122            }
10123        }
10124    }
10125    // XMM float pinning is enabled for Main-loop REGIONS whose ops are all
10126    // XMM-aware. Array regions are now admitted: the earlier spectral_norm
10127    // SIGSEGV was a TYPE-REUSED slot (a `MulF` result reused as an `ArrStore`
10128    // index) being float-pinned — fixed above by blocking every integer-role
10129    // slot from the float-pin budget, so a mem-form array op never spills an
10130    // f64 over an integer index. FUNCTIONS still keep their floats frame-
10131    // resident (the mode-B call boundary round-trips them anyway).
10132    let block_float_pins = !region || !ops.iter().all(xmm_pin_safe);
10133    // GP analog of `float_blocked`: a frame-reading INT stencil (NotInt/Popcnt/Lzcnt/Tzcnt) reads its
10134    // SOURCE from the frame slot, so a GP-pinned source (e.g. a hot induction variable in a
10135    // `count_ones(k)` loop) would leave that slot stale and the frame stencil would read the wrong value.
10136    // Force such a source to stay frame-resident by keeping it out of the GP-pin budget — always sound
10137    // (the frame is the source of truth), and it fixes a latent NotInt hazard too. (When a source IS
10138    // pinned anyway, the register-form `V_POPCNT`/`V_LZCNT`/`V_TZCNT` reads the pin directly, so
10139    // correctness never depends on this — it just keeps the fast frame stencil applicable.)
10140    let mut gp_blocked: std::collections::HashSet<u16> = std::collections::HashSet::new();
10141    for op in ops {
10142        if let MicroOp::NotInt { src, .. }
10143        | MicroOp::Popcnt { src, .. }
10144        | MicroOp::Lzcnt { src, .. }
10145        | MicroOp::Tzcnt { src, .. }
10146        | MicroOp::ChrGuard { src, .. }
10147        | MicroOp::Utf8Len { src, .. } = *op
10148        {
10149            gp_blocked.insert(src);
10150        }
10151    }
10152    for (slot, _) in ranked {
10153        if float_slots.contains(&slot) {
10154            if !block_float_pins
10155                && !float_blocked.contains(&slot)
10156                && !fma_result_temps.contains(&slot)
10157                && float_pins.len() < 6
10158            {
10159                float_pins.push(slot);
10160            }
10161        } else if gp_pins.len() < 4 && !gp_blocked.contains(&slot) {
10162            gp_pins.push(slot);
10163        }
10164    }
10165    (gp_pins, float_pins)
10166}
10167
10168impl NativeTier for ForgeTier {
10169    fn compile_function(
10170        &self,
10171        code: &[Op],
10172        entry_pc: usize,
10173        constants: &[Constant],
10174        enums: &[EnumTypeDef],
10175        param_count: u16,
10176        register_count: u16,
10177        self_fi: u16,
10178        param_kinds: &[Option<ParamKind>],
10179        cow_exempt_regs: &[u16],
10180        ret_kind: Option<SlotKind>,
10181        ctx: &NativeCtx,
10182        callees: &[CalleeSig],
10183    ) -> Option<Box<dyn NativeFn>> {
10184        self.compiles.fetch_add(1, Ordering::SeqCst);
10185        // The frame layout (and therefore the limit slot the Call micros
10186        // bake) depends on the mode — compute it before adapting, with
10187        // EXACTLY the adapter's pin accounting (params + allocation sites
10188        // + list-returning self-call results); the adapter asserts the
10189        // agreement.
10190        let (list_mode, nodes) = function_lanes(code, param_kinds);
10191        // `LOGOS_JIT_NODES=0` keeps every function that handles enum values on the VM.
10192        if nodes && std::env::var("LOGOS_JIT_NODES").as_deref() == Ok("0") {
10193            self.note_function_decline("enum-tier-disabled");
10194            return None;
10195        }
10196        let mode_b = list_mode || nodes;
10197        let fn_returns_lists = ret_kind.is_none() && list_mode;
10198        let list_param_regs: Vec<u16> = param_kinds
10199            .iter()
10200            .enumerate()
10201            .filter_map(|(i, k)| matches!(k, Some(ParamKind::List(_))).then_some(i as u16))
10202            .collect();
10203        let npins = discover_list_regs(
10204            code,
10205            &list_param_regs,
10206            fn_returns_lists,
10207            self_fi,
10208            register_count as usize + 2,
10209        )
10210        .iter()
10211        .filter(|&&b| b)
10212        .count();
10213        let scope_exports = function_scope_export_slots(code, param_count, nodes);
10214        let frame_size =
10215            function_frame_size(register_count as usize, mode_b, npins, nodes, scope_exports);
10216        if frame_size > u16::MAX as usize {
10217            self.note_function_decline("frame-slots-overflow");
10218            return None;
10219        }
10220        // Self-recursion advances one full frame per level and stages the
10221        // callee window BEFORE the depth check runs — the arena must hold
10222        // MAX_CALL_DEPTH + 1 frames so staging writes can never cross the
10223        // buffer even on the deopt path.
10224        let arena_slots = frame_size * (logicaffeine_compile::semantics::MAX_CALL_DEPTH + 1);
10225        if arena_slots > ARENA_SLOTS {
10226            jt("arena");
10227            self.note_function_decline("arena-frame-too-large");
10228            return None;
10229        }
10230        let call_ctx = CallCtx {
10231            table_addr: ctx.table.slot_addr(self_fi as usize),
10232            depth_addr: std::sync::Arc::as_ptr(&ctx.depth) as i64,
10233            status_addr: std::sync::Arc::as_ptr(&ctx.status) as i64,
10234            limit_slot: (frame_size - 1) as u16,
10235            depth_limit: logicaffeine_compile::semantics::MAX_CALL_DEPTH as i64,
10236            self_fi,
10237            table: ctx.table.as_ref(),
10238            callees,
10239        };
10240        let Some(adapted) = adapt_function(
10241            code,
10242            entry_pc,
10243            constants,
10244            enums,
10245            param_count,
10246            register_count,
10247            self_fi,
10248            param_kinds,
10249            cow_exempt_regs,
10250            ret_kind,
10251            &call_ctx,
10252            callees,
10253        ) else {
10254            self.note_function_decline("unsupported-bytecode-shape");
10255            return None;
10256        };
10257        if std::env::var_os("LOGOS_JIT_TRACE_OPS").is_some() {
10258            eprintln!(
10259                "jit-trace: compile fn={self_fi} entry={entry_pc} mode_b={mode_b} ops={:?}",
10260                adapted.micro,
10261            );
10262        }
10263        debug_assert_eq!(adapted.frame_size, frame_size);
10264        // LINEAR SCAN (EXODIA 3.1), mode A only: mode B's precise deopt
10265        // reads the frame mid-run, which the pinning contract forbids.
10266        // Profit = variant-family uses − spill/reload churn at memory-form
10267        // ops − the prologue reload; the four best positive slots pin.
10268        // The value-form float `>`/`>=` compares (`GtF`/`GtEqF`) now have a
10269        // mem-form lowering (Lever 2a: swap operands, reuse the LtF/LeF stencil —
10270        // IEEE-exact, NaN-false), so they spill/reload their pinned operands like
10271        // any mem-form op and no longer force the whole function unpinned.
10272        // `ListClear` is still excluded: the mem-form emitter cannot lower it
10273        // without leaving a pinned ptr/len register stale (it would miscompile —
10274        // observed on knapsack).
10275        let pinnable = !adapted
10276            .micro
10277            .iter()
10278            .any(|op| matches!(op, MicroOp::ListClear { .. }));
10279        // WS-G WAVE 12: the CONTIGUOUS regalloc FUNCTION backend. For a
10280        // non-precise mode-A function whose every op (the self-calls included)
10281        // is in the backend's supported subset, emit ONE register-allocated
10282        // x86-64 function with a real SysV self-call — 4-6x faster than the
10283        // per-piece tier on the recursion cluster. Returns None on any
10284        // unsupported op (a cross-function Call, list/map/byte ops, …), in which
10285        // case we fall through to the pinned per-piece tier, byte-identical to
10286        // today. The self-entry patch is INTERNAL (an entry cell), so the
10287        // stencil patch path below is skipped for this chain. `LOGOS_REGALLOC=0`
10288        // is the kill-switch.
10289        #[cfg(target_arch = "x86_64")]
10290        let regalloc_enabled = logicaffeine_forge::regalloc::regalloc_enabled()
10291            && !std::env::var("LOGOS_JIT_REGALLOC").is_ok_and(|v| v == "0");
10292        #[cfg(target_arch = "x86_64")]
10293        let regalloc_chain: Option<CompiledChain> = if !regalloc_enabled {
10294            None
10295        } else if adapted.precise.is_none() {
10296            // MODE A (scalar, classic replay deopt): the original contiguous
10297            // FUNCTION backend.
10298            logicaffeine_forge::regalloc::compile_function_regalloc(
10299                &adapted.micro,
10300                Some(ctx.status.clone()),
10301                call_ctx.depth_addr,
10302            )
10303        } else if std::env::var("LOGOS_REGALLOC_PRECISE").as_deref() != Ok("0") {
10304            // MODE B (list-param, in-place array mutation): the PRECISE
10305            // contiguous backend — a side exit materializes the native frame and
10306            // resumes AT the faulting op (no replay-from-head double-apply). Only
10307            // when the adapter built the per-op deopt-code table. `None` on any
10308            // unsupported op (e.g. a list-RETURN allocation/Map shape) → fall back
10309            // to the per-piece precise stencil tier, byte-identical to today.
10310            // `LOGOS_REGALLOC_PRECISE=0` is the targeted kill-switch.
10311            adapted.deopt_codes.as_deref().and_then(|codes| {
10312                logicaffeine_forge::regalloc::compile_function_regalloc_precise(
10313                    &adapted.micro,
10314                    Some(ctx.status.clone()),
10315                    call_ctx.depth_addr,
10316                    codes,
10317                )
10318            })
10319        } else {
10320            None
10321        };
10322        #[cfg(not(target_arch = "x86_64"))]
10323        let regalloc_chain: Option<CompiledChain> = None;
10324
10325        let chain = if let Some(c) = regalloc_chain {
10326            self.regalloc_functions.fetch_add(1, Ordering::SeqCst);
10327            // A `CallSelfCopy` in the stream is a FUSED contiguous-arg self-call
10328            // (Lever A's fusion, decided by the adapter) — the regalloc backend
10329            // stages the contiguous arg block in one go just like the stencil
10330            // tier did, so it remains the same observable. Count it (the
10331            // kill-switch path emits per-`Move` `CallSelf` instead, leaving this
10332            // at zero).
10333            let fused = adapted
10334                .micro
10335                .iter()
10336                .filter(|op| matches!(op, MicroOp::CallSelfCopy { .. }))
10337                .count() as u32;
10338            if fused != 0 {
10339                self.pinned_self_calls.fetch_add(fused, Ordering::SeqCst);
10340            }
10341            c
10342        } else {
10343            let (gp_pins, float_pins): (Vec<u16>, Vec<u16>) = if pinnable
10344                && adapted.precise.is_none()
10345                && !std::env::var("LOGOS_JIT_REGALLOC").is_ok_and(|v| v == "0")
10346            {
10347                select_pins(&adapted.micro, register_count, false)
10348            } else {
10349                (Vec::new(), Vec::new())
10350            };
10351            let built = if gp_pins.is_empty() && float_pins.is_empty() {
10352                compile_straightline_coded(
10353                    &adapted.micro,
10354                    Some(ctx.status.clone()),
10355                    adapted.deopt_codes.as_deref(),
10356                    call_ctx.depth_addr,
10357                )
10358            } else {
10359                compile_straightline_pinned_float(
10360                    &adapted.micro,
10361                    &gp_pins,
10362                    &float_pins,
10363                    Some(ctx.status.clone()),
10364                )
10365            };
10366            let chain = match built {
10367                Ok(chain) => chain,
10368                Err(_) => {
10369                    self.note_function_decline("machine-code-lowering-failed");
10370                    return None;
10371                }
10372            };
10373            if !gp_pins.is_empty() || !float_pins.is_empty() {
10374                self.pinned_register_compiles
10375                    .fetch_add(1, Ordering::Relaxed);
10376            }
10377            // Self-entry patch: write this chain's base into every direct
10378            // self-call site. Targets without post-seal patching (MAP_JIT)
10379            // fail here — fall back to bytecode rather than run unpatched.
10380            if chain.has_patch_marks() && chain.patch_marked(chain.base()).is_err() {
10381                self.note_function_decline("self-call-patch-failed");
10382                return None;
10383            }
10384            let fused = adapted
10385                .micro
10386                .iter()
10387                .filter(|op| matches!(op, MicroOp::CallSelfCopy { .. }))
10388                .count() as u32;
10389            if fused != 0 {
10390                self.pinned_self_calls.fetch_add(fused, Ordering::SeqCst);
10391            }
10392            chain
10393        };
10394        if std::env::var_os("LOGOS_JIT_TRACE_OPS").is_some() {
10395            eprintln!(
10396                "jit-trace: compiled fn={self_fi} entry={:#x} slot={:#x}",
10397                chain.base(),
10398                call_ctx.table_addr,
10399            );
10400        }
10401        self.successes.fetch_add(1, Ordering::SeqCst);
10402        let rotates = adapted
10403            .micro
10404            .iter()
10405            .filter(|op| matches!(op, MicroOp::Rotate { .. }))
10406            .count() as u32;
10407        if rotates != 0 {
10408            self.native_rotate_instructions
10409                .fetch_add(rotates, Ordering::Relaxed);
10410        }
10411        Some(Box::new(ChainFn {
10412            chain,
10413            function_index: self_fi,
10414            limit_slot: call_ctx.limit_slot as usize,
10415            arena_slots,
10416            depth: ctx.depth.clone(),
10417            ret: adapted.ret,
10418            ret_elem: adapted.ret_elem,
10419            published_regc: (frame_size - 3) as i64,
10420            precise: adapted.precise,
10421            stats: self.runtime.clone(),
10422            _shapes: adapted.shapes,
10423            param_kinds: param_kinds.to_vec(),
10424        }))
10425    }
10426
10427    fn compile_region(
10428        &self,
10429        code: &[Op],
10430        head_pc: usize,
10431        exit_pc: usize,
10432        constants: &[Constant],
10433        register_count: u16,
10434        named: &[bool],
10435        observed: &[ObservedKind],
10436        ctx: &NativeCtx,
10437        callees: &[logicaffeine_compile::vm::CalleeSig],
10438    ) -> Option<Box<dyn RegionFn>> {
10439        self.region_compiles.fetch_add(1, Ordering::SeqCst);
10440        let dbg = std::env::var_os("LOGOS_RDIAG").is_some();
10441        let Some((
10442            mut micro,
10443            frame_size,
10444            guard,
10445            free,
10446            writes,
10447            arrays,
10448            region_return,
10449            hoist_guards,
10450            precise,
10451        )) = adapt_region(
10452            code,
10453            head_pc,
10454            exit_pc,
10455            constants,
10456            register_count,
10457            named,
10458            observed,
10459            ctx,
10460            callees,
10461        )
10462        else {
10463            let has_push = code.iter().any(|op| matches!(op, Op::ListPush { .. }));
10464            let has_call = code.iter().any(|op| matches!(op, Op::Call { .. }));
10465            let has_fresh_list_return_call = code.iter().any(|op| match op {
10466                Op::Call { func, .. } => callees
10467                    .get(*func as usize)
10468                    .is_some_and(|sig| sig.ret.is_none() && !sig.returns_list_param),
10469                _ => false,
10470            });
10471            let has_index_side_exit = code.iter().any(|op| matches!(op, Op::Index { .. }))
10472                && code
10473                    .iter()
10474                    .any(|op| matches!(op, Op::Return { .. } | Op::ReturnNothing));
10475            let reason = if has_push && has_call {
10476                "list-push-with-call"
10477            } else if has_fresh_list_return_call {
10478                "fresh-list-return-call"
10479            } else if has_index_side_exit {
10480                "list-index-side-exit"
10481            } else {
10482                "unsupported-bytecode-shape"
10483            };
10484            self.note_region_decline(reason);
10485            if dbg {
10486                eprintln!("RDIAG head_pc={head_pc}: adapt_region -> None ({reason})");
10487            }
10488            return None;
10489        };
10490        if std::env::var_os("LOGOS_JIT_TRACE_OPS").is_some() {
10491            eprintln!(
10492                "jit-trace: region head={head_pc} exit={exit_pc} code={code:?} micro={micro:?}",
10493            );
10494        }
10495        // Record the lowering on the successful compiled-region path below.
10496        // Looking at the micro-op (rather than the source AddAssign) makes the
10497        // trace prove that the Int-specific allocation-free lane was selected.
10498        let string_append_int = micro.iter().any(|op| {
10499            matches!(
10500                op,
10501                MicroOp::StrAppend {
10502                    src: logicaffeine_forge::jit::StrSrc::Int(_),
10503                    ..
10504                }
10505            )
10506        });
10507        let has_calls = code.iter().any(|op| matches!(op, Op::Call { .. }));
10508        // A calling region's chain must check the SHARED status cell — the
10509        // call stencil writes its deopt marker there. A PRECISE region needs it
10510        // too: every side exit stores its encoded resume pc through it.
10511        let status = (has_calls || precise.is_some()).then(|| ctx.status.clone());
10512        // REGION REGISTER ALLOCATION (EXODIA 3.1, sprint 13's deferred half).
10513        // Pin the hottest INTEGER slots that are not in the write-set or the
10514        // array-handle set: the write-set must stay frame-resident for the
10515        // VM's success copy-back, and dead-at-exit slots (loop counters,
10516        // read-only bounds, scratch) need only the prologue reload — so NO
10517        // exit-spill machinery is required, and a mid-loop side-exit keeps
10518        // the discard-and-replay contract untouched (the VM replays from the
10519        // region head on its OWN registers; the native frame's scalars are
10520        // never read back). The value-form float `>`/`>=` compares (`GtF`/
10521        // `GtEqF`) now have a mem-form lowering (Lever 2a: swap operands, reuse
10522        // the LtF/LeF stencil — IEEE-exact, NaN-false), so a region carrying a
10523        // value-form float `>`/`>=` keeps its XMM pins instead of dropping all
10524        // of them. (A float `>` USED AS A BRANCH already fuses into the register-
10525        // form `BranchF`; only the VALUE form produces a surviving `GtF`/`GtEqF`.)
10526        //
10527        // `ListClear` is still excluded: the mem-form emitter has no arm for it
10528        // (it resets a list's vec/ptr/len through a helper, which would leave a
10529        // pinned ptr/len register stale), so a pinned region containing one
10530        // would miscompile (observed: knapsack's DP-row reuse). Such a region
10531        // stays unpinned and runs the correct unpinned path.
10532        let pinnable = !micro.iter().any(|op| {
10533            // A `MemMem` region reads/writes every operand through the frame in
10534            // its helper, so it must run UNPINNED (no register-resident slot the
10535            // helper would miss); `ListClear`'s mem-form emitter has no pinned arm.
10536            matches!(op, MicroOp::ListClear { .. } | MicroOp::MemMem { .. })
10537        });
10538        let (gp_pins, float_pins): (Vec<u16>, Vec<u16>) = if !pinnable
10539            // Precise regions materialize the frame's scalars on a side exit, so
10540            // every scalar must stay frame-resident — no GP register pinning
10541            // (mirrors the function tier's `adapted.precise.is_none()` gate).
10542            || precise.is_some()
10543            || std::env::var("LOGOS_JIT_REGALLOC").is_ok_and(|v| v == "0")
10544        {
10545            (Vec::new(), Vec::new())
10546        } else {
10547            // Phase 2 (write-set pinning): the WRITE-SET is now eligible —
10548            // the pinned compiler's success-exit epilogue spills each pinned
10549            // slot back to its frame cell, so the VM's write-back still sees
10550            // loop-carried values. Only ARRAY handle registers stay excluded
10551            // (they are pinned through the dedicated ptr/len triple, not GP
10552            // register threading).
10553            let array_regs: std::collections::HashSet<u16> = arrays.iter().map(|a| a.reg).collect();
10554            let (gp, fp) = select_pins(&micro, register_count, true);
10555            let mut gp: Vec<u16> = gp.into_iter().filter(|r| !array_regs.contains(r)).collect();
10556            let fp: Vec<u16> = fp.into_iter().filter(|r| !array_regs.contains(r)).collect();
10557            // REGISTER-FORM array access: hand the hottest INT array whose base
10558            // pointer is STABLE (never pushed-to in this region → no realloc) a
10559            // free GP register, so its word ArrLoad/ArrStore read the pointer
10560            // from a register instead of re-loading the frame cell every access.
10561            // Parked default-OFF: measured ~0% (the interpreter is per-op
10562            // DISPATCH-bound, not frame-traffic-bound — re-reading the array
10563            // pointer from its L1-hot frame cell is free next to the stencil
10564            // dispatch). `LOGOS_ARRPTR=1` re-enables for experiments.
10565            if gp.len() < 4 && std::env::var("LOGOS_ARRPTR").is_ok() {
10566                let pushed: std::collections::HashSet<u16> = micro
10567                    .iter()
10568                    .filter_map(|op| match op {
10569                        MicroOp::ArrPush { vec_slot, .. } => Some(*vec_slot),
10570                        _ => None,
10571                    })
10572                    .collect();
10573                let mut best: Option<(u16, usize)> = None;
10574                for a in &arrays {
10575                    if a.elem != PinElem::Int || pushed.contains(&a.vec_slot) {
10576                        continue;
10577                    }
10578                    let cnt = micro
10579                        .iter()
10580                        .filter(|op| match op {
10581                            MicroOp::ArrLoad {
10582                                ptr_slot,
10583                                byte: false,
10584                                ..
10585                            }
10586                            | MicroOp::ArrStore {
10587                                ptr_slot,
10588                                byte: false,
10589                                ..
10590                            } => *ptr_slot == a.ptr_slot,
10591                            _ => false,
10592                        })
10593                        .count();
10594                    if cnt > 0 && best.map_or(true, |(_, b)| cnt > b) {
10595                        best = Some((a.ptr_slot, cnt));
10596                    }
10597                }
10598                if let Some((ptr_slot, _)) = best {
10599                    gp.push(ptr_slot);
10600                }
10601            }
10602            (gp, fp)
10603        };
10604        let mut copyprop_fired = false;
10605        let mut array_rmw_fired = false;
10606        let mut two_buffer_load_fired = false;
10607        let mut fma_fired = false;
10608        let mut regalloc_fma_fired = false;
10609        let mut conditional_swap_fired = false;
10610        let mut swap_fired = false;
10611        let mut affine_index_fired = false;
10612        // COPY-PROPAGATION + CONSTANT CSE — kills the redundant scratch-Move
10613        // chains and re-loaded constants the bytecode lowering leaves in hot
10614        // loops (the per-op DISPATCH is the floor, so fewer ops = faster). Run
10615        // AFTER pin selection, protecting the chosen pins, so it never perturbs
10616        // the greedy allocator (the reason the earlier pre-selection version had
10617        // to be array-free-gated) — now it applies in array regions too. Sound
10618        // only for replay-from-head (non-precise) regions: removing micro ops
10619        // renumbers jump targets (remapped) but would break per-op precise
10620        // resume codes. `LOGOS_COPYPROP=0` is the kill-switch.
10621        if precise.is_none() && std::env::var("LOGOS_COPYPROP").as_deref() != Ok("0") {
10622            let pinset: std::collections::HashSet<u16> =
10623                gp_pins.iter().chain(float_pins.iter()).copied().collect();
10624            let before = micro.len();
10625            copy_propagate(&mut micro, named, register_count, &pinset);
10626            copyprop_fired = micro.len() < before;
10627        }
10628        // WS-G PRE-FUSION SNAPSHOT (approach a). The array-fusion passes below
10629        // (`ArrRMW`/`ArrLoad2`/`ArrLoadAffine`/`ArrCondSwap`/`ArrSwap`) exist to
10630        // cut PIECE count in the per-piece stencil tier. The CONTIGUOUS regalloc
10631        // backend has no per-piece overhead and handles RAW `ArrLoad`/`ArrStore`
10632        // directly, so it must see the UN-fused stream. Snapshot the cleaned
10633        // (copy-propagated) micro here, BEFORE the fusions, and try regalloc on
10634        // it at the dispatch below; only if regalloc declines do the fusions and
10635        // the per-piece stencil tier take over the (mutated) `micro`. The
10636        // snapshot is taken only for a non-precise region (the only kind
10637        // regalloc compiles); precise regions never reach it.
10638        #[cfg(target_arch = "x86_64")]
10639        let mut prefusion_micro: Option<Vec<MicroOp>> = (precise.is_none()
10640            && logicaffeine_forge::regalloc::regalloc_enabled())
10641        .then(|| micro.clone());
10642        // ARRAY READ-MODIFY-WRITE FUSION: after copy-prop/CSE has cleaned the
10643        // stream and deduped the operand constant, collapse `arr[i] = arr[i] OP
10644        // operand` (ArrLoad + int ALU + ArrStore) into one ArrRMW stencil — the
10645        // dispatch-reduction lever for the indexed-RMW loops (histogram,
10646        // counting sort). Non-precise only (it renumbers micro indices).
10647        // `LOGOS_RMW=0` is the kill-switch.
10648        if precise.is_none() && std::env::var("LOGOS_RMW").as_deref() != Ok("0") {
10649            let pinset: std::collections::HashSet<u16> =
10650                gp_pins.iter().chain(float_pins.iter()).copied().collect();
10651            let before = micro.len();
10652            fuse_array_rmw(&mut micro, named, register_count, &pinset);
10653            array_rmw_fired = micro.len() < before;
10654        }
10655        // TWO-BUFFER INTEGER LOAD+BINOP FUSION: collapse `a[i] OP b[j]`
10656        // (ArrLoad + ArrLoad + int Add/Sub/Mul) into one ArrLoad2 stencil — the
10657        // dispatch-reduction lever for the integer dot-product / matrix-multiply
10658        // inner loop, where two distinct pinned buffers feed a binop. Runs after
10659        // RMW (the c-accumulator's load+add+mod+store is not a clean RMW, so the
10660        // two passes never contend for the same ops). Non-precise only (it
10661        // renumbers micro indices). `LOGOS_LD2=0` is the kill-switch.
10662        if precise.is_none() && std::env::var("LOGOS_LD2").as_deref() != Ok("0") {
10663            let pinset: std::collections::HashSet<u16> =
10664                gp_pins.iter().chain(float_pins.iter()).copied().collect();
10665            let before = micro.len();
10666            fuse_array_ld2(&mut micro, named, register_count, &pinset);
10667            two_buffer_load_fired = micro.len() < before;
10668        }
10669        // FLOAT MULTIPLY-ADD FUSION: merge `a*b; +c` (MulF feeding a single-use
10670        // AddF) into one FmaF stencil — the dispatch-reduction lever for the
10671        // float arithmetic chains in the float cluster (nbody). Only fuses
10672        // frame-resident operands (spill-free). `LOGOS_FMA=0` is the kill-switch.
10673        if precise.is_none() && std::env::var("LOGOS_FMA").as_deref() != Ok("0") {
10674            let pinset: std::collections::HashSet<u16> =
10675                gp_pins.iter().chain(float_pins.iter()).copied().collect();
10676            let before = micro.len();
10677            fuse_fma(&mut micro, named, register_count, &pinset);
10678            fma_fired = micro.len() < before;
10679            // The contiguous backend deliberately receives the raw array-op
10680            // stream, but FmaF is part of its supported ISA and removes a real
10681            // arithmetic spill/store/reload pair there too. Fuse its private
10682            // snapshot with no stencil pins: the contiguous allocator assigns
10683            // locations after fusion and lowers resident or spilled operands
10684            // directly.
10685            #[cfg(target_arch = "x86_64")]
10686            if let Some(regalloc_micro) = prefusion_micro.as_mut() {
10687                let before = regalloc_micro.len();
10688                fuse_fma(
10689                    regalloc_micro,
10690                    named,
10691                    register_count,
10692                    &std::collections::HashSet::new(),
10693                );
10694                regalloc_fma_fired = regalloc_micro.len() < before;
10695            }
10696        }
10697        // CONDITIONAL-SWAP FUSION: collapse the sort inner-loop compare-and-swap
10698        // (ArrLoad×2 + Branch + ArrStore×2 → 1) — now fires thanks to the
10699        // precise-region-live-out keystone freeing the loop-local a/b.
10700        // `LOGOS_CONDSWAP=0` kills it.
10701        if std::env::var("LOGOS_DUMP_MICRO")
10702            .ok()
10703            .and_then(|v| v.parse::<usize>().ok())
10704            == Some(head_pc)
10705        {
10706            eprintln!("=== MICRO head_pc={head_pc} ({} ops) ===", micro.len());
10707            for (i, m) in micro.iter().enumerate() {
10708                eprintln!("  [{i}] {m:?}");
10709            }
10710        }
10711        if precise.is_none() && std::env::var("LOGOS_CONDSWAP").as_deref() != Ok("0") {
10712            let pinset: std::collections::HashSet<u16> =
10713                gp_pins.iter().chain(float_pins.iter()).copied().collect();
10714            let before = micro.len();
10715            fuse_cond_swap(&mut micro, named, register_count, &pinset);
10716            conditional_swap_fired = micro.len() < before;
10717        }
10718        // UNCONDITIONAL-SWAP FUSION: collapse the `tmp` exchange (quick/heap/merge
10719        // sort: load,load,store,store → 1). `LOGOS_SWAP=0` kills it.
10720        if precise.is_none() && std::env::var("LOGOS_SWAP").as_deref() != Ok("0") {
10721            let pinset: std::collections::HashSet<u16> =
10722                gp_pins.iter().chain(float_pins.iter()).copied().collect();
10723            let before = micro.len();
10724            fuse_swap(&mut micro, named, register_count, &pinset);
10725            swap_fired = micro.len() < before;
10726        }
10727        // AFFINE-INDEX LOAD FUSION: fold the index arithmetic of a read-only
10728        // array load (`prev[w - wi + 1]`, the heap-sift reads, graph adjacency
10729        // reads) into the load stencil. Runs LAST among the array fusions so the
10730        // two-buffer (`ArrLoad2`), RMW, and swap fusions claim their raw loads
10731        // first; this pass only takes the plain `ArrLoad`s they leave behind.
10732        // `LOGOS_AFFINE=0` is the kill-switch.
10733        if precise.is_none() && std::env::var("LOGOS_AFFINE").as_deref() != Ok("0") {
10734            let pinset: std::collections::HashSet<u16> =
10735                gp_pins.iter().chain(float_pins.iter()).copied().collect();
10736            let before = micro.len();
10737            fuse_index_affine(&mut micro, named, register_count, &pinset);
10738            affine_index_fired = micro.len() < before;
10739        }
10740        if dbg {
10741            eprintln!(
10742                "RDIAG head_pc={head_pc}: adapt OK frame={frame_size} pinnable={pinnable} gp_pins={gp_pins:?} float_pins={float_pins:?} arrays={}",
10743                arrays.len()
10744            );
10745        }
10746        // WS-G CONTIGUOUS REGALLOC BACKEND (LOGOS_REGALLOC default ON).
10747        // For a non-precise integer region whose every op is in the contiguous
10748        // backend's supported subset, emit ONE register-allocated function (no
10749        // per-piece stencil boundaries). Returns None on any unsupported op →
10750        // we fall through to the existing per-piece tiers, so behavior with the
10751        // flag off — or on an unsupported region — is byte-identical to today.
10752        //
10753        // It is tried on the PRE-FUSION snapshot (approach a): the backend has
10754        // no per-piece cost, so it wants the RAW `ArrLoad`/`ArrStore` stream,
10755        // not the fused `ArrRMW`/`ArrLoad2`/… the array fusions produced for the
10756        // stencil tier. If regalloc declines (an unsupported op — float arrays,
10757        // byte loads, calls, globals, list ops, …) we fall through to the
10758        // already-fused `micro` and the per-piece tier, byte-identical to today.
10759        //
10760        // The frame slots the VM reads once the region exits: the write-back
10761        // registers and the region-return flag and value.
10762        #[cfg(target_arch = "x86_64")]
10763        let live_out: Vec<u16> = writes
10764            .iter()
10765            .map(|&(r, _)| r)
10766            .chain(
10767                region_return
10768                    .iter()
10769                    .flat_map(|rr| [rr.flag_slot, rr.value_slot]),
10770            )
10771            .collect();
10772        #[cfg(target_arch = "x86_64")]
10773        let regalloc_chain: Option<CompiledChain> = prefusion_micro.as_ref().and_then(|m| {
10774            logicaffeine_forge::regalloc::compile_region_regalloc(m, status.clone(), &live_out)
10775        });
10776        #[cfg(not(target_arch = "x86_64"))]
10777        let regalloc_chain: Option<CompiledChain> = None;
10778
10779        let used_regalloc = regalloc_chain.is_some();
10780        let chain = if let Some(c) = regalloc_chain {
10781            self.regalloc_regions.fetch_add(1, Ordering::SeqCst);
10782            if dbg {
10783                eprintln!(
10784                    "RDIAG head_pc={head_pc}: CONTIGUOUS REGALLOC backend (arrays={})",
10785                    arrays.len()
10786                );
10787            }
10788            c
10789        } else if let Some(p) = precise.as_ref() {
10790            // PRECISE region (the fannkuch / graph_bfs worklist shape: an
10791            // in-place `SetIndex` beside a reallocating `ArrPush`). The depth
10792            // cell value rides the resume tag's high 32 bits; the VM masks it out
10793            // of the region resume (only the low-32 resume code is read back).
10794            let depth_addr = std::sync::Arc::as_ptr(&ctx.depth) as i64;
10795            // WS-G WAVE 21: try the CONTIGUOUS regalloc backend FIRST, with the
10796            // per-op precise deopt codes. It register-allocates the region's
10797            // scalars (the per-piece precise stencil tier kept every scalar
10798            // frame-resident and paid the 4-6× per-piece dispatch overhead) while
10799            // flushing every resident-written scalar to its frame slot at each
10800            // precise side exit, so the VM's resume reads correct values. No
10801            // fusions / copy-prop ran (all gated `precise.is_none()`), so `micro`
10802            // is the raw lowered stream `p.deopt_codes` is parallel to. On any
10803            // unsupported op the backend declines and the per-piece precise tier
10804            // takes over — byte-identical to before this wave.
10805            //
10806            // Cross-function calls mixed with list mutation retain the coded-stencil
10807            // path. Host helpers are safe here: the allocator forces their input/output
10808            // windows and list triples into the frame, spills volatile registers,
10809            // and invalidates array hoists across each helper call.
10810            // ListTriple only refreshes declared frame slots after adoption.
10811            // All four slots are forced frame-resident and invalidate array
10812            // hoists; it does not allocate or mutate the list itself.
10813            let mixes_frame_calls_and_list_mutation =
10814                micro.iter().any(|op| matches!(op, MicroOp::Call { .. }))
10815                    && micro.iter().any(|op| {
10816                        matches!(
10817                            op,
10818                            MicroOp::NewList { .. }
10819                                | MicroOp::ArrPush { .. }
10820                                | MicroOp::ListClear { .. }
10821                        ) || matches!(
10822                            op,
10823                            MicroOp::ListTriple { helper_addr, .. }
10824                                if *helper_addr != logos_rt_list_triple as usize as i64
10825                        )
10826                    });
10827            #[cfg(target_arch = "x86_64")]
10828            let precise_regalloc: Option<CompiledChain> =
10829                (logicaffeine_forge::regalloc::regalloc_enabled()
10830                    && std::env::var("LOGOS_REGALLOC_PRECISE").as_deref() != Ok("0")
10831                    && std::env::var("LOGOS_REGALLOC_PRECISE_REGION").as_deref() != Ok("0")
10832                    && !mixes_frame_calls_and_list_mutation)
10833                    .then(|| {
10834                        logicaffeine_forge::regalloc::compile_region_regalloc_precise(
10835                            &micro,
10836                            status.clone(),
10837                            depth_addr,
10838                            &p.deopt_codes,
10839                            &live_out,
10840                        )
10841                    })
10842                    .flatten();
10843            #[cfg(not(target_arch = "x86_64"))]
10844            let precise_regalloc: Option<CompiledChain> = None;
10845            if let Some(c) = precise_regalloc {
10846                self.regalloc_regions.fetch_add(1, Ordering::SeqCst);
10847                self.regalloc_precise_regions.fetch_add(1, Ordering::SeqCst);
10848                if dbg {
10849                    eprintln!(
10850                        "RDIAG head_pc={head_pc}: CONTIGUOUS REGALLOC backend (PRECISE, arrays={})",
10851                        arrays.len()
10852                    );
10853                }
10854                c
10855            } else {
10856                match compile_straightline_coded(&micro, status, Some(&p.deopt_codes), depth_addr) {
10857                    Ok(c) => c,
10858                    Err(e) => {
10859                        if dbg {
10860                            eprintln!("RDIAG head_pc={head_pc}: compile_straightline_coded(precise) -> Err({e:?})");
10861                        }
10862                        self.note_region_decline("machine-code-lowering-failed");
10863                        return None;
10864                    }
10865                }
10866            }
10867        } else if gp_pins.is_empty() && float_pins.is_empty() {
10868            match compile_straightline_with(&micro, status) {
10869                Ok(c) => c,
10870                Err(e) => {
10871                    if dbg {
10872                        eprintln!(
10873                            "RDIAG head_pc={head_pc}: compile_straightline_with -> Err({e:?})"
10874                        );
10875                    }
10876                    self.note_region_decline("machine-code-lowering-failed");
10877                    return None;
10878                }
10879            }
10880        } else {
10881            match compile_straightline_pinned_float(&micro, &gp_pins, &float_pins, status) {
10882                Ok(c) => {
10883                    self.pinned_register_compiles
10884                        .fetch_add(1, Ordering::Relaxed);
10885                    c
10886                }
10887                Err(e) => {
10888                    if dbg {
10889                        eprintln!("RDIAG head_pc={head_pc}: compile_straightline_pinned_float -> Err({e:?})");
10890                    }
10891                    self.note_region_decline("machine-code-lowering-failed");
10892                    return None;
10893                }
10894            }
10895        };
10896        if copyprop_fired {
10897            self.copy_propagations.fetch_add(1, Ordering::Relaxed);
10898        }
10899        if !used_regalloc {
10900            if array_rmw_fired {
10901                self.array_rmw_fusions.fetch_add(1, Ordering::Relaxed);
10902            }
10903            if two_buffer_load_fired {
10904                self.two_buffer_load_fusions.fetch_add(1, Ordering::Relaxed);
10905            }
10906            if conditional_swap_fired {
10907                self.conditional_swap_fusions
10908                    .fetch_add(1, Ordering::Relaxed);
10909            }
10910            if swap_fired {
10911                self.swap_fusions.fetch_add(1, Ordering::Relaxed);
10912            }
10913            if affine_index_fired {
10914                self.affine_index_fusions.fetch_add(1, Ordering::Relaxed);
10915            }
10916        }
10917        if (used_regalloc && regalloc_fma_fired) || (!used_regalloc && fma_fired) {
10918            self.fma_fusions.fetch_add(1, Ordering::Relaxed);
10919        }
10920        if string_append_int {
10921            self.string_append_ints.fetch_add(1, Ordering::Relaxed);
10922        }
10923        let rotates = micro
10924            .iter()
10925            .filter(|op| matches!(op, MicroOp::Rotate { .. }))
10926            .count() as u32;
10927        if rotates != 0 {
10928            self.native_rotate_instructions
10929                .fetch_add(rotates, Ordering::Relaxed);
10930        }
10931        self.region_successes.fetch_add(1, Ordering::SeqCst);
10932        let call_support =
10933            has_calls.then(|| (ARENA_SLOTS, (frame_size - 1) as u16, ctx.depth.clone()));
10934        Some(Box::new(RegionChain {
10935            chain,
10936            frame_size,
10937            call_support,
10938            call_sites: code
10939                .iter()
10940                .enumerate()
10941                .filter_map(|(i, op)| {
10942                    if let Op::Call { func, .. } = *op {
10943                        Some((head_pc + i, func))
10944                    } else {
10945                        None
10946                    }
10947                })
10948                .collect(),
10949            guard,
10950            free,
10951            writes,
10952            arrays,
10953            region_return,
10954            hoist_guards,
10955            resume_on_return: precise.as_ref().is_some_and(|p| p.resume_on_return),
10956            precise_kinds: precise.map(|p| p.kinds_by_pc),
10957            stats: self.runtime.clone(),
10958        }))
10959    }
10960
10961    fn engine_name(&self) -> &'static str {
10962        "exodia"
10963    }
10964
10965    fn compile_summary(&self) -> String {
10966        let (fn_tries, fn_ok) = self.function_counts();
10967        let (loop_tries, loop_ok) = self.region_counts();
10968        format!("{fn_ok}/{fn_tries} functions, {loop_ok}/{loop_tries} loops compiled")
10969    }
10970
10971    fn decline_summary(&self) -> String {
10972        let functions = self
10973            .function_declines
10974            .lock()
10975            .unwrap_or_else(|e| e.into_inner());
10976        let regions = self
10977            .region_declines
10978            .lock()
10979            .unwrap_or_else(|e| e.into_inner());
10980        let render = |counts: &std::collections::BTreeMap<&'static str, u32>, missing: u32| {
10981            let mut rendered = counts
10982                .iter()
10983                .map(|(reason, count)| format!("{reason}={count}"))
10984                .collect::<Vec<_>>();
10985            if missing != 0 {
10986                rendered.push(format!("unclassified={missing}"));
10987            }
10988            rendered.join(",")
10989        };
10990        let (function_attempts, function_successes) = self.function_counts();
10991        let (region_attempts, region_successes) = self.region_counts();
10992        let classified_functions: u32 = functions.values().copied().sum();
10993        let classified_regions: u32 = regions.values().copied().sum();
10994        let missing_functions = function_attempts
10995            .saturating_sub(function_successes)
10996            .saturating_sub(classified_functions);
10997        let missing_regions = region_attempts
10998            .saturating_sub(region_successes)
10999            .saturating_sub(classified_regions);
11000        let mut parts = Vec::new();
11001        if !functions.is_empty() || missing_functions != 0 {
11002            parts.push(format!(
11003                "functions[{}]",
11004                render(&functions, missing_functions)
11005            ));
11006        }
11007        if !regions.is_empty() || missing_regions != 0 {
11008            parts.push(format!("loops[{}]", render(&regions, missing_regions)));
11009        }
11010        parts.join("; ")
11011    }
11012
11013    fn optimization_summary(&self) -> String {
11014        self.optimization_trace().keywords().join(",")
11015    }
11016
11017    fn execution_summary(&self) -> String {
11018        let function_entries = self.runtime.entries.load(Ordering::Relaxed);
11019        let function_completions = self.runtime.completions.load(Ordering::Relaxed);
11020        let function_deopts = self.runtime.deopts.load(Ordering::Relaxed);
11021        let function_deopt_ats = self.runtime.deopt_ats.load(Ordering::Relaxed);
11022        // Regions already maintain process-local relaxed counters on their hot
11023        // boundary. Reuse them here instead of adding more atomics to every
11024        // loop entry just for diagnostics; each benchmark probe is a fresh
11025        // `largo` process, so these are per-artifact execution totals.
11026        let region_completions = REGION_RUNS.load(Ordering::Relaxed);
11027        let region_deopts = REGION_DEOPTS.load(Ordering::Relaxed);
11028        let region_entries = region_completions.saturating_add(region_deopts);
11029        format!(
11030            "functions entries={function_entries} completions={function_completions} \
11031             deopts={function_deopts} precise_deopts={function_deopt_ats}; \
11032             loops entries={region_entries} completions={region_completions} deopts={region_deopts}"
11033        )
11034    }
11035}
11036
11037/// Stage-separated evidence for one execution through the production
11038/// run-optimizer -> VM -> forge-JIT pipeline.
11039///
11040/// [`shared`](Self::shared) uses the same optimization registry as Rust, C and VM traces.
11041/// [`native`](Self::native) keeps forge's detailed lowering vocabulary instead of pretending
11042/// register allocation or a stencil fusion is a source optimizer pass.
11043#[derive(Debug, Clone, PartialEq, Eq)]
11044pub struct JitBackendOptimizationTrace {
11045    pub shared: logicaffeine_compile::optimization::BackendOptimizationTrace,
11046    pub native: JitOptimizationTrace,
11047    pub function_attempts: u32,
11048    pub function_successes: u32,
11049    pub region_attempts: u32,
11050    pub region_successes: u32,
11051    pub declines: String,
11052    pub execution: String,
11053    pub outcome: logicaffeine_compile::compile::RunOutcome,
11054}
11055
11056/// Execute through the production eager optimizer and a fresh private forge
11057/// tier, returning both shared-pass and native-lowering evidence. Native
11058/// refusals enter the common fallback channel as `Jit -> Vm`, so a missed tier
11059/// can no longer hide behind a successful bytecode completion.
11060pub fn optimization_trace_jit(
11061    source: &str,
11062    program_args: &[String],
11063) -> JitBackendOptimizationTrace {
11064    use logicaffeine_compile::optimization::{OptimizationBackend, OptimizationFallback, Tier};
11065
11066    logicaffeine_compile::optimize::begin_backend_trace(OptimizationBackend::Jit);
11067    let tier = ForgeTier::new();
11068    let outcome = logicaffeine_compile::compile::vm_outcome_tiered(
11069        source,
11070        program_args,
11071        Tier::T3,
11072        Some(&tier as &dyn NativeTier),
11073    );
11074    let native = tier.optimization_trace();
11075    let (function_attempts, function_successes) = tier.function_counts();
11076    let (region_attempts, region_successes) = tier.region_counts();
11077    let declines = tier.decline_summary();
11078    let execution = tier.execution_summary();
11079    let mut shared = logicaffeine_compile::optimize::end_backend_trace()
11080        .expect("the JIT backend trace was just started");
11081    if !declines.is_empty() {
11082        shared.fallbacks.push(OptimizationFallback {
11083            from: OptimizationBackend::Jit,
11084            to: OptimizationBackend::Vm,
11085            reason: declines.clone(),
11086        });
11087    }
11088
11089    JitBackendOptimizationTrace {
11090        shared,
11091        native,
11092        function_attempts,
11093        function_successes,
11094        region_attempts,
11095        region_successes,
11096        declines,
11097        execution,
11098        outcome,
11099    }
11100}
11101
11102/// Install the forge tier as the process-wide native tier. Idempotent —
11103/// the first call wins; later calls return the already-installed tier.
11104///
11105/// Call once at binary startup (CLI, server). The live VM constructors in
11106/// `logicaffeine-compile` pick it up for every program they run.
11107///
11108/// `LOGOS_NATIVE_TIER=0` skips installation entirely — the diagnostic
11109/// kill-switch that isolates pure-bytecode wall time from tiered runs.
11110/// Install the diagnostic SIGSEGV/SIGBUS tracer (no-op unless `LOGOS_SEGV_TRAP`
11111/// is set). Used to localize faults inside JIT'd code while root-causing.
11112pub fn segv_trace_install() {
11113    logicaffeine_forge::segv_trace::install();
11114}
11115
11116pub fn install() -> &'static ForgeTier {
11117    static TIER: std::sync::OnceLock<ForgeTier> = std::sync::OnceLock::new();
11118    let tier = TIER.get_or_init(ForgeTier::new);
11119    if !std::env::var("LOGOS_NATIVE_TIER").is_ok_and(|v| v == "0") {
11120        install_native_tier(tier);
11121    }
11122    tier
11123}
11124
11125#[cfg(test)]
11126#[path = "../../logicaffeine_tests/unit/logicaffeine_jit/memmem_safety_tests.rs"]
11127mod memmem_safety_tests;
11128
11129#[cfg(test)]
11130#[path = "../../logicaffeine_tests/unit/logicaffeine_jit/select_pins_tests.rs"]
11131mod select_pins_tests;
11132
11133#[cfg(test)]
11134#[path = "../../logicaffeine_tests/unit/logicaffeine_jit/fuse_rmw_tests.rs"]
11135mod fuse_rmw_tests;
11136
11137#[cfg(test)]
11138#[path = "../../logicaffeine_tests/unit/logicaffeine_jit/fuse_ld2_tests.rs"]
11139mod fuse_ld2_tests;
11140
11141#[cfg(test)]
11142#[path = "../../logicaffeine_tests/unit/logicaffeine_jit/fuse_affine_tests.rs"]
11143mod fuse_affine_tests;
11144
11145#[cfg(test)]
11146#[path = "../../logicaffeine_tests/unit/logicaffeine_jit/scalar_swap_tests.rs"]
11147mod scalar_swap_tests;
11148
11149#[cfg(test)]
11150#[path = "../../logicaffeine_tests/unit/logicaffeine_jit/capacity_hint_tests.rs"]
11151mod capacity_hint_tests;