Skip to main content

polydat_core/compile/jit/
codegen.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! JIT codegen: Cranelift IR generation, operation classification, and
5//! extern "C" runtime helpers called from JIT-compiled code.
6//!
7//! `JitOp` classifies each DAG node into an inline IR pattern or an
8//! extern call. `compile_jit_impl` lowers a slice of `(JitOp, inputs,
9//! outputs)` steps into a single native function via Cranelift.
10//! The four `compile_jit_*` constructors wrap the result in the
11//! appropriate kernel struct from `kernels`.
12
13use std::collections::HashMap;
14use std::mem;
15
16use cranelift_codegen::ir::{self, AbiParam, InstBuilder, types};
17use cranelift_codegen::settings::{self, Configurable};
18use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
19use cranelift_jit::{JITBuilder, JITModule};
20use cranelift_module::{Linkage, Module};
21
22use crate::ast::PolydatNode;
23use crate::ast::SlotShape;
24
25use super::kernels::{JitCore, JitKernelPushPull, JitKernelRaw};
26
27// ── Extern "C" runtime helpers ─────────────────────────────
28
29/// Extern function: xxhash3 of a u64 (called from JIT code).
30extern "C" fn jit_xxh3_hash(value: u64) -> u64 {
31    guarded(|| xxhash_rust::xxh3::xxh3_64(&value.to_le_bytes()))
32}
33
34/// Extern function: interleave bits of two u64 values (called from JIT code).
35extern "C" fn jit_interleave(a: u64, b: u64) -> u64 {
36    guarded(|| {
37        let mut result: u64 = 0;
38        for i in 0..32 {
39            result |= ((a >> i) & 1) << (2 * i);
40            result |= ((b >> i) & 1) << (2 * i + 1);
41        }
42        result
43    })
44}
45
46/// Extern function: interpolating LUT sample (called from JIT code).
47///
48/// Input is f64 bits in [0,1]. LUT pointer + length are baked constants.
49/// Returns f64 result as u64 bits.
50extern "C" fn jit_lut_sample(input_bits: u64, lut_ptr: u64, lut_len: u64) -> u64 {
51    guarded(|| {
52        let u = f64::from_bits(input_bits).clamp(0.0, 1.0);
53        let n = (lut_len - 1) as f64;
54        let pos = u * n;
55        let idx = (pos as usize).min(lut_len as usize - 2);
56        let frac = pos - idx as f64;
57        let result = unsafe {
58            let ptr = lut_ptr as *const f64;
59            let a = *ptr.add(idx);
60            let b = *ptr.add(idx + 1);
61            a * (1.0 - frac) + b * frac
62        };
63        result.to_bits()
64    })
65}
66
67/// Extern function: LFSR shuffle (called from JIT code).
68extern "C" fn jit_shuffle(input: u64, feedback: u64, size: u64, min: u64) -> u64 {
69    // The same body the `shuffle` node runs, not a copy of it: native
70    // code and the interpreter agree here by construction.
71    guarded(|| crate::numeric::permute::shuffle_bounded(input, feedback, size, min))
72}
73
74// Extern functions for math operations (called from JIT code).
75extern "C" fn jit_sin(bits: u64) -> u64 {
76    guarded(|| f64::from_bits(bits).sin().to_bits())
77}
78extern "C" fn jit_cos(bits: u64) -> u64 {
79    guarded(|| f64::from_bits(bits).cos().to_bits())
80}
81extern "C" fn jit_tan(bits: u64) -> u64 {
82    guarded(|| f64::from_bits(bits).tan().to_bits())
83}
84extern "C" fn jit_asin(bits: u64) -> u64 {
85    guarded(|| f64::from_bits(bits).asin().to_bits())
86}
87extern "C" fn jit_acos(bits: u64) -> u64 {
88    guarded(|| f64::from_bits(bits).acos().to_bits())
89}
90extern "C" fn jit_atan(bits: u64) -> u64 {
91    guarded(|| f64::from_bits(bits).atan().to_bits())
92}
93extern "C" fn jit_sqrt(bits: u64) -> u64 {
94    guarded(|| f64::from_bits(bits).sqrt().to_bits())
95}
96extern "C" fn jit_abs_f64(bits: u64) -> u64 {
97    guarded(|| f64::from_bits(bits).abs().to_bits())
98}
99extern "C" fn jit_ln(bits: u64) -> u64 {
100    guarded(|| f64::from_bits(bits).ln().to_bits())
101}
102extern "C" fn jit_exp(bits: u64) -> u64 {
103    guarded(|| f64::from_bits(bits).exp().to_bits())
104}
105extern "C" fn jit_floor_base10(bits: u64) -> u64 {
106    guarded(|| {
107        use crate::numeric::round_numbers::*;
108        let x = f64::from_bits(bits);
109        let r = if !positive_finite(x) {
110            0.0
111        } else {
112            floor_pow10(x)
113        };
114        r.to_bits()
115    })
116}
117extern "C" fn jit_ceiling_base10(bits: u64) -> u64 {
118    guarded(|| {
119        use crate::numeric::round_numbers::*;
120        let x = f64::from_bits(bits);
121        let r = if !positive_finite(x) {
122            0.0
123        } else {
124            let lo = floor_pow10(x);
125            if lo == x { lo } else { lo * 10.0 }
126        };
127        r.to_bits()
128    })
129}
130extern "C" fn jit_closest_base10(bits: u64) -> u64 {
131    guarded(|| {
132        use crate::numeric::round_numbers::*;
133        let x = f64::from_bits(bits);
134        let r = if !positive_finite(x) {
135            0.0
136        } else {
137            let lo = floor_pow10(x);
138            let hi = if lo == x { lo } else { lo * 10.0 };
139            pick_closest(x, lo, hi)
140        };
141        r.to_bits()
142    })
143}
144extern "C" fn jit_floor_decade(bits: u64) -> u64 {
145    guarded(|| {
146        use crate::numeric::round_numbers::*;
147        let x = f64::from_bits(bits);
148        let r = if !positive_finite(x) {
149            0.0
150        } else {
151            let base = floor_pow10(x);
152            (x / base).floor() * base
153        };
154        r.to_bits()
155    })
156}
157extern "C" fn jit_ceiling_decade(bits: u64) -> u64 {
158    guarded(|| {
159        use crate::numeric::round_numbers::*;
160        let x = f64::from_bits(bits);
161        let r = if !positive_finite(x) {
162            0.0
163        } else {
164            let base = floor_pow10(x);
165            (x / base).ceil() * base
166        };
167        r.to_bits()
168    })
169}
170extern "C" fn jit_closest_decade(bits: u64) -> u64 {
171    guarded(|| {
172        use crate::numeric::round_numbers::*;
173        let x = f64::from_bits(bits);
174        let r = if !positive_finite(x) {
175            0.0
176        } else {
177            let base = floor_pow10(x);
178            (x / base).round() * base
179        };
180        r.to_bits()
181    })
182}
183extern "C" fn jit_floor_binomial(bits: u64) -> u64 {
184    guarded(|| {
185        use crate::numeric::round_numbers::*;
186        let x = f64::from_bits(bits);
187        let r = if !positive_finite(x) {
188            0.0
189        } else {
190            floor_pow2(x)
191        };
192        r.to_bits()
193    })
194}
195extern "C" fn jit_ceiling_binomial(bits: u64) -> u64 {
196    guarded(|| {
197        use crate::numeric::round_numbers::*;
198        let x = f64::from_bits(bits);
199        let r = if !positive_finite(x) {
200            0.0
201        } else {
202            let lo = floor_pow2(x);
203            if lo == x { lo } else { lo * 2.0 }
204        };
205        r.to_bits()
206    })
207}
208extern "C" fn jit_closest_binomial(bits: u64) -> u64 {
209    guarded(|| {
210        use crate::numeric::round_numbers::*;
211        let x = f64::from_bits(bits);
212        let r = if !positive_finite(x) {
213            0.0
214        } else {
215            let lo = floor_pow2(x);
216            let hi = if lo == x { lo } else { lo * 2.0 };
217            pick_closest(x, lo, hi)
218        };
219        r.to_bits()
220    })
221}
222extern "C" fn jit_floor_fibonacci(bits: u64) -> u64 {
223    guarded(|| {
224        use crate::numeric::round_numbers::*;
225        let x = f64::from_bits(bits);
226        let r = if !positive_finite(x) {
227            0.0
228        } else {
229            floor_fibonacci_val(x)
230        };
231        r.to_bits()
232    })
233}
234extern "C" fn jit_ceiling_fibonacci(bits: u64) -> u64 {
235    guarded(|| {
236        use crate::numeric::round_numbers::*;
237        let x = f64::from_bits(bits);
238        let r = if !positive_finite(x) {
239            0.0
240        } else {
241            ceiling_fibonacci_val(x)
242        };
243        r.to_bits()
244    })
245}
246extern "C" fn jit_closest_fibonacci(bits: u64) -> u64 {
247    guarded(|| {
248        use crate::numeric::round_numbers::*;
249        let x = f64::from_bits(bits);
250        let r = if !positive_finite(x) {
251            0.0
252        } else {
253            pick_closest(x, floor_fibonacci_val(x), ceiling_fibonacci_val(x))
254        };
255        r.to_bits()
256    })
257}
258
259extern "C" fn jit_atan2(y_bits: u64, x_bits: u64) -> u64 {
260    guarded(|| {
261        f64::from_bits(y_bits)
262            .atan2(f64::from_bits(x_bits))
263            .to_bits()
264    })
265}
266extern "C" fn jit_pow(base_bits: u64, exp_bits: u64) -> u64 {
267    guarded(|| {
268        f64::from_bits(base_bits)
269            .powf(f64::from_bits(exp_bits))
270            .to_bits()
271    })
272}
273extern "C" fn jit_round_nearest(x_bits: u64, iv_bits: u64) -> u64 {
274    guarded(|| {
275        let x = f64::from_bits(x_bits);
276        let interval = f64::from_bits(iv_bits);
277        let r = if !(interval.is_finite() && interval > 0.0) {
278            x
279        } else {
280            (x / interval).round() * interval
281        };
282        r.to_bits()
283    })
284}
285extern "C" fn jit_round_floor(x_bits: u64, iv_bits: u64) -> u64 {
286    guarded(|| {
287        let x = f64::from_bits(x_bits);
288        let interval = f64::from_bits(iv_bits);
289        let r = if !(interval.is_finite() && interval > 0.0) {
290            x
291        } else {
292            (x / interval).floor() * interval
293        };
294        r.to_bits()
295    })
296}
297extern "C" fn jit_round_ceiling(x_bits: u64, iv_bits: u64) -> u64 {
298    guarded(|| {
299        let x = f64::from_bits(x_bits);
300        let interval = f64::from_bits(iv_bits);
301        let r = if !(interval.is_finite() && interval > 0.0) {
302            x
303        } else {
304            (x / interval).ceil() * interval
305        };
306        r.to_bits()
307    })
308}
309
310extern "C" fn jit_pcg(input: u64, seed: u64, stream: u64) -> u64 {
311    guarded(|| {
312        let inc = 2u64.wrapping_mul(stream).wrapping_add(1);
313        crate::numeric::pcg::pcg_seek(seed, inc, input)
314    })
315}
316extern "C" fn jit_pcg_stream(input: u64, stream: u64, seed: u64) -> u64 {
317    guarded(|| {
318        let inc = 2u64.wrapping_mul(stream).wrapping_add(1);
319        crate::numeric::pcg::pcg_seek(seed, inc, input)
320    })
321}
322extern "C" fn jit_n_of(input: u64, n: u64, m: u64) -> u64 {
323    guarded(|| {
324        if m == 0 {
325            return 0;
326        }
327        crate::numeric::n_of_m::n_of_m_eval(input, n, m)
328    })
329}
330
331extern "C" fn jit_cycle_walk(pos: u64, range: u64, seed: u64, inc: u64) -> u64 {
332    guarded(|| {
333        let stream = inc.saturating_sub(1) / 2;
334        let state = crate::numeric::pcg::build_cycle_walk_state(range, seed, stream);
335        crate::numeric::pcg::cycle_walk_inner(
336            pos,
337            range,
338            state.half_bits,
339            state.half_mask,
340            &state.round_keys,
341        )
342    })
343}
344
345extern "C" fn jit_perlin_1d(input: u64, perm_ptr: u64, freq_bits: u64) -> u64 {
346    guarded(|| {
347        let perm = unsafe { &*(perm_ptr as *const crate::numeric::noise::PermTable) };
348        let freq = f64::from_bits(freq_bits);
349        let r = crate::numeric::noise::perlin_1d_algo(perm, input as f64 * freq);
350        r.to_bits()
351    })
352}
353
354extern "C" fn jit_perlin_2d(x: u64, y: u64, perm_ptr: u64, freq_bits: u64) -> u64 {
355    guarded(|| {
356        let perm = unsafe { &*(perm_ptr as *const crate::numeric::noise::PermTable) };
357        let freq = f64::from_bits(freq_bits);
358        let r = crate::numeric::noise::perlin_2d_algo(perm, x as f64 * freq, y as f64 * freq);
359        r.to_bits()
360    })
361}
362
363extern "C" fn jit_simplex_2d(x: u64, y: u64, perm_ptr: u64, freq_bits: u64) -> u64 {
364    guarded(|| {
365        let perm = unsafe { &*(perm_ptr as *const crate::numeric::noise::PermTable) };
366        let freq = f64::from_bits(freq_bits);
367        let r = crate::numeric::noise::simplex_2d_algo(perm, x as f64 * freq, y as f64 * freq);
368        r.to_bits()
369    })
370}
371
372extern "C" fn jit_fractal_noise_1d(input: u64, perm_ptr: u64, freq_bits: u64, octaves: u64) -> u64 {
373    guarded(|| {
374        let perm = unsafe { &*(perm_ptr as *const crate::numeric::noise::PermTable) };
375        let freq = f64::from_bits(freq_bits);
376        let r = crate::numeric::noise::fbm_1d(perm, input as f64, freq, octaves as u32);
377        r.to_bits()
378    })
379}
380
381extern "C" fn jit_fractal_noise_2d(
382    x: u64,
383    y: u64,
384    perm_ptr: u64,
385    freq_bits: u64,
386    octaves: u64,
387) -> u64 {
388    guarded(|| {
389        let perm = unsafe { &*(perm_ptr as *const crate::numeric::noise::PermTable) };
390        let freq = f64::from_bits(freq_bits);
391        let r = crate::numeric::noise::fbm_2d(perm, x as f64, y as f64, freq, octaves as u32);
392        r.to_bits()
393    })
394}
395
396extern "C" fn jit_thread_id() -> u64 {
397    guarded(|| {
398        let id = std::thread::current().id();
399        let id_str = format!("{id:?}");
400        let num = id_str.trim_start_matches("ThreadId(").trim_end_matches(')');
401        num.parse().unwrap_or(0)
402    })
403}
404
405extern "C" fn jit_current_epoch_millis() -> u64 {
406    guarded(|| {
407        std::time::SystemTime::now()
408            .duration_since(std::time::UNIX_EPOCH)
409            .unwrap()
410            .as_millis() as u64
411    })
412}
413
414// ── Catchable predicate violations via setjmp/longjmp ─────────
415//
416// Cranelift-JIT emits DWARF unwind info (`unwind_info=true`) but
417// does not call `__register_frame`; teaching the system
418// unwinder about JIT frames needs either an upstream Cranelift
419// change or a personality-routine shim that's a project on its
420// own. The self-contained route is used instead: a setjmp
421// sentinel installed by the Rust eval wrapper, and extern
422// helpers that `longjmp` back to it on violation
423// (jit_boundary.md §"The setjmp / longjmp workaround").
424//
425// The longjmp skips over the JIT frame entirely — no unwind,
426// no personality lookup, no catch-block walk. Control returns
427// to the Rust wrapper which reads the violation message from a
428// thread-local and raises a normal Rust `panic!`. That panic
429// unwinds through the Rust caller's frames (which have proper
430// `rust_eh_personality` FDEs) and `catch_unwind` catches it
431// like any other panic, so a failing call never aborts the
432// process.
433//
434// Safety
435//   - longjmp skips C-level destructors. The JIT code is pure
436//     machine code with no Drop semantics, so nothing leaks.
437//     The extern helpers themselves hold no resources.
438//   - The thread-local buffer is per-thread, so concurrent
439//     kernels on different tokio worker threads don't share
440//     state. A nested evaluation on the same thread installs
441//     its own buffer and `JmpBufGuard` restores the enclosing
442//     one on every exit path, so the slot behaves as a stack.
443
444/// Platform-independent jmp_buf shim. Allocated oversize (512
445/// bytes, 16-aligned) so the biggest real platform buffer
446/// (glibc Linux: ~200 bytes, macOS: ~192) fits with margin.
447/// We link against the C library's `_setjmp` / `_longjmp`
448/// symbols directly — the `setjmp` macro in the glibc header
449/// expands to `__sigsetjmp`, which saves the signal mask; we
450/// don't need that and `_setjmp` is faster.
451#[repr(C, align(16))]
452struct JitJmpBuf([u8; 512]);
453
454#[cfg(not(windows))]
455unsafe extern "C" {
456    fn _setjmp(env: *mut JitJmpBuf) -> i32;
457    fn _longjmp(env: *mut JitJmpBuf, val: i32) -> !;
458}
459
460// MSVC CRT spelling of the same pair: it exports `longjmp`
461// (no underscore — `_longjmp` doesn't exist there, LNK2019)
462// and an x64 `_setjmp` whose second register argument is
463// recorded as the jmp_buf's `Frame` field. The C compiler
464// normally fills that in via intrinsic; calling from Rust we
465// pass NULL explicitly, which is load-bearing twice over: it
466// keeps rdx from carrying garbage into the buffer, and a zero
467// `Frame` makes `longjmp` do a plain register restore instead
468// of an `RtlUnwindEx` unwind — mandatory here because the
469// frames being skipped are JIT code with no unwind tables
470// registered (the exact problem this setjmp path exists to
471// avoid; see the module comment above).
472#[cfg(windows)]
473unsafe extern "C" {
474    fn _setjmp(env: *mut JitJmpBuf, frame: *mut std::ffi::c_void) -> i32;
475    #[link_name = "longjmp"]
476    fn _longjmp(env: *mut JitJmpBuf, val: i32) -> !;
477}
478
479use std::cell::{Cell, RefCell};
480thread_local! {
481    /// Set by [`invoke_with_catch`] before entering JIT code;
482    /// cleared on return. The extern longjmp helpers consult
483    /// this slot to find their return target. `None` means "no
484    /// wrapper installed" → fall back to abort so violations
485    /// outside a catching wrapper still terminate cleanly
486    /// rather than triggering undefined behavior.
487    static JIT_JMP_BUF: Cell<Option<*mut JitJmpBuf>> = const { Cell::new(None) };
488    /// Populated by the extern helpers right before the
489    /// longjmp; drained by the wrapper after setjmp returns
490    /// non-zero.
491    static JIT_VIOLATION_MSG: RefCell<Option<String>> = const { RefCell::new(None) };
492}
493
494/// Store the violation message and longjmp back to the wrapper.
495/// Used by every predicate extern on the fail path. If no
496/// wrapper is installed on the current thread (e.g. someone
497/// calling the JIT code directly without `invoke_with_catch`),
498/// prints the message and aborts — matches the original
499/// behavior for that call pattern.
500fn jit_violation_longjmp(msg: String) -> ! {
501    JIT_VIOLATION_MSG.with(|m| *m.borrow_mut() = Some(msg.clone()));
502    let buf_ptr: Option<*mut JitJmpBuf> = JIT_JMP_BUF.with(|b| b.get());
503    match buf_ptr {
504        Some(ptr) => unsafe { _longjmp(ptr, 1) },
505        None => {
506            let mut err = std::io::stderr().lock();
507            use std::io::Write;
508            let _ = writeln!(err, "{msg}");
509            let _ = err.flush();
510            std::process::abort();
511        }
512    }
513}
514
515/// RAII restore of the enclosing thread-local `JIT_JMP_BUF`
516/// slot. Ensures the wrapper's buffer pointer doesn't outlive
517/// its stack frame — even if the wrapped closure panics for a
518/// reason unrelated to the JIT predicate (a bug in a
519/// non-JIT sub-path, an OOM, etc.) the guard's `Drop`
520/// reinstates the previous slot so the next `invoke_with_catch`
521/// call doesn't see a dangling pointer.
522struct JmpBufGuard {
523    prev: Option<*mut JitJmpBuf>,
524}
525
526impl Drop for JmpBufGuard {
527    fn drop(&mut self) {
528        JIT_JMP_BUF.with(|b| b.set(self.prev));
529    }
530}
531
532/// Wrapper the kernels, cones, and hybrid segments run fallible
533/// native code under (code that calls a helper); code with no
534/// helper call runs bare. Sets up the setjmp sentinel, runs the
535/// closure (which calls into JIT code), and translates a longjmp
536/// return into a Rust panic carrying the violation message. The panic happens in Rust
537/// land, so `catch_unwind` catches it normally.
538///
539/// Both entry/exit paths flow through the [`JmpBufGuard`] so a
540/// panic from inside `f()` that isn't a JIT violation still
541/// restores the outer slot correctly.
542pub(crate) fn invoke_with_catch<F: FnOnce()>(f: F) {
543    use std::mem::MaybeUninit;
544    let mut buf: MaybeUninit<JitJmpBuf> = MaybeUninit::uninit();
545    let buf_ptr = buf.as_mut_ptr();
546    // Install the jmp_buf for the duration of the call. The
547    // guard restores the previous slot on every exit path
548    // (normal return, longjmp, or non-JIT panic unwinding
549    // through our frame).
550    let prev: Option<*mut JitJmpBuf> = JIT_JMP_BUF.with(|b| b.replace(Some(buf_ptr)));
551    let _guard = JmpBufGuard { prev };
552    #[cfg(not(windows))]
553    let jmpval = unsafe { _setjmp(buf_ptr) };
554    // NULL frame → non-unwinding longjmp; see the extern block.
555    #[cfg(windows)]
556    let jmpval = unsafe { _setjmp(buf_ptr, std::ptr::null_mut()) };
557    if jmpval == 0 {
558        f();
559    } else {
560        // longjmp return. The guard will restore the outer
561        // slot when this frame exits; drain the violation
562        // message and raise a normal Rust panic so the
563        // caller's `catch_unwind` can see it.
564        let msg = JIT_VIOLATION_MSG
565            .with(|m| m.borrow_mut().take())
566            .unwrap_or_else(|| "JIT predicate violation (no message)".into());
567        // Not `panic!`: the hook already saw the original panic (under
568        // `guarded`) and recorded its location for the enrichment the
569        // kernel adds; a second hook call would overwrite it.
570        std::panic::resume_unwind(Box::new(msg));
571    }
572}
573
574/// Extern function: longjmp back to the enclosing wrapper with
575/// an `is_positive` violation message. Called from JIT code on
576/// the predicate-fail path.
577extern "C" fn jit_is_positive_fail(value: u64, name_ptr: u64, name_len: u64) -> u64 {
578    // The pointer targets the `name` const in the node's NodeMeta;
579    // the node is kept alive for the life of the compiled code by
580    // `JitCore::_nodes` / the cone node's `members`, so the str
581    // data is stable. (ptr, len) == (0, 0) means the default name.
582    let name = if name_ptr != 0 {
583        unsafe {
584            std::str::from_utf8_unchecked(std::slice::from_raw_parts(
585                name_ptr as *const u8,
586                name_len as usize,
587            ))
588        }
589    } else {
590        "value"
591    };
592    jit_violation_longjmp(format!(
593        "is_positive({name}): value must be > 0, got {value}"
594    ));
595}
596
597/// Extern function: longjmp back to the enclosing wrapper with
598/// an `in_range` violation message.
599extern "C" fn jit_in_range_fail(value: u64, lo: u64, hi: u64) -> u64 {
600    jit_violation_longjmp(format!("in_range: value {value} outside [{lo}, {hi}]"));
601}
602
603/// Extern function: the failure a node whose body divides by a wire
604/// or constant raises on a zero divisor, in the words the interpreter
605/// raises it (Rust's own): `kind` 0 for a quotient, 1 for a remainder.
606extern "C" fn jit_div_zero_fail(kind: u64) -> u64 {
607    jit_violation_longjmp(
608        if kind == 0 {
609            "attempt to divide by zero"
610        } else {
611            "attempt to calculate the remainder with a divisor of zero"
612        }
613        .to_string(),
614    );
615}
616
617/// `f64_mod` natively: the body itself, since Rust's `%` on floats is
618/// the truncated remainder with the dividend's sign, which no sequence
619/// of Cranelift float instructions reproduces for every input.
620extern "C" fn jit_f64_mod(a_bits: u64, b_bits: u64) -> u64 {
621    let (a, b) = (f64::from_bits(a_bits), f64::from_bits(b_bits));
622    (if b != 0.0 { a % b } else { 0.0 }).to_bits()
623}
624
625/// Extern function: longjmp back to the enclosing wrapper with
626/// an `is_one_of` violation message, carrying the allow-list
627/// contents so the message matches the interpreter's byte for
628/// byte. The pointer targets the node's meta VecU64 const; the
629/// node is kept alive for the life of the compiled code by
630/// `JitCore::_nodes` / the cone node's members, so the data is
631/// stable. (ptr, len) == (0, 0) degrades to an elided set.
632extern "C" fn jit_is_one_of_fail(value: u64, set_ptr: u64, set_len: u64) -> u64 {
633    let msg = if set_ptr != 0 {
634        let set = unsafe { std::slice::from_raw_parts(set_ptr as *const u64, set_len as usize) };
635        format!("is_one_of: value {value} not in allowed set {set:?}")
636    } else {
637        format!("is_one_of: value {value} not in allowed set [..]")
638    };
639    jit_violation_longjmp(msg);
640}
641
642/// Extern function: weighted pick via alias table (called from JIT code).
643///
644/// Performs O(1) alias sampling and value lookup. All array pointers
645/// are baked as i64 immediates in the JIT code.
646extern "C" fn jit_weighted_pick(
647    input: u64,
648    values_ptr: u64,
649    biases_ptr: u64,
650    primaries_ptr: u64,
651    aliases_ptr: u64,
652    n: u64,
653) -> u64 {
654    guarded(|| {
655        let n = n as usize;
656        let slot = (input as usize) % n;
657        let bias_test = ((input >> 32) as f64) / (u32::MAX as f64);
658        unsafe {
659            let biases = std::slice::from_raw_parts(biases_ptr as *const f64, n);
660            let primaries = std::slice::from_raw_parts(primaries_ptr as *const u64, n);
661            let aliases = std::slice::from_raw_parts(aliases_ptr as *const u64, n);
662            let values = std::slice::from_raw_parts(values_ptr as *const u64, n);
663            let index = if bias_test < biases[slot] {
664                primaries[slot]
665            } else {
666                aliases[slot]
667            };
668            values[index as usize]
669        }
670    })
671}
672
673/// Run a body that may panic as its P1 node panics inside an
674/// `extern "C"` helper, where a panic would abort: the panic is caught
675/// and re-raised through the longjmp path, so it surfaces in Rust land
676/// as the same panic the P1 node raises.
677fn guarded<T>(body: impl FnOnce() -> T) -> T {
678    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)) {
679        Ok(v) => v,
680        Err(payload) => {
681            let msg = payload
682                .downcast_ref::<String>()
683                .cloned()
684                .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
685                .unwrap_or_else(|| "panic in a compiled helper".to_string());
686            jit_violation_longjmp(msg)
687        }
688    }
689}
690
691/// A node's slot kit as native code holds it: shared by every kernel
692/// compiled from the program, compared by identity.
693#[derive(Clone)]
694pub struct SlotKitRef(pub std::sync::Arc<crate::ast::CompiledSlotKit>);
695
696impl SlotKitRef {
697    fn new(kit: crate::ast::CompiledSlotKit) -> Self {
698        SlotKitRef(std::sync::Arc::new(kit))
699    }
700}
701
702impl std::fmt::Debug for SlotKitRef {
703    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
704        write!(
705            f,
706            "SlotKitRef({:p}, {} scratch)",
707            std::sync::Arc::as_ptr(&self.0),
708            self.0.scratch.len()
709        )
710    }
711}
712
713impl PartialEq for SlotKitRef {
714    fn eq(&self, other: &Self) -> bool {
715        std::sync::Arc::ptr_eq(&self.0, &other.0)
716    }
717}
718
719/// The helper behind [`JitOp::SlotCall`]: run a kit's closure over
720/// inputs gathered into the native frame, outputs to scatter from it,
721/// and the state's scratch entries from `base`. A panic in the closure
722/// is the node's own failure and is re-raised through the longjmp path
723/// like every other helper's.
724///
725/// # Safety
726/// Called only from generated code, which passes the kit the step was
727/// compiled with (kept alive by the code that calls it), frame arrays
728/// of the stated lengths, and the scratch the calling state owns, laid
729/// out as the builder placed the kit's entries.
730extern "C" fn jit_slot_call(
731    kit: *const crate::ast::CompiledSlotKit,
732    inputs: *const u64,
733    n_in: u64,
734    outputs: *mut u64,
735    n_out: u64,
736    scratch: *mut crate::ast::ScratchBuf,
737    base: u64,
738    n_scratch: u64,
739) {
740    guarded(|| unsafe {
741        let kit = &*kit;
742        let ins = std::slice::from_raw_parts(inputs, n_in as usize);
743        let outs = std::slice::from_raw_parts_mut(outputs, n_out as usize);
744        let sc = std::slice::from_raw_parts_mut(scratch.add(base as usize), n_scratch as usize);
745        (kit.op)(ins, outs, sc)
746    })
747}
748
749impl JitOp {
750    /// The kit a slot call runs, if this is one.
751    pub(crate) fn slot_kit(&self) -> Option<&SlotKitRef> {
752        match self {
753            JitOp::SlotCall { kit, .. } | JitOp::Convert { kit, .. } => Some(kit),
754            _ => None,
755        }
756    }
757
758    /// The scratch entries the step needs in the state that runs it.
759    pub(crate) fn scratch_elems(&self) -> &[crate::ast::ScratchElem] {
760        const STR_ENTRY: [crate::ast::ScratchElem; 1] = [crate::ast::ScratchElem::Str];
761        const F32_ENTRY: [crate::ast::ScratchElem; 1] = [crate::ast::ScratchElem::F32];
762        match self {
763            JitOp::SlotCall { kit, .. } | JitOp::Convert { kit, .. } => &kit.0.scratch,
764            JitOp::U64ToStr { .. }
765            | JitOp::I64ToStr { .. }
766            | JitOp::F64ToStr { .. }
767            | JitOp::StrConcat { .. }
768            | JitOp::JsonToStr { .. } => &STR_ENTRY,
769            JitOp::VecProduce { .. } => &F32_ENTRY,
770            _ => &[],
771        }
772    }
773
774    /// Place the step's scratch entries at `base` in the state's
775    /// scratch; the builder that lays the state out calls this once.
776    pub(crate) fn place_scratch(&mut self, base: usize) {
777        match self {
778            JitOp::SlotCall { scratch_base, .. }
779            | JitOp::Convert { scratch_base, .. }
780            | JitOp::U64ToStr { scratch_base }
781            | JitOp::I64ToStr { scratch_base }
782            | JitOp::F64ToStr { scratch_base }
783            | JitOp::StrConcat { scratch_base }
784            | JitOp::JsonToStr { scratch_base }
785            | JitOp::VecProduce { scratch_base, .. } => *scratch_base = base,
786            _ => {}
787        }
788    }
789}
790
791/// The vector producers with a named lowering (compiled_handles.md
792/// §6): each writes its result into the step's own `F32` entry and
793/// publishes the pair.
794#[derive(Debug, Clone, Copy, PartialEq, Eq)]
795pub enum VecProducer {
796    /// `vec_add_f32(a, b)` over two `vec_f32` wires.
797    Add,
798    /// `vec_scale_f32(a, k)` over a `vec_f32` and an `f64` wire.
799    Scale,
800    /// `vec_norm_f32(a)` over a `vec_f32` wire.
801    Norm,
802    /// `hash_vec(seed, dim)`.
803    HashVec,
804    /// `xxhash3_vec(seed, dim)`.
805    XxHash3Vec,
806    /// `reg_to_vec_f32(r)`.
807    RegToVec,
808}
809
810/// The vector reductions with a named lowering: each returns the
811/// bits of its `f64` result.
812#[derive(Debug, Clone, Copy, PartialEq, Eq)]
813pub enum VecReducer {
814    /// `vec_dot_f32(a, b)`.
815    Dot,
816    /// `vec_l2_f32(a, b)`.
817    L2,
818    /// `vec_cosine_f32(a, b)`.
819    Cosine,
820    /// `lid_mle(distances, k)`.
821    LidMle,
822}
823
824/// The register lane reads with a named lowering: each returns the
825/// lane as the slot word its port stores.
826#[derive(Debug, Clone, Copy, PartialEq, Eq)]
827pub enum RegLaneRead {
828    /// `reg_lane_f32(r, i)`, widened to f64.
829    F32,
830    /// `reg_lane_i16(r, i)`, sign-extended.
831    I16,
832    /// `reg_lane_i64(r, i)`.
833    I64,
834}
835
836/// The register producers that run through a helper: a bounds check
837/// on a wire index, or a lane operation Cranelift has no instruction
838/// for. Each writes its word into the output slots.
839#[derive(Debug, Clone, Copy, PartialEq, Eq)]
840pub enum RegProducer {
841    /// `reg_with_lane_f32(r, i, v)`.
842    WithLaneF32,
843    /// `reg_gather_f32(v, offset)`.
844    GatherF32,
845    /// `vec_to_reg_f32(v)`.
846    VecToRegF32,
847    /// `reg_mul_i8(a, b)`.
848    MulI8,
849}
850
851/// The `vec_f32` slice a wire's pair names.
852///
853/// # Safety
854/// The pair was published by its producing step into storage alive
855/// until that step reruns (axioms S3, S4), and the wire is a `vec_f32`.
856unsafe fn vec_f32_of<'a>(ptr: u64, len: u64) -> &'a [f32] {
857    if len == 0 {
858        &[]
859    } else {
860        unsafe { std::slice::from_raw_parts(ptr as usize as *const f32, len as usize) }
861    }
862}
863
864/// Write a vector into the step's own `F32` entry and publish its
865/// pair into the output slots: what every vector producer's lowering
866/// does around its arithmetic. `f` fills the entry.
867///
868/// # Safety
869/// As for [`write_str_entry`].
870unsafe fn write_f32_entry(
871    scratch: *mut crate::ast::ScratchBuf,
872    base: u64,
873    buffer: *mut u64,
874    out_slot: u64,
875    f: impl FnOnce(&mut Vec<f32>),
876) {
877    unsafe {
878        let entry = &mut *scratch.add(base as usize);
879        let crate::ast::ScratchBuf::F32(v) = entry else {
880            panic!("a vector lowering's scratch entry is not an f32 vector");
881        };
882        f(v);
883        *buffer.add(out_slot as usize) = v.as_ptr() as usize as u64;
884        *buffer.add(out_slot as usize + 1) = v.len() as u64;
885    }
886}
887
888/// The vector producers natively: the step's input words in order
889/// (`w0..w3`, zero past the last), the same body the node runs, into
890/// the entry.
891macro_rules! vec_producer {
892    ($name:ident, |$out:ident, $w0:ident, $w1:ident, $w2:ident, $w3:ident| $body:expr) => {
893        extern "C" fn $name(
894            scratch: *mut crate::ast::ScratchBuf,
895            base: u64,
896            buffer: *mut u64,
897            out_slot: u64,
898            $w0: u64,
899            $w1: u64,
900            $w2: u64,
901            $w3: u64,
902        ) {
903            guarded(|| unsafe {
904                let _ = ($w2, $w3);
905                write_f32_entry(scratch, base, buffer, out_slot, |$out| $body)
906            })
907        }
908    };
909}
910
911vec_producer!(jit_vec_add, |out, a_ptr, a_len, b_ptr, b_len| {
912    let (a, b) = (vec_f32_of(a_ptr, a_len), vec_f32_of(b_ptr, b_len));
913    crate::numeric::vector::check_lens("vec_add_f32", a.len(), b.len());
914    crate::numeric::vector::add_f32_into(a, b, out)
915});
916vec_producer!(jit_vec_scale, |out, a_ptr, a_len, k_bits, _z| {
917    let a = vec_f32_of(a_ptr, a_len);
918    crate::numeric::vector::scale_f32_into(a, f64::from_bits(k_bits) as f32, out)
919});
920vec_producer!(jit_vec_norm, |out, a_ptr, a_len, _y, _z| {
921    crate::numeric::vector::norm_f32_into(vec_f32_of(a_ptr, a_len), out)
922});
923vec_producer!(jit_hash_vec, |out, seed, dim, _y, _z| {
924    crate::numeric::vector::hash_vec_into(seed, dim, out)
925});
926vec_producer!(jit_xxhash3_vec, |out, seed, dim, _y, _z| {
927    crate::numeric::vector::xxhash3_vec_into(seed, dim, out)
928});
929vec_producer!(jit_reg_to_vec_f32, |out, lo, hi, _y, _z| {
930    out.clear();
931    out.extend_from_slice(&crate::ast::Bits128([lo, hi]).lanes_f32())
932});
933
934/// The vector reductions natively: the input words in order, the
935/// result's bits back.
936macro_rules! vec_reducer {
937    ($name:ident, |$w0:ident, $w1:ident, $w2:ident, $w3:ident| $body:expr) => {
938        extern "C" fn $name($w0: u64, $w1: u64, $w2: u64, $w3: u64) -> u64 {
939            guarded(|| unsafe {
940                let _ = ($w2, $w3);
941                let r: f64 = $body;
942                r.to_bits()
943            })
944        }
945    };
946}
947
948vec_reducer!(jit_vec_dot, |a_ptr, a_len, b_ptr, b_len| {
949    let (a, b) = (vec_f32_of(a_ptr, a_len), vec_f32_of(b_ptr, b_len));
950    crate::numeric::vector::check_lens("vec_dot_f32", a.len(), b.len());
951    crate::numeric::vector::dot_f32(a, b) as f64
952});
953vec_reducer!(jit_vec_l2, |a_ptr, a_len, b_ptr, b_len| {
954    let (a, b) = (vec_f32_of(a_ptr, a_len), vec_f32_of(b_ptr, b_len));
955    crate::numeric::vector::check_lens("vec_l2_f32", a.len(), b.len());
956    (crate::numeric::vector::l2sq_f32(a, b) as f64).sqrt()
957});
958vec_reducer!(jit_vec_cosine, |a_ptr, a_len, b_ptr, b_len| {
959    let (a, b) = (vec_f32_of(a_ptr, a_len), vec_f32_of(b_ptr, b_len));
960    crate::numeric::vector::check_lens("vec_cosine_f32", a.len(), b.len());
961    crate::numeric::vector::cosine_f32(a, b)
962});
963vec_reducer!(jit_lid_mle, |d_ptr, d_len, k_bits, _z| {
964    crate::numeric::vector::lid_mle_of(vec_f32_of(d_ptr, d_len), f64::from_bits(k_bits))
965});
966
967/// `reg_lane_f32` natively: the lane widened, as f64 bits.
968extern "C" fn jit_reg_lane_f32(lo: u64, hi: u64, i: u64) -> u64 {
969    guarded(|| crate::numeric::register::lane_f32(crate::ast::Bits128([lo, hi]), i).to_bits())
970}
971
972/// `reg_lane_i16` natively: the lane sign-extended into the slot word.
973extern "C" fn jit_reg_lane_i16(lo: u64, hi: u64, i: u64) -> u64 {
974    guarded(|| crate::numeric::register::lane_i16(crate::ast::Bits128([lo, hi]), i) as i64 as u64)
975}
976
977/// `reg_lane_i64` natively.
978extern "C" fn jit_reg_lane_i64(lo: u64, hi: u64, i: u64) -> u64 {
979    guarded(|| crate::numeric::register::lane_i64(crate::ast::Bits128([lo, hi]), i) as u64)
980}
981
982/// The register producers natively: the input words in order, the
983/// word into the two output slots.
984macro_rules! reg_producer {
985    ($name:ident, |$w0:ident, $w1:ident, $w2:ident, $w3:ident| $body:expr) => {
986        extern "C" fn $name(
987            buffer: *mut u64,
988            out_slot: u64,
989            $w0: u64,
990            $w1: u64,
991            $w2: u64,
992            $w3: u64,
993        ) {
994            guarded(|| unsafe {
995                let _ = ($w2, $w3);
996                let r: crate::ast::Bits128 = $body;
997                *buffer.add(out_slot as usize) = r.0[0];
998                *buffer.add(out_slot as usize + 1) = r.0[1];
999            })
1000        }
1001    };
1002}
1003
1004reg_producer!(jit_reg_with_lane_f32, |lo, hi, i, v_bits| {
1005    crate::numeric::register::with_lane_f32(
1006        crate::ast::Bits128([lo, hi]),
1007        i,
1008        f64::from_bits(v_bits),
1009    )
1010});
1011reg_producer!(jit_reg_gather_f32, |v_ptr, v_len, offset, _z| {
1012    crate::numeric::register::gather_f32(vec_f32_of(v_ptr, v_len), offset)
1013});
1014reg_producer!(jit_vec_to_reg_f32, |v_ptr, v_len, _y, _z| {
1015    crate::numeric::register::to_reg_f32(vec_f32_of(v_ptr, v_len))
1016});
1017reg_producer!(jit_reg_mul_i8, |a_lo, a_hi, b_lo, b_hi| {
1018    crate::numeric::register::mul_i8(
1019        crate::ast::Bits128([a_lo, a_hi]),
1020        crate::ast::Bits128([b_lo, b_hi]),
1021    )
1022});
1023
1024/// Write a string into the step's own entry and publish its pair into
1025/// the output slots: what every named string lowering does around its
1026/// formatting. `f` fills the cleared entry.
1027///
1028/// # Safety
1029/// Called only from the helpers below, with the state's scratch and
1030/// the entry index the builder placed for the step, and the buffer and
1031/// output slot the step writes.
1032unsafe fn write_str_entry(
1033    scratch: *mut crate::ast::ScratchBuf,
1034    base: u64,
1035    buffer: *mut u64,
1036    out_slot: u64,
1037    f: impl FnOnce(&mut Vec<u8>),
1038) {
1039    unsafe {
1040        let entry = &mut *scratch.add(base as usize);
1041        let crate::ast::ScratchBuf::Str(v) = entry else {
1042            panic!("a string lowering's scratch entry is not a string");
1043        };
1044        v.clear();
1045        f(v);
1046        *buffer.add(out_slot as usize) = v.as_ptr() as usize as u64;
1047        *buffer.add(out_slot as usize + 1) = v.len() as u64;
1048    }
1049}
1050
1051/// `__u64_to_string` natively: the digits straight into the entry.
1052extern "C" fn jit_u64_to_str(
1053    scratch: *mut crate::ast::ScratchBuf,
1054    base: u64,
1055    buffer: *mut u64,
1056    out_slot: u64,
1057    value: u64,
1058) {
1059    use std::io::Write;
1060    guarded(|| unsafe {
1061        write_str_entry(scratch, base, buffer, out_slot, |v| {
1062            write!(v, "{value}").expect("a vector accepts every write")
1063        })
1064    })
1065}
1066
1067/// `__i64_to_string` natively.
1068extern "C" fn jit_i64_to_str(
1069    scratch: *mut crate::ast::ScratchBuf,
1070    base: u64,
1071    buffer: *mut u64,
1072    out_slot: u64,
1073    value: u64,
1074) {
1075    use std::io::Write;
1076    guarded(|| unsafe {
1077        write_str_entry(scratch, base, buffer, out_slot, |v| {
1078            write!(v, "{}", value as i64).expect("a vector accepts every write")
1079        })
1080    })
1081}
1082
1083/// `__f64_to_string` natively: `Display`, which is what `to_string`
1084/// writes on the interpreter.
1085extern "C" fn jit_f64_to_str(
1086    scratch: *mut crate::ast::ScratchBuf,
1087    base: u64,
1088    buffer: *mut u64,
1089    out_slot: u64,
1090    bits: u64,
1091) {
1092    use std::io::Write;
1093    guarded(|| unsafe {
1094        write_str_entry(scratch, base, buffer, out_slot, |v| {
1095            write!(v, "{}", f64::from_bits(bits)).expect("a vector accepts every write")
1096        })
1097    })
1098}
1099
1100/// `str_concat` over string wires natively: every pair's bytes
1101/// appended in order. `pairs` holds `n` `(ptr, len)` pairs the
1102/// generated code stored into its frame.
1103extern "C" fn jit_str_concat(
1104    scratch: *mut crate::ast::ScratchBuf,
1105    base: u64,
1106    buffer: *mut u64,
1107    out_slot: u64,
1108    pairs: *const u64,
1109    n: u64,
1110) {
1111    guarded(|| unsafe {
1112        let words = std::slice::from_raw_parts(pairs, 2 * n as usize);
1113        write_str_entry(scratch, base, buffer, out_slot, |v| {
1114            for pair in words.as_chunks::<2>().0 {
1115                // SAFETY: each pair was published by its producing step
1116                // into storage alive until that step reruns (axioms S3,
1117                // S4), and the wire is a string.
1118                let bytes =
1119                    std::slice::from_raw_parts(pair[0] as usize as *const u8, pair[1] as usize);
1120                v.extend_from_slice(bytes);
1121            }
1122        })
1123    })
1124}
1125
1126/// `json_to_str` natively: the compact serialization straight into
1127/// the entry, the bytes `serde_json::Value::to_string` produces.
1128extern "C" fn jit_json_to_str(
1129    scratch: *mut crate::ast::ScratchBuf,
1130    base: u64,
1131    buffer: *mut u64,
1132    out_slot: u64,
1133    ptr: u64,
1134    len: u64,
1135) {
1136    guarded(|| unsafe {
1137        let pair = [ptr, len];
1138        let value = crate::derive_support::ref_value(&pair);
1139        let json = match value {
1140            crate::ast::Value::Json(j) => j.as_ref(),
1141            other => panic!("expected Json wire, got {other:?}"),
1142        };
1143        write_str_entry(scratch, base, buffer, out_slot, |v| {
1144            serde_json::to_writer(v, json).expect("a vector accepts every write")
1145        })
1146    })
1147}
1148
1149/// The scalar kinds a conversion lowers between, by how each rides its
1150/// 64-bit carrier: an unsigned integer zero-extended, a signed one
1151/// sign-extended, a `bool` as 0 or 1, an `f64` as its bits, and an
1152/// `f32` as its own bits in the low word, as their `Wire` impls inject
1153/// them. `f16` and the 128-bit types are not here; their conversions
1154/// stay slot calls.
1155#[derive(Debug, Clone, Copy, PartialEq)]
1156enum Scalar {
1157    Unsigned(u32),
1158    Signed(u32),
1159    Bool,
1160    F32,
1161    F64,
1162}
1163
1164impl Scalar {
1165    fn of(t: crate::ast::PortType) -> Option<Self> {
1166        use crate::ast::PortType as P;
1167        Some(match t {
1168            P::U8 => Self::Unsigned(8),
1169            P::U16 => Self::Unsigned(16),
1170            P::U32 => Self::Unsigned(32),
1171            P::U64 => Self::Unsigned(64),
1172            P::I8 => Self::Signed(8),
1173            P::I16 => Self::Signed(16),
1174            P::I32 => Self::Signed(32),
1175            P::I64 => Self::Signed(64),
1176            P::Bool => Self::Bool,
1177            P::F32 => Self::F32,
1178            P::F64 => Self::F64,
1179            _ => return None,
1180        })
1181    }
1182
1183    /// The integer values the kind holds, for an integer or `bool`.
1184    fn int_range(self) -> Option<(i128, i128)> {
1185        match self {
1186            Self::Unsigned(b) => Some((0, (1i128 << b) - 1)),
1187            Self::Signed(b) => Some((-(1i128 << (b - 1)), (1i128 << (b - 1)) - 1)),
1188            Self::Bool => Some((0, 1)),
1189            Self::F32 | Self::F64 => None,
1190        }
1191    }
1192}
1193
1194/// The lowering of a conversion adapter, if `node` is one.
1195///
1196/// A node is the conversion from `X` to `Y` when it takes one wire of
1197/// type `X`, has one output of type `Y`, and is the node the assembler's
1198/// own conversion table names for that pair (`boundary_adapter`). So a
1199/// conversion is recognized by the table and lowered by its two types,
1200/// and neither the table nor the types are restated here by name. The
1201/// node's kit is the path outside the inline domain, which keeps the
1202/// node's body the one statement of its rule wherever the inline form
1203/// could not prove it matches.
1204fn conversion_op(node: &dyn PolydatNode) -> Option<JitOp> {
1205    use crate::ast::Slot;
1206    let meta = node.meta();
1207    let [Slot::Wire(input)] = meta.ins.as_slice() else {
1208        return None;
1209    };
1210    let [output] = meta.outs.as_slice() else {
1211        return None;
1212    };
1213    let (from, to) = (input.typ, output.typ);
1214    Scalar::of(from)?;
1215    Scalar::of(to)?;
1216    let canonical = crate::compile::assembly::boundary_adapter(from, to)?;
1217    if canonical.meta().name != meta.name {
1218        return None;
1219    }
1220    let op = node.compiled_u64()?;
1221    Some(JitOp::Convert {
1222        from,
1223        to,
1224        kit: SlotKitRef::new(crate::ast::CompiledSlotKit {
1225            scratch: Vec::new(),
1226            op: Box::new(move |inputs, outputs, _| op(inputs, outputs)),
1227        }),
1228        scratch_base: 0,
1229    })
1230}
1231
1232/// Classify a node with the types of its wire inputs known. A node
1233/// with a named native lowering takes it; any other node with a kit
1234/// is a [`JitOp::SlotCall`] of that kit, so a reference pair on either
1235/// side is no bar to native code, and neither is nondeterminism or a
1236/// side effect: the kernels that run the code keep such a step's
1237/// currency its own (a segment of its own on the hybrid kernel, a
1238/// never-current step on pure native code). A node with neither stays
1239/// interpreted.
1240pub fn classify_node_typed(node: &dyn PolydatNode, wire_types: &[crate::ast::PortType]) -> JitOp {
1241    use crate::ast::PortType as PT;
1242    let is_ref = |t: &crate::ast::PortType| t.slot_color() == crate::ast::SlotColor::Ref2;
1243    let vec_produce = |kind: VecProducer| JitOp::VecProduce {
1244        kind,
1245        scratch_base: 0,
1246    };
1247    let ref_copy = |ty: crate::ast::PortType| {
1248        crate::compile::assembly::ref_copy_kit(ty)
1249            .map(|kit| JitOp::SlotCall {
1250                kit: SlotKitRef::new(kit),
1251                scratch_base: 0,
1252            })
1253            .unwrap_or(JitOp::Fallback)
1254    };
1255    let meta = node.meta();
1256    let named = match meta.name.as_str() {
1257        // The string producers with a lowering that writes straight
1258        // into the step's entry (compiled_handles.md §6).
1259        "__u64_to_string" => JitOp::U64ToStr { scratch_base: 0 },
1260        "__i64_to_string" => JitOp::I64ToStr { scratch_base: 0 },
1261        "__f64_to_string" => JitOp::F64ToStr { scratch_base: 0 },
1262        "json_to_str" if wire_types == [crate::ast::PortType::Json] => {
1263            JitOp::JsonToStr { scratch_base: 0 }
1264        }
1265        "str_concat"
1266            if !wire_types.is_empty()
1267                && wire_types.iter().all(|t| *t == crate::ast::PortType::Str) =>
1268        {
1269            JitOp::StrConcat { scratch_base: 0 }
1270        }
1271        // The vector group: each lowering runs the node's own body on
1272        // the wires' slices and writes into the step's entry or
1273        // returns its scalar. Keyed on the exact wire types the body
1274        // is written for; any adapted shape takes the kit.
1275        "vec_add_f32" if wire_types == [PT::VecF32, PT::VecF32] => vec_produce(VecProducer::Add),
1276        "vec_scale_f32" if wire_types == [PT::VecF32, PT::F64] => vec_produce(VecProducer::Scale),
1277        "vec_norm_f32" if wire_types == [PT::VecF32] => vec_produce(VecProducer::Norm),
1278        "hash_vec" if wire_types == [PT::U64, PT::U64] => vec_produce(VecProducer::HashVec),
1279        "xxhash3_vec" if wire_types == [PT::U64, PT::U64] => vec_produce(VecProducer::XxHash3Vec),
1280        "reg_to_vec_f32" if wire_types == [PT::RegF32x4] => vec_produce(VecProducer::RegToVec),
1281        "vec_dot_f32" if wire_types == [PT::VecF32, PT::VecF32] => {
1282            JitOp::VecReduce(VecReducer::Dot)
1283        }
1284        "vec_l2_f32" if wire_types == [PT::VecF32, PT::VecF32] => JitOp::VecReduce(VecReducer::L2),
1285        "vec_cosine_f32" if wire_types == [PT::VecF32, PT::VecF32] => {
1286            JitOp::VecReduce(VecReducer::Cosine)
1287        }
1288        "lid_mle" if wire_types == [PT::VecF32, PT::F64] => JitOp::VecReduce(VecReducer::LidMle),
1289        // The register group: the lane reads and the producers with a
1290        // bounds check run through a helper; the dot product and the
1291        // byte shuffle are inline vector instructions.
1292        "reg_lane_f32" if wire_types == [PT::RegF32x4, PT::U64] => JitOp::RegLane(RegLaneRead::F32),
1293        "reg_lane_i16" if wire_types == [PT::RegI16x8, PT::U64] => JitOp::RegLane(RegLaneRead::I16),
1294        "reg_lane_i64" if wire_types == [PT::RegI64x2, PT::U64] => JitOp::RegLane(RegLaneRead::I64),
1295        "reg_with_lane_f32" if wire_types == [PT::RegF32x4, PT::U64, PT::F64] => {
1296            JitOp::RegProduce(RegProducer::WithLaneF32)
1297        }
1298        "reg_gather_f32" if wire_types == [PT::VecF32, PT::U64] => {
1299            JitOp::RegProduce(RegProducer::GatherF32)
1300        }
1301        "vec_to_reg_f32" if wire_types == [PT::VecF32] => {
1302            JitOp::RegProduce(RegProducer::VecToRegF32)
1303        }
1304        "reg_mul_i8" if wire_types == [PT::RegI8x16, PT::RegI8x16] => {
1305            JitOp::RegProduce(RegProducer::MulI8)
1306        }
1307        "reg_dot_f32" if wire_types == [PT::RegF32x4, PT::RegF32x4] => JitOp::RegDotF32,
1308        // The compiler's input passthrough and `default_or(value,
1309        // fallback)` (`value` unless it is `None`, which a compiled slot
1310        // never carries; engines.md §3.3): a slot copy of an
1311        // immediate, a copy into the step's own scratch of a reference
1312        // value (axiom S3: a pair is never forwarded).
1313        n if n.starts_with("__port_") || n == "default_or" => match meta.outs.first() {
1314            Some(o) if is_ref(&o.typ) => return ref_copy(o.typ),
1315            _ => JitOp::Identity,
1316        },
1317        // The named selects are native only between one-slot
1318        // immediates; any other shape takes the node's kit below.
1319        "select" | "select_u64" if wire_types.iter().skip(1).any(|t| t.slot_width() != 1) => {
1320            JitOp::Fallback
1321        }
1322        _ if wire_types.iter().any(is_ref) || meta.outs.iter().any(|o| is_ref(&o.typ)) => {
1323            JitOp::Fallback
1324        }
1325        _ => classify_node(node),
1326    };
1327    if !matches!(named, JitOp::Fallback) {
1328        return named;
1329    }
1330    if let Some(kit) = node.compiled_slot(
1331        wire_types,
1332        crate::compile::select::Engine::Native(crate::compile::select::Provenance::Auto),
1333    ) {
1334        return JitOp::SlotCall {
1335            kit: SlotKitRef::new(kit),
1336            scratch_base: 0,
1337        };
1338    }
1339    if let Some(op) = node.compiled_u64() {
1340        return JitOp::SlotCall {
1341            kit: SlotKitRef::new(crate::ast::CompiledSlotKit {
1342                scratch: Vec::new(),
1343                op: Box::new(move |inputs, outputs, _| op(inputs, outputs)),
1344            }),
1345            scratch_base: 0,
1346        };
1347    }
1348    JitOp::Fallback
1349}
1350
1351// ── JitOp ──────────────────────────────────────────────────
1352
1353/// Description of a JIT step — what operation to generate.
1354///
1355/// For f64 operations, values are stored in the u64 buffer as their
1356/// bit representation. Cranelift `bitcast` converts between i64/f64.
1357#[derive(Debug, Clone, PartialEq)]
1358pub enum JitOp {
1359    // --- u64 integer ops ---
1360    /// `output[i] = input[i]` for every slot the port spans  (identity / copy)
1361    Identity,
1362    /// `output[0] = input[0] + constant`
1363    AddConst(u64),
1364    /// `output[0] = input[0] * constant`
1365    MulConst(u64),
1366    /// `output[0] = input[0] / constant`
1367    DivConst(u64),
1368    /// `output[0] = input[0] % constant`
1369    ModConst(u64),
1370    /// `output[0] = clamp(input[0], min, max)`  (unsigned)
1371    ClampConst(u64, u64),
1372    /// `output[0] = interleave_bits(input[0], input[1])`  (extern call)
1373    Interleave,
1374    /// `output[i] = mixed-radix decomposition of input[0]`  (inline urem/udiv)
1375    MixedRadixConst(Vec<u64>),
1376    /// `output[0] = xxh3_hash(input[0])`  (extern call)
1377    Hash,
1378    /// `output[0] = splitmix64(input[0]) (fully inlined 64-bit ALU bit mixer)`
1379    SplitMix64,
1380    /// `output[0] = shuffle(input[0])`  (extern call: feedback, size, min)
1381    ShuffleConst(u64, u64, u64),
1382
1383    // --- f64 ops (values stored as u64 bits in buffer) ---
1384    /// `output[0] = input[0] as f64 / u64::MAX as f64`  (u64 → f64 bits)
1385    UnitInterval,
1386    /// `output[0] = f64::from_bits(input[0]) as u64`  (f64 bits → u64, truncate)
1387    F64ToU64,
1388    /// `output[0] = f64::from_bits(input[0]).round() as u64`: half
1389    /// away from zero, as Rust rounds, then the saturating conversion.
1390    RoundToU64,
1391    /// `output[0] = f64::from_bits(input[0]).floor() as u64`
1392    FloorToU64,
1393    /// `output[0] = f64::from_bits(input[0]).ceil() as u64`
1394    CeilToU64,
1395    /// `output[0] = clamp(f64::from_bits(input[0]), min, max)`  → f64 bits
1396    ClampF64Const(u64, u64), // min.to_bits(), max.to_bits()
1397    /// `output[0] = a + (b - a) * f64::from_bits(input[0])`  → f64 bits
1398    LerpConst(u64, u64), // a.to_bits(), b.to_bits()
1399    /// `output[0] = min + range * (input[0] as f64 / MAX)`  → f64 bits  (u64 input)
1400    ScaleRangeConst(u64, u64), // min.to_bits(), range.to_bits()
1401    /// `output[0] = round(f64::from_bits(input[0]) / step) * step`  → f64 bits
1402    QuantizeConst(u64), // step.to_bits()
1403    /// `output[0] = discretize(f64 input, range, buckets)`  → u64
1404    DiscretizeConst(u64, u64), // range.to_bits(), buckets
1405    /// `output[0] = lut_sample(f64 input, lut_ptr, lut_len)`  → f64 bits  (extern call)
1406    LutSampleConst(u64, u64), // lut_ptr as u64, lut_len
1407    /// `output[0] = weighted_pick(input, values_ptr, biases_ptr, primaries_ptr, aliases_ptr, n)`
1408    WeightedPickConst(u64, u64, u64, u64, u64), // values_ptr, biases_ptr, primaries_ptr, aliases_ptr, n
1409
1410    /// Unary f64 math function via extern call. The u8 identifies which function.
1411    /// 0=sin 1=cos 2=tan 3=asin 4=acos 5=atan 6=sqrt 7=abs 8=ln 9=exp
1412    /// 10=floor_base10 11=ceiling_base10 12=closest_base10
1413    /// 13=floor_decade 14=ceiling_decade 15=closest_decade
1414    /// 16=floor_binomial 17=ceiling_binomial 18=closest_binomial
1415    /// 19=floor_fibonacci 20=ceiling_fibonacci 21=closest_fibonacci
1416    MathUnary(u8),
1417    /// Binary f64 math function via extern call.
1418    /// 0=atan2 1=pow 2=round_nearest 3=round_floor 4=round_ceiling
1419    MathBinary(u8),
1420
1421    // --- Two-wire u64 integer ops ---
1422    /// output = `input[0]` + `input[1]`  (wrapping)
1423    U64Add2,
1424    /// output = `input[0]` - `input[1]`  (wrapping)
1425    U64Sub2,
1426    /// output = `input[0]` * `input[1]`  (wrapping)
1427    U64Mul2,
1428    /// output = `input[0]` / `input[1]`  (0 if divisor is 0)
1429    U64Div2,
1430    /// output = `input[0]` % `input[1]`  (0 if divisor is 0)
1431    U64Mod2,
1432    /// output = `input[0]` & `input[1]`
1433    U64And,
1434    /// output = `input[0]` | `input[1]`
1435    U64Or,
1436    /// output = `input[0]` ^ `input[1]`
1437    U64Xor,
1438    /// output = `input[0]` << `input[1]`
1439    U64Shl,
1440    /// output = `input[0]` >> `input[1]`  (logical)
1441    U64Shr,
1442    /// output = !`input[0]`  (unary bitwise NOT)
1443    U64Not,
1444
1445    // --- Inline binary f64 arithmetic (no extern call) ---
1446    /// output = input as f64 (integer to float conversion, not bit reinterpret)
1447    ToF64,
1448
1449    /// output = f64(a) + f64(b)
1450    F64Add,
1451    /// output = f64(a) - f64(b)
1452    F64Sub,
1453    /// output = f64(a) * f64(b)
1454    F64Mul,
1455    /// output = f64(a) / f64(b) (0 if b==0)
1456    F64Div,
1457    /// output = f64(a) % f64(b) (0 if b==0), through `jit_f64_mod`
1458    F64Mod,
1459    /// `output[0] = input[0] / input[1]`, failing on a zero divisor as
1460    /// the body's `/` does (`div_wire`)
1461    U64DivWire,
1462    /// `output[0] = input[0] % input[1]`, failing on a zero divisor as
1463    /// the body's `%` does (`mod_wire`)
1464    U64ModWire,
1465
1466    /// A call of the node's own slot kit from native code
1467    /// (compiled_handles.md §6): the inputs are gathered into the
1468    /// frame, `jit_slot_call` runs the kit's closure over them and the
1469    /// state's scratch entries at `scratch_base`, and the outputs are
1470    /// scattered back. Every node with a kit lowers this way, so a
1471    /// reference pair rides through a segment or a cone as it rides
1472    /// through a closure step.
1473    SlotCall {
1474        /// The kit, shared by every kernel compiled from the program
1475        /// and kept alive by the code that calls it.
1476        kit: SlotKitRef,
1477        /// Index of the kit's first scratch entry in the state's
1478        /// scratch, assigned by the builder that lays the state out.
1479        scratch_base: usize,
1480    },
1481
1482    /// A conversion adapter lowered by its port types (engines.md
1483    /// §7.1). Where the native instruction provably equals the node's
1484    /// rule it runs inline: always for a total conversion, and inside a
1485    /// conservative domain for a checked one (a narrowing, a float to
1486    /// an integer). Outside that domain the step is a call of the
1487    /// node's own kit, so the node alone decides what it returns or how
1488    /// it fails. See `conversion_op` and `emit_conversion`.
1489    Convert {
1490        /// The source type.
1491        from: crate::ast::PortType,
1492        /// The target type.
1493        to: crate::ast::PortType,
1494        /// The node's kit, the path outside the inline domain.
1495        kit: SlotKitRef,
1496        /// As for [`JitOp::SlotCall`].
1497        scratch_base: usize,
1498    },
1499
1500    // --- Named lowerings that write a string into the step's own
1501    // entry (compiled_handles.md §6): no intermediate `String`, no
1502    // frame, the pair published by the helper. Each owns one `Str`
1503    // scratch entry at `scratch_base`.
1504    /// `output = decimal digits of input[0] as a u64`
1505    U64ToStr {
1506        /// The step's string entry in the state's scratch.
1507        scratch_base: usize,
1508    },
1509    /// `output = decimal digits of input[0] as an i64`
1510    I64ToStr {
1511        /// The step's string entry in the state's scratch.
1512        scratch_base: usize,
1513    },
1514    /// `output = Display form of input[0] as an f64`
1515    F64ToStr {
1516        /// The step's string entry in the state's scratch.
1517        scratch_base: usize,
1518    },
1519    /// `output = the concatenation of every input pair's bytes`, for
1520    /// a `str_concat` whose wires are all strings.
1521    StrConcat {
1522        /// The step's string entry in the state's scratch.
1523        scratch_base: usize,
1524    },
1525    /// `output = compact serialization of the JSON value input[0..2] names`
1526    JsonToStr {
1527        /// The step's string entry in the state's scratch.
1528        scratch_base: usize,
1529    },
1530
1531    // --- The vector and register groups (compiled_handles.md §6) ---
1532    /// `output = a vec_f32 written into the step's own `F32` entry`
1533    /// by the producer's body over the input words.
1534    VecProduce {
1535        /// Which producer.
1536        kind: VecProducer,
1537        /// The step's `F32` entry in the state's scratch.
1538        scratch_base: usize,
1539    },
1540    /// `output[0] = f64 bits of the reduction over the input words`
1541    VecReduce(VecReducer),
1542    /// `output[0] = lane input[2] of the register word input[0..2]`,
1543    /// bounds-checked by the helper.
1544    RegLane(RegLaneRead),
1545    /// `output[0..2] = the producer's word over the input words`
1546    RegProduce(RegProducer),
1547    /// `output[0] = ((a0*b0 + a1*b1) + (a2*b2 + a3*b3)) as f64`, the
1548    /// fixed tree of `reg_dot_f32`, over f32x4 words: one `fmul`,
1549    /// four lane extracts, three adds, one promotion.
1550    RegDotF32,
1551    /// `output[0..2] = byte permutation of input[0..2]` by a baked
1552    /// 16-entry mask, one `shuffle`.
1553    RegShuffleConst([u8; 16]),
1554
1555    /// Parameter predicate: pass `input[0]` through to `output[0]`;
1556    /// if `input[0]` == 0, call `jit_is_positive_fail` (panics)
1557    /// with the configured predicate name — (ptr, len) into the
1558    /// node's meta const, (0, 0) for the default. Message parity
1559    /// with the interpreter's `is_positive({name}): …` is asserted
1560    /// by the failure parity suite.
1561    IsPositiveCheck {
1562        /// Address of the predicate's name, or 0 for the default.
1563        name_ptr: u64,
1564        /// Its length in bytes.
1565        name_len: u64,
1566    },
1567    /// Parameter predicate: pass `input[0]` through to `output[0]`;
1568    /// if `input[0]` < lo or `input[0]` > hi, call
1569    /// `jit_in_range_fail` (panics). Stored as (lo, hi).
1570    InRangeCheck(u64, u64),
1571    /// Parameter predicate: pass `input[0]` through to `output[0]`;
1572    /// if `input[0]` is not in the allow-list, call
1573    /// `jit_is_one_of_fail` (panics) with the allow-list contents
1574    /// — (ptr, len) into the node's meta VecU64 const, (0, 0)
1575    /// when unavailable. Message parity with the interpreter's
1576    /// `is_one_of: … not in allowed set […]` is asserted by the
1577    /// failure parity suite. Inline comparisons use the baked vector.
1578    IsOneOfCheck {
1579        /// The allow-list, baked into the comparisons.
1580        allowed: Vec<u64>,
1581        /// Address of the node's allow-list constant for the message, or 0.
1582        set_ptr: u64,
1583        /// Its length.
1584        set_len: u64,
1585    },
1586
1587    // --- Register-plane ops (type_system_alignment.md §3, native tier of §7) ---
1588    // A register value occupies two consecutive u64 slots; the
1589    // codegen emits one unaligned 128-bit load/store per value
1590    // (buffer is only 8-aligned) and a single vector instruction.
1591    /// Element-wise register binop. (lane_ty index, arith index)
1592    /// — lanes: 0=i8x16 1=i16x8 2=i32x4 3=i64x2 4=f32x4 5=f64x2;
1593    /// arith: 0=add 1=sub 2=mul.
1594    RegBinOp(u8, u8),
1595    /// View retag / two-slot copy (`__reg_view_*`): one 128-bit
1596    /// load + store; the lane typing is static, so no instruction
1597    /// beyond the move.
1598    RegCopy,
1599    /// Broadcast a scalar wire into all lanes. Same lane index
1600    /// vocabulary as `RegBinOp`; float lanes read the f64 slot
1601    /// and demote as needed, integer lanes reduce from u64.
1602    RegSplat(u8),
1603
1604    // --- Comparisons & selections ---
1605    /// Integer comparison: `output[0]` = if a `<cond>` b { 1 } else { 0 }
1606    U64Cmp(ir::condcodes::IntCC),
1607    /// Float comparison: `output[0]` = if a `<cond>` b { 1 } else { 0 }
1608    F64Cmp(ir::condcodes::FloatCC),
1609    /// Conditional select for u64: `output[0]` = if cond != 0 { a } else { b }
1610    SelectU64,
1611    /// Conditional select for f64: `output[0]` = if cond != 0 { a } else { b }
1612    SelectF64,
1613
1614    // --- Type conversions & lattice adapters ---
1615    /// Signed integer to float: `output[0]` = (`input[0]` as i64 as f64).to_bits()
1616    I64ToF64,
1617    /// Truthiness boolean coercion: `output[0]` = if `input[0]` != 0 { 1 } else { 0 }
1618    ToBool,
1619    /// Constant u64: `output[0]` = val
1620    ConstU64(u64),
1621    /// Constant f64: `output[0]` = val_bits
1622    ConstF64(u64),
1623
1624    // --- Interpolation & Hashing ---
1625    /// Hash range: `output[0]` = if max == 0 { 0 } else { hash(`input[0]`) % max }
1626    HashRangeConst(u64),
1627    /// Hash interval: `output[0]` = min + (hash(`input[0]`) / MAX) * (max - min)
1628    HashIntervalConst(u64, u64),
1629    /// Inverse lerp: `output[0]` = ((`input[0]` - a) / (b - a)).clamp(0, 1)
1630    InvLerpConst(u64, u64),
1631    /// Remap: `output[0]` = out_min + ((`input[0]` - in_min) / (in_max - in_min)) * (out_max - out_min)
1632    RemapConst(u64, u64, u64, u64),
1633
1634    // --- Context & Datetime ---
1635    /// Epoch offset: `output[0]` = `input[0]`.wrapping_add(base)
1636    EpochOffsetConst(u64),
1637    /// Epoch scale: `output[0]` = `input[0]`.wrapping_mul(factor)
1638    EpochScaleConst(u64),
1639    /// OS thread ID
1640    ThreadId,
1641    /// Wall clock millis
1642    CurrentEpochMillis,
1643
1644    // --- Coherent Noise ---
1645    /// `output[0] = jit_perlin_1d(input[0], perm, freq)`: (permutation table address, frequency bits).
1646    Perlin1dConst(u64, u64),
1647    /// `jit_perlin_2d` over two inputs: (permutation table address, frequency bits).
1648    Perlin2dConst(u64, u64),
1649    /// `jit_simplex_2d` over two inputs: (permutation table address, frequency bits).
1650    Simplex2dConst(u64, u64),
1651    /// `jit_fractal_noise_1d`: (permutation table address, frequency bits, octaves).
1652    FractalNoise1dConst(u64, u64, u64),
1653    /// `jit_fractal_noise_2d` over two inputs: (permutation table address, frequency bits, octaves).
1654    FractalNoise2dConst(u64, u64, u64),
1655
1656    // --- Variadics & wire arithmetic ---
1657    /// Variadic sum across all inputs
1658    VariadicSum,
1659    /// Variadic product across all inputs
1660    VariadicProduct,
1661    /// Variadic minimum across all inputs (unsigned)
1662    VariadicMin,
1663    /// Variadic maximum across all inputs (unsigned)
1664    VariadicMax,
1665    /// Checked unsigned addition: `output[0]` = a.checked_add(b).unwrap_or(0)
1666    CheckedAdd,
1667    /// Saturating unsigned subtraction: `output[0]` = a.saturating_sub(b)
1668    CheckedSub,
1669    /// Checked unsigned multiplication: `output[0]` = a.checked_mul(b).unwrap_or(0)
1670    CheckedMul,
1671    /// Smallest multiple of multiple >= value: `output[0]` = if m == 0 { v } else { v.div_ceil(m).saturating_mul(m) }
1672    CeilToMultiple,
1673    /// Multiples at least: `output[0]` = if m == 0 { 0 } else { v.div_ceil(m) }
1674    MultiplesAtLeast,
1675
1676    // --- Probability & permutations ---
1677    /// Fair coin flip: `output[0]` = `input[0]` & 1
1678    FairCoin,
1679    /// Float blend with constant mix: `output[0]` = (fa * (1 - mix) + fb * mix).round() as u64
1680    BlendConst(u64),
1681    /// LFSR advance step with constant feedback polynomial:
1682    /// `output[0] = (input[0] >> 1) ^ (if input[0] & 1 != 0 { feedback } else { 0 })`
1683    LfsrStepConst(u64),
1684    /// PCG random with constant seed and stream: (seed, stream)
1685    PcgConst(u64, u64),
1686    /// PCG random with wire stream and constant seed: (seed)
1687    PcgStreamConst(u64),
1688    /// Cycle walk: (range, seed, inc)
1689    CycleWalkConst(u64, u64, u64),
1690    /// Unfair coin with constant probability: (p_bits)
1691    UnfairCoinConst(u64),
1692    /// `coin_flip`: the input compared unsigned against a threshold the
1693    /// node computed from its probability at construction; no hash.
1694    CoinFlipConst(u64),
1695    /// Chance with constant probability: (p_bits)
1696    ChanceConst(u64),
1697    /// N-of-M selection with constant n and m: (n, m)
1698    NOfConst(u64, u64),
1699
1700    /// Fallback: no native lowering; the node runs as a closure step
1701    /// on the hybrid kernel and stays interpreted otherwise.
1702    Fallback,
1703}
1704
1705// ── Node classification ────────────────────────────────────
1706
1707/// Classify a Polydat node into a JIT-able operation.
1708///
1709/// Uses `jit_constants()` to extract assembly-time constants
1710/// directly from the node — no probing hacks needed.
1711pub fn classify_node(node: &dyn PolydatNode) -> JitOp {
1712    if let Some(op) = conversion_op(node) {
1713        return op;
1714    }
1715    let name = node.meta().name.as_str();
1716    let consts = node.jit_constants();
1717
1718    match name {
1719        "identity" => JitOp::Identity,
1720        "hash" | "splitmix64" | "scatter" => JitOp::SplitMix64,
1721        "fair_coin" => JitOp::FairCoin,
1722        "unfair_coin" => {
1723            if let Some(&p) = consts.first() {
1724                JitOp::UnfairCoinConst(p)
1725            } else {
1726                JitOp::Fallback
1727            }
1728        }
1729        "chance" => {
1730            if let Some(&p) = consts.first() {
1731                JitOp::ChanceConst(p)
1732            } else {
1733                JitOp::Fallback
1734            }
1735        }
1736        "xxhash3" | "xxh3" => JitOp::Hash,
1737        "hash_range" => {
1738            if let Some(&c) = consts.first() {
1739                JitOp::HashRangeConst(c)
1740            } else {
1741                JitOp::Fallback
1742            }
1743        }
1744        "hash_interval" => {
1745            if consts.len() >= 2 {
1746                JitOp::HashIntervalConst(consts[0], consts[1])
1747            } else {
1748                JitOp::Fallback
1749            }
1750        }
1751        "add" => {
1752            if let Some(&c) = consts.first() {
1753                JitOp::AddConst(c)
1754            } else {
1755                JitOp::Fallback
1756            }
1757        }
1758        "mul" => {
1759            if let Some(&c) = consts.first() {
1760                JitOp::MulConst(c)
1761            } else {
1762                JitOp::Fallback
1763            }
1764        }
1765        "div" => {
1766            if let Some(&c) = consts.first() {
1767                JitOp::DivConst(c)
1768            } else {
1769                JitOp::Fallback
1770            }
1771        }
1772        "mod" => {
1773            if let Some(&c) = consts.first() {
1774                JitOp::ModConst(c)
1775            } else {
1776                JitOp::Fallback
1777            }
1778        }
1779        "clamp" => {
1780            // `Ord::clamp` panics on an inverted range, and `umax`
1781            // followed by `umin` quietly answers `max` instead. The
1782            // bounds are constants, so the disagreement is decidable
1783            // here: an inverted pair is not lowered, and the body says
1784            // what it says on every other engine.
1785            if consts.len() >= 2 && consts[0] <= consts[1] {
1786                JitOp::ClampConst(consts[0], consts[1])
1787            } else {
1788                JitOp::Fallback
1789            }
1790        }
1791        "interleave" => JitOp::Interleave,
1792        "mixed_radix" => {
1793            if consts.is_empty() {
1794                JitOp::Fallback
1795            } else {
1796                JitOp::MixedRadixConst(consts)
1797            }
1798        }
1799        "shuffle" => {
1800            if consts.len() >= 3 {
1801                JitOp::ShuffleConst(consts[0], consts[1], consts[2])
1802            } else {
1803                JitOp::Fallback
1804            }
1805        }
1806        // f64 ops
1807        "unit_interval" => JitOp::UnitInterval,
1808        "f64_to_u64" => JitOp::F64ToU64,
1809        "round_to_u64" => JitOp::RoundToU64,
1810        "floor_to_u64" => JitOp::FloorToU64,
1811        "ceil_to_u64" => JitOp::CeilToU64,
1812        "clamp_f64" => {
1813            if consts.len() >= 2 {
1814                JitOp::ClampF64Const(consts[0], consts[1])
1815            } else {
1816                JitOp::Fallback
1817            }
1818        }
1819        "lerp" => {
1820            if consts.len() >= 2 {
1821                JitOp::LerpConst(consts[0], consts[1])
1822            } else {
1823                JitOp::Fallback
1824            }
1825        }
1826        "scale_range" => {
1827            if consts.len() >= 2 {
1828                JitOp::ScaleRangeConst(consts[0], consts[1])
1829            } else {
1830                JitOp::Fallback
1831            }
1832        }
1833        "quantize" => {
1834            if let Some(&c) = consts.first() {
1835                JitOp::QuantizeConst(c)
1836            } else {
1837                JitOp::Fallback
1838            }
1839        }
1840        "discretize" => {
1841            if consts.len() >= 2 {
1842                JitOp::DiscretizeConst(consts[0], consts[1])
1843            } else {
1844                JitOp::Fallback
1845            }
1846        }
1847        "lut_sample" | "dist_normal" | "icd_normal" | "dist_exponential" | "icd_exponential"
1848        | "dist_uniform" | "dist_pareto" | "dist_zipf" | "dist_empirical" => {
1849            if consts.len() >= 2 {
1850                JitOp::LutSampleConst(consts[0], consts[1])
1851            } else {
1852                JitOp::Fallback
1853            }
1854        }
1855        // Math functions
1856        "sin" => JitOp::MathUnary(0),
1857        "cos" => JitOp::MathUnary(1),
1858        "tan" => JitOp::MathUnary(2),
1859        "asin" => JitOp::MathUnary(3),
1860        "acos" => JitOp::MathUnary(4),
1861        "atan" => JitOp::MathUnary(5),
1862        "sqrt" => JitOp::MathUnary(6),
1863        "abs_f64" => JitOp::MathUnary(7),
1864        "ln" => JitOp::MathUnary(8),
1865        "exp" => JitOp::MathUnary(9),
1866        "floor_base10" => JitOp::MathUnary(10),
1867        "ceiling_base10" => JitOp::MathUnary(11),
1868        "closest_base10" => JitOp::MathUnary(12),
1869        "floor_decade" => JitOp::MathUnary(13),
1870        "ceiling_decade" => JitOp::MathUnary(14),
1871        "closest_decade" => JitOp::MathUnary(15),
1872        "floor_binomial" => JitOp::MathUnary(16),
1873        "ceiling_binomial" => JitOp::MathUnary(17),
1874        "closest_binomial" => JitOp::MathUnary(18),
1875        "floor_fibonacci" => JitOp::MathUnary(19),
1876        "ceiling_fibonacci" => JitOp::MathUnary(20),
1877        "closest_fibonacci" => JitOp::MathUnary(21),
1878        "atan2" => JitOp::MathBinary(0),
1879        "pow" => JitOp::MathBinary(1),
1880        "round_nearest" => JitOp::MathBinary(2),
1881        "round_floor" => JitOp::MathBinary(3),
1882        "round_ceiling" => JitOp::MathBinary(4),
1883        "to_f64" => JitOp::ToF64,
1884        // Two-wire u64 ops (no constants)
1885        "u64_add" => JitOp::U64Add2,
1886        "u64_sub" => JitOp::U64Sub2,
1887        "u64_mul" => JitOp::U64Mul2,
1888        "u64_div" => JitOp::U64Div2,
1889        "u64_mod" => JitOp::U64Mod2,
1890        "u64_and" => JitOp::U64And,
1891        "u64_or" => JitOp::U64Or,
1892        "u64_xor" => JitOp::U64Xor,
1893        "u64_shl" => JitOp::U64Shl,
1894        "u64_shr" => JitOp::U64Shr,
1895        "u64_not" => JitOp::U64Not,
1896
1897        // ── Register plane (type_system_alignment.md §3, native tier of §7) ──
1898        "reg_add_i8" => JitOp::RegBinOp(0, 0),
1899        "reg_sub_i8" => JitOp::RegBinOp(0, 1),
1900        // `imul.i8x16` has no cranelift lowering (x86 has no
1901        // byte-lane multiply short of AVX-512; cranelift 0.116
1902        // rejects it in ISLE); `classify_node_typed` lowers
1903        // `reg_mul_i8` through its helper.
1904        "reg_shuffle_bytes" => {
1905            let mut mask = [0u8; 16];
1906            if consts.len() == 16 && consts.iter().all(|&m| m < 16) {
1907                for (m, &c) in mask.iter_mut().zip(consts.iter()) {
1908                    *m = c as u8;
1909                }
1910                JitOp::RegShuffleConst(mask)
1911            } else {
1912                JitOp::Fallback
1913            }
1914        }
1915        "reg_add_i16" => JitOp::RegBinOp(1, 0),
1916        "reg_sub_i16" => JitOp::RegBinOp(1, 1),
1917        "reg_mul_i16" => JitOp::RegBinOp(1, 2),
1918        "reg_add_i32" => JitOp::RegBinOp(2, 0),
1919        "reg_sub_i32" => JitOp::RegBinOp(2, 1),
1920        "reg_mul_i32" => JitOp::RegBinOp(2, 2),
1921        "reg_add_i64" => JitOp::RegBinOp(3, 0),
1922        "reg_sub_i64" => JitOp::RegBinOp(3, 1),
1923        "reg_mul_i64" => JitOp::RegBinOp(3, 2),
1924        "reg_add_f32" => JitOp::RegBinOp(4, 0),
1925        "reg_sub_f32" => JitOp::RegBinOp(4, 1),
1926        "reg_mul_f32" => JitOp::RegBinOp(4, 2),
1927        "reg_add_f64" => JitOp::RegBinOp(5, 0),
1928        "reg_sub_f64" => JitOp::RegBinOp(5, 1),
1929        "reg_mul_f64" => JitOp::RegBinOp(5, 2),
1930        "__reg_view_raw" | "__reg_view_i8x16" | "__reg_view_i16x8" | "__reg_view_i32x4"
1931        | "__reg_view_i64x2" | "__reg_view_f16x8" | "__reg_view_f32x4" | "__reg_view_f64x2" => {
1932            JitOp::RegCopy
1933        }
1934        "reg_splat_i8" => JitOp::RegSplat(0),
1935        "reg_splat_i16" => JitOp::RegSplat(1),
1936        "reg_splat_i32" => JitOp::RegSplat(2),
1937        "reg_splat_i64" => JitOp::RegSplat(3),
1938        "reg_splat_f32" => JitOp::RegSplat(4),
1939        "reg_splat_f64" => JitOp::RegSplat(5),
1940
1941        "f64_add" => JitOp::F64Add,
1942        "f64_sub" => JitOp::F64Sub,
1943        "f64_mul" => JitOp::F64Mul,
1944        "f64_div" => JitOp::F64Div,
1945        "f64_mod" => JitOp::F64Mod,
1946
1947        // ── Comparisons & Selections ─────────────────────────────
1948        "u64_eq" => JitOp::U64Cmp(ir::condcodes::IntCC::Equal),
1949        "u64_ne" => JitOp::U64Cmp(ir::condcodes::IntCC::NotEqual),
1950        "u64_lt" => JitOp::U64Cmp(ir::condcodes::IntCC::UnsignedLessThan),
1951        "u64_le" => JitOp::U64Cmp(ir::condcodes::IntCC::UnsignedLessThanOrEqual),
1952        "u64_gt" => JitOp::U64Cmp(ir::condcodes::IntCC::UnsignedGreaterThan),
1953        "u64_ge" => JitOp::U64Cmp(ir::condcodes::IntCC::UnsignedGreaterThanOrEqual),
1954        "f64_eq" => JitOp::F64Cmp(ir::condcodes::FloatCC::Equal),
1955        "f64_ne" => JitOp::F64Cmp(ir::condcodes::FloatCC::NotEqual),
1956        "f64_lt" => JitOp::F64Cmp(ir::condcodes::FloatCC::LessThan),
1957        "f64_le" => JitOp::F64Cmp(ir::condcodes::FloatCC::LessThanOrEqual),
1958        "f64_gt" => JitOp::F64Cmp(ir::condcodes::FloatCC::GreaterThan),
1959        "f64_ge" => JitOp::F64Cmp(ir::condcodes::FloatCC::GreaterThanOrEqual),
1960        "select_u64" | "select" => JitOp::SelectU64,
1961        "select_f64" => JitOp::SelectF64,
1962
1963        // ── Wire Arithmetic & Multiples ──────────────────────────
1964        "div_wire" => JitOp::U64DivWire,
1965        "mod_wire" => JitOp::U64ModWire,
1966        "ceil_to_multiple" => JitOp::CeilToMultiple,
1967        "multiples_at_least" => JitOp::MultiplesAtLeast,
1968        "checked_add" => JitOp::CheckedAdd,
1969        "checked_sub" => JitOp::CheckedSub,
1970        "checked_mul" => JitOp::CheckedMul,
1971
1972        // ── Variadics ────────────────────────────────────────────
1973        "sum" => JitOp::VariadicSum,
1974        "product" => JitOp::VariadicProduct,
1975        "min" => JitOp::VariadicMin,
1976        "max" => JitOp::VariadicMax,
1977
1978        // ── PRNG & Probability ───────────────────────────────────
1979        "blend" => {
1980            // No range guard here: `mix` carries a declared
1981            // `RangeF64` constraint, so the factory refuses an
1982            // out-of-range constant before a node exists to lower.
1983            if let Some(&c) = consts.first() {
1984                JitOp::BlendConst(c)
1985            } else {
1986                JitOp::Fallback
1987            }
1988        }
1989        "lfsr_step" => {
1990            if let Some(&fb) = consts.first() {
1991                JitOp::LfsrStepConst(fb)
1992            } else {
1993                JitOp::Fallback
1994            }
1995        }
1996        "pcg" => {
1997            if consts.len() >= 2 {
1998                JitOp::PcgConst(consts[0], consts[1])
1999            } else {
2000                JitOp::Fallback
2001            }
2002        }
2003        "pcg_stream" => {
2004            if let Some(&seed) = consts.first() {
2005                JitOp::PcgStreamConst(seed)
2006            } else {
2007                JitOp::Fallback
2008            }
2009        }
2010        "n_of" => {
2011            if consts.len() >= 2 {
2012                JitOp::NOfConst(consts[0], consts[1])
2013            } else {
2014                JitOp::Fallback
2015            }
2016        }
2017
2018        "cycle_walk" => {
2019            if consts.len() >= 3 {
2020                JitOp::CycleWalkConst(consts[0], consts[1], consts[2])
2021            } else {
2022                JitOp::Fallback
2023            }
2024        }
2025        "coin_flip" => {
2026            // The body is `input < threshold` over the raw input
2027            // (library/fixed.rs), not a hashed unit interval as
2028            // `unfair_coin` is; the node bakes its threshold as its
2029            // one constant.
2030            if let Some(&threshold) = consts.first() {
2031                JitOp::CoinFlipConst(threshold)
2032            } else {
2033                JitOp::Fallback
2034            }
2035        }
2036        // `default_or` without wire types: the typed classifier decides
2037        // (a copy of the value, since a compiled slot is never `None`).
2038        "default_or" => JitOp::Identity,
2039        "const_u64" | "const_bool" => {
2040            if let Some(&c) = consts.first() {
2041                JitOp::ConstU64(c)
2042            } else {
2043                JitOp::Fallback
2044            }
2045        }
2046        "const_f64" => {
2047            if let Some(&c) = consts.first() {
2048                JitOp::ConstF64(c)
2049            } else {
2050                JitOp::Fallback
2051            }
2052        }
2053        "inv_lerp" => {
2054            if consts.len() >= 2 {
2055                JitOp::InvLerpConst(consts[0], consts[1])
2056            } else {
2057                JitOp::Fallback
2058            }
2059        }
2060        "remap" => {
2061            if consts.len() >= 4 {
2062                JitOp::RemapConst(consts[0], consts[1], consts[2], consts[3])
2063            } else {
2064                JitOp::Fallback
2065            }
2066        }
2067        "epoch_offset" => {
2068            if let Some(&c) = consts.first() {
2069                JitOp::EpochOffsetConst(c)
2070            } else {
2071                JitOp::Fallback
2072            }
2073        }
2074        "epoch_scale" => {
2075            if let Some(&c) = consts.first() {
2076                JitOp::EpochScaleConst(c)
2077            } else {
2078                JitOp::Fallback
2079            }
2080        }
2081        "thread_id" => JitOp::ThreadId,
2082        "current_epoch_millis" => JitOp::CurrentEpochMillis,
2083        "perlin_1d" => {
2084            if consts.len() >= 2 {
2085                JitOp::Perlin1dConst(consts[0], consts[1])
2086            } else {
2087                JitOp::Fallback
2088            }
2089        }
2090        "perlin_2d" => {
2091            if consts.len() >= 2 {
2092                JitOp::Perlin2dConst(consts[0], consts[1])
2093            } else {
2094                JitOp::Fallback
2095            }
2096        }
2097        "simplex_2d" => {
2098            if consts.len() >= 2 {
2099                JitOp::Simplex2dConst(consts[0], consts[1])
2100            } else {
2101                JitOp::Fallback
2102            }
2103        }
2104        "fractal_noise_1d" => {
2105            if consts.len() >= 3 {
2106                JitOp::FractalNoise1dConst(consts[0], consts[1], consts[2])
2107            } else {
2108                JitOp::Fallback
2109            }
2110        }
2111        "fractal_noise_2d" => {
2112            if consts.len() >= 3 {
2113                JitOp::FractalNoise2dConst(consts[0], consts[1], consts[2])
2114            } else {
2115                JitOp::Fallback
2116            }
2117        }
2118
2119        // The conversion adapters are not named here. `conversion_op`
2120        // recognizes one from the conversion table and its port types
2121        // and lowers it by those types (engines.md §7.1).
2122        "trunc_u64" => JitOp::F64ToU64,
2123        // `round_u64` rounds half away from zero before the saturating
2124        // conversion, which is what `round_to_u64` does too.
2125        "round_u64" => JitOp::RoundToU64,
2126
2127        "weighted_pick" => {
2128            if consts.len() >= 5 {
2129                JitOp::WeightedPickConst(consts[0], consts[1], consts[2], consts[3], consts[4])
2130            } else {
2131                JitOp::Fallback
2132            }
2133        }
2134
2135        // ── Parameter helpers (library_catalog.md) ─────────────
2136        // `is_positive` / `in_range` are JIT-lowered inline: one
2137        // comparison on the happy path, an extern call on the
2138        // fail path (which panics). The pass-through is a plain
2139        // store, no function call overhead on the typical cycle.
2140        "is_positive" => {
2141            let name = node.meta().ins.iter().find_map(|slot| match slot {
2142                crate::ast::Slot::Const {
2143                    name,
2144                    value: crate::ast::ConstValue::Str(v),
2145                } if name == "name" => Some(v),
2146                _ => None,
2147            });
2148            match name {
2149                Some(v) => JitOp::IsPositiveCheck {
2150                    name_ptr: v.as_ptr() as u64,
2151                    name_len: v.len() as u64,
2152                },
2153                None => JitOp::IsPositiveCheck {
2154                    name_ptr: 0,
2155                    name_len: 0,
2156                },
2157            }
2158        }
2159        "in_range" => {
2160            if consts.len() >= 2 {
2161                JitOp::InRangeCheck(consts[0], consts[1])
2162            } else {
2163                JitOp::Fallback
2164            }
2165        }
2166        "is_one_of" => {
2167            if consts.is_empty() {
2168                JitOp::Fallback
2169            } else {
2170                let set = node.meta().ins.iter().find_map(|slot| match slot {
2171                    crate::ast::Slot::Const {
2172                        name,
2173                        value: crate::ast::ConstValue::VecU64(v),
2174                    } if name == "allowed" => Some(v),
2175                    _ => None,
2176                });
2177                let (set_ptr, set_len) = match set {
2178                    Some(v) => (v.as_ptr() as u64, v.len() as u64),
2179                    None => (0, 0),
2180                };
2181                JitOp::IsOneOfCheck {
2182                    allowed: consts,
2183                    set_ptr,
2184                    set_len,
2185                }
2186            }
2187        }
2188        // Every other node with a kit (`required`, `this_or`,
2189        // `matches`, the context nodes) takes `JitOp::SlotCall` in
2190        // `classify_node_typed`; only a node with no kit stays
2191        // interpreted.
2192        _ => JitOp::Fallback,
2193    }
2194}
2195
2196// ── Kernel constructors ────────────────────────────────────
2197
2198/// Compile a set of JIT steps into a raw (no-provenance) native kernel.
2199///
2200/// Each step has: jit_op, input_slots (buffer indices), output_slots.
2201/// The generated function reads coords from the buffer, executes
2202/// all steps in order, and writes results to the buffer.
2203#[doc(hidden)]
2204pub fn compile_jit_raw(
2205    coord_count: usize,
2206    total_slots: usize,
2207    steps: Vec<(JitOp, Vec<usize>, Vec<usize>)>,
2208    output_map: HashMap<String, usize>,
2209    nodes: Vec<Box<dyn PolydatNode>>,
2210) -> Result<JitKernelRaw, String> {
2211    let alone = vec![false; steps.len()];
2212    compile_jit_raw_with(
2213        coord_count,
2214        total_slots,
2215        steps,
2216        output_map,
2217        nodes,
2218        crate::compile::externs::Externs::coordinates_only(coord_count),
2219        super::kernels::ScratchPlan::default(),
2220        Vec::new(),
2221        alone,
2222    )
2223}
2224
2225/// The fusion units of a pure-native program (compile::fusion_units):
2226/// steps joined where one reads another's output, a volatile step never
2227/// with a pure one, and a step marked `alone` (a side channel) in a unit
2228/// of its own. A step never shares a unit with one that depends on other
2229/// externs of `unset_read`, the slots of the externs a host can leave
2230/// with no value, sorted: a pull is refused for an unset extern only
2231/// where its output depends on it. The steps' own order is the
2232/// preferred one.
2233fn pure_units(
2234    steps: &[(JitOp, Vec<usize>, Vec<usize>)],
2235    total_slots: usize,
2236    alone: &[bool],
2237    volatile: &[usize],
2238    unset_read: &[usize],
2239) -> crate::compile::fusion_units::UnitPlan {
2240    let mut producer = vec![usize::MAX; total_slots + 1];
2241    for (i, (_, _, outs)) in steps.iter().enumerate() {
2242        for &s in outs {
2243            if s < producer.len() {
2244                producer[s] = i;
2245            }
2246        }
2247    }
2248    let preds: Vec<Vec<usize>> = steps
2249        .iter()
2250        .map(|(_, ins, _)| {
2251            let mut p: Vec<usize> = ins
2252                .iter()
2253                .filter_map(|&s| producer.get(s).copied().filter(|&p| p != usize::MAX))
2254                .collect();
2255            p.sort_unstable();
2256            p.dedup();
2257            p
2258        })
2259        .collect();
2260    // A slot no step writes is a kernel input; its slot is its id.
2261    let inputs_read: Vec<Vec<usize>> = steps
2262        .iter()
2263        .map(|(_, ins, _)| {
2264            ins.iter()
2265                .copied()
2266                .filter(|&s| producer.get(s).is_some_and(|&p| p == usize::MAX))
2267                .collect()
2268        })
2269        .collect();
2270    let fusible: Vec<bool> = (0..steps.len())
2271        .map(|i| !alone.get(i).copied().unwrap_or(false))
2272        .collect();
2273    let mut class = vec![0u64; steps.len()];
2274    for &v in volatile {
2275        if v < class.len() {
2276            class[v] = 1;
2277        }
2278    }
2279    let reads: Vec<Vec<usize>> = inputs_read
2280        .iter()
2281        .map(|ins| {
2282            ins.iter()
2283                .copied()
2284                .filter(|s| unset_read.binary_search(s).is_ok())
2285                .collect()
2286        })
2287        .collect();
2288    let class = crate::compile::fusion_units::refine_by_externs(&preds, &reads, &class);
2289    let rank: Vec<usize> = (0..steps.len()).collect();
2290    crate::compile::fusion_units::plan_units(&preds, &inputs_read, &fusible, &class, &rank, &|_| {
2291        false
2292    })
2293}
2294
2295/// Per input slot, the units that read it, directly or not, from the
2296/// same per-step lists.
2297fn unit_dependents(
2298    input_dependents: Vec<Vec<usize>>,
2299    plan: &crate::compile::fusion_units::UnitPlan,
2300) -> Vec<Vec<usize>> {
2301    input_dependents
2302        .into_iter()
2303        .map(|steps| {
2304            let mut units: Vec<usize> = steps.iter().map(|&s| plan.unit_of[s]).collect();
2305            units.sort_unstable();
2306            units.dedup();
2307            units
2308        })
2309        .collect()
2310}
2311
2312/// `compile_jit_raw` for a graph with extern inputs: their defaults
2313/// are written through into the buffer at build.
2314#[allow(clippy::too_many_arguments)]
2315pub(crate) fn compile_jit_raw_with(
2316    coord_count: usize,
2317    total_slots: usize,
2318    steps: Vec<(JitOp, Vec<usize>, Vec<usize>)>,
2319    output_map: HashMap<String, usize>,
2320    nodes: Vec<Box<dyn PolydatNode>>,
2321    externs: crate::compile::externs::Externs,
2322    scratch: super::kernels::ScratchPlan,
2323    volatile: Vec<usize>,
2324    alone: Vec<bool>,
2325) -> Result<JitKernelRaw, String> {
2326    // The dispatched entry, as push-pull has: raw differs in what a
2327    // write dirties (every unit, a new round) and not in how a pull runs.
2328    let plan = pure_units(
2329        &steps,
2330        total_slots,
2331        &alone,
2332        &volatile,
2333        &externs.unset_read_slots(),
2334    );
2335    let (_, entry, code) = compile_jit_impl(&steps, Some(&plan.units), Some(total_slots))?;
2336    let cones =
2337        super::kernels::ConePlan::new(&steps, total_slots, &plan, output_map.values().copied());
2338    let mut core = JitCore::new(
2339        total_slots,
2340        coord_count,
2341        output_map,
2342        code,
2343        nodes,
2344        scratch,
2345        volatile,
2346        entry,
2347        cones,
2348    );
2349    core.set_externs(externs);
2350    core.engine =
2351        crate::compile::select::Engine::PureNative(crate::compile::select::Provenance::Raw);
2352    Ok(JitKernelRaw { core })
2353}
2354
2355/// A compiled segment for an engine that owns its own buffer: the
2356/// entry point and the module that keeps it alive (interpreter cones,
2357/// hybrid JIT segments).
2358pub(crate) type JitSegmentCode = (NativeFn, super::kernels::JitCode);
2359
2360/// An entry with no kernel wrapper: a cone node or a hybrid segment
2361/// owns the function pointer and code, and the state evaluating it
2362/// provides the buffer and the scratch.
2363pub(crate) fn compile_jit_entry(
2364    steps: &[(JitOp, Vec<usize>, Vec<usize>)],
2365    tracker: Option<usize>,
2366) -> Result<JitSegmentCode, String> {
2367    let (raw_fn, _, code) = compile_jit_impl(steps, None, tracker)?;
2368    Ok((raw_fn, code))
2369}
2370
2371/// Compile a set of JIT steps into a push+pull (full optimization) native kernel.
2372#[allow(clippy::too_many_arguments)]
2373pub(crate) fn compile_jit_push_pull(
2374    coord_count: usize,
2375    total_slots: usize,
2376    steps: Vec<(JitOp, Vec<usize>, Vec<usize>)>,
2377    output_map: HashMap<String, usize>,
2378    nodes: Vec<Box<dyn PolydatNode>>,
2379    input_dependents: Vec<Vec<usize>>,
2380    externs: crate::compile::externs::Externs,
2381    scratch: super::kernels::ScratchPlan,
2382    volatile: Vec<usize>,
2383    alone: Vec<bool>,
2384) -> Result<JitKernelPushPull, String> {
2385    let buffer_len = total_slots;
2386    let plan = pure_units(
2387        &steps,
2388        total_slots,
2389        &alone,
2390        &volatile,
2391        &externs.unset_read_slots(),
2392    );
2393    let (_, entry, code) = compile_jit_impl(&steps, Some(&plan.units), Some(total_slots))?;
2394    let step_outs: Vec<&[usize]> = steps.iter().map(|(_, _, o)| o.as_slice()).collect();
2395    let slot_provenance =
2396        crate::compile::slot_provenance(coord_count, buffer_len, &step_outs, &input_dependents);
2397    let cones =
2398        super::kernels::ConePlan::new(&steps, total_slots, &plan, output_map.values().copied());
2399    let input_dependents = unit_dependents(input_dependents, &plan);
2400    let mut core = JitCore::new(
2401        total_slots,
2402        coord_count,
2403        output_map,
2404        code,
2405        nodes,
2406        scratch,
2407        volatile,
2408        entry,
2409        cones,
2410    );
2411    core.set_externs(externs);
2412    Ok(JitKernelPushPull {
2413        core,
2414        input_dependents,
2415        slot_provenance,
2416        changed_mask: crate::kernel::ProvMask::all_below(coord_count),
2417        force_run: false,
2418    })
2419}
2420
2421// ── Core Cranelift IR generation ───────────────────────────
2422
2423/// A native entry point over a state's slot buffer and scratch.
2424pub type NativeFn = unsafe fn(*const u64, *mut u64, *mut crate::ast::ScratchBuf);
2425/// The dispatched variant: after the scratch, a list of unit indices
2426/// and its length. The code runs those units, each one block of its
2427/// steps, in the list's order, and nothing else.
2428pub type NativeDispatchFn =
2429    unsafe fn(*const u64, *mut u64, *mut crate::ast::ScratchBuf, *const u32, u64, *mut u8);
2430
2431/// `(straight_fn, dispatch_fn, code)` — produced by the core JIT
2432/// compile: the entry that runs every step in order, the entry that
2433/// runs a list of units, and the finalized code that keeps them alive
2434/// with the kits they call. One of the two entries is real, per the
2435/// `dispatch` argument; the other is the same address and never called.
2436type JitCompiled = (NativeFn, NativeDispatchFn, super::kernels::JitCode);
2437
2438/// One compiled function of a module: its two views, as in
2439/// [`JitCompiled`], and whether it calls a helper and so can fail.
2440type JitEntry = (NativeFn, NativeDispatchFn, bool);
2441
2442/// The steps of one function to compile and, for the dispatched form,
2443/// its units.
2444type JitFunctionSpec<'a> = (
2445    &'a [(JitOp, Vec<usize>, Vec<usize>)],
2446    Option<&'a [Vec<usize>]>,
2447);
2448
2449/// Core JIT compilation of one function. With `dispatch`, the function
2450/// takes a list of the given units to run; without, it runs every step
2451/// in order.
2452fn compile_jit_impl(
2453    steps: &[(JitOp, Vec<usize>, Vec<usize>)],
2454    dispatch: Option<&[Vec<usize>]>,
2455    tracker: Option<usize>,
2456) -> Result<JitCompiled, String> {
2457    let (entries, code) = compile_jit_module(&[(steps, dispatch)], tracker)?;
2458    let (straight_fn, dispatch_fn, _) = entries[0];
2459    Ok((straight_fn, dispatch_fn, code))
2460}
2461
2462/// One step of native code: its op, its input slots, its output slots.
2463pub(crate) type JitStep = (JitOp, Vec<usize>, Vec<usize>);
2464
2465/// The straight entries of several step lists, compiled as functions
2466/// of one module: a hybrid kernel's segments, whose code then lies
2467/// together. Each entry comes with whether it can fail.
2468pub(crate) fn compile_jit_entries(
2469    batches: &[&[JitStep]],
2470    tracker: Option<usize>,
2471) -> Result<(Vec<(NativeFn, bool)>, super::kernels::JitCode), String> {
2472    let specs: Vec<JitFunctionSpec> = batches.iter().map(|&b| (b, None)).collect();
2473    let (entries, code) = compile_jit_module(&specs, tracker)?;
2474    Ok((
2475        entries
2476            .into_iter()
2477            .map(|(f, _, fallible)| (f, fallible))
2478            .collect(),
2479        code,
2480    ))
2481}
2482
2483/// Core JIT compilation: every function of `functions` into one module.
2484fn compile_jit_module(
2485    functions: &[JitFunctionSpec],
2486    tracker: Option<usize>,
2487) -> Result<(Vec<JitEntry>, super::kernels::JitCode), String> {
2488    let mut flag_builder = settings::builder();
2489    flag_builder.set("opt_level", "speed").unwrap();
2490    // Unwind tables and frame pointers are kept for debuggers and
2491    // profilers walking JIT frames; failures never unwind through
2492    // native code, they longjmp past it (see the setjmp section
2493    // above).
2494    flag_builder.set("unwind_info", "true").unwrap();
2495    flag_builder.set("preserve_frame_pointers", "true").unwrap();
2496    let isa = super::host_isa::build_host_isa(flag_builder)?;
2497
2498    let mut jit_builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
2499
2500    // Register extern functions
2501    jit_builder.symbol("jit_xxh3_hash", jit_xxh3_hash as *const u8);
2502    jit_builder.symbol("jit_interleave", jit_interleave as *const u8);
2503    jit_builder.symbol("jit_shuffle", jit_shuffle as *const u8);
2504    jit_builder.symbol("jit_lut_sample", jit_lut_sample as *const u8);
2505    jit_builder.symbol("jit_weighted_pick", jit_weighted_pick as *const u8);
2506    jit_builder.symbol("jit_pcg", jit_pcg as *const u8);
2507    jit_builder.symbol("jit_pcg_stream", jit_pcg_stream as *const u8);
2508    jit_builder.symbol("jit_n_of", jit_n_of as *const u8);
2509    jit_builder.symbol("jit_cycle_walk", jit_cycle_walk as *const u8);
2510    jit_builder.symbol("jit_perlin_1d", jit_perlin_1d as *const u8);
2511    jit_builder.symbol("jit_perlin_2d", jit_perlin_2d as *const u8);
2512    jit_builder.symbol("jit_simplex_2d", jit_simplex_2d as *const u8);
2513    jit_builder.symbol("jit_fractal_noise_1d", jit_fractal_noise_1d as *const u8);
2514    jit_builder.symbol("jit_fractal_noise_2d", jit_fractal_noise_2d as *const u8);
2515    jit_builder.symbol("jit_thread_id", jit_thread_id as *const u8);
2516    jit_builder.symbol(
2517        "jit_current_epoch_millis",
2518        jit_current_epoch_millis as *const u8,
2519    );
2520    // Parameter-helper predicates (library_catalog.md §"Parameter
2521    // resolution and validation"): happy path is inline, violation is an
2522    // extern call that never returns.
2523    jit_builder.symbol("jit_is_positive_fail", jit_is_positive_fail as *const u8);
2524    jit_builder.symbol("jit_in_range_fail", jit_in_range_fail as *const u8);
2525    jit_builder.symbol("jit_is_one_of_fail", jit_is_one_of_fail as *const u8);
2526    // A node's slot kit, called from native code (compiled_handles.md §6),
2527    // and the string producers that write into the step's entry directly.
2528    jit_builder.symbol("jit_slot_call", jit_slot_call as *const u8);
2529    jit_builder.symbol("jit_u64_to_str", jit_u64_to_str as *const u8);
2530    jit_builder.symbol("jit_i64_to_str", jit_i64_to_str as *const u8);
2531    jit_builder.symbol("jit_f64_to_str", jit_f64_to_str as *const u8);
2532    jit_builder.symbol("jit_str_concat", jit_str_concat as *const u8);
2533    jit_builder.symbol("jit_json_to_str", jit_json_to_str as *const u8);
2534    jit_builder.symbol("jit_vec_add", jit_vec_add as *const u8);
2535    jit_builder.symbol("jit_vec_scale", jit_vec_scale as *const u8);
2536    jit_builder.symbol("jit_vec_norm", jit_vec_norm as *const u8);
2537    jit_builder.symbol("jit_hash_vec", jit_hash_vec as *const u8);
2538    jit_builder.symbol("jit_xxhash3_vec", jit_xxhash3_vec as *const u8);
2539    jit_builder.symbol("jit_reg_to_vec_f32", jit_reg_to_vec_f32 as *const u8);
2540    jit_builder.symbol("jit_vec_dot", jit_vec_dot as *const u8);
2541    jit_builder.symbol("jit_vec_l2", jit_vec_l2 as *const u8);
2542    jit_builder.symbol("jit_vec_cosine", jit_vec_cosine as *const u8);
2543    jit_builder.symbol("jit_lid_mle", jit_lid_mle as *const u8);
2544    jit_builder.symbol("jit_reg_lane_f32", jit_reg_lane_f32 as *const u8);
2545    jit_builder.symbol("jit_reg_lane_i16", jit_reg_lane_i16 as *const u8);
2546    jit_builder.symbol("jit_reg_lane_i64", jit_reg_lane_i64 as *const u8);
2547    jit_builder.symbol("jit_reg_with_lane_f32", jit_reg_with_lane_f32 as *const u8);
2548    jit_builder.symbol("jit_reg_gather_f32", jit_reg_gather_f32 as *const u8);
2549    jit_builder.symbol("jit_vec_to_reg_f32", jit_vec_to_reg_f32 as *const u8);
2550    jit_builder.symbol("jit_reg_mul_i8", jit_reg_mul_i8 as *const u8);
2551    // Math externs
2552    jit_builder.symbol("jit_sin", jit_sin as *const u8);
2553    jit_builder.symbol("jit_cos", jit_cos as *const u8);
2554    jit_builder.symbol("jit_tan", jit_tan as *const u8);
2555    jit_builder.symbol("jit_asin", jit_asin as *const u8);
2556    jit_builder.symbol("jit_acos", jit_acos as *const u8);
2557    jit_builder.symbol("jit_atan", jit_atan as *const u8);
2558    jit_builder.symbol("jit_sqrt", jit_sqrt as *const u8);
2559    jit_builder.symbol("jit_abs_f64", jit_abs_f64 as *const u8);
2560    jit_builder.symbol("jit_ln", jit_ln as *const u8);
2561    jit_builder.symbol("jit_exp", jit_exp as *const u8);
2562    jit_builder.symbol("jit_floor_base10", jit_floor_base10 as *const u8);
2563    jit_builder.symbol("jit_ceiling_base10", jit_ceiling_base10 as *const u8);
2564    jit_builder.symbol("jit_closest_base10", jit_closest_base10 as *const u8);
2565    jit_builder.symbol("jit_floor_decade", jit_floor_decade as *const u8);
2566    jit_builder.symbol("jit_ceiling_decade", jit_ceiling_decade as *const u8);
2567    jit_builder.symbol("jit_closest_decade", jit_closest_decade as *const u8);
2568    jit_builder.symbol("jit_floor_binomial", jit_floor_binomial as *const u8);
2569    jit_builder.symbol("jit_ceiling_binomial", jit_ceiling_binomial as *const u8);
2570    jit_builder.symbol("jit_closest_binomial", jit_closest_binomial as *const u8);
2571    jit_builder.symbol("jit_floor_fibonacci", jit_floor_fibonacci as *const u8);
2572    jit_builder.symbol("jit_ceiling_fibonacci", jit_ceiling_fibonacci as *const u8);
2573    jit_builder.symbol("jit_closest_fibonacci", jit_closest_fibonacci as *const u8);
2574    jit_builder.symbol("jit_atan2", jit_atan2 as *const u8);
2575    jit_builder.symbol("jit_pow", jit_pow as *const u8);
2576    jit_builder.symbol("jit_round_nearest", jit_round_nearest as *const u8);
2577    jit_builder.symbol("jit_round_floor", jit_round_floor as *const u8);
2578    jit_builder.symbol("jit_round_ceiling", jit_round_ceiling as *const u8);
2579    jit_builder.symbol("jit_f64_mod", jit_f64_mod as *const u8);
2580    jit_builder.symbol("jit_div_zero_fail", jit_div_zero_fail as *const u8);
2581
2582    let mut module = JITModule::new(jit_builder);
2583
2584    // Declare extern: hash(u64) -> u64
2585    let hash_func_id = {
2586        let mut sig = module.make_signature();
2587        sig.params.push(AbiParam::new(types::I64));
2588        sig.returns.push(AbiParam::new(types::I64));
2589        module
2590            .declare_function("jit_xxh3_hash", Linkage::Import, &sig)
2591            .map_err(|e| format!("declare hash: {e}"))?
2592    };
2593
2594    // Declare extern: interleave(u64, u64) -> u64
2595    let interleave_func_id = {
2596        let mut sig = module.make_signature();
2597        sig.params.push(AbiParam::new(types::I64));
2598        sig.params.push(AbiParam::new(types::I64));
2599        sig.returns.push(AbiParam::new(types::I64));
2600        module
2601            .declare_function("jit_interleave", Linkage::Import, &sig)
2602            .map_err(|e| format!("declare interleave: {e}"))?
2603    };
2604
2605    // Declare extern: shuffle(u64, u64, u64, u64) -> u64
2606    let shuffle_func_id = {
2607        let mut sig = module.make_signature();
2608        for _ in 0..4 {
2609            sig.params.push(AbiParam::new(types::I64));
2610        }
2611        sig.returns.push(AbiParam::new(types::I64));
2612        module
2613            .declare_function("jit_shuffle", Linkage::Import, &sig)
2614            .map_err(|e| format!("declare shuffle: {e}"))?
2615    };
2616
2617    // Declare extern: lut_sample(u64, u64, u64) -> u64
2618    let lut_sample_func_id = {
2619        let mut sig = module.make_signature();
2620        for _ in 0..3 {
2621            sig.params.push(AbiParam::new(types::I64));
2622        }
2623        sig.returns.push(AbiParam::new(types::I64));
2624        module
2625            .declare_function("jit_lut_sample", Linkage::Import, &sig)
2626            .map_err(|e| format!("declare lut_sample: {e}"))?
2627    };
2628
2629    // Declare extern: weighted_pick(u64, u64, u64, u64, u64, u64) -> u64
2630    let weighted_pick_func_id = {
2631        let mut sig = module.make_signature();
2632        for _ in 0..6 {
2633            sig.params.push(AbiParam::new(types::I64));
2634        }
2635        sig.returns.push(AbiParam::new(types::I64));
2636        module
2637            .declare_function("jit_weighted_pick", Linkage::Import, &sig)
2638            .map_err(|e| format!("declare weighted_pick: {e}"))?
2639    };
2640
2641    let pcg_func_id = {
2642        let mut sig = module.make_signature();
2643        for _ in 0..3 {
2644            sig.params.push(AbiParam::new(types::I64));
2645        }
2646        sig.returns.push(AbiParam::new(types::I64));
2647        module
2648            .declare_function("jit_pcg", Linkage::Import, &sig)
2649            .map_err(|e| format!("declare pcg: {e}"))?
2650    };
2651    let pcg_stream_func_id = {
2652        let mut sig = module.make_signature();
2653        for _ in 0..3 {
2654            sig.params.push(AbiParam::new(types::I64));
2655        }
2656        sig.returns.push(AbiParam::new(types::I64));
2657        module
2658            .declare_function("jit_pcg_stream", Linkage::Import, &sig)
2659            .map_err(|e| format!("declare pcg_stream: {e}"))?
2660    };
2661    let n_of_func_id = {
2662        let mut sig = module.make_signature();
2663        for _ in 0..3 {
2664            sig.params.push(AbiParam::new(types::I64));
2665        }
2666        sig.returns.push(AbiParam::new(types::I64));
2667        module
2668            .declare_function("jit_n_of", Linkage::Import, &sig)
2669            .map_err(|e| format!("declare n_of: {e}"))?
2670    };
2671    let cycle_walk_func_id = {
2672        let mut sig = module.make_signature();
2673        for _ in 0..4 {
2674            sig.params.push(AbiParam::new(types::I64));
2675        }
2676        sig.returns.push(AbiParam::new(types::I64));
2677        module
2678            .declare_function("jit_cycle_walk", Linkage::Import, &sig)
2679            .map_err(|e| format!("declare cycle_walk: {e}"))?
2680    };
2681    let perlin_1d_func_id = {
2682        let mut sig = module.make_signature();
2683        for _ in 0..3 {
2684            sig.params.push(AbiParam::new(types::I64));
2685        }
2686        sig.returns.push(AbiParam::new(types::I64));
2687        module
2688            .declare_function("jit_perlin_1d", Linkage::Import, &sig)
2689            .map_err(|e| format!("declare perlin_1d: {e}"))?
2690    };
2691    let perlin_2d_func_id = {
2692        let mut sig = module.make_signature();
2693        for _ in 0..4 {
2694            sig.params.push(AbiParam::new(types::I64));
2695        }
2696        sig.returns.push(AbiParam::new(types::I64));
2697        module
2698            .declare_function("jit_perlin_2d", Linkage::Import, &sig)
2699            .map_err(|e| format!("declare perlin_2d: {e}"))?
2700    };
2701    let simplex_2d_func_id = {
2702        let mut sig = module.make_signature();
2703        for _ in 0..4 {
2704            sig.params.push(AbiParam::new(types::I64));
2705        }
2706        sig.returns.push(AbiParam::new(types::I64));
2707        module
2708            .declare_function("jit_simplex_2d", Linkage::Import, &sig)
2709            .map_err(|e| format!("declare simplex_2d: {e}"))?
2710    };
2711    let fractal_noise_1d_func_id = {
2712        let mut sig = module.make_signature();
2713        for _ in 0..4 {
2714            sig.params.push(AbiParam::new(types::I64));
2715        }
2716        sig.returns.push(AbiParam::new(types::I64));
2717        module
2718            .declare_function("jit_fractal_noise_1d", Linkage::Import, &sig)
2719            .map_err(|e| format!("declare fractal_noise_1d: {e}"))?
2720    };
2721    let fractal_noise_2d_func_id = {
2722        let mut sig = module.make_signature();
2723        for _ in 0..5 {
2724            sig.params.push(AbiParam::new(types::I64));
2725        }
2726        sig.returns.push(AbiParam::new(types::I64));
2727        module
2728            .declare_function("jit_fractal_noise_2d", Linkage::Import, &sig)
2729            .map_err(|e| format!("declare fractal_noise_2d: {e}"))?
2730    };
2731    let thread_id_func_id = {
2732        let mut sig = module.make_signature();
2733        sig.returns.push(AbiParam::new(types::I64));
2734        module
2735            .declare_function("jit_thread_id", Linkage::Import, &sig)
2736            .map_err(|e| format!("declare thread_id: {e}"))?
2737    };
2738    let current_epoch_millis_func_id = {
2739        let mut sig = module.make_signature();
2740        sig.returns.push(AbiParam::new(types::I64));
2741        module
2742            .declare_function("jit_current_epoch_millis", Linkage::Import, &sig)
2743            .map_err(|e| format!("declare current_epoch_millis: {e}"))?
2744    };
2745
2746    // Declare math externs: unary (u64) -> u64
2747    let math_unary_names = [
2748        "jit_sin",
2749        "jit_cos",
2750        "jit_tan",
2751        "jit_asin",
2752        "jit_acos",
2753        "jit_atan",
2754        "jit_sqrt",
2755        "jit_abs_f64",
2756        "jit_ln",
2757        "jit_exp",
2758        "jit_floor_base10",
2759        "jit_ceiling_base10",
2760        "jit_closest_base10",
2761        "jit_floor_decade",
2762        "jit_ceiling_decade",
2763        "jit_closest_decade",
2764        "jit_floor_binomial",
2765        "jit_ceiling_binomial",
2766        "jit_closest_binomial",
2767        "jit_floor_fibonacci",
2768        "jit_ceiling_fibonacci",
2769        "jit_closest_fibonacci",
2770    ];
2771    let mut math_unary_ids = Vec::new();
2772    for name in &math_unary_names {
2773        let mut sig = module.make_signature();
2774        sig.params.push(AbiParam::new(types::I64));
2775        sig.returns.push(AbiParam::new(types::I64));
2776        math_unary_ids.push(
2777            module
2778                .declare_function(name, Linkage::Import, &sig)
2779                .map_err(|e| format!("declare {name}: {e}"))?,
2780        );
2781    }
2782
2783    // Declare param-helper extern:
2784    // jit_is_positive_fail(u64, name_ptr, name_len) -> u64
2785    // (never returns, but the ABI requires a return type).
2786    let is_positive_fail_id = {
2787        let mut sig = module.make_signature();
2788        sig.params.push(AbiParam::new(types::I64));
2789        sig.params.push(AbiParam::new(types::I64));
2790        sig.params.push(AbiParam::new(types::I64));
2791        sig.returns.push(AbiParam::new(types::I64));
2792        module
2793            .declare_function("jit_is_positive_fail", Linkage::Import, &sig)
2794            .map_err(|e| format!("declare is_positive_fail: {e}"))?
2795    };
2796
2797    // Declare param-helper extern: jit_in_range_fail(u64, u64, u64) -> u64
2798    let in_range_fail_id = {
2799        let mut sig = module.make_signature();
2800        for _ in 0..3 {
2801            sig.params.push(AbiParam::new(types::I64));
2802        }
2803        sig.returns.push(AbiParam::new(types::I64));
2804        module
2805            .declare_function("jit_in_range_fail", Linkage::Import, &sig)
2806            .map_err(|e| format!("declare in_range_fail: {e}"))?
2807    };
2808
2809    // Declare param-helper extern:
2810    // jit_is_one_of_fail(u64, set_ptr, set_len) -> u64
2811    let is_one_of_fail_id = {
2812        let mut sig = module.make_signature();
2813        sig.params.push(AbiParam::new(types::I64));
2814        sig.params.push(AbiParam::new(types::I64));
2815        sig.params.push(AbiParam::new(types::I64));
2816        sig.returns.push(AbiParam::new(types::I64));
2817        module
2818            .declare_function("jit_is_one_of_fail", Linkage::Import, &sig)
2819            .map_err(|e| format!("declare is_one_of_fail: {e}"))?
2820    };
2821
2822    // Declare math externs: binary (u64, u64) -> u64
2823    let math_binary_names = [
2824        "jit_atan2",
2825        "jit_pow",
2826        "jit_round_nearest",
2827        "jit_round_floor",
2828        "jit_round_ceiling",
2829        "jit_f64_mod",
2830    ];
2831    const F64_MOD_HELPER: usize = 5;
2832
2833    // Declare the zero-divisor failure: jit_div_zero_fail(kind) -> u64
2834    let div_zero_fail_id = {
2835        let mut sig = module.make_signature();
2836        sig.params.push(AbiParam::new(types::I64));
2837        sig.returns.push(AbiParam::new(types::I64));
2838        module
2839            .declare_function("jit_div_zero_fail", Linkage::Import, &sig)
2840            .map_err(|e| format!("declare div_zero_fail: {e}"))?
2841    };
2842    let mut math_binary_ids = Vec::new();
2843    for name in &math_binary_names {
2844        let mut sig = module.make_signature();
2845        sig.params.push(AbiParam::new(types::I64));
2846        sig.params.push(AbiParam::new(types::I64));
2847        sig.returns.push(AbiParam::new(types::I64));
2848        math_binary_ids.push(
2849            module
2850                .declare_function(name, Linkage::Import, &sig)
2851                .map_err(|e| format!("declare {name}: {e}"))?,
2852        );
2853    }
2854
2855    // Declare extern: jit_slot_call(kit, inputs, n_in, outputs, n_out,
2856    // scratch, base, n_scratch)
2857    let slot_call_id = {
2858        let mut sig = module.make_signature();
2859        for _ in 0..8 {
2860            sig.params.push(AbiParam::new(types::I64));
2861        }
2862        module
2863            .declare_function("jit_slot_call", Linkage::Import, &sig)
2864            .map_err(|e| format!("declare jit_slot_call: {e}"))?
2865    };
2866
2867    // Declare the string producers: (scratch, base, buffer, out_slot,
2868    // value) for the scalar conversions, (…, ptr, len) for the JSON
2869    // serialization and (…, pairs ptr, n) for the concatenation.
2870    let mut declare_str = |name: &str, args: usize| -> Result<cranelift_module::FuncId, String> {
2871        let mut sig = module.make_signature();
2872        for _ in 0..args {
2873            sig.params.push(AbiParam::new(types::I64));
2874        }
2875        module
2876            .declare_function(name, Linkage::Import, &sig)
2877            .map_err(|e| format!("declare {name}: {e}"))
2878    };
2879    let u64_to_str_id = declare_str("jit_u64_to_str", 5)?;
2880    let i64_to_str_id = declare_str("jit_i64_to_str", 5)?;
2881    let f64_to_str_id = declare_str("jit_f64_to_str", 5)?;
2882    let str_concat_id = declare_str("jit_str_concat", 6)?;
2883    let json_to_str_id = declare_str("jit_json_to_str", 6)?;
2884
2885    // Declare the vector and register helpers: a producer takes
2886    // (scratch, base, buffer, out_slot, w0..w3), a reducer (w0..w3)
2887    // and returns bits, a lane read (lo, hi, i) and returns the word,
2888    // a register producer (buffer, out_slot, w0..w3).
2889    let mut declare_words =
2890        |name: &str, args: usize, returns: bool| -> Result<cranelift_module::FuncId, String> {
2891            let mut sig = module.make_signature();
2892            for _ in 0..args {
2893                sig.params.push(AbiParam::new(types::I64));
2894            }
2895            if returns {
2896                sig.returns.push(AbiParam::new(types::I64));
2897            }
2898            module
2899                .declare_function(name, Linkage::Import, &sig)
2900                .map_err(|e| format!("declare {name}: {e}"))
2901        };
2902    let vec_producer_ids = [
2903        (VecProducer::Add, declare_words("jit_vec_add", 8, false)?),
2904        (
2905            VecProducer::Scale,
2906            declare_words("jit_vec_scale", 8, false)?,
2907        ),
2908        (VecProducer::Norm, declare_words("jit_vec_norm", 8, false)?),
2909        (
2910            VecProducer::HashVec,
2911            declare_words("jit_hash_vec", 8, false)?,
2912        ),
2913        (
2914            VecProducer::XxHash3Vec,
2915            declare_words("jit_xxhash3_vec", 8, false)?,
2916        ),
2917        (
2918            VecProducer::RegToVec,
2919            declare_words("jit_reg_to_vec_f32", 8, false)?,
2920        ),
2921    ];
2922    let vec_reducer_ids = [
2923        (VecReducer::Dot, declare_words("jit_vec_dot", 4, true)?),
2924        (VecReducer::L2, declare_words("jit_vec_l2", 4, true)?),
2925        (
2926            VecReducer::Cosine,
2927            declare_words("jit_vec_cosine", 4, true)?,
2928        ),
2929        (VecReducer::LidMle, declare_words("jit_lid_mle", 4, true)?),
2930    ];
2931    let reg_lane_ids = [
2932        (
2933            RegLaneRead::F32,
2934            declare_words("jit_reg_lane_f32", 3, true)?,
2935        ),
2936        (
2937            RegLaneRead::I16,
2938            declare_words("jit_reg_lane_i16", 3, true)?,
2939        ),
2940        (
2941            RegLaneRead::I64,
2942            declare_words("jit_reg_lane_i64", 3, true)?,
2943        ),
2944    ];
2945    let reg_producer_ids = [
2946        (
2947            RegProducer::WithLaneF32,
2948            declare_words("jit_reg_with_lane_f32", 6, false)?,
2949        ),
2950        (
2951            RegProducer::GatherF32,
2952            declare_words("jit_reg_gather_f32", 6, false)?,
2953        ),
2954        (
2955            RegProducer::VecToRegF32,
2956            declare_words("jit_vec_to_reg_f32", 6, false)?,
2957        ),
2958        (
2959            RegProducer::MulI8,
2960            declare_words("jit_reg_mul_i8", 6, false)?,
2961        ),
2962    ];
2963
2964    // Every function of the module, built one after another: they share
2965    // the imports above and one finalization, and their code lies
2966    // together, so a kernel that runs many of them per cycle does not
2967    // walk a code region per function.
2968    let mut defined: Vec<(cranelift_module::FuncId, bool)> = Vec::with_capacity(functions.len());
2969    for (function_idx, &(steps, dispatch)) in functions.iter().enumerate() {
2970        // Straight: fn(coords: *const u64, buffer: *mut u64, scratch: *mut ScratchBuf)
2971        // Dispatched: fn(coords, buffer, scratch, units: *const u32, count: u64,
2972        // clean: *mut u8)
2973        let mut sig = module.make_signature();
2974        sig.params.push(AbiParam::new(types::I64)); // coords ptr
2975        sig.params.push(AbiParam::new(types::I64)); // buffer ptr
2976        sig.params.push(AbiParam::new(types::I64)); // scratch ptr
2977        if dispatch.is_some() {
2978            sig.params.push(AbiParam::new(types::I64)); // unit list ptr
2979            sig.params.push(AbiParam::new(types::I64)); // unit count
2980            sig.params.push(AbiParam::new(types::I64)); // unit clean flags
2981        }
2982        let func_id = module
2983            .declare_function(
2984                &format!("polydat_kernel_{function_idx}"),
2985                Linkage::Local,
2986                &sig,
2987            )
2988            .map_err(|e| format!("declare kernel: {e}"))?;
2989
2990        let mut ctx = module.make_context();
2991        ctx.func.signature = sig;
2992
2993        let mut fb_ctx = FunctionBuilderContext::new();
2994        {
2995            let mut builder = FunctionBuilder::new(&mut ctx.func, &mut fb_ctx);
2996            let block = builder.create_block();
2997            builder.append_block_params_for_function_params(block);
2998            builder.switch_to_block(block);
2999            builder.seal_block(block);
3000
3001            let _coords_ptr = builder.block_params(block)[0];
3002            let buffer_ptr = builder.block_params(block)[1];
3003            let scratch_ptr = builder.block_params(block)[2];
3004
3005            // Import extern functions for calls
3006            let hash_func_ref = module.declare_func_in_func(hash_func_id, builder.func);
3007            let interleave_func_ref = module.declare_func_in_func(interleave_func_id, builder.func);
3008            let shuffle_func_ref = module.declare_func_in_func(shuffle_func_id, builder.func);
3009            let lut_sample_func_ref = module.declare_func_in_func(lut_sample_func_id, builder.func);
3010            let weighted_pick_func_ref =
3011                module.declare_func_in_func(weighted_pick_func_id, builder.func);
3012            let is_positive_fail_ref =
3013                module.declare_func_in_func(is_positive_fail_id, builder.func);
3014            let in_range_fail_ref = module.declare_func_in_func(in_range_fail_id, builder.func);
3015            let div_zero_fail_ref = module.declare_func_in_func(div_zero_fail_id, builder.func);
3016            let is_one_of_fail_ref = module.declare_func_in_func(is_one_of_fail_id, builder.func);
3017            let slot_call_ref = module.declare_func_in_func(slot_call_id, builder.func);
3018            let u64_to_str_ref = module.declare_func_in_func(u64_to_str_id, builder.func);
3019            let i64_to_str_ref = module.declare_func_in_func(i64_to_str_id, builder.func);
3020            let f64_to_str_ref = module.declare_func_in_func(f64_to_str_id, builder.func);
3021            let str_concat_ref = module.declare_func_in_func(str_concat_id, builder.func);
3022            let json_to_str_ref = module.declare_func_in_func(json_to_str_id, builder.func);
3023            let vec_producer_refs: Vec<(VecProducer, ir::FuncRef)> = vec_producer_ids
3024                .iter()
3025                .map(|(k, id)| (*k, module.declare_func_in_func(*id, builder.func)))
3026                .collect();
3027            let vec_reducer_refs: Vec<(VecReducer, ir::FuncRef)> = vec_reducer_ids
3028                .iter()
3029                .map(|(k, id)| (*k, module.declare_func_in_func(*id, builder.func)))
3030                .collect();
3031            let reg_lane_refs: Vec<(RegLaneRead, ir::FuncRef)> = reg_lane_ids
3032                .iter()
3033                .map(|(k, id)| (*k, module.declare_func_in_func(*id, builder.func)))
3034                .collect();
3035            let reg_producer_refs: Vec<(RegProducer, ir::FuncRef)> = reg_producer_ids
3036                .iter()
3037                .map(|(k, id)| (*k, module.declare_func_in_func(*id, builder.func)))
3038                .collect();
3039            let pcg_func_ref = module.declare_func_in_func(pcg_func_id, builder.func);
3040            let pcg_stream_func_ref = module.declare_func_in_func(pcg_stream_func_id, builder.func);
3041            let n_of_func_ref = module.declare_func_in_func(n_of_func_id, builder.func);
3042            let cycle_walk_func_ref = module.declare_func_in_func(cycle_walk_func_id, builder.func);
3043            let perlin_1d_func_ref = module.declare_func_in_func(perlin_1d_func_id, builder.func);
3044            let perlin_2d_func_ref = module.declare_func_in_func(perlin_2d_func_id, builder.func);
3045            let simplex_2d_func_ref = module.declare_func_in_func(simplex_2d_func_id, builder.func);
3046            let fractal_noise_1d_func_ref =
3047                module.declare_func_in_func(fractal_noise_1d_func_id, builder.func);
3048            let fractal_noise_2d_func_ref =
3049                module.declare_func_in_func(fractal_noise_2d_func_id, builder.func);
3050            let thread_id_func_ref = module.declare_func_in_func(thread_id_func_id, builder.func);
3051            let current_epoch_millis_func_ref =
3052                module.declare_func_in_func(current_epoch_millis_func_id, builder.func);
3053            let math_unary_refs: Vec<_> = math_unary_ids
3054                .iter()
3055                .map(|id| module.declare_func_in_func(*id, builder.func))
3056                .collect();
3057            let math_binary_refs: Vec<_> = math_binary_ids
3058                .iter()
3059                .map(|id| module.declare_func_in_func(*id, builder.func))
3060                .collect();
3061            // The dispatched form walks a list of units, each one block of
3062            // its steps in order, through a jump table: the caller hands it
3063            // a pull's precomputed cone order (runtime_model.md R2), and the
3064            // code tests each unit's clean flag itself, skips a current one,
3065            // and marks each it runs current when the unit's block ends. So
3066            // a pull runs the stale units of its cone in native code and
3067            // nothing else. Without units, the steps run in order.
3068            let everything: [Vec<usize>; 1] = [(0..steps.len()).collect()];
3069            let schedule: &[Vec<usize>] = dispatch.unwrap_or(&everything);
3070            let dispatcher = dispatch.map(|units| {
3071                let list_ptr = builder.block_params(block)[3];
3072                let list_len = builder.block_params(block)[4];
3073                let clean_ptr = builder.block_params(block)[5];
3074                let at = builder.create_sized_stack_slot(ir::StackSlotData::new(
3075                    ir::StackSlotKind::ExplicitSlot,
3076                    8,
3077                    3,
3078                ));
3079                let zero = builder.ins().iconst(types::I64, 0);
3080                builder.ins().stack_store(zero, at, 0);
3081                let head = builder.create_block();
3082                let fetch = builder.create_block();
3083                let dispatch_unit = builder.create_block();
3084                let skip = builder.create_block();
3085                let exit = builder.create_block();
3086                let unit_blocks: Vec<ir::Block> =
3087                    units.iter().map(|_| builder.create_block()).collect();
3088                builder.ins().jump(head, &[]);
3089                // head: stop at the end of the list.
3090                builder.switch_to_block(head);
3091                let i = builder.ins().stack_load(types::I64, at, 0);
3092                let done = builder.ins().icmp(
3093                    ir::condcodes::IntCC::UnsignedGreaterThanOrEqual,
3094                    i,
3095                    list_len,
3096                );
3097                builder.ins().brif(done, exit, &[], fetch, &[]);
3098                // fetch: the next unit's index and its clean flag; a current
3099                // unit is skipped.
3100                builder.switch_to_block(fetch);
3101                builder.seal_block(fetch);
3102                let offset = builder.ins().ishl_imm(i, 2);
3103                let addr = builder.ins().iadd(list_ptr, offset);
3104                let unit = builder
3105                    .ins()
3106                    .load(types::I32, ir::MemFlags::trusted(), addr, 0);
3107                let unit_wide = builder.ins().uextend(types::I64, unit);
3108                let flag_addr = builder.ins().iadd(clean_ptr, unit_wide);
3109                let flag = builder
3110                    .ins()
3111                    .load(types::I8, ir::MemFlags::trusted(), flag_addr, 0);
3112                builder.ins().brif(flag, skip, &[], dispatch_unit, &[]);
3113                // skip: on to the next in the list.
3114                builder.switch_to_block(skip);
3115                builder.seal_block(skip);
3116                let next = builder.ins().iadd_imm(i, 1);
3117                builder.ins().stack_store(next, at, 0);
3118                builder.ins().jump(head, &[]);
3119                // dispatch_unit: the unit's block.
3120                builder.switch_to_block(dispatch_unit);
3121                builder.seal_block(dispatch_unit);
3122                let default = builder.func.dfg.block_call(exit, &[]);
3123                let targets: Vec<ir::BlockCall> = unit_blocks
3124                    .iter()
3125                    .map(|&b| builder.func.dfg.block_call(b, &[]))
3126                    .collect();
3127                let table = builder.create_jump_table(ir::JumpTableData::new(default, &targets));
3128                builder.ins().br_table(unit, table);
3129                (at, head, exit, unit_blocks, clean_ptr)
3130            });
3131
3132            // Generate code for each step, unit by unit.
3133            for (unit_idx, members) in schedule.iter().enumerate() {
3134                if let Some((_, _, _, unit_blocks, _)) = &dispatcher {
3135                    builder.switch_to_block(unit_blocks[unit_idx]);
3136                    builder.seal_block(unit_blocks[unit_idx]);
3137                }
3138                for &step_idx in members {
3139                    let (jit_op, input_slots, output_slots) = &steps[step_idx];
3140                    // Name the step for the failure path (engines.md §3.4). The
3141                    // store stays only when the step calls a helper, the one way
3142                    // native code fails; a step of inline arithmetic pays nothing.
3143                    let tracker_store = tracker.map(|t| {
3144                        let idx = builder.ins().iconst(types::I64, step_idx as i64);
3145                        let inst = store_slot(&mut builder, buffer_ptr, t, idx);
3146                        (inst, builder.func.dfg.num_insts())
3147                    });
3148                    match jit_op {
3149                        JitOp::Identity => {
3150                            // A copy of every slot the port spans: one for a
3151                            // carrier or handle, two for a 128-bit immediate.
3152                            for (&i, &o) in input_slots.iter().zip(output_slots.iter()) {
3153                                let val = load_slot(&mut builder, buffer_ptr, i);
3154                                store_slot(&mut builder, buffer_ptr, o, val);
3155                            }
3156                        }
3157                        JitOp::AddConst(c) => {
3158                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3159                            let c_val = builder.ins().iconst(types::I64, *c as i64);
3160                            let result = builder.ins().iadd(val, c_val);
3161                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3162                        }
3163                        JitOp::MulConst(c) => {
3164                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3165                            let c_val = builder.ins().iconst(types::I64, *c as i64);
3166                            let result = builder.ins().imul(val, c_val);
3167                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3168                        }
3169                        JitOp::DivConst(c) | JitOp::ModConst(c) => {
3170                            // The body's `/` or `%` by the constant: a zero
3171                            // constant fails at every evaluation as it does.
3172                            let is_div = matches!(jit_op, JitOp::DivConst(_));
3173                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3174                            if *c == 0 {
3175                                let kind =
3176                                    builder.ins().iconst(types::I64, if is_div { 0 } else { 1 });
3177                                let _ = builder.ins().call(div_zero_fail_ref, &[kind]);
3178                                store_slot(&mut builder, buffer_ptr, output_slots[0], val);
3179                            } else {
3180                                let c_val = builder.ins().iconst(types::I64, *c as i64);
3181                                let result = if is_div {
3182                                    builder.ins().udiv(val, c_val)
3183                                } else {
3184                                    builder.ins().urem(val, c_val)
3185                                };
3186                                store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3187                            }
3188                        }
3189                        JitOp::U64DivWire | JitOp::U64ModWire => {
3190                            // The body's `/` or `%` by the wire: a zero divisor
3191                            // fails as it does there; `udiv` and `urem` trap on
3192                            // one, so the failure branches first.
3193                            let is_div = matches!(jit_op, JitOp::U64DivWire);
3194                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3195                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3196                            let zero = builder.ins().iconst(types::I64, 0);
3197                            let is_zero = builder.ins().icmp(ir::condcodes::IntCC::Equal, b, zero);
3198                            let fail_block = builder.create_block();
3199                            let ok_block = builder.create_block();
3200                            builder.ins().brif(is_zero, fail_block, &[], ok_block, &[]);
3201                            builder.switch_to_block(fail_block);
3202                            builder.seal_block(fail_block);
3203                            let kind = builder.ins().iconst(types::I64, if is_div { 0 } else { 1 });
3204                            let _ = builder.ins().call(div_zero_fail_ref, &[kind]);
3205                            builder.ins().jump(ok_block, &[]);
3206                            builder.switch_to_block(ok_block);
3207                            builder.seal_block(ok_block);
3208                            let result = if is_div {
3209                                builder.ins().udiv(a, b)
3210                            } else {
3211                                builder.ins().urem(a, b)
3212                            };
3213                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3214                        }
3215                        JitOp::ClampConst(min, max) => {
3216                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3217                            let min_val = builder.ins().iconst(types::I64, *min as i64);
3218                            let max_val = builder.ins().iconst(types::I64, *max as i64);
3219                            let clamped_lo = builder.ins().umax(val, min_val);
3220                            let clamped = builder.ins().umin(clamped_lo, max_val);
3221                            store_slot(&mut builder, buffer_ptr, output_slots[0], clamped);
3222                        }
3223                        JitOp::Interleave => {
3224                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3225                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3226                            let call = builder.ins().call(interleave_func_ref, &[a, b]);
3227                            let result = builder.inst_results(call)[0];
3228                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3229                        }
3230                        JitOp::MixedRadixConst(radixes) => {
3231                            // Unrolled: for each radix, emit urem + udiv
3232                            let mut remainder = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3233                            for (i, &radix) in radixes.iter().enumerate() {
3234                                if radix == 0 {
3235                                    // Unbounded: output = remainder
3236                                    store_slot(
3237                                        &mut builder,
3238                                        buffer_ptr,
3239                                        output_slots[i],
3240                                        remainder,
3241                                    );
3242                                } else {
3243                                    let r = builder.ins().iconst(types::I64, radix as i64);
3244                                    let digit = builder.ins().urem(remainder, r);
3245                                    store_slot(&mut builder, buffer_ptr, output_slots[i], digit);
3246                                    remainder = builder.ins().udiv(remainder, r);
3247                                }
3248                            }
3249                        }
3250                        JitOp::Hash => {
3251                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3252                            let call = builder.ins().call(hash_func_ref, &[val]);
3253                            let result = builder.inst_results(call)[0];
3254                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3255                        }
3256                        JitOp::SplitMix64 => {
3257                            let x0 = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3258                            let c_gamma = builder
3259                                .ins()
3260                                .iconst(types::I64, 0x9e3779b97f4a7c15u64 as i64);
3261                            let x1 = builder.ins().iadd(x0, c_gamma);
3262                            let s30 = builder.ins().ushr_imm(x1, 30);
3263                            let x2 = builder.ins().bxor(x1, s30);
3264                            let c_m1 = builder
3265                                .ins()
3266                                .iconst(types::I64, 0xbf58476d1ce4e5b9u64 as i64);
3267                            let x3 = builder.ins().imul(x2, c_m1);
3268                            let s27 = builder.ins().ushr_imm(x3, 27);
3269                            let x4 = builder.ins().bxor(x3, s27);
3270                            let c_m2 = builder
3271                                .ins()
3272                                .iconst(types::I64, 0x94d049bb133111ebu64 as i64);
3273                            let x5 = builder.ins().imul(x4, c_m2);
3274                            let s31 = builder.ins().ushr_imm(x5, 31);
3275                            let result = builder.ins().bxor(x5, s31);
3276                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3277                        }
3278                        JitOp::FairCoin => {
3279                            let x0 = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3280                            let c_gamma = builder
3281                                .ins()
3282                                .iconst(types::I64, 0x9e3779b97f4a7c15u64 as i64);
3283                            let x1 = builder.ins().iadd(x0, c_gamma);
3284                            let s30 = builder.ins().ushr_imm(x1, 30);
3285                            let x2 = builder.ins().bxor(x1, s30);
3286                            let c_m1 = builder
3287                                .ins()
3288                                .iconst(types::I64, 0xbf58476d1ce4e5b9u64 as i64);
3289                            let x3 = builder.ins().imul(x2, c_m1);
3290                            let s27 = builder.ins().ushr_imm(x3, 27);
3291                            let x4 = builder.ins().bxor(x3, s27);
3292                            let c_m2 = builder
3293                                .ins()
3294                                .iconst(types::I64, 0x94d049bb133111ebu64 as i64);
3295                            let x5 = builder.ins().imul(x4, c_m2);
3296                            let s31 = builder.ins().ushr_imm(x5, 31);
3297                            let h = builder.ins().bxor(x5, s31);
3298                            let one = builder.ins().iconst(types::I64, 1);
3299                            let result = builder.ins().band(h, one);
3300                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3301                        }
3302                        JitOp::CoinFlipConst(threshold) => {
3303                            let x = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3304                            let thr = builder.ins().iconst(types::I64, *threshold as i64);
3305                            let cmp =
3306                                builder
3307                                    .ins()
3308                                    .icmp(ir::condcodes::IntCC::UnsignedLessThan, x, thr);
3309                            let zero = builder.ins().iconst(types::I64, 0);
3310                            let one = builder.ins().iconst(types::I64, 1);
3311                            let result = builder.ins().select(cmp, one, zero);
3312                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3313                        }
3314                        JitOp::UnfairCoinConst(p_bits) => {
3315                            let x0 = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3316                            let c_gamma = builder
3317                                .ins()
3318                                .iconst(types::I64, 0x9e3779b97f4a7c15u64 as i64);
3319                            let x1 = builder.ins().iadd(x0, c_gamma);
3320                            let s30 = builder.ins().ushr_imm(x1, 30);
3321                            let x2 = builder.ins().bxor(x1, s30);
3322                            let c_m1 = builder
3323                                .ins()
3324                                .iconst(types::I64, 0xbf58476d1ce4e5b9u64 as i64);
3325                            let x3 = builder.ins().imul(x2, c_m1);
3326                            let s27 = builder.ins().ushr_imm(x3, 27);
3327                            let x4 = builder.ins().bxor(x3, s27);
3328                            let c_m2 = builder
3329                                .ins()
3330                                .iconst(types::I64, 0x94d049bb133111ebu64 as i64);
3331                            let x5 = builder.ins().imul(x4, c_m2);
3332                            let s31 = builder.ins().ushr_imm(x5, 31);
3333                            let h = builder.ins().bxor(x5, s31);
3334
3335                            let fval = builder.ins().fcvt_from_uint(types::F64, h);
3336                            let max_f = builder.ins().f64const(u64::MAX as f64);
3337                            let unit = builder.ins().fdiv(fval, max_f);
3338                            let p_f = builder.ins().f64const(f64::from_bits(*p_bits));
3339                            let cmp =
3340                                builder
3341                                    .ins()
3342                                    .fcmp(ir::condcodes::FloatCC::LessThan, unit, p_f);
3343                            let zero = builder.ins().iconst(types::I64, 0);
3344                            let one = builder.ins().iconst(types::I64, 1);
3345                            let result = builder.ins().select(cmp, one, zero);
3346                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3347                        }
3348                        JitOp::ChanceConst(p_bits) => {
3349                            let x0 = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3350                            let c_gamma = builder
3351                                .ins()
3352                                .iconst(types::I64, 0x9e3779b97f4a7c15u64 as i64);
3353                            let x1 = builder.ins().iadd(x0, c_gamma);
3354                            let s30 = builder.ins().ushr_imm(x1, 30);
3355                            let x2 = builder.ins().bxor(x1, s30);
3356                            let c_m1 = builder
3357                                .ins()
3358                                .iconst(types::I64, 0xbf58476d1ce4e5b9u64 as i64);
3359                            let x3 = builder.ins().imul(x2, c_m1);
3360                            let s27 = builder.ins().ushr_imm(x3, 27);
3361                            let x4 = builder.ins().bxor(x3, s27);
3362                            let c_m2 = builder
3363                                .ins()
3364                                .iconst(types::I64, 0x94d049bb133111ebu64 as i64);
3365                            let x5 = builder.ins().imul(x4, c_m2);
3366                            let s31 = builder.ins().ushr_imm(x5, 31);
3367                            let h = builder.ins().bxor(x5, s31);
3368
3369                            let fval = builder.ins().fcvt_from_uint(types::F64, h);
3370                            let max_f = builder.ins().f64const(u64::MAX as f64);
3371                            let unit = builder.ins().fdiv(fval, max_f);
3372                            let p_f = builder.ins().f64const(f64::from_bits(*p_bits));
3373                            let cmp =
3374                                builder
3375                                    .ins()
3376                                    .fcmp(ir::condcodes::FloatCC::LessThan, unit, p_f);
3377                            let zero_bits =
3378                                builder.ins().iconst(types::I64, 0.0_f64.to_bits() as i64);
3379                            let one_bits =
3380                                builder.ins().iconst(types::I64, 1.0_f64.to_bits() as i64);
3381                            let result = builder.ins().select(cmp, one_bits, zero_bits);
3382                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3383                        }
3384                        JitOp::ShuffleConst(feedback, size, min) => {
3385                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3386                            let fb = builder.ins().iconst(types::I64, *feedback as i64);
3387                            let sz = builder.ins().iconst(types::I64, *size as i64);
3388                            let mn = builder.ins().iconst(types::I64, *min as i64);
3389                            let call = builder.ins().call(shuffle_func_ref, &[val, fb, sz, mn]);
3390                            let result = builder.inst_results(call)[0];
3391                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3392                        }
3393
3394                        // --- f64 ops ---
3395                        JitOp::UnitInterval => {
3396                            // u64 → f64: input as f64 / u64::MAX as f64
3397                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3398                            let fval = builder.ins().fcvt_from_uint(types::F64, val);
3399                            let max_f = builder.ins().f64const(u64::MAX as f64);
3400                            let result = builder.ins().fdiv(fval, max_f);
3401                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], result);
3402                        }
3403                        JitOp::F64ToU64 => {
3404                            let fval = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3405                            let result = builder.ins().fcvt_to_uint_sat(types::I64, fval);
3406                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3407                        }
3408                        JitOp::RoundToU64 => {
3409                            let fval = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3410                            let rounded = round_half_away(&mut builder, fval);
3411                            let result = builder.ins().fcvt_to_uint_sat(types::I64, rounded);
3412                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3413                        }
3414                        JitOp::FloorToU64 => {
3415                            let fval = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3416                            let floored = builder.ins().floor(fval);
3417                            let result = builder.ins().fcvt_to_uint_sat(types::I64, floored);
3418                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3419                        }
3420                        JitOp::CeilToU64 => {
3421                            let fval = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3422                            let ceiled = builder.ins().ceil(fval);
3423                            let result = builder.ins().fcvt_to_uint_sat(types::I64, ceiled);
3424                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3425                        }
3426                        JitOp::ClampF64Const(min_bits, max_bits) => {
3427                            let fval = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3428                            let fmin = builder.ins().f64const(f64::from_bits(*min_bits));
3429                            let fmax = builder.ins().f64const(f64::from_bits(*max_bits));
3430                            let clamped = clamp_ir(&mut builder, fval, fmin, fmax);
3431                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], clamped);
3432                        }
3433                        JitOp::LerpConst(a_bits, b_bits) => {
3434                            // a + t * (b - a)
3435                            let t = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3436                            let a = builder.ins().f64const(f64::from_bits(*a_bits));
3437                            let b = builder.ins().f64const(f64::from_bits(*b_bits));
3438                            let diff = builder.ins().fsub(b, a);
3439                            let scaled = builder.ins().fmul(t, diff);
3440                            let result = builder.ins().fadd(a, scaled);
3441                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], result);
3442                        }
3443                        JitOp::ScaleRangeConst(min_bits, range_bits) => {
3444                            // min + range * (input as f64 / u64::MAX as f64)
3445                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3446                            let fval = builder.ins().fcvt_from_uint(types::F64, val);
3447                            let max_f = builder.ins().f64const(u64::MAX as f64);
3448                            let t = builder.ins().fdiv(fval, max_f);
3449                            let fmin = builder.ins().f64const(f64::from_bits(*min_bits));
3450                            let frange = builder.ins().f64const(f64::from_bits(*range_bits));
3451                            let scaled = builder.ins().fmul(t, frange);
3452                            let result = builder.ins().fadd(fmin, scaled);
3453                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], result);
3454                        }
3455                        JitOp::QuantizeConst(step_bits) => {
3456                            // round(val / step) * step
3457                            let fval = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3458                            let step = builder.ins().f64const(f64::from_bits(*step_bits));
3459                            let divided = builder.ins().fdiv(fval, step);
3460                            let rounded = round_half_away(&mut builder, divided);
3461                            let result = builder.ins().fmul(rounded, step);
3462                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], result);
3463                        }
3464
3465                        JitOp::LutSampleConst(lut_ptr, lut_len) => {
3466                            // Extern call: jit_lut_sample(input_bits, lut_ptr, lut_len) -> f64 bits
3467                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3468                            let ptr_val = builder.ins().iconst(types::I64, *lut_ptr as i64);
3469                            let len_val = builder.ins().iconst(types::I64, *lut_len as i64);
3470                            let call = builder
3471                                .ins()
3472                                .call(lut_sample_func_ref, &[input, ptr_val, len_val]);
3473                            let result = builder.inst_results(call)[0];
3474                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3475                        }
3476                        JitOp::DiscretizeConst(range_bits, buckets) => {
3477                            // min(clamp(input, 0.0, range) / range * buckets, buckets - 1),
3478                            // the node's body. Its declared constraints make the
3479                            // range positive and `buckets` at least one, so the
3480                            // `- 1` below cannot underflow.
3481                            let fval = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3482                            let range = f64::from_bits(*range_bits);
3483                            let fzero = builder.ins().f64const(0.0);
3484                            let frange = builder.ins().f64const(range);
3485                            let fbuckets = builder.ins().f64const(*buckets as f64);
3486                            let clamped = clamp_ir(&mut builder, fval, fzero, frange);
3487                            let divided = builder.ins().fdiv(clamped, frange);
3488                            let scaled = builder.ins().fmul(divided, fbuckets);
3489                            let as_u64 = builder.ins().fcvt_to_uint_sat(types::I64, scaled);
3490                            let max_bucket =
3491                                builder.ins().iconst(types::I64, (*buckets - 1) as i64);
3492                            let result = builder.ins().umin(as_u64, max_bucket);
3493                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3494                        }
3495
3496                        JitOp::WeightedPickConst(
3497                            values_ptr,
3498                            biases_ptr,
3499                            primaries_ptr,
3500                            aliases_ptr,
3501                            n,
3502                        ) => {
3503                            // Extern call: jit_weighted_pick(input, values_ptr, biases_ptr, primaries_ptr, aliases_ptr, n)
3504                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3505                            let v_ptr = builder.ins().iconst(types::I64, *values_ptr as i64);
3506                            let b_ptr = builder.ins().iconst(types::I64, *biases_ptr as i64);
3507                            let p_ptr = builder.ins().iconst(types::I64, *primaries_ptr as i64);
3508                            let a_ptr = builder.ins().iconst(types::I64, *aliases_ptr as i64);
3509                            let n_val = builder.ins().iconst(types::I64, *n as i64);
3510                            let call = builder.ins().call(
3511                                weighted_pick_func_ref,
3512                                &[input, v_ptr, b_ptr, p_ptr, a_ptr, n_val],
3513                            );
3514                            let result = builder.inst_results(call)[0];
3515                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3516                        }
3517
3518                        JitOp::MathUnary(idx) => {
3519                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3520                            let func_ref = math_unary_refs[*idx as usize];
3521                            let call = builder.ins().call(func_ref, &[input]);
3522                            let result = builder.inst_results(call)[0];
3523                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3524                        }
3525
3526                        JitOp::MathBinary(idx) => {
3527                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3528                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3529                            let func_ref = math_binary_refs[*idx as usize];
3530                            let call = builder.ins().call(func_ref, &[a, b]);
3531                            let result = builder.inst_results(call)[0];
3532                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3533                        }
3534
3535                        JitOp::ToF64 => {
3536                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3537                            let fval = builder.ins().fcvt_from_uint(types::F64, val);
3538                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], fval);
3539                        }
3540
3541                        // ── Register plane: one vector instruction per op ──
3542                        JitOp::RegBinOp(lane, arith) => {
3543                            let vt = reg_lane_type(*lane);
3544                            let a = load_reg128(&mut builder, buffer_ptr, input_slots[0], vt);
3545                            let b = load_reg128(&mut builder, buffer_ptr, input_slots[2], vt);
3546                            let is_float = matches!(*lane, 4 | 5);
3547                            let r = match (arith, is_float) {
3548                                (0, false) => builder.ins().iadd(a, b),
3549                                (1, false) => builder.ins().isub(a, b),
3550                                (2, false) => builder.ins().imul(a, b),
3551                                (0, true) => builder.ins().fadd(a, b),
3552                                (1, true) => builder.ins().fsub(a, b),
3553                                (2, true) => builder.ins().fmul(a, b),
3554                                _ => unreachable!("RegBinOp arith index out of range"),
3555                            };
3556                            store_reg128(&mut builder, buffer_ptr, output_slots[0], r);
3557                        }
3558                        JitOp::RegCopy => {
3559                            let v =
3560                                load_reg128(&mut builder, buffer_ptr, input_slots[0], types::I64X2);
3561                            store_reg128(&mut builder, buffer_ptr, output_slots[0], v);
3562                        }
3563                        JitOp::RegSplat(lane) => {
3564                            let vt = reg_lane_type(*lane);
3565                            let scalar = match *lane {
3566                                // Integer lanes: u64 slot reduced to lane width.
3567                                0 => {
3568                                    let v = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3569                                    builder.ins().ireduce(types::I8, v)
3570                                }
3571                                1 => {
3572                                    let v = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3573                                    builder.ins().ireduce(types::I16, v)
3574                                }
3575                                2 => {
3576                                    let v = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3577                                    builder.ins().ireduce(types::I32, v)
3578                                }
3579                                3 => load_slot(&mut builder, buffer_ptr, input_slots[0]),
3580                                // Float lanes: f64 slot, demoted for f32.
3581                                4 => {
3582                                    let f = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3583                                    builder.ins().fdemote(types::F32, f)
3584                                }
3585                                5 => load_slot_f64(&mut builder, buffer_ptr, input_slots[0]),
3586                                _ => unreachable!("RegSplat lane index out of range"),
3587                            };
3588                            let v = builder.ins().splat(vt, scalar);
3589                            store_reg128(&mut builder, buffer_ptr, output_slots[0], v);
3590                        }
3591
3592                        // Two-wire u64 integer ops — pure Cranelift, no extern call
3593                        JitOp::U64Add2 => {
3594                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3595                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3596                            let result = builder.ins().iadd(a, b);
3597                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3598                        }
3599                        JitOp::U64Sub2 => {
3600                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3601                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3602                            let result = builder.ins().isub(a, b);
3603                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3604                        }
3605                        JitOp::U64Mul2 => {
3606                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3607                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3608                            let result = builder.ins().imul(a, b);
3609                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3610                        }
3611                        JitOp::U64Div2 => {
3612                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3613                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3614                            // Guard: if b == 0, store 0; else store a / b.
3615                            // Must branch because udiv traps on zero divisor.
3616                            let zero = builder.ins().iconst(types::I64, 0);
3617                            let is_zero = builder.ins().icmp(ir::condcodes::IntCC::Equal, b, zero);
3618                            let div_block = builder.create_block();
3619                            let merge_block = builder.create_block();
3620                            builder.append_block_param(merge_block, types::I64);
3621                            builder
3622                                .ins()
3623                                .brif(is_zero, merge_block, &[zero], div_block, &[]);
3624                            builder.switch_to_block(div_block);
3625                            builder.seal_block(div_block);
3626                            let div_result = builder.ins().udiv(a, b);
3627                            builder.ins().jump(merge_block, &[div_result]);
3628                            builder.switch_to_block(merge_block);
3629                            builder.seal_block(merge_block);
3630                            let result = builder.block_params(merge_block)[0];
3631                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3632                        }
3633                        JitOp::U64Mod2 => {
3634                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3635                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3636                            // Guard: if b == 0, store 0; else store a % b.
3637                            // Must branch because urem traps on zero divisor.
3638                            let zero = builder.ins().iconst(types::I64, 0);
3639                            let is_zero = builder.ins().icmp(ir::condcodes::IntCC::Equal, b, zero);
3640                            let rem_block = builder.create_block();
3641                            let merge_block = builder.create_block();
3642                            builder.append_block_param(merge_block, types::I64);
3643                            builder
3644                                .ins()
3645                                .brif(is_zero, merge_block, &[zero], rem_block, &[]);
3646                            builder.switch_to_block(rem_block);
3647                            builder.seal_block(rem_block);
3648                            let rem_result = builder.ins().urem(a, b);
3649                            builder.ins().jump(merge_block, &[rem_result]);
3650                            builder.switch_to_block(merge_block);
3651                            builder.seal_block(merge_block);
3652                            let result = builder.block_params(merge_block)[0];
3653                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3654                        }
3655                        JitOp::U64And => {
3656                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3657                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3658                            let result = builder.ins().band(a, b);
3659                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3660                        }
3661                        JitOp::U64Or => {
3662                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3663                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3664                            let result = builder.ins().bor(a, b);
3665                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3666                        }
3667                        JitOp::U64Xor => {
3668                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3669                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3670                            let result = builder.ins().bxor(a, b);
3671                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3672                        }
3673                        JitOp::U64Shl => {
3674                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3675                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3676                            let result = builder.ins().ishl(a, b);
3677                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3678                        }
3679                        JitOp::U64Shr => {
3680                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3681                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3682                            let result = builder.ins().ushr(a, b);
3683                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3684                        }
3685                        JitOp::U64Not => {
3686                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3687                            let result = builder.ins().bnot(a);
3688                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3689                        }
3690
3691                        // Inline binary f64 arithmetic — pure Cranelift, no extern call
3692                        JitOp::F64Add => {
3693                            let a = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3694                            let b = load_slot_f64(&mut builder, buffer_ptr, input_slots[1]);
3695                            let result = builder.ins().fadd(a, b);
3696                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], result);
3697                        }
3698                        JitOp::F64Sub => {
3699                            let a = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3700                            let b = load_slot_f64(&mut builder, buffer_ptr, input_slots[1]);
3701                            let result = builder.ins().fsub(a, b);
3702                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], result);
3703                        }
3704                        JitOp::F64Mul => {
3705                            let a = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3706                            let b = load_slot_f64(&mut builder, buffer_ptr, input_slots[1]);
3707                            let result = builder.ins().fmul(a, b);
3708                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], result);
3709                        }
3710                        JitOp::F64Div => {
3711                            let a = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3712                            let b = load_slot_f64(&mut builder, buffer_ptr, input_slots[1]);
3713                            // Guard: if b == 0, result = 0; else result = a / b
3714                            let zero = builder.ins().f64const(0.0);
3715                            let is_zero =
3716                                builder.ins().fcmp(ir::condcodes::FloatCC::Equal, b, zero);
3717                            let div_result = builder.ins().fdiv(a, b);
3718                            let result = builder.ins().select(is_zero, zero, div_result);
3719                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], result);
3720                        }
3721                        JitOp::F64Mod => {
3722                            // The body through its helper: Rust's `%` on floats.
3723                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3724                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3725                            let call = builder
3726                                .ins()
3727                                .call(math_binary_refs[F64_MOD_HELPER], &[a, b]);
3728                            let result = builder.inst_results(call)[0];
3729                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3730                        }
3731
3732                        JitOp::IsPositiveCheck { name_ptr, name_len } => {
3733                            // if input == 0: call jit_is_positive_fail (panics);
3734                            // else: store input → output.
3735                            // The branch splits to a fail block for the
3736                            // violation path; the merge reads through the
3737                            // common path after either branch completes.
3738                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3739                            let zero = builder.ins().iconst(types::I64, 0);
3740                            let is_zero =
3741                                builder.ins().icmp(ir::condcodes::IntCC::Equal, val, zero);
3742                            let fail_block = builder.create_block();
3743                            let ok_block = builder.create_block();
3744                            builder.ins().brif(is_zero, fail_block, &[], ok_block, &[]);
3745
3746                            builder.switch_to_block(fail_block);
3747                            builder.seal_block(fail_block);
3748                            let np = builder.ins().iconst(types::I64, *name_ptr as i64);
3749                            let nl = builder.ins().iconst(types::I64, *name_len as i64);
3750                            let _ = builder.ins().call(is_positive_fail_ref, &[val, np, nl]);
3751                            // Extern panics — this is unreachable. Jump to
3752                            // ok_block to keep the IR well-formed; the
3753                            // branch never runs in practice.
3754                            builder.ins().jump(ok_block, &[]);
3755
3756                            builder.switch_to_block(ok_block);
3757                            builder.seal_block(ok_block);
3758                            store_slot(&mut builder, buffer_ptr, output_slots[0], val);
3759                        }
3760
3761                        JitOp::InRangeCheck(lo, hi) => {
3762                            // if input < lo || input > hi: call
3763                            // jit_in_range_fail (panics); else store
3764                            // input → output.
3765                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3766                            let lo_v = builder.ins().iconst(types::I64, *lo as i64);
3767                            let hi_v = builder.ins().iconst(types::I64, *hi as i64);
3768                            let below = builder.ins().icmp(
3769                                ir::condcodes::IntCC::UnsignedLessThan,
3770                                val,
3771                                lo_v,
3772                            );
3773                            let above = builder.ins().icmp(
3774                                ir::condcodes::IntCC::UnsignedGreaterThan,
3775                                val,
3776                                hi_v,
3777                            );
3778                            let out_of_range = builder.ins().bor(below, above);
3779
3780                            let fail_block = builder.create_block();
3781                            let ok_block = builder.create_block();
3782                            builder
3783                                .ins()
3784                                .brif(out_of_range, fail_block, &[], ok_block, &[]);
3785
3786                            builder.switch_to_block(fail_block);
3787                            builder.seal_block(fail_block);
3788                            let _ = builder.ins().call(in_range_fail_ref, &[val, lo_v, hi_v]);
3789                            builder.ins().jump(ok_block, &[]);
3790
3791                            builder.switch_to_block(ok_block);
3792                            builder.seal_block(ok_block);
3793                            store_slot(&mut builder, buffer_ptr, output_slots[0], val);
3794                        }
3795
3796                        JitOp::IsOneOfCheck {
3797                            allowed,
3798                            set_ptr,
3799                            set_len,
3800                        } => {
3801                            // Unroll the allow-list as N inline eq
3802                            // comparisons OR'd together. Fast-path is
3803                            // 1–8 values (the common case); pathologically
3804                            // large allow-lists still JIT but cost N
3805                            // comparisons per cycle.
3806                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3807                            let mut any_match = builder.ins().iconst(types::I8, 0);
3808                            for allow in allowed.iter() {
3809                                let c = builder.ins().iconst(types::I64, *allow as i64);
3810                                let eq = builder.ins().icmp(ir::condcodes::IntCC::Equal, val, c);
3811                                any_match = builder.ins().bor(any_match, eq);
3812                            }
3813                            let fail_block = builder.create_block();
3814                            let ok_block = builder.create_block();
3815                            // If any_match == 0 (no equality hit),
3816                            // branch to the fail extern. Otherwise
3817                            // jump straight to ok_block.
3818                            builder
3819                                .ins()
3820                                .brif(any_match, ok_block, &[], fail_block, &[]);
3821
3822                            builder.switch_to_block(fail_block);
3823                            builder.seal_block(fail_block);
3824                            let sp = builder.ins().iconst(types::I64, *set_ptr as i64);
3825                            let sl = builder.ins().iconst(types::I64, *set_len as i64);
3826                            let _ = builder.ins().call(is_one_of_fail_ref, &[val, sp, sl]);
3827                            builder.ins().jump(ok_block, &[]);
3828
3829                            builder.switch_to_block(ok_block);
3830                            builder.seal_block(ok_block);
3831                            store_slot(&mut builder, buffer_ptr, output_slots[0], val);
3832                        }
3833
3834                        JitOp::U64Cmp(cc) => {
3835                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3836                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
3837                            let cmp = builder.ins().icmp(*cc, a, b);
3838                            let zero = builder.ins().iconst(types::I64, 0);
3839                            let one = builder.ins().iconst(types::I64, 1);
3840                            let result = builder.ins().select(cmp, one, zero);
3841                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3842                        }
3843                        JitOp::F64Cmp(cc) => {
3844                            let a = load_slot_f64(&mut builder, buffer_ptr, input_slots[0]);
3845                            let b = load_slot_f64(
3846                                &mut builder,
3847                                buffer_ptr,
3848                                if input_slots.len() > 1 {
3849                                    input_slots[1]
3850                                } else {
3851                                    input_slots[0]
3852                                },
3853                            );
3854                            let cmp = builder.ins().fcmp(*cc, a, b);
3855                            let zero = builder.ins().iconst(types::I64, 0);
3856                            let one = builder.ins().iconst(types::I64, 1);
3857                            let result = builder.ins().select(cmp, one, zero);
3858                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3859                        }
3860                        JitOp::SelectU64 => {
3861                            let cond = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3862                            let a = load_slot(
3863                                &mut builder,
3864                                buffer_ptr,
3865                                if input_slots.len() > 1 {
3866                                    input_slots[1]
3867                                } else {
3868                                    input_slots[0]
3869                                },
3870                            );
3871                            let b = load_slot(
3872                                &mut builder,
3873                                buffer_ptr,
3874                                if input_slots.len() > 2 {
3875                                    input_slots[2]
3876                                } else {
3877                                    input_slots[0]
3878                                },
3879                            );
3880                            let zero = builder.ins().iconst(types::I64, 0);
3881                            let is_nonzero =
3882                                builder
3883                                    .ins()
3884                                    .icmp(ir::condcodes::IntCC::NotEqual, cond, zero);
3885                            let result = builder.ins().select(is_nonzero, a, b);
3886                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3887                        }
3888                        JitOp::SelectF64 => {
3889                            let cond = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3890                            let a = load_slot_f64(
3891                                &mut builder,
3892                                buffer_ptr,
3893                                if input_slots.len() > 1 {
3894                                    input_slots[1]
3895                                } else {
3896                                    input_slots[0]
3897                                },
3898                            );
3899                            let b = load_slot_f64(
3900                                &mut builder,
3901                                buffer_ptr,
3902                                if input_slots.len() > 2 {
3903                                    input_slots[2]
3904                                } else {
3905                                    input_slots[0]
3906                                },
3907                            );
3908                            let zero = builder.ins().iconst(types::I64, 0);
3909                            let is_nonzero =
3910                                builder
3911                                    .ins()
3912                                    .icmp(ir::condcodes::IntCC::NotEqual, cond, zero);
3913                            let result = builder.ins().select(is_nonzero, a, b);
3914                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], result);
3915                        }
3916
3917                        JitOp::I64ToF64 => {
3918                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3919                            let fval = builder.ins().fcvt_from_sint(types::F64, val);
3920                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], fval);
3921                        }
3922                        JitOp::ToBool => {
3923                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3924                            let zero = builder.ins().iconst(types::I64, 0);
3925                            let one = builder.ins().iconst(types::I64, 1);
3926                            let cmp = builder
3927                                .ins()
3928                                .icmp(ir::condcodes::IntCC::NotEqual, val, zero);
3929                            let result = builder.ins().select(cmp, one, zero);
3930                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3931                        }
3932                        JitOp::ConstU64(v) | JitOp::ConstF64(v) => {
3933                            let result = builder.ins().iconst(types::I64, *v as i64);
3934                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
3935                        }
3936                        JitOp::HashRangeConst(max) => {
3937                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3938                            let c_gamma = builder
3939                                .ins()
3940                                .iconst(types::I64, 0x9e3779b97f4a7c15u64 as i64);
3941                            let x1 = builder.ins().iadd(input, c_gamma);
3942                            let s30 = builder.ins().ushr_imm(x1, 30);
3943                            let x2 = builder.ins().bxor(x1, s30);
3944                            let c_m1 = builder
3945                                .ins()
3946                                .iconst(types::I64, 0xbf58476d1ce4e5b9u64 as i64);
3947                            let x3 = builder.ins().imul(x2, c_m1);
3948                            let s27 = builder.ins().ushr_imm(x3, 27);
3949                            let x4 = builder.ins().bxor(x3, s27);
3950                            let c_m2 = builder
3951                                .ins()
3952                                .iconst(types::I64, 0x94d049bb133111ebu64 as i64);
3953                            let x5 = builder.ins().imul(x4, c_m2);
3954                            let s31 = builder.ins().ushr_imm(x5, 31);
3955                            let h = builder.ins().bxor(x5, s31);
3956                            if *max == 0 {
3957                                let zero = builder.ins().iconst(types::I64, 0);
3958                                store_slot(&mut builder, buffer_ptr, output_slots[0], zero);
3959                            } else {
3960                                let m = builder.ins().iconst(types::I64, *max as i64);
3961                                let rem = builder.ins().urem(h, m);
3962                                store_slot(&mut builder, buffer_ptr, output_slots[0], rem);
3963                            }
3964                        }
3965                        JitOp::HashIntervalConst(min_bits, max_bits) => {
3966                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
3967                            let c_gamma = builder
3968                                .ins()
3969                                .iconst(types::I64, 0x9e3779b97f4a7c15u64 as i64);
3970                            let x1 = builder.ins().iadd(input, c_gamma);
3971                            let s30 = builder.ins().ushr_imm(x1, 30);
3972                            let x2 = builder.ins().bxor(x1, s30);
3973                            let c_m1 = builder
3974                                .ins()
3975                                .iconst(types::I64, 0xbf58476d1ce4e5b9u64 as i64);
3976                            let x3 = builder.ins().imul(x2, c_m1);
3977                            let s27 = builder.ins().ushr_imm(x3, 27);
3978                            let x4 = builder.ins().bxor(x3, s27);
3979                            let c_m2 = builder
3980                                .ins()
3981                                .iconst(types::I64, 0x94d049bb133111ebu64 as i64);
3982                            let x5 = builder.ins().imul(x4, c_m2);
3983                            let s31 = builder.ins().ushr_imm(x5, 31);
3984                            let h = builder.ins().bxor(x5, s31);
3985
3986                            let h_f = builder.ins().fcvt_from_uint(types::F64, h);
3987                            let denom = builder.ins().f64const(u64::MAX as f64);
3988                            let unit = builder.ins().fdiv(h_f, denom);
3989                            let min_f = f64::from_bits(*min_bits);
3990                            let max_f = f64::from_bits(*max_bits);
3991                            let span = builder.ins().f64const(max_f - min_f);
3992                            let min_val = builder.ins().f64const(min_f);
3993                            let scaled = builder.ins().fmul(unit, span);
3994                            let res_f = builder.ins().fadd(min_val, scaled);
3995                            let res = builder
3996                                .ins()
3997                                .bitcast(types::I64, ir::MemFlags::new(), res_f);
3998                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
3999                        }
4000                        JitOp::InvLerpConst(a_bits, b_bits) => {
4001                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4002                            let in_f =
4003                                builder
4004                                    .ins()
4005                                    .bitcast(types::F64, ir::MemFlags::new(), input);
4006                            let a_f = f64::from_bits(*a_bits);
4007                            let b_f = f64::from_bits(*b_bits);
4008                            let a_val = builder.ins().f64const(a_f);
4009                            // The body's operations in its order: the reciprocal
4010                            // of the span (infinite for an empty one), the
4011                            // product, the clamp.
4012                            let inv_span = builder.ins().f64const(1.0 / (b_f - a_f));
4013                            let diff = builder.ins().fsub(in_f, a_val);
4014                            let t = builder.ins().fmul(diff, inv_span);
4015                            let zero = builder.ins().f64const(0.0);
4016                            let one = builder.ins().f64const(1.0);
4017                            let res_f = clamp_ir(&mut builder, t, zero, one);
4018                            let res = builder
4019                                .ins()
4020                                .bitcast(types::I64, ir::MemFlags::new(), res_f);
4021                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4022                        }
4023                        JitOp::RemapConst(in_min_bits, in_max_bits, out_min_bits, out_max_bits) => {
4024                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4025                            let in_f =
4026                                builder
4027                                    .ins()
4028                                    .bitcast(types::F64, ir::MemFlags::new(), input);
4029                            let in_min = f64::from_bits(*in_min_bits);
4030                            let in_max = f64::from_bits(*in_max_bits);
4031                            let out_min = f64::from_bits(*out_min_bits);
4032                            let out_max = f64::from_bits(*out_max_bits);
4033                            // The body's operations in its order: a division by
4034                            // the span (not a product with its reciprocal, which
4035                            // differs in the last bit), then the affine step.
4036                            let in_span_val = builder.ins().f64const(in_max - in_min);
4037                            let in_min_val = builder.ins().f64const(in_min);
4038                            let out_min_val = builder.ins().f64const(out_min);
4039                            let out_span_val = builder.ins().f64const(out_max - out_min);
4040                            let diff = builder.ins().fsub(in_f, in_min_val);
4041                            let t = builder.ins().fdiv(diff, in_span_val);
4042                            let scaled = builder.ins().fmul(t, out_span_val);
4043                            let res_f = builder.ins().fadd(out_min_val, scaled);
4044                            let res = builder
4045                                .ins()
4046                                .bitcast(types::I64, ir::MemFlags::new(), res_f);
4047                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4048                        }
4049                        JitOp::EpochOffsetConst(base) => {
4050                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4051                            let b = builder.ins().iconst(types::I64, *base as i64);
4052                            let res = builder.ins().iadd(val, b);
4053                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4054                        }
4055                        JitOp::EpochScaleConst(factor) => {
4056                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4057                            let f = builder.ins().iconst(types::I64, *factor as i64);
4058                            let res = builder.ins().imul(val, f);
4059                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4060                        }
4061                        JitOp::ThreadId => {
4062                            let call = builder.ins().call(thread_id_func_ref, &[]);
4063                            let res = builder.inst_results(call)[0];
4064                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4065                        }
4066                        JitOp::CurrentEpochMillis => {
4067                            let call = builder.ins().call(current_epoch_millis_func_ref, &[]);
4068                            let res = builder.inst_results(call)[0];
4069                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4070                        }
4071                        JitOp::Perlin1dConst(perm_ptr, freq_bits) => {
4072                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4073                            let p = builder.ins().iconst(types::I64, *perm_ptr as i64);
4074                            let fb = builder.ins().iconst(types::I64, *freq_bits as i64);
4075                            let call = builder.ins().call(perlin_1d_func_ref, &[input, p, fb]);
4076                            let res = builder.inst_results(call)[0];
4077                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4078                        }
4079                        JitOp::Perlin2dConst(perm_ptr, freq_bits) => {
4080                            let x = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4081                            let y = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4082                            let p = builder.ins().iconst(types::I64, *perm_ptr as i64);
4083                            let fb = builder.ins().iconst(types::I64, *freq_bits as i64);
4084                            let call = builder.ins().call(perlin_2d_func_ref, &[x, y, p, fb]);
4085                            let res = builder.inst_results(call)[0];
4086                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4087                        }
4088                        JitOp::Simplex2dConst(perm_ptr, freq_bits) => {
4089                            let x = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4090                            let y = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4091                            let p = builder.ins().iconst(types::I64, *perm_ptr as i64);
4092                            let fb = builder.ins().iconst(types::I64, *freq_bits as i64);
4093                            let call = builder.ins().call(simplex_2d_func_ref, &[x, y, p, fb]);
4094                            let res = builder.inst_results(call)[0];
4095                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4096                        }
4097                        JitOp::FractalNoise1dConst(perm_ptr, freq_bits, octaves) => {
4098                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4099                            let p = builder.ins().iconst(types::I64, *perm_ptr as i64);
4100                            let fb = builder.ins().iconst(types::I64, *freq_bits as i64);
4101                            let oct = builder.ins().iconst(types::I64, *octaves as i64);
4102                            let call = builder
4103                                .ins()
4104                                .call(fractal_noise_1d_func_ref, &[input, p, fb, oct]);
4105                            let res = builder.inst_results(call)[0];
4106                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4107                        }
4108                        JitOp::FractalNoise2dConst(perm_ptr, freq_bits, octaves) => {
4109                            let x = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4110                            let y = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4111                            let p = builder.ins().iconst(types::I64, *perm_ptr as i64);
4112                            let fb = builder.ins().iconst(types::I64, *freq_bits as i64);
4113                            let oct = builder.ins().iconst(types::I64, *octaves as i64);
4114                            let call = builder
4115                                .ins()
4116                                .call(fractal_noise_2d_func_ref, &[x, y, p, fb, oct]);
4117                            let res = builder.inst_results(call)[0];
4118                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4119                        }
4120                        JitOp::CycleWalkConst(range, seed, inc) => {
4121                            let pos = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4122                            let r = builder.ins().iconst(types::I64, *range as i64);
4123                            let s = builder.ins().iconst(types::I64, *seed as i64);
4124                            let i = builder.ins().iconst(types::I64, *inc as i64);
4125                            let call = builder.ins().call(cycle_walk_func_ref, &[pos, r, s, i]);
4126                            let res = builder.inst_results(call)[0];
4127                            store_slot(&mut builder, buffer_ptr, output_slots[0], res);
4128                        }
4129
4130                        JitOp::VariadicSum => {
4131                            if input_slots.is_empty() {
4132                                let zero = builder.ins().iconst(types::I64, 0);
4133                                store_slot(&mut builder, buffer_ptr, output_slots[0], zero);
4134                            } else {
4135                                let mut acc = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4136                                for &slot in &input_slots[1..] {
4137                                    let v = load_slot(&mut builder, buffer_ptr, slot);
4138                                    acc = builder.ins().iadd(acc, v);
4139                                }
4140                                store_slot(&mut builder, buffer_ptr, output_slots[0], acc);
4141                            }
4142                        }
4143                        JitOp::VariadicProduct => {
4144                            if input_slots.is_empty() {
4145                                let one = builder.ins().iconst(types::I64, 1);
4146                                store_slot(&mut builder, buffer_ptr, output_slots[0], one);
4147                            } else {
4148                                let mut acc = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4149                                for &slot in &input_slots[1..] {
4150                                    let v = load_slot(&mut builder, buffer_ptr, slot);
4151                                    acc = builder.ins().imul(acc, v);
4152                                }
4153                                store_slot(&mut builder, buffer_ptr, output_slots[0], acc);
4154                            }
4155                        }
4156                        JitOp::VariadicMin => {
4157                            if input_slots.is_empty() {
4158                                // `min`'s identity is `u64::MAX`, declared on the
4159                                // node (`identity = u64::MAX`), because the least
4160                                // of nothing must lose to every value. Zero is
4161                                // `max`'s identity, and writing it here made
4162                                // `min()` answer 0 on native and `u64::MAX` on
4163                                // the interpreter. These four constants mirror
4164                                // `FuncSig.identity`; the zero-arity test in
4165                                // `engine_parity` is what keeps them mirrored.
4166                                let ident = builder.ins().iconst(types::I64, u64::MAX as i64);
4167                                store_slot(&mut builder, buffer_ptr, output_slots[0], ident);
4168                            } else {
4169                                let mut acc = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4170                                for &slot in &input_slots[1..] {
4171                                    let v = load_slot(&mut builder, buffer_ptr, slot);
4172                                    let cmp = builder.ins().icmp(
4173                                        ir::condcodes::IntCC::UnsignedLessThan,
4174                                        v,
4175                                        acc,
4176                                    );
4177                                    acc = builder.ins().select(cmp, v, acc);
4178                                }
4179                                store_slot(&mut builder, buffer_ptr, output_slots[0], acc);
4180                            }
4181                        }
4182                        JitOp::VariadicMax => {
4183                            if input_slots.is_empty() {
4184                                let zero = builder.ins().iconst(types::I64, 0);
4185                                store_slot(&mut builder, buffer_ptr, output_slots[0], zero);
4186                            } else {
4187                                let mut acc = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4188                                for &slot in &input_slots[1..] {
4189                                    let v = load_slot(&mut builder, buffer_ptr, slot);
4190                                    let cmp = builder.ins().icmp(
4191                                        ir::condcodes::IntCC::UnsignedGreaterThan,
4192                                        v,
4193                                        acc,
4194                                    );
4195                                    acc = builder.ins().select(cmp, v, acc);
4196                                }
4197                                store_slot(&mut builder, buffer_ptr, output_slots[0], acc);
4198                            }
4199                        }
4200
4201                        JitOp::CeilToMultiple => {
4202                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4203                            let m = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4204                            let zero = builder.ins().iconst(types::I64, 0);
4205                            let one = builder.ins().iconst(types::I64, 1);
4206                            let is_zero = builder.ins().icmp(ir::condcodes::IntCC::Equal, m, zero);
4207                            let calc_block = builder.create_block();
4208                            let merge_block = builder.create_block();
4209                            builder.append_block_param(merge_block, types::I64);
4210                            builder
4211                                .ins()
4212                                .brif(is_zero, merge_block, &[val], calc_block, &[]);
4213                            builder.switch_to_block(calc_block);
4214                            builder.seal_block(calc_block);
4215                            // `div_ceil` without the sum that overflows near the
4216                            // top, then the saturating product: the body's.
4217                            let div = div_ceil(&mut builder, val, m, one);
4218                            let high = builder.ins().umulhi(div, m);
4219                            let low = builder.ins().imul(div, m);
4220                            let zero_hi = builder.ins().iconst(types::I64, 0);
4221                            let overflows =
4222                                builder
4223                                    .ins()
4224                                    .icmp(ir::condcodes::IntCC::NotEqual, high, zero_hi);
4225                            let max = builder.ins().iconst(types::I64, -1);
4226                            let mul = builder.ins().select(overflows, max, low);
4227                            builder.ins().jump(merge_block, &[mul]);
4228                            builder.switch_to_block(merge_block);
4229                            builder.seal_block(merge_block);
4230                            let result = builder.block_params(merge_block)[0];
4231                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
4232                        }
4233                        JitOp::CheckedAdd => {
4234                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4235                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4236                            let sum = builder.ins().iadd(a, b);
4237                            let is_overflow =
4238                                builder
4239                                    .ins()
4240                                    .icmp(ir::condcodes::IntCC::UnsignedLessThan, sum, a);
4241                            let zero = builder.ins().iconst(types::I64, 0);
4242                            let result = builder.ins().select(is_overflow, zero, sum);
4243                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
4244                        }
4245                        JitOp::CheckedSub => {
4246                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4247                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4248                            let is_lt =
4249                                builder
4250                                    .ins()
4251                                    .icmp(ir::condcodes::IntCC::UnsignedLessThan, a, b);
4252                            let diff = builder.ins().isub(a, b);
4253                            let zero = builder.ins().iconst(types::I64, 0);
4254                            let result = builder.ins().select(is_lt, zero, diff);
4255                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
4256                        }
4257                        JitOp::CheckedMul => {
4258                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4259                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4260                            let prod = builder.ins().imul(a, b);
4261                            let zero = builder.ins().iconst(types::I64, 0);
4262                            let a_is_zero =
4263                                builder.ins().icmp(ir::condcodes::IntCC::Equal, a, zero);
4264                            let div_block = builder.create_block();
4265                            let merge_block = builder.create_block();
4266                            builder.append_block_param(merge_block, types::I64);
4267                            builder
4268                                .ins()
4269                                .brif(a_is_zero, merge_block, &[zero], div_block, &[]);
4270                            builder.switch_to_block(div_block);
4271                            builder.seal_block(div_block);
4272                            let div = builder.ins().udiv(prod, a);
4273                            let ok = builder.ins().icmp(ir::condcodes::IntCC::Equal, div, b);
4274                            let mul_res = builder.ins().select(ok, prod, zero);
4275                            builder.ins().jump(merge_block, &[mul_res]);
4276                            builder.switch_to_block(merge_block);
4277                            builder.seal_block(merge_block);
4278                            let result = builder.block_params(merge_block)[0];
4279                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
4280                        }
4281                        JitOp::MultiplesAtLeast => {
4282                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4283                            let m = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4284                            let zero = builder.ins().iconst(types::I64, 0);
4285                            let one = builder.ins().iconst(types::I64, 1);
4286                            let is_zero = builder.ins().icmp(ir::condcodes::IntCC::Equal, m, zero);
4287                            let calc_block = builder.create_block();
4288                            let merge_block = builder.create_block();
4289                            builder.append_block_param(merge_block, types::I64);
4290                            builder
4291                                .ins()
4292                                .brif(is_zero, merge_block, &[zero], calc_block, &[]);
4293                            builder.switch_to_block(calc_block);
4294                            builder.seal_block(calc_block);
4295                            let div = div_ceil(&mut builder, val, m, one);
4296                            builder.ins().jump(merge_block, &[div]);
4297                            builder.switch_to_block(merge_block);
4298                            builder.seal_block(merge_block);
4299                            let result = builder.block_params(merge_block)[0];
4300                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
4301                        }
4302
4303                        JitOp::BlendConst(mix_bits) => {
4304                            // The body reinterprets both inputs' bits as f64
4305                            // and returns the mix's bits (`blend` in
4306                            // polydat-nodes `probability.rs`); the lowering does the
4307                            // same, not a numeric conversion.
4308                            let a = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4309                            let b = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4310                            let fa = builder.ins().bitcast(types::F64, ir::MemFlags::new(), a);
4311                            let fb = builder.ins().bitcast(types::F64, ir::MemFlags::new(), b);
4312                            let mix_f64 = f64::from_bits(*mix_bits);
4313                            let mix_val = builder.ins().f64const(mix_f64);
4314                            let one = builder.ins().f64const(1.0);
4315                            let one_minus_mix = builder.ins().fsub(one, mix_val);
4316                            let a_part = builder.ins().fmul(fa, one_minus_mix);
4317                            let b_part = builder.ins().fmul(fb, mix_val);
4318                            let sum = builder.ins().fadd(a_part, b_part);
4319                            let result =
4320                                builder.ins().bitcast(types::I64, ir::MemFlags::new(), sum);
4321                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
4322                        }
4323                        JitOp::LfsrStepConst(feedback) => {
4324                            let val = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4325                            let feedback = builder.ins().iconst(types::I64, *feedback as i64);
4326                            let one = builder.ins().iconst(types::I64, 1);
4327                            let zero = builder.ins().iconst(types::I64, 0);
4328                            let shifted = builder.ins().ushr(val, one);
4329                            let lsb = builder.ins().band(val, one);
4330                            let is_odd =
4331                                builder
4332                                    .ins()
4333                                    .icmp(ir::condcodes::IntCC::NotEqual, lsb, zero);
4334                            let fb_mask = builder.ins().select(is_odd, feedback, zero);
4335                            let result = builder.ins().bxor(shifted, fb_mask);
4336                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
4337                        }
4338                        JitOp::PcgConst(seed, stream) => {
4339                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4340                            let s = builder.ins().iconst(types::I64, *seed as i64);
4341                            let st = builder.ins().iconst(types::I64, *stream as i64);
4342                            let call = builder.ins().call(pcg_func_ref, &[input, s, st]);
4343                            let result = builder.inst_results(call)[0];
4344                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
4345                        }
4346                        JitOp::PcgStreamConst(seed) => {
4347                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4348                            let st = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4349                            let s = builder.ins().iconst(types::I64, *seed as i64);
4350                            let call = builder.ins().call(pcg_stream_func_ref, &[input, st, s]);
4351                            let result = builder.inst_results(call)[0];
4352                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
4353                        }
4354                        JitOp::NOfConst(n, m) => {
4355                            let input = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4356                            let n_val = builder.ins().iconst(types::I64, *n as i64);
4357                            let m_val = builder.ins().iconst(types::I64, *m as i64);
4358                            let call = builder.ins().call(n_of_func_ref, &[input, n_val, m_val]);
4359                            let result = builder.inst_results(call)[0];
4360                            store_slot(&mut builder, buffer_ptr, output_slots[0], result);
4361                        }
4362
4363                        JitOp::SlotCall { kit, scratch_base } => {
4364                            emit_slot_call(
4365                                &mut builder,
4366                                buffer_ptr,
4367                                scratch_ptr,
4368                                slot_call_ref,
4369                                kit,
4370                                *scratch_base,
4371                                input_slots,
4372                                output_slots,
4373                            );
4374                        }
4375
4376                        JitOp::Convert {
4377                            from,
4378                            to,
4379                            kit,
4380                            scratch_base,
4381                        } => {
4382                            emit_conversion(
4383                                &mut builder,
4384                                buffer_ptr,
4385                                input_slots[0],
4386                                output_slots[0],
4387                                *from,
4388                                *to,
4389                                |builder| {
4390                                    emit_slot_call(
4391                                        builder,
4392                                        buffer_ptr,
4393                                        scratch_ptr,
4394                                        slot_call_ref,
4395                                        kit,
4396                                        *scratch_base,
4397                                        input_slots,
4398                                        output_slots,
4399                                    )
4400                                },
4401                            );
4402                        }
4403
4404                        JitOp::U64ToStr { scratch_base }
4405                        | JitOp::I64ToStr { scratch_base }
4406                        | JitOp::F64ToStr { scratch_base } => {
4407                            // The helper writes the digits into the step's entry
4408                            // and publishes the pair into the output slots.
4409                            let func = match jit_op {
4410                                JitOp::U64ToStr { .. } => u64_to_str_ref,
4411                                JitOp::I64ToStr { .. } => i64_to_str_ref,
4412                                _ => f64_to_str_ref,
4413                            };
4414                            let value = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4415                            let base_v = builder.ins().iconst(types::I64, *scratch_base as i64);
4416                            let out_v = builder.ins().iconst(types::I64, output_slots[0] as i64);
4417                            builder
4418                                .ins()
4419                                .call(func, &[scratch_ptr, base_v, buffer_ptr, out_v, value]);
4420                        }
4421                        JitOp::JsonToStr { scratch_base } => {
4422                            let ptr = load_slot(&mut builder, buffer_ptr, input_slots[0]);
4423                            let len = load_slot(&mut builder, buffer_ptr, input_slots[1]);
4424                            let base_v = builder.ins().iconst(types::I64, *scratch_base as i64);
4425                            let out_v = builder.ins().iconst(types::I64, output_slots[0] as i64);
4426                            builder.ins().call(
4427                                json_to_str_ref,
4428                                &[scratch_ptr, base_v, buffer_ptr, out_v, ptr, len],
4429                            );
4430                        }
4431                        JitOp::StrConcat { scratch_base } => {
4432                            // The input pairs go into the frame in order; the
4433                            // helper appends each one's bytes into the entry.
4434                            let n_words = input_slots.len();
4435                            let frame = builder.create_sized_stack_slot(ir::StackSlotData::new(
4436                                ir::StackSlotKind::ExplicitSlot,
4437                                (n_words.max(1) * 8) as u32,
4438                                3,
4439                            ));
4440                            for (k, &s) in input_slots.iter().enumerate() {
4441                                let v = load_slot(&mut builder, buffer_ptr, s);
4442                                builder.ins().stack_store(v, frame, (k * 8) as i32);
4443                            }
4444                            let pairs_ptr = builder.ins().stack_addr(types::I64, frame, 0);
4445                            let n_v = builder.ins().iconst(types::I64, (n_words / 2) as i64);
4446                            let base_v = builder.ins().iconst(types::I64, *scratch_base as i64);
4447                            let out_v = builder.ins().iconst(types::I64, output_slots[0] as i64);
4448                            builder.ins().call(
4449                                str_concat_ref,
4450                                &[scratch_ptr, base_v, buffer_ptr, out_v, pairs_ptr, n_v],
4451                            );
4452                        }
4453
4454                        JitOp::VecProduce { kind, scratch_base } => {
4455                            // The helper runs the node's body over the input
4456                            // words and publishes the pair from the step's
4457                            // entry.
4458                            let func = func_of(&vec_producer_refs, *kind);
4459                            let base_v = builder.ins().iconst(types::I64, *scratch_base as i64);
4460                            let out_v = builder.ins().iconst(types::I64, output_slots[0] as i64);
4461                            let words = load_words(&mut builder, buffer_ptr, input_slots, 4);
4462                            let mut args = vec![scratch_ptr, base_v, buffer_ptr, out_v];
4463                            args.extend(words);
4464                            builder.ins().call(func, &args);
4465                        }
4466                        JitOp::VecReduce(kind) => {
4467                            let func = func_of(&vec_reducer_refs, *kind);
4468                            let words = load_words(&mut builder, buffer_ptr, input_slots, 4);
4469                            let call = builder.ins().call(func, &words);
4470                            let bits = builder.inst_results(call)[0];
4471                            store_slot(&mut builder, buffer_ptr, output_slots[0], bits);
4472                        }
4473                        JitOp::RegLane(kind) => {
4474                            let func = func_of(&reg_lane_refs, *kind);
4475                            let words = load_words(&mut builder, buffer_ptr, input_slots, 3);
4476                            let call = builder.ins().call(func, &words);
4477                            let word = builder.inst_results(call)[0];
4478                            store_slot(&mut builder, buffer_ptr, output_slots[0], word);
4479                        }
4480                        JitOp::RegProduce(kind) => {
4481                            let func = func_of(&reg_producer_refs, *kind);
4482                            let out_v = builder.ins().iconst(types::I64, output_slots[0] as i64);
4483                            let words = load_words(&mut builder, buffer_ptr, input_slots, 4);
4484                            let mut args = vec![buffer_ptr, out_v];
4485                            args.extend(words);
4486                            builder.ins().call(func, &args);
4487                        }
4488                        JitOp::RegDotF32 => {
4489                            // The products at f32 precision, then the fixed
4490                            // tree ((p0+p1)+(p2+p3)) at f32, then widened: the
4491                            // node's body, operation for operation.
4492                            let a =
4493                                load_reg128(&mut builder, buffer_ptr, input_slots[0], types::F32X4);
4494                            let b =
4495                                load_reg128(&mut builder, buffer_ptr, input_slots[2], types::F32X4);
4496                            let p = builder.ins().fmul(a, b);
4497                            let p0 = builder.ins().extractlane(p, 0);
4498                            let p1 = builder.ins().extractlane(p, 1);
4499                            let p2 = builder.ins().extractlane(p, 2);
4500                            let p3 = builder.ins().extractlane(p, 3);
4501                            let s01 = builder.ins().fadd(p0, p1);
4502                            let s23 = builder.ins().fadd(p2, p3);
4503                            let s = builder.ins().fadd(s01, s23);
4504                            let wide = builder.ins().fpromote(types::F64, s);
4505                            store_slot_f64(&mut builder, buffer_ptr, output_slots[0], wide);
4506                        }
4507                        JitOp::RegShuffleConst(mask) => {
4508                            // Output byte i is input byte mask[i]: the word's
4509                            // bytes lie in memory in little-endian order, which
4510                            // is the order `shuffle` numbers its lanes.
4511                            let x =
4512                                load_reg128(&mut builder, buffer_ptr, input_slots[0], types::I8X16);
4513                            let imm = builder
4514                                .func
4515                                .dfg
4516                                .immediates
4517                                .push(ir::ConstantData::from(&mask[..]));
4518                            let r = builder.ins().shuffle(x, x, imm);
4519                            store_reg128(&mut builder, buffer_ptr, output_slots[0], r);
4520                        }
4521
4522                        JitOp::Fallback => {
4523                            // Can't JIT this node — skip (caller should
4524                            // not include fallback ops in JIT steps)
4525                        }
4526                    }
4527                    if let Some((inst, mark)) = tracker_store {
4528                        let calls = (mark..builder.func.dfg.num_insts()).any(|i| {
4529                            builder.func.dfg.insts[ir::Inst::from_u32(i as u32)]
4530                                .opcode()
4531                                .is_call()
4532                        });
4533                        if !calls {
4534                            builder.func.layout.remove_inst(inst);
4535                        }
4536                    }
4537                }
4538                // The unit is done and current: on to the next in the list. A
4539                // unit that fails does not get here, so it stays stale.
4540                if let Some((at, head, _, _, clean_ptr)) = &dispatcher {
4541                    let one = builder.ins().iconst(types::I8, 1);
4542                    builder
4543                        .ins()
4544                        .store(ir::MemFlags::trusted(), one, *clean_ptr, unit_idx as i32);
4545                    let i = builder.ins().stack_load(types::I64, *at, 0);
4546                    let next = builder.ins().iadd_imm(i, 1);
4547                    builder.ins().stack_store(next, *at, 0);
4548                    builder.ins().jump(*head, &[]);
4549                }
4550            }
4551
4552            if let Some((_, head, exit, _, _)) = dispatcher {
4553                // Every unit block jumps back to the head, so it is sealed
4554                // once they are all emitted.
4555                builder.seal_block(head);
4556                builder.switch_to_block(exit);
4557                builder.seal_block(exit);
4558            }
4559            builder.ins().return_(&[]);
4560            builder.finalize();
4561        }
4562        // Code that calls nothing cannot fail: no helper, no longjmp, no
4563        // panic. The kernel that runs it skips the catch.
4564        let fallible = ctx.func.layout.blocks().any(|block| {
4565            ctx.func
4566                .layout
4567                .block_insts(block)
4568                .any(|inst| ctx.func.dfg.insts[inst].opcode().is_call())
4569        });
4570
4571        module
4572            .define_function(func_id, &mut ctx)
4573            .map_err(|e| format!("define function: {e}"))?;
4574        module.clear_context(&mut ctx);
4575        defined.push((func_id, fallible));
4576    }
4577    module
4578        .finalize_definitions()
4579        .map_err(|e| format!("finalize: {e}"))?;
4580
4581    let entries: Vec<JitEntry> = defined
4582        .iter()
4583        .map(|&(func_id, fallible)| {
4584            let code_ptr = module.get_finalized_function(func_id);
4585            let straight_fn: NativeFn = unsafe { mem::transmute(code_ptr) };
4586            let dispatch_fn: NativeDispatchFn = unsafe { mem::transmute(code_ptr) };
4587            (straight_fn, dispatch_fn, fallible)
4588        })
4589        .collect();
4590    // The kits the code calls, kept alive beside it.
4591    let kits: Vec<SlotKitRef> = functions
4592        .iter()
4593        .flat_map(|(steps, _)| steps.iter())
4594        .filter_map(|(op, _, _)| op.slot_kit().cloned())
4595        .collect();
4596    let any_fallible = defined.iter().any(|&(_, f)| f);
4597    let code = super::kernels::JitCode::new(module, kits, any_fallible);
4598    Ok((entries, code))
4599}
4600
4601// ── Buffer slot helpers ────────────────────────────────────
4602
4603/// Load a u64 from buffer[slot].
4604/// A call of a node's own kit from native code: gather the inputs into
4605/// the frame, call the kit over them and the state's scratch, and
4606/// scatter the outputs back. The kit's address is an immediate: the
4607/// kit is shared by every kernel compiled from the program and
4608/// outlives the code.
4609#[allow(clippy::too_many_arguments)]
4610fn emit_slot_call(
4611    builder: &mut FunctionBuilder,
4612    buffer_ptr: ir::Value,
4613    scratch_ptr: ir::Value,
4614    slot_call_ref: ir::FuncRef,
4615    kit: &SlotKitRef,
4616    scratch_base: usize,
4617    input_slots: &[usize],
4618    output_slots: &[usize],
4619) {
4620    let n_in = input_slots.len();
4621    let n_out = output_slots.len();
4622    let frame = |builder: &mut FunctionBuilder, n: usize| {
4623        builder.create_sized_stack_slot(ir::StackSlotData::new(
4624            ir::StackSlotKind::ExplicitSlot,
4625            (n.max(1) * 8) as u32,
4626            3,
4627        ))
4628    };
4629    let in_frame = frame(builder, n_in);
4630    let out_frame = frame(builder, n_out);
4631    for (k, &s) in input_slots.iter().enumerate() {
4632        let v = load_slot(builder, buffer_ptr, s);
4633        builder.ins().stack_store(v, in_frame, (k * 8) as i32);
4634    }
4635    let kit_ptr = builder
4636        .ins()
4637        .iconst(types::I64, std::sync::Arc::as_ptr(&kit.0) as usize as i64);
4638    let in_ptr = builder.ins().stack_addr(types::I64, in_frame, 0);
4639    let n_in_v = builder.ins().iconst(types::I64, n_in as i64);
4640    let out_ptr = builder.ins().stack_addr(types::I64, out_frame, 0);
4641    let n_out_v = builder.ins().iconst(types::I64, n_out as i64);
4642    let base_v = builder.ins().iconst(types::I64, scratch_base as i64);
4643    let n_sc_v = builder.ins().iconst(types::I64, kit.0.scratch.len() as i64);
4644    builder.ins().call(
4645        slot_call_ref,
4646        &[
4647            kit_ptr,
4648            in_ptr,
4649            n_in_v,
4650            out_ptr,
4651            n_out_v,
4652            scratch_ptr,
4653            base_v,
4654            n_sc_v,
4655        ],
4656    );
4657    for (k, &s) in output_slots.iter().enumerate() {
4658        let v = builder
4659            .ins()
4660            .stack_load(types::I64, out_frame, (k * 8) as i32);
4661        store_slot(builder, buffer_ptr, s, v);
4662    }
4663}
4664
4665/// A conversion from `from` to `to` (engines.md §7.1), derived from the
4666/// two types and how each rides its carrier (`Scalar`).
4667///
4668/// A total conversion is one instruction or none: a widening keeps the
4669/// carrier's word, an integer becomes a float with the rounding `as`
4670/// uses, `f32` and `f64` promote and demote, and anything is a `bool`
4671/// by being non-zero and not NaN. A checked conversion runs inline only
4672/// inside a domain where the instruction provably equals the node: a
4673/// narrowing whose value fits the target, and a float to an integer in
4674/// `[lo, hi)` of the target, where truncation is exact and cannot trap.
4675/// Everything else, including NaN and the edges where a node's own rule
4676/// has quirks of its own, is `slow`: the node's kit, which decides.
4677fn emit_conversion(
4678    builder: &mut FunctionBuilder,
4679    buffer_ptr: ir::Value,
4680    in_slot: usize,
4681    out_slot: usize,
4682    from: crate::ast::PortType,
4683    to: crate::ast::PortType,
4684    slow: impl FnOnce(&mut FunctionBuilder),
4685) {
4686    use Scalar::{Bool, F32, F64, Signed, Unsigned};
4687    use ir::condcodes::{FloatCC, IntCC};
4688    let (Some(src), Some(dst)) = (Scalar::of(from), Scalar::of(to)) else {
4689        slow(builder);
4690        return;
4691    };
4692    let raw = load_slot(builder, buffer_ptr, in_slot);
4693
4694    // A float source as an `f64`; the promotion from `f32` is exact.
4695    let float_of = |builder: &mut FunctionBuilder| -> ir::Value {
4696        match src {
4697            F32 => {
4698                let bits = builder.ins().ireduce(types::I32, raw);
4699                let x = builder.ins().bitcast(types::F32, ir::MemFlags::new(), bits);
4700                builder.ins().fpromote(types::F64, x)
4701            }
4702            _ => builder.ins().bitcast(types::F64, ir::MemFlags::new(), raw),
4703        }
4704    };
4705    // Store a float as the target's carrier: an `f64` as its bits, an
4706    // `f32` as its own bits zero-extended.
4707    let store_float = |builder: &mut FunctionBuilder, x: ir::Value| {
4708        let word = if dst == F32 {
4709            let bits = builder.ins().bitcast(types::I32, ir::MemFlags::new(), x);
4710            builder.ins().uextend(types::I64, bits)
4711        } else {
4712            builder.ins().bitcast(types::I64, ir::MemFlags::new(), x)
4713        };
4714        store_slot(builder, buffer_ptr, out_slot, word);
4715    };
4716
4717    match (src, dst) {
4718        // Anything to `bool`: non-zero, and for a float also not NaN;
4719        // `-0.0` is zero.
4720        (_, Bool) => {
4721            let truth = match src {
4722                F32 | F64 => {
4723                    // Not equal to zero (which NaN is too) and ordered
4724                    // (which NaN is not). `OrderedNotEqual` says both
4725                    // at once, but Cranelift's aarch64 backend leaves
4726                    // it unimplemented and panics lowering it.
4727                    let x = float_of(builder);
4728                    let zero = builder.ins().f64const(0.0);
4729                    let nonzero = builder.ins().fcmp(FloatCC::NotEqual, x, zero);
4730                    let ordered = builder.ins().fcmp(FloatCC::Ordered, x, x);
4731                    builder.ins().band(nonzero, ordered)
4732                }
4733                _ => builder.ins().icmp_imm(IntCC::NotEqual, raw, 0),
4734            };
4735            let word = builder.ins().uextend(types::I64, truth);
4736            store_slot(builder, buffer_ptr, out_slot, word);
4737        }
4738        // Integer to integer: the carrier's word is the value in both
4739        // types wherever the value fits the target.
4740        (s, d) if s.int_range().is_some() && d.int_range().is_some() => {
4741            let (smin, smax) = s.int_range().expect("an integer");
4742            let (dmin, dmax) = d.int_range().expect("an integer");
4743            let mut fits = Vec::new();
4744            if dmin > smin {
4745                // Only a signed source reaches below the target.
4746                fits.push(builder.ins().icmp_imm(
4747                    IntCC::SignedGreaterThanOrEqual,
4748                    raw,
4749                    dmin as i64,
4750                ));
4751            }
4752            if dmax < smax {
4753                let cc = if matches!(s, Signed(_)) {
4754                    IntCC::SignedLessThanOrEqual
4755                } else {
4756                    IntCC::UnsignedLessThanOrEqual
4757                };
4758                fits.push(builder.ins().icmp_imm(cc, raw, dmax as u64 as i64));
4759            }
4760            branch_on(
4761                builder,
4762                fits,
4763                |b| {
4764                    store_slot(b, buffer_ptr, out_slot, raw);
4765                },
4766                slow,
4767            );
4768        }
4769        // Integer to float, rounded to nearest as `as` rounds.
4770        (s, F32 | F64) if s.int_range().is_some() => {
4771            let ty = if dst == F32 { types::F32 } else { types::F64 };
4772            let x = if matches!(s, Signed(_)) {
4773                builder.ins().fcvt_from_sint(ty, raw)
4774            } else {
4775                builder.ins().fcvt_from_uint(ty, raw)
4776            };
4777            store_float(builder, x);
4778        }
4779        (F32, F64) => {
4780            let x = float_of(builder);
4781            store_float(builder, x);
4782        }
4783        (F64, F32) => {
4784            let x = float_of(builder);
4785            let narrow = builder.ins().fdemote(types::F32, x);
4786            store_float(builder, narrow);
4787        }
4788        // Float to integer: inside `[lo, hi)` of the target, truncation
4789        // is the node's rule and the saturating instruction is exact.
4790        // NaN fails both comparisons and takes the node.
4791        (F32 | F64, d) => {
4792            let (lo, hi) = match d {
4793                Unsigned(b) => (0.0, 2f64.powi(b as i32)),
4794                Signed(b) => (-(2f64.powi(b as i32 - 1)), 2f64.powi(b as i32 - 1)),
4795                _ => {
4796                    slow(builder);
4797                    return;
4798                }
4799            };
4800            let x = float_of(builder);
4801            let lo_v = builder.ins().f64const(lo);
4802            let hi_v = builder.ins().f64const(hi);
4803            let above = builder.ins().fcmp(FloatCC::GreaterThanOrEqual, x, lo_v);
4804            let below = builder.ins().fcmp(FloatCC::LessThan, x, hi_v);
4805            branch_on(
4806                builder,
4807                vec![above, below],
4808                |b| {
4809                    let word = if matches!(d, Signed(_)) {
4810                        b.ins().fcvt_to_sint_sat(types::I64, x)
4811                    } else {
4812                        b.ins().fcvt_to_uint_sat(types::I64, x)
4813                    };
4814                    store_slot(b, buffer_ptr, out_slot, word);
4815                },
4816                slow,
4817            );
4818        }
4819        _ => slow(builder),
4820    }
4821}
4822
4823/// `fast` when every condition holds, else `slow`, joined after. No
4824/// conditions is `fast` alone.
4825fn branch_on(
4826    builder: &mut FunctionBuilder,
4827    conds: Vec<ir::Value>,
4828    fast: impl FnOnce(&mut FunctionBuilder),
4829    slow: impl FnOnce(&mut FunctionBuilder),
4830) {
4831    let mut conds = conds.into_iter();
4832    let Some(first) = conds.next() else {
4833        fast(builder);
4834        return;
4835    };
4836    let mut ok = first;
4837    for c in conds {
4838        ok = builder.ins().band(ok, c);
4839    }
4840    let fast_block = builder.create_block();
4841    let slow_block = builder.create_block();
4842    let done = builder.create_block();
4843    builder.ins().brif(ok, fast_block, &[], slow_block, &[]);
4844    builder.switch_to_block(fast_block);
4845    builder.seal_block(fast_block);
4846    fast(builder);
4847    builder.ins().jump(done, &[]);
4848    builder.switch_to_block(slow_block);
4849    builder.seal_block(slow_block);
4850    slow(builder);
4851    builder.ins().jump(done, &[]);
4852    builder.switch_to_block(done);
4853    builder.seal_block(done);
4854}
4855
4856fn load_slot(builder: &mut FunctionBuilder, buffer_ptr: ir::Value, slot: usize) -> ir::Value {
4857    let offset = (slot * 8) as i32;
4858    builder
4859        .ins()
4860        .load(types::I64, ir::MemFlags::trusted(), buffer_ptr, offset)
4861}
4862
4863/// Store a u64 to buffer[slot].
4864fn store_slot(
4865    builder: &mut FunctionBuilder,
4866    buffer_ptr: ir::Value,
4867    slot: usize,
4868    value: ir::Value,
4869) -> ir::Inst {
4870    let offset = (slot * 8) as i32;
4871    builder
4872        .ins()
4873        .store(ir::MemFlags::trusted(), value, buffer_ptr, offset)
4874}
4875
4876/// Cranelift vector type for a register lane index (the
4877/// `RegBinOp`/`RegSplat` vocabulary).
4878fn reg_lane_type(lane: u8) -> ir::Type {
4879    match lane {
4880        0 => types::I8X16,
4881        1 => types::I16X8,
4882        2 => types::I32X4,
4883        3 => types::I64X2,
4884        4 => types::F32X4,
4885        5 => types::F64X2,
4886        _ => unreachable!("register lane index out of range"),
4887    }
4888}
4889
4890/// Load a 128-bit register value from its two consecutive slots
4891/// (an `Imm2` port occupies two consecutive slots, axiom S1). The buffer is only
4892/// 8-aligned, so the load must NOT carry the aligned flag —
4893/// `MemFlags::new()` permits unaligned 128-bit access.
4894fn load_reg128(
4895    builder: &mut FunctionBuilder,
4896    buffer_ptr: ir::Value,
4897    first_slot: usize,
4898    vt: ir::Type,
4899) -> ir::Value {
4900    let offset = (first_slot * 8) as i32;
4901    builder
4902        .ins()
4903        .load(vt, ir::MemFlags::new(), buffer_ptr, offset)
4904}
4905
4906/// Store a 128-bit register value into its two consecutive slots.
4907fn store_reg128(
4908    builder: &mut FunctionBuilder,
4909    buffer_ptr: ir::Value,
4910    first_slot: usize,
4911    value: ir::Value,
4912) {
4913    let offset = (first_slot * 8) as i32;
4914    builder
4915        .ins()
4916        .store(ir::MemFlags::new(), value, buffer_ptr, offset);
4917}
4918
4919/// `x` rounded half away from zero, as `f64::round` rounds: the
4920/// truncation, plus one in the sign of `x` when the fraction's
4921/// magnitude reaches a half. Exact: where the fraction is nonzero the
4922/// truncation is below 2^52, so the step is representable.
4923fn round_half_away(builder: &mut FunctionBuilder, x: ir::Value) -> ir::Value {
4924    let t = builder.ins().trunc(x);
4925    let frac = builder.ins().fsub(x, t);
4926    let mag = builder.ins().fabs(frac);
4927    let half = builder.ins().f64const(0.5);
4928    let reaches = builder
4929        .ins()
4930        .fcmp(ir::condcodes::FloatCC::GreaterThanOrEqual, mag, half);
4931    let one = builder.ins().f64const(1.0);
4932    let step = builder.ins().fcopysign(one, x);
4933    let up = builder.ins().fadd(t, step);
4934    builder.ins().select(reaches, up, t)
4935}
4936
4937/// `x.clamp(lo, hi)` as `f64::clamp` computes it: `lo` when `x < lo`,
4938/// `hi` when `x > hi`, else `x` itself, so a negative zero and a NaN
4939/// pass through as they do there (`fmax`/`fmin` would return the
4940/// bound's zero for `-0.0`).
4941fn clamp_ir(
4942    builder: &mut FunctionBuilder,
4943    x: ir::Value,
4944    lo: ir::Value,
4945    hi: ir::Value,
4946) -> ir::Value {
4947    let below = builder.ins().fcmp(ir::condcodes::FloatCC::LessThan, x, lo);
4948    let above = builder
4949        .ins()
4950        .fcmp(ir::condcodes::FloatCC::GreaterThan, x, hi);
4951    let capped = builder.ins().select(above, hi, x);
4952    builder.ins().select(below, lo, capped)
4953}
4954
4955/// `val.div_ceil(m)` for a nonzero `m`: the quotient, plus one when
4956/// the remainder is nonzero, with no sum that can overflow.
4957fn div_ceil(
4958    builder: &mut FunctionBuilder,
4959    val: ir::Value,
4960    m: ir::Value,
4961    one: ir::Value,
4962) -> ir::Value {
4963    let q = builder.ins().udiv(val, m);
4964    let r = builder.ins().urem(val, m);
4965    let zero = builder.ins().iconst(types::I64, 0);
4966    let inexact = builder.ins().icmp(ir::condcodes::IntCC::NotEqual, r, zero);
4967    let q1 = builder.ins().iadd(q, one);
4968    builder.ins().select(inexact, q1, q)
4969}
4970
4971/// The function reference declared for one helper of a group.
4972fn func_of<K: PartialEq + Copy>(refs: &[(K, ir::FuncRef)], key: K) -> ir::FuncRef {
4973    refs.iter()
4974        .find(|(k, _)| *k == key)
4975        .map(|(_, r)| *r)
4976        .expect("every helper of the group is declared")
4977}
4978
4979/// Load a step's input words in order, zero past the last, as the
4980/// arguments of a helper that takes a fixed count of words.
4981fn load_words(
4982    builder: &mut FunctionBuilder,
4983    buffer_ptr: ir::Value,
4984    input_slots: &[usize],
4985    n: usize,
4986) -> Vec<ir::Value> {
4987    (0..n)
4988        .map(|k| match input_slots.get(k) {
4989            Some(&s) => load_slot(builder, buffer_ptr, s),
4990            None => builder.ins().iconst(types::I64, 0),
4991        })
4992        .collect()
4993}
4994
4995/// Load an f64 from buffer[slot] (bitcast from i64).
4996fn load_slot_f64(builder: &mut FunctionBuilder, buffer_ptr: ir::Value, slot: usize) -> ir::Value {
4997    let i64_val = load_slot(builder, buffer_ptr, slot);
4998    builder
4999        .ins()
5000        .bitcast(types::F64, ir::MemFlags::new(), i64_val)
5001}
5002
5003/// Store an f64 to buffer[slot] (bitcast to i64).
5004fn store_slot_f64(
5005    builder: &mut FunctionBuilder,
5006    buffer_ptr: ir::Value,
5007    slot: usize,
5008    value: ir::Value,
5009) {
5010    let i64_val = builder
5011        .ins()
5012        .bitcast(types::I64, ir::MemFlags::new(), value);
5013    store_slot(builder, buffer_ptr, slot, i64_val);
5014}
5015
5016// ── Tests ──────────────────────────────────────────────────
5017
5018#[cfg(test)]
5019mod tests {
5020    use super::*;
5021
5022    /// Every conversion the table makes between two scalar kinds lowers
5023    /// as `Convert`, by its types. A conversion named in `classify_node`
5024    /// instead would be a second copy of the node's rule again, and it
5025    /// would shadow this one.
5026    #[test]
5027    fn every_scalar_conversion_lowers_by_its_types() {
5028        let mut missing = Vec::new();
5029        for &from in crate::ast::PortType::ALL {
5030            for &to in crate::ast::PortType::ALL {
5031                if from == to || Scalar::of(from).is_none() || Scalar::of(to).is_none() {
5032                    continue;
5033                }
5034                let Some(node) = crate::compile::assembly::boundary_adapter(from, to) else {
5035                    continue;
5036                };
5037                match classify_node(node.as_ref()) {
5038                    JitOp::Convert { from: f, to: t, .. } if f == from && t == to => {}
5039                    other => missing.push(format!(
5040                        "{} ({from:?} -> {to:?}) classified as {other:?}",
5041                        node.meta().name
5042                    )),
5043                }
5044            }
5045        }
5046        assert!(missing.is_empty(), "{}", missing.join("\n"));
5047    }
5048
5049    #[test]
5050    fn jit_identity() {
5051        let steps = vec![(JitOp::Identity, vec![0], vec![1])];
5052        let mut output_map = HashMap::new();
5053        output_map.insert("out".into(), 1);
5054        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5055        kernel.eval(&[42]);
5056        assert_eq!(kernel.get("out"), 42);
5057    }
5058
5059    #[test]
5060    fn jit_add_const() {
5061        let steps = vec![(JitOp::AddConst(100), vec![0], vec![1])];
5062        let mut output_map = HashMap::new();
5063        output_map.insert("out".into(), 1);
5064        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5065        kernel.eval(&[5]);
5066        assert_eq!(kernel.get("out"), 105);
5067    }
5068
5069    #[test]
5070    fn jit_mul_const() {
5071        let steps = vec![(JitOp::MulConst(7), vec![0], vec![1])];
5072        let mut output_map = HashMap::new();
5073        output_map.insert("out".into(), 1);
5074        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5075        kernel.eval(&[6]);
5076        assert_eq!(kernel.get("out"), 42);
5077    }
5078
5079    #[test]
5080    fn jit_mod_const() {
5081        let steps = vec![(JitOp::ModConst(100), vec![0], vec![1])];
5082        let mut output_map = HashMap::new();
5083        output_map.insert("out".into(), 1);
5084        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5085        kernel.eval(&[542]);
5086        assert_eq!(kernel.get("out"), 42);
5087    }
5088
5089    #[test]
5090    fn jit_hash() {
5091        let steps = vec![(JitOp::Hash, vec![0], vec![1])];
5092        let mut output_map = HashMap::new();
5093        output_map.insert("out".into(), 1);
5094        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5095
5096        kernel.eval(&[42]);
5097        let v1 = kernel.get("out");
5098
5099        // Verify it matches the Rust xxh3 implementation
5100        let expected = xxhash_rust::xxh3::xxh3_64(&42u64.to_le_bytes());
5101        assert_eq!(v1, expected);
5102    }
5103
5104    #[test]
5105    fn jit_hash_deterministic() {
5106        let steps = vec![(JitOp::Hash, vec![0], vec![1])];
5107        let mut output_map = HashMap::new();
5108        output_map.insert("out".into(), 1);
5109        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5110
5111        kernel.eval(&[42]);
5112        let v1 = kernel.get("out");
5113        kernel.eval(&[42]);
5114        let v2 = kernel.get("out");
5115        assert_eq!(v1, v2);
5116    }
5117
5118    #[test]
5119    fn jit_chain_hash_mod() {
5120        // hash(cycle) → mod(result, 1000000)
5121        let steps = vec![
5122            (JitOp::Hash, vec![0], vec![1]), // slot 1 = hash(coord 0)
5123            (JitOp::ModConst(1_000_000), vec![1], vec![2]), // slot 2 = slot 1 % 1M
5124        ];
5125        let mut output_map = HashMap::new();
5126        output_map.insert("user_id".into(), 2);
5127        let mut kernel = compile_jit_raw(1, 3, steps, output_map, Vec::new()).unwrap();
5128
5129        kernel.eval(&[42]);
5130        let uid = kernel.get("user_id");
5131        assert!(uid < 1_000_000, "got {uid}");
5132    }
5133
5134    #[test]
5135    fn jit_clamp_const() {
5136        let steps = vec![(JitOp::ClampConst(10, 50), vec![0], vec![1])];
5137        let mut output_map = HashMap::new();
5138        output_map.insert("out".into(), 1);
5139        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5140
5141        kernel.eval(&[5]);
5142        assert_eq!(kernel.get("out"), 10); // below min
5143
5144        kernel.eval(&[30]);
5145        assert_eq!(kernel.get("out"), 30); // in range
5146
5147        kernel.eval(&[100]);
5148        assert_eq!(kernel.get("out"), 50); // above max
5149    }
5150
5151    #[test]
5152    fn jit_interleave() {
5153        let steps = vec![(JitOp::Interleave, vec![0, 1], vec![2])];
5154        let mut output_map = HashMap::new();
5155        output_map.insert("out".into(), 2);
5156        let mut kernel = compile_jit_raw(2, 3, steps, output_map, Vec::new()).unwrap();
5157
5158        kernel.eval(&[0b101, 0b010]);
5159        // Same as the Interleave node test: result = 0b011001
5160        assert_eq!(kernel.get("out"), 0b01_10_01);
5161    }
5162
5163    #[test]
5164    fn jit_mixed_radix() {
5165        // 100 × 1000 × unbounded
5166        let steps = vec![(
5167            JitOp::MixedRadixConst(vec![100, 1000, 0]),
5168            vec![0],
5169            vec![1, 2, 3],
5170        )];
5171        let mut output_map = HashMap::new();
5172        output_map.insert("d0".into(), 1);
5173        output_map.insert("d1".into(), 2);
5174        output_map.insert("d2".into(), 3);
5175        let mut kernel = compile_jit_raw(1, 4, steps, output_map, Vec::new()).unwrap();
5176
5177        // 4201337 → (37, 13, 42)
5178        kernel.eval(&[4_201_337]);
5179        assert_eq!(kernel.get("d0"), 37);
5180        assert_eq!(kernel.get("d1"), 13);
5181        assert_eq!(kernel.get("d2"), 42);
5182    }
5183
5184    #[test]
5185    fn jit_unit_interval() {
5186        let steps = vec![(JitOp::UnitInterval, vec![0], vec![1])];
5187        let mut output_map = HashMap::new();
5188        output_map.insert("out".into(), 1);
5189        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5190
5191        kernel.eval(&[0]);
5192        let v = f64::from_bits(kernel.get("out"));
5193        assert!((v - 0.0).abs() < 1e-10);
5194
5195        kernel.eval(&[u64::MAX]);
5196        let v = f64::from_bits(kernel.get("out"));
5197        assert!((v - 1.0).abs() < 1e-10);
5198    }
5199
5200    #[test]
5201    fn jit_f64_to_u64() {
5202        // Store 3.7 as f64 bits in coord slot, convert to u64
5203        let steps = vec![(JitOp::F64ToU64, vec![0], vec![1])];
5204        let mut output_map = HashMap::new();
5205        output_map.insert("out".into(), 1);
5206        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5207
5208        kernel.eval(&[3.7f64.to_bits()]);
5209        assert_eq!(kernel.get("out"), 3); // truncate toward zero
5210    }
5211
5212    #[test]
5213    fn jit_round_to_u64() {
5214        let steps = vec![(JitOp::RoundToU64, vec![0], vec![1])];
5215        let mut output_map = HashMap::new();
5216        output_map.insert("out".into(), 1);
5217        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5218
5219        kernel.eval(&[3.7f64.to_bits()]);
5220        assert_eq!(kernel.get("out"), 4);
5221
5222        kernel.eval(&[3.2f64.to_bits()]);
5223        assert_eq!(kernel.get("out"), 3);
5224    }
5225
5226    #[test]
5227    fn jit_clamp_f64() {
5228        let steps = vec![(
5229            JitOp::ClampF64Const(0.0f64.to_bits(), 1.0f64.to_bits()),
5230            vec![0],
5231            vec![1],
5232        )];
5233        let mut output_map = HashMap::new();
5234        output_map.insert("out".into(), 1);
5235        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5236
5237        kernel.eval(&[(-0.5f64).to_bits()]);
5238        assert_eq!(f64::from_bits(kernel.get("out")), 0.0);
5239
5240        kernel.eval(&[0.5f64.to_bits()]);
5241        assert_eq!(f64::from_bits(kernel.get("out")), 0.5);
5242
5243        kernel.eval(&[1.5f64.to_bits()]);
5244        assert_eq!(f64::from_bits(kernel.get("out")), 1.0);
5245    }
5246
5247    #[test]
5248    fn jit_lerp() {
5249        let steps = vec![(
5250            JitOp::LerpConst(10.0f64.to_bits(), 20.0f64.to_bits()),
5251            vec![0],
5252            vec![1],
5253        )];
5254        let mut output_map = HashMap::new();
5255        output_map.insert("out".into(), 1);
5256        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5257
5258        kernel.eval(&[0.0f64.to_bits()]);
5259        assert_eq!(f64::from_bits(kernel.get("out")), 10.0);
5260
5261        kernel.eval(&[1.0f64.to_bits()]);
5262        assert_eq!(f64::from_bits(kernel.get("out")), 20.0);
5263
5264        kernel.eval(&[0.5f64.to_bits()]);
5265        assert_eq!(f64::from_bits(kernel.get("out")), 15.0);
5266    }
5267
5268    #[test]
5269    fn jit_scale_range() {
5270        let steps = vec![(
5271            JitOp::ScaleRangeConst(10.0f64.to_bits(), 10.0f64.to_bits()),
5272            vec![0],
5273            vec![1],
5274        )];
5275        let mut output_map = HashMap::new();
5276        output_map.insert("out".into(), 1);
5277        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5278
5279        kernel.eval(&[0]);
5280        let v = f64::from_bits(kernel.get("out"));
5281        assert!((v - 10.0).abs() < 0.001);
5282
5283        kernel.eval(&[u64::MAX]);
5284        let v = f64::from_bits(kernel.get("out"));
5285        assert!((v - 20.0).abs() < 0.001);
5286    }
5287
5288    #[test]
5289    fn jit_quantize() {
5290        let steps = vec![(JitOp::QuantizeConst(10.0f64.to_bits()), vec![0], vec![1])];
5291        let mut output_map = HashMap::new();
5292        output_map.insert("out".into(), 1);
5293        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5294
5295        kernel.eval(&[13.0f64.to_bits()]);
5296        assert_eq!(f64::from_bits(kernel.get("out")), 10.0);
5297
5298        kernel.eval(&[17.0f64.to_bits()]);
5299        assert_eq!(f64::from_bits(kernel.get("out")), 20.0);
5300    }
5301
5302    #[test]
5303    fn jit_discretize() {
5304        let steps = vec![(
5305            JitOp::DiscretizeConst(100.0f64.to_bits(), 10),
5306            vec![0],
5307            vec![1],
5308        )];
5309        let mut output_map = HashMap::new();
5310        output_map.insert("out".into(), 1);
5311        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5312
5313        kernel.eval(&[0.0f64.to_bits()]);
5314        assert_eq!(kernel.get("out"), 0);
5315
5316        kernel.eval(&[55.0f64.to_bits()]);
5317        assert_eq!(kernel.get("out"), 5);
5318
5319        kernel.eval(&[99.0f64.to_bits()]);
5320        assert_eq!(kernel.get("out"), 9);
5321
5322        // Clamp above range
5323        kernel.eval(&[200.0f64.to_bits()]);
5324        assert_eq!(kernel.get("out"), 9);
5325    }
5326
5327    #[test]
5328    fn jit_chain_unit_interval_lerp() {
5329        // u64 → unit_interval → lerp(100, 200)
5330        let steps = vec![
5331            (JitOp::UnitInterval, vec![0], vec![1]),
5332            (
5333                JitOp::LerpConst(100.0f64.to_bits(), 200.0f64.to_bits()),
5334                vec![1],
5335                vec![2],
5336            ),
5337        ];
5338        let mut output_map = HashMap::new();
5339        output_map.insert("out".into(), 2);
5340        let mut kernel = compile_jit_raw(1, 3, steps, output_map, Vec::new()).unwrap();
5341
5342        kernel.eval(&[0]);
5343        let v = f64::from_bits(kernel.get("out"));
5344        assert!((v - 100.0).abs() < 0.001);
5345
5346        kernel.eval(&[u64::MAX]);
5347        let v = f64::from_bits(kernel.get("out"));
5348        assert!((v - 200.0).abs() < 0.001);
5349    }
5350
5351    #[test]
5352    fn jit_multi_step_chain() {
5353        // cycle → add(10) → mul(3) → mod(100)
5354        let steps = vec![
5355            (JitOp::AddConst(10), vec![0], vec![1]),
5356            (JitOp::MulConst(3), vec![1], vec![2]),
5357            (JitOp::ModConst(100), vec![2], vec![3]),
5358        ];
5359        let mut output_map = HashMap::new();
5360        output_map.insert("out".into(), 3);
5361        let mut kernel = compile_jit_raw(1, 4, steps, output_map, Vec::new()).unwrap();
5362
5363        kernel.eval(&[5]);
5364        // (5 + 10) * 3 = 45, 45 % 100 = 45
5365        assert_eq!(kernel.get("out"), 45);
5366    }
5367
5368    // ── Parameter helper predicates ────────────────────────────
5369
5370    #[test]
5371    fn jit_is_positive_check_passes_positive() {
5372        let steps = vec![(
5373            JitOp::IsPositiveCheck {
5374                name_ptr: 0,
5375                name_len: 0,
5376            },
5377            vec![0],
5378            vec![1],
5379        )];
5380        let mut output_map = HashMap::new();
5381        output_map.insert("out".into(), 1);
5382        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5383        kernel.eval(&[42]);
5384        assert_eq!(kernel.get("out"), 42);
5385        // Large values pass through unchanged — happy path is a
5386        // bare store, not a clamp.
5387        kernel.eval(&[u64::MAX]);
5388        assert_eq!(kernel.get("out"), u64::MAX);
5389    }
5390
5391    #[test]
5392    fn jit_in_range_check_passes_interior() {
5393        let steps = vec![(JitOp::InRangeCheck(10, 100), vec![0], vec![1])];
5394        let mut output_map = HashMap::new();
5395        output_map.insert("out".into(), 1);
5396        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5397        kernel.eval(&[50]);
5398        assert_eq!(kernel.get("out"), 50);
5399        // Boundaries are inclusive.
5400        kernel.eval(&[10]);
5401        assert_eq!(kernel.get("out"), 10);
5402        kernel.eval(&[100]);
5403        assert_eq!(kernel.get("out"), 100);
5404    }
5405
5406    // Violation paths longjmp back to `invoke_with_catch` and
5407    // surface as ordinary panics; the tests below catch them
5408    // in-process.
5409
5410    #[test]
5411    fn jit_is_one_of_check_passes_allowed_values() {
5412        let steps = vec![(
5413            JitOp::IsOneOfCheck {
5414                allowed: vec![1, 2, 3, 5, 8],
5415                set_ptr: 0,
5416                set_len: 0,
5417            },
5418            vec![0],
5419            vec![1],
5420        )];
5421        let mut output_map = HashMap::new();
5422        output_map.insert("out".into(), 1);
5423        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5424        // Every allowed value passes straight through.
5425        for v in [1u64, 2, 3, 5, 8] {
5426            kernel.eval(&[v]);
5427            assert_eq!(kernel.get("out"), v);
5428        }
5429    }
5430
5431    #[test]
5432    fn jit_is_one_of_check_accepts_single_element_allow_list() {
5433        // Degenerate case — one-value allow-list reduces to an
5434        // equality check with panic on mismatch.
5435        let steps = vec![(
5436            JitOp::IsOneOfCheck {
5437                allowed: vec![42],
5438                set_ptr: 0,
5439                set_len: 0,
5440            },
5441            vec![0],
5442            vec![1],
5443        )];
5444        let mut output_map = HashMap::new();
5445        output_map.insert("out".into(), 1);
5446        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5447        kernel.eval(&[42]);
5448        assert_eq!(kernel.get("out"), 42);
5449    }
5450
5451    // ── Catchable panic from JIT predicate fails ──────────────
5452    //
5453    // The extern fail helpers use `_longjmp` back to the Rust
5454    // wrapper, which then raises a Rust `panic!` carrying the
5455    // violation message. The panic originates in Rust land
5456    // (the JIT frame has already been jumped past), so its
5457    // unwind works through Rust-personality FDEs and
5458    // `std::panic::catch_unwind` catches it normally.
5459
5460    fn extract_panic_msg(payload: Box<dyn std::any::Any + Send + 'static>) -> String {
5461        payload
5462            .downcast_ref::<String>()
5463            .cloned()
5464            .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
5465            .unwrap_or_else(|| "(non-string panic)".into())
5466    }
5467
5468    #[test]
5469    fn jit_is_positive_violation_is_catchable() {
5470        let steps = vec![(
5471            JitOp::IsPositiveCheck {
5472                name_ptr: 0,
5473                name_len: 0,
5474            },
5475            vec![0],
5476            vec![1],
5477        )];
5478        let mut output_map = HashMap::new();
5479        output_map.insert("out".into(), 1);
5480        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5481        let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kernel.eval(&[0])))
5482            .expect_err("JIT violation should panic");
5483        assert!(extract_panic_msg(err).contains("must be > 0"));
5484    }
5485
5486    #[test]
5487    fn jit_in_range_violation_is_catchable() {
5488        let steps = vec![(JitOp::InRangeCheck(10, 100), vec![0], vec![1])];
5489        let mut output_map = HashMap::new();
5490        output_map.insert("out".into(), 1);
5491        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5492
5493        let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kernel.eval(&[5])))
5494            .expect_err("below-range should panic");
5495        assert!(extract_panic_msg(err).contains("outside [10, 100]"));
5496
5497        let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kernel.eval(&[500])))
5498            .expect_err("above-range should panic");
5499        assert!(extract_panic_msg(err).contains("outside [10, 100]"));
5500    }
5501
5502    #[test]
5503    fn jit_is_one_of_violation_is_catchable() {
5504        let steps = vec![(
5505            JitOp::IsOneOfCheck {
5506                allowed: vec![1, 3, 5],
5507                set_ptr: 0,
5508                set_len: 0,
5509            },
5510            vec![0],
5511            vec![1],
5512        )];
5513        let mut output_map = HashMap::new();
5514        output_map.insert("out".into(), 1);
5515        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5516        let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kernel.eval(&[2])))
5517            .expect_err("disallowed value should panic");
5518        assert!(extract_panic_msg(err).contains("not in allowed set"));
5519    }
5520
5521    #[test]
5522    fn invoke_with_catch_restores_slot_after_foreign_panic() {
5523        // A non-JIT panic from inside `f()` (simulating a bug
5524        // in a hybrid-closure step or any other non-longjmp
5525        // path that may run between setjmp and return) must
5526        // still leave the thread-local JIT_JMP_BUF slot in a
5527        // consistent state. The next `invoke_with_catch` that
5528        // actually calls into JIT code should see a clean
5529        // sentinel.
5530        let caught = std::panic::catch_unwind(|| {
5531            invoke_with_catch(|| panic!("foreign panic"));
5532        });
5533        assert!(caught.is_err(), "foreign panic should propagate out");
5534
5535        // Subsequent legitimate JIT violation is still caught.
5536        let steps = vec![(
5537            JitOp::IsPositiveCheck {
5538                name_ptr: 0,
5539                name_len: 0,
5540            },
5541            vec![0],
5542            vec![1],
5543        )];
5544        let mut output_map = HashMap::new();
5545        output_map.insert("out".into(), 1);
5546        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5547        let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kernel.eval(&[0])))
5548            .expect_err("JIT violation should panic cleanly after foreign panic");
5549        assert!(extract_panic_msg(err).contains("must be > 0"));
5550
5551        // And the happy path too — no stale pointer lingering.
5552        kernel.eval(&[42]);
5553        assert_eq!(kernel.get("out"), 42);
5554    }
5555
5556    #[test]
5557    fn jit_kernel_survives_multiple_violations() {
5558        // After a caught violation the kernel remains usable —
5559        // the jmp_buf slot is correctly cleared and a
5560        // subsequent happy-path eval returns normally.
5561        let steps = vec![(
5562            JitOp::IsPositiveCheck {
5563                name_ptr: 0,
5564                name_len: 0,
5565            },
5566            vec![0],
5567            vec![1],
5568        )];
5569        let mut output_map = HashMap::new();
5570        output_map.insert("out".into(), 1);
5571        let mut kernel = compile_jit_raw(1, 2, steps, output_map, Vec::new()).unwrap();
5572
5573        for _ in 0..3 {
5574            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kernel.eval(&[0])))
5575                .expect_err("violation should still panic");
5576        }
5577        // Happy path still works.
5578        kernel.eval(&[42]);
5579        assert_eq!(kernel.get("out"), 42);
5580    }
5581
5582    /// The engine ladder's graph (crates/polydat/examples), with each
5583    /// `mod` as a `mul` and `u64_xor` as a `u64_add`, the nodes of the
5584    /// same shape this crate's test library has.
5585    const LADDER: &str = "input cycle: u64\ninput tenant_seed: u64\ninput operation_seed: u64\n\
5586        seeded_cycle := u64_add(cycle, tenant_seed)\nidentity_entropy := hash(seeded_cycle)\n\
5587        account_id := mul(identity_entropy, 10000000)\n\
5588        route_seed := u64_add(account_id, operation_seed)\nroute_entropy := hash(route_seed)\n\
5589        shard := mul(route_entropy, 64)\n\
5590        payload_seed := u64_add(identity_entropy, operation_seed)\n\
5591        payload_entropy := hash(payload_seed)\npayload_class := mul(payload_entropy, 8)\n\
5592        token_seed := u64_add(route_entropy, payload_entropy)\nevent_token := hash(token_seed)\n";
5593
5594    /// Pure native's units and native's segments for `src`.
5595    fn unit_counts(src: &str) -> (usize, usize) {
5596        let asm = || crate::dsl::compile::compile_polydat_to_assembler(src).unwrap();
5597        let pure = asm()
5598            .try_compile_pure_jit_raw()
5599            .unwrap()
5600            .core
5601            .cones
5602            .unit_count();
5603        let native = crate::dsl::compile::compile_polydat_with(
5604            src,
5605            crate::compile::select::Engine::Native(crate::compile::select::Provenance::Raw),
5606        )
5607        .unwrap()
5608        .plan()
5609        .native_segments;
5610        (pure, native)
5611    }
5612
5613    /// A program with no extern plans the units it always did: the
5614    /// ladder's graph is one unit on pure native and one segment on
5615    /// native. An extern splits the nodes that depend on it from those
5616    /// that do not, on both: with `operation_seed` an extern, the
5617    /// identity path, which does not read it, is a unit of its own.
5618    #[test]
5619    fn only_an_extern_splits_a_unit() {
5620        assert_eq!(unit_counts(LADDER), (1, 1));
5621        let extern_seed = LADDER.replace(
5622            "input operation_seed: u64",
5623            "extern operation_seed: u64 = 7",
5624        );
5625        assert_eq!(unit_counts(&extern_seed), (2, 2));
5626        // `b` reads `mode` and `c` reads `b`; `t` and `a` depend on
5627        // neither, so they are one unit and `b` and `c` another.
5628        let shape = "input x: u64\nMODE\nt := hash(x)\na := hash(t)\n\
5629                     b := u64_add(t, mode)\nc := add(b, 1)\n";
5630        assert_eq!(
5631            unit_counts(&shape.replace("MODE", "input mode: u64")),
5632            (1, 1)
5633        );
5634        assert_eq!(
5635            unit_counts(&shape.replace("MODE", "extern mode: u64 = 3")),
5636            (2, 2)
5637        );
5638    }
5639}