Skip to main content

byteflow/jit/
dispatch.rs

1//! Execute compiled traces and map exits back to VM state.
2#![allow(unsafe_code)]
3
4use std::sync::Arc;
5
6use crate::{Chunk, Fault, Value, Vm, VmResult};
7
8use super::compiler::TraceCompiler;
9use super::exit::{ExitReason, JitReturn};
10use super::frame::{JitCallRecord, JitFrame, MAX_JIT_CALL_DEPTH};
11use super::module_local::with_jit_module;
12use super::runtime::JitRuntime;
13use super::trace::{CompiledTrace, JitContext, TraceKey, HOT_THRESHOLD};
14
15/// Result of copying VM registers into JIT shadow slots.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum SyncSlotsResult {
18    Ok,
19    /// Every register is `Float`, `Bool`, or `Unit`, and at least one is
20    /// `Float`. Slots hold IEEE bits.
21    Float,
22    /// A register held a type this specialization cannot guard.
23    Deopt,
24    /// Frame unavailable.
25    Unavailable,
26}
27
28/// Tags of the active frame at the moment a trace is entered.
29///
30/// The public slot runners pass [`EntryTags::INT`]: every inherited `Move`
31/// writes an `Int`. The VM runners fill the real `Bool` and `Unit` bits.
32#[derive(Clone, Copy)]
33struct EntryTags {
34    as_bool: [u64; 4],
35    as_unit: [u64; 4],
36    as_float: [u64; 4],
37}
38
39impl EntryTags {
40    const INT: Self = Self {
41        as_bool: [0; 4],
42        as_unit: [0; 4],
43        as_float: [0; 4],
44    };
45
46    fn from_vm(vm: &Vm) -> Self {
47        let mut tags = Self::INT;
48        let Some(regs) = vm.top_registers() else {
49            return tags;
50        };
51        for (index, value) in regs.iter().enumerate() {
52            if index >= 256 {
53                break;
54            }
55            let bit = 1u64 << (index % 64);
56            let word = index / 64;
57            match value {
58                Value::Bool(_) => tags.as_bool[word] |= bit,
59                Value::Unit => tags.as_unit[word] |= bit,
60                Value::Float(_) => tags.as_float[word] |= bit,
61                _ => {}
62            }
63        }
64        tags
65    }
66}
67
68/// Attempt one native trace at the current `(function, pc)`.
69fn try_jit_step(vm: &mut Vm, ctx: &mut JitContext, budget: u32) -> Option<VmResult> {
70    if !Arc::ptr_eq(&ctx.chunk, &vm.chunk_arc()) {
71        return None;
72    }
73    let pc = vm.current_pc()?;
74    let function = vm.current_function();
75    let register_count = vm.current_num_registers()?;
76
77    let mut slots = vec![0i64; slot_capacity(vm)];
78    let floats = match sync_slots_from_vm(vm, &mut slots) {
79        SyncSlotsResult::Ok => false,
80        SyncSlotsResult::Float => true,
81        SyncSlotsResult::Deopt | SyncSlotsResult::Unavailable => return None,
82    };
83
84    let key = TraceKey {
85        function,
86        entry_pc: pc as u32,
87        floats,
88    };
89    let exit = try_run_hot_tagged(
90        ctx,
91        vm.chunk_arc().as_ref(),
92        key,
93        &mut HotCall {
94            slots: &mut slots,
95            budget,
96            register_count,
97            metrics: None,
98            tags: EntryTags::from_vm(vm),
99        },
100    )?;
101    match apply_exit_tagged(vm, &slots, exit) {
102        Ok(Some(result)) => Some(result),
103        Ok(None) => None,
104        Err(fault) => Some(VmResult::Trap(fault)),
105    }
106}
107
108fn try_jit_step_runtime(
109    vm: &mut Vm,
110    runtime: &JitRuntime,
111    budget: u32,
112    metrics: Option<&crate::scheduler::RuntimeMetrics>,
113) -> Option<VmResult> {
114    if !runtime.matches_chunk(&vm.chunk_arc()) {
115        return None;
116    }
117    let pc = vm.current_pc()?;
118    let function = vm.current_function();
119    let register_count = vm.current_num_registers()?;
120
121    let mut slots = vec![0i64; slot_capacity(vm)];
122    let floats = match sync_slots_from_vm(vm, &mut slots) {
123        SyncSlotsResult::Ok => false,
124        SyncSlotsResult::Float => true,
125        SyncSlotsResult::Deopt => {
126            if let Some(m) = metrics {
127                crate::scheduler::RuntimeMetrics::inc(&m.jit_deopts);
128            }
129            return None;
130        }
131        SyncSlotsResult::Unavailable => return None,
132    };
133
134    let key = TraceKey {
135        function,
136        entry_pc: pc as u32,
137        floats,
138    };
139    let exit = try_run_hot_runtime_tagged(
140        runtime,
141        vm.chunk_arc().as_ref(),
142        key,
143        &mut HotCall {
144            slots: &mut slots,
145            budget,
146            register_count,
147            metrics,
148            tags: EntryTags::from_vm(vm),
149        },
150    )?;
151    match apply_exit_tagged(vm, &slots, exit) {
152        Ok(Some(result)) => Some(result),
153        Ok(None) => None,
154        Err(fault) => Some(VmResult::Trap(fault)),
155    }
156}
157
158/// Run at most `budget` instructions, retrying compiled traces after each
159/// interpreter step when a site becomes hot.
160pub fn run_vm_with_jit(vm: &mut Vm, budget: u32, ctx: &mut JitContext) -> VmResult {
161    run_vm_with_jit_loop(vm, budget, |vm, remaining| try_jit_step(vm, ctx, remaining))
162}
163
164/// Runtime path: shared cache, per-thread compilation module.
165pub fn run_vm_with_jit_runtime(
166    vm: &mut Vm,
167    budget: u32,
168    runtime: &JitRuntime,
169    metrics: Option<&crate::scheduler::RuntimeMetrics>,
170) -> VmResult {
171    run_vm_with_jit_loop(vm, budget, |vm, remaining| {
172        try_jit_step_runtime(vm, runtime, remaining, metrics)
173    })
174}
175
176fn run_vm_with_jit_loop(
177    vm: &mut Vm,
178    budget: u32,
179    mut try_step: impl FnMut(&mut Vm, u32) -> Option<VmResult>,
180) -> VmResult {
181    let mut remaining = budget;
182    while remaining > 0 {
183        if let Some(result) = try_step(vm, remaining) {
184            return result;
185        }
186        match vm.run(1) {
187            VmResult::Yield => {
188                remaining -= 1;
189            }
190            other => return other,
191        }
192    }
193    VmResult::Yield
194}
195
196fn slot_capacity(vm: &Vm) -> usize {
197    let chunk = vm.chunk_arc();
198    let max_in_chunk = chunk
199        .functions
200        .iter()
201        .map(|f| f.num_registers as usize)
202        .max();
203    match (max_in_chunk, vm.current_num_registers()) {
204        (Some(max_regs), Some(current)) => max_regs.max(current as usize),
205        (Some(max_regs), None) => max_regs,
206        (None, Some(current)) => current as usize,
207        (None, None) => 0,
208    }
209}
210
211/// Run a compiled trace against the shadow slot table.
212///
213/// Inherited `Move`s are written back as `Int`. The VM entry path records
214/// the real `Bool` and `Unit` bits before calling the trace.
215pub fn run_compiled_trace(
216    entry: super::frame::JitEntry,
217    slots: &mut [i64],
218    pc: u32,
219    budget: u32,
220    function: u32,
221    register_count: u32,
222) -> JitReturn {
223    run_compiled_trace_with_tags(
224        entry,
225        slots,
226        pc,
227        budget,
228        function,
229        register_count,
230        EntryTags::INT,
231    )
232}
233
234fn run_compiled_trace_with_tags(
235    entry: super::frame::JitEntry,
236    slots: &mut [i64],
237    pc: u32,
238    budget: u32,
239    function: u32,
240    register_count: u32,
241    tags: EntryTags,
242) -> JitReturn {
243    let mut call_stack = [JitCallRecord {
244        return_pc: 0,
245        return_function: 0,
246        dest_reg: 0,
247        caller_register_count: 0,
248        written: [0; 4],
249        as_bool: [0; 4],
250        as_unit: [0; 4],
251    }; MAX_JIT_CALL_DEPTH];
252    let stride = slots.len();
253    let mut spill = vec![0i64; stride.saturating_mul(MAX_JIT_CALL_DEPTH)];
254    let mut frame = JitFrame {
255        slots: slots.as_mut_ptr(),
256        register_count,
257        pc,
258        budget,
259        function,
260        exit_kind: 0,
261        return_reg: 0,
262        call_depth: 0,
263        call_stack: call_stack.as_mut_ptr(),
264        spill: spill.as_mut_ptr(),
265        spill_stride: stride as u32,
266        written: [0; 4],
267        as_bool: [0; 4],
268        as_unit: [0; 4],
269        entry_as_bool: tags.as_bool,
270        entry_as_unit: tags.as_unit,
271        as_float: [0; 4],
272        entry_as_float: tags.as_float,
273    };
274    unsafe { (entry)(&mut frame) };
275    JitReturn {
276        kind: frame.exit_kind,
277        pc: frame.pc,
278        return_reg: frame.return_reg,
279        written: frame.written,
280        as_bool: frame.as_bool,
281        as_unit: frame.as_unit,
282        as_float: frame.as_float,
283    }
284}
285
286/// Run a cached trace by reference.
287pub fn run_compiled_trace_ref(
288    trace: &CompiledTrace,
289    slots: &mut [i64],
290    pc: u32,
291    budget: u32,
292    function: u32,
293    register_count: u32,
294) -> JitReturn {
295    run_compiled_trace(trace.entry, slots, pc, budget, function, register_count)
296}
297
298struct HotCall<'a> {
299    slots: &'a mut [i64],
300    budget: u32,
301    register_count: u8,
302    metrics: Option<&'a crate::scheduler::RuntimeMetrics>,
303    tags: EntryTags,
304}
305
306/// Compile `key` if needed and execute once. Returns `None` when compilation
307/// fails (caller should fall back to the interpreter).
308pub fn try_run_hot(
309    ctx: &mut JitContext,
310    chunk: &Chunk,
311    key: TraceKey,
312    slots: &mut [i64],
313    budget: u32,
314    register_count: u8,
315    metrics: Option<&crate::scheduler::RuntimeMetrics>,
316) -> Option<ExitReason> {
317    try_run_hot_tagged(
318        ctx,
319        chunk,
320        key,
321        &mut HotCall {
322            slots,
323            budget,
324            register_count,
325            metrics,
326            tags: EntryTags::INT,
327        },
328    )
329    .map(JitReturn::into_reason)
330}
331
332fn try_run_hot_tagged(
333    ctx: &mut JitContext,
334    chunk: &Chunk,
335    key: TraceKey,
336    call: &mut HotCall<'_>,
337) -> Option<JitReturn> {
338    if ctx.cache.get(&key).is_none() {
339        if !ctx.hot.hit(key, ctx.hot_threshold) {
340            if let Some(m) = call.metrics {
341                crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
342            }
343            return None;
344        }
345        let mut compiler = TraceCompiler::new(ctx.module_mut());
346        match compiler.compile_trace(chunk, key) {
347            Ok(compiled) => {
348                ctx.cache.insert(key, compiled);
349                if let Some(m) = call.metrics {
350                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
351                }
352            }
353            Err(_) => {
354                if let Some(m) = call.metrics {
355                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
356                }
357                return None;
358            }
359        }
360    }
361    let trace = ctx.cache.get(&key)?;
362    if let Some(m) = call.metrics {
363        crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
364    }
365    Some(run_compiled_trace_with_tags(
366        trace.entry,
367        call.slots,
368        key.entry_pc,
369        call.budget,
370        key.function,
371        u32::from(call.register_count),
372        call.tags,
373    ))
374}
375
376/// Shared-runtime variant (no global lock during execution).
377pub fn try_run_hot_runtime(
378    runtime: &JitRuntime,
379    chunk: &Chunk,
380    key: TraceKey,
381    slots: &mut [i64],
382    budget: u32,
383    register_count: u8,
384    metrics: Option<&crate::scheduler::RuntimeMetrics>,
385) -> Option<ExitReason> {
386    try_run_hot_runtime_tagged(
387        runtime,
388        chunk,
389        key,
390        &mut HotCall {
391            slots,
392            budget,
393            register_count,
394            metrics,
395            tags: EntryTags::INT,
396        },
397    )
398    .map(JitReturn::into_reason)
399}
400
401fn try_run_hot_runtime_tagged(
402    runtime: &JitRuntime,
403    chunk: &Chunk,
404    key: TraceKey,
405    call: &mut HotCall<'_>,
406) -> Option<JitReturn> {
407    if let Some(copy) = runtime.get_trace(&key) {
408        if let Some(m) = call.metrics {
409            crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
410        }
411        return Some(run_compiled_trace_with_tags(
412            copy.entry,
413            call.slots,
414            key.entry_pc,
415            call.budget,
416            key.function,
417            u32::from(call.register_count),
418            call.tags,
419        ));
420    }
421
422    if !runtime.record_hot_hit(key) {
423        if let Some(m) = call.metrics {
424            crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
425        }
426        return None;
427    }
428
429    // Double-checked compile after hot threshold.
430    if runtime.get_trace(&key).is_some() {
431        return try_run_hot_runtime_tagged(runtime, chunk, key, call);
432    }
433
434    let compiled =
435        match with_jit_module(|module| TraceCompiler::new(module).compile_trace(chunk, key)) {
436            Ok(trace) => trace,
437            Err(_) => {
438                if let Some(m) = call.metrics {
439                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
440                }
441                return None;
442            }
443        };
444
445    runtime.insert_trace(key, compiled);
446    if let Some(m) = call.metrics {
447        crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
448    }
449
450    try_run_hot_runtime_tagged(runtime, chunk, key, call)
451}
452
453fn tag_bit(words: &[u64; 4], reg: usize) -> bool {
454    if reg >= 256 {
455        return false;
456    }
457    words[reg / 64] & (1u64 << (reg % 64)) != 0
458}
459
460/// Write back only registers the trace assigned. Untouched `Unit` / `Bool`
461/// values stay as they were. A `Move` of either tag is written back as that
462/// tag. Comparison results come back as `Bool`.
463fn sync_slots_tagged(vm: &mut Vm, slots: &[i64], ret: &JitReturn) -> Result<(), Fault> {
464    let Some(regs) = vm.top_registers_mut() else {
465        return Err(Fault::Invariant("empty frame stack while syncing slots"));
466    };
467    for (index, reg) in regs.iter_mut().enumerate() {
468        if !tag_bit(&ret.written, index) {
469            continue;
470        }
471        let Some(slot) = slots.get(index).copied() else {
472            continue;
473        };
474        *reg = if tag_bit(&ret.as_unit, index) {
475            Value::Unit
476        } else if tag_bit(&ret.as_bool, index) {
477            Value::Bool(slot != 0)
478        } else if tag_bit(&ret.as_float, index) {
479            Value::Float(f64::from_bits(slot as u64))
480        } else {
481            Value::Int(slot)
482        };
483    }
484    Ok(())
485}
486
487fn apply_exit_tagged(
488    vm: &mut Vm,
489    slots: &[i64],
490    ret: JitReturn,
491) -> Result<Option<VmResult>, Fault> {
492    match ret.kind {
493        super::exit::JIT_RETURN => {
494            sync_slots_tagged(vm, slots, &ret)?;
495            let return_reg = ret.return_reg as u8;
496            let value = match vm
497                .top_registers()
498                .and_then(|regs| regs.get(usize::from(return_reg)))
499            {
500                Some(v) => v.clone(),
501                None => {
502                    let frame_size = match vm.current_num_registers() {
503                        Some(n) => n,
504                        None => 0,
505                    };
506                    return Err(Fault::RegisterOutOfRange {
507                        reg: return_reg,
508                        frame_size,
509                    });
510                }
511            };
512            let pc = vm
513                .current_pc()
514                .ok_or(Fault::Invariant("empty frame stack while running"))?;
515            vm.set_pc(pc.saturating_add(1));
516            vm.return_value(value)
517        }
518        super::exit::JIT_TRAP => {
519            vm.set_pc(ret.pc as usize);
520            Ok(Some(VmResult::Trap(Fault::DivideByZero)))
521        }
522        super::exit::JIT_BUDGET => {
523            vm.set_pc(ret.pc as usize);
524            sync_slots_tagged(vm, slots, &ret)?;
525            Ok(None)
526        }
527        super::exit::JIT_CONTINUE | super::exit::JIT_EFFECT => {
528            vm.set_pc(ret.pc as usize);
529            sync_slots_tagged(vm, slots, &ret)?;
530            Ok(None)
531        }
532        _ => {
533            vm.set_pc(ret.pc as usize);
534            Ok(None)
535        }
536    }
537}
538
539/// Apply a native trace exit to a live [`Vm`], producing an optional early
540/// [`VmResult`] when the trace finished the flow.
541pub fn apply_exit_to_vm(
542    vm: &mut Vm,
543    slots: &[i64],
544    exit: ExitReason,
545) -> Result<Option<VmResult>, Fault> {
546    match exit {
547        ExitReason::Return { return_reg } => {
548            let Some(bits) = slots.get(usize::from(return_reg)).copied() else {
549                return Err(Fault::RegisterOutOfRange {
550                    reg: return_reg,
551                    frame_size: u8::try_from(slots.len()).unwrap_or(u8::MAX),
552                });
553            };
554            let value = Value::Int(bits);
555            vm.set_register(return_reg, value.clone())?;
556            let pc = vm
557                .current_pc()
558                .ok_or(Fault::Invariant("empty frame stack while running"))?;
559            vm.set_pc(pc.saturating_add(1));
560            vm.return_value(value)
561        }
562        ExitReason::Trap { pc } => {
563            vm.set_pc(pc as usize);
564            Ok(Some(VmResult::Trap(Fault::DivideByZero)))
565        }
566        ExitReason::Budget { pc } => {
567            vm.set_pc(pc as usize);
568            sync_slots_to_vm(vm, slots)?;
569            Ok(None)
570        }
571        ExitReason::Continue { pc } | ExitReason::Effect { pc } | ExitReason::Deopt { pc } => {
572            vm.set_pc(pc as usize);
573            if matches!(
574                exit,
575                ExitReason::Continue { .. } | ExitReason::Effect { .. }
576            ) {
577                sync_slots_to_vm(vm, slots)?;
578            }
579            Ok(None)
580        }
581    }
582}
583
584/// Copy int-compatible registers from the VM into JIT shadow slots.
585pub fn sync_slots_from_vm(vm: &Vm, slots: &mut [i64]) -> SyncSlotsResult {
586    let Some(regs) = vm.top_registers() else {
587        return SyncSlotsResult::Unavailable;
588    };
589    let mut saw_float = false;
590    let mut saw_int = false;
591    for value in regs.iter().take(slots.len()) {
592        match value {
593            Value::Int(_) => saw_int = true,
594            Value::Float(_) => saw_float = true,
595            Value::Bool(_) | Value::Unit => {}
596            _ => return SyncSlotsResult::Deopt,
597        }
598    }
599    if saw_int && saw_float {
600        return SyncSlotsResult::Deopt;
601    }
602    for (slot, value) in slots.iter_mut().zip(regs.iter()) {
603        *slot = match value {
604            Value::Int(i) => *i,
605            Value::Bool(b) => i64::from(*b),
606            Value::Unit => 0,
607            Value::Float(n) => n.to_bits() as i64,
608            _ => 0,
609        };
610    }
611    if saw_float {
612        SyncSlotsResult::Float
613    } else {
614        SyncSlotsResult::Ok
615    }
616}
617
618/// Write JIT shadow slots back into the active VM register file.
619pub fn sync_slots_to_vm(vm: &mut Vm, slots: &[i64]) -> Result<(), Fault> {
620    let Some(regs) = vm.top_registers_mut() else {
621        return Err(Fault::Invariant("empty frame stack while syncing slots"));
622    };
623    for (reg, slot) in regs.iter_mut().zip(slots.iter()) {
624        *reg = Value::Int(*slot);
625    }
626    Ok(())
627}
628
629/// Threshold at which a `(function, pc)` pair becomes a compilation candidate.
630pub const fn hot_threshold() -> u32 {
631    HOT_THRESHOLD
632}
633
634/// Force-compile a trace (tests / benchmarks).
635pub fn force_compile(
636    ctx: &mut JitContext,
637    chunk: &Chunk,
638    key: TraceKey,
639) -> Result<(), super::error::CompileError> {
640    if ctx.cache.get(&key).is_none() {
641        let mut compiler = TraceCompiler::new(ctx.module_mut());
642        let compiled = compiler.compile_trace(chunk, key)?;
643        ctx.cache.insert(key, compiled);
644    }
645    Ok(())
646}
647
648#[cfg(test)]
649mod tests {
650    use std::sync::Arc;
651
652    use crate::{
653        bytecode::builder::ChunkBuilder, FlowOutcome, NativeTable, Opcode, Runtime, Value, Vm,
654        VmResult,
655    };
656
657    use super::*;
658    use crate::jit::trace::{JitContext, TraceKey};
659
660    type TestResult = Result<(), Box<dyn std::error::Error>>;
661
662    fn add_chunk() -> std::sync::Arc<crate::Chunk> {
663        let mut b = ChunkBuilder::new("jit-add");
664        b.begin_function("main", 0, 3);
665        b.emit_load_imm(0, 41);
666        b.emit_load_imm(1, 1);
667        b.emit_binop(Opcode::Add, 2, 0, 1);
668        b.emit_return(2);
669        Arc::new(b.finish())
670    }
671
672    #[test]
673    fn run_vm_with_jit_completes_scalar_add() -> TestResult {
674        let chunk = add_chunk();
675        let mut ctx = JitContext::new(chunk.clone())?;
676        let key = TraceKey {
677            function: 0,
678            entry_pc: 0,
679
680            floats: false,
681        };
682        force_compile(&mut ctx, &chunk, key)?;
683
684        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
685        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
686        assert!(matches!(result, VmResult::Complete(Value::Int(42))));
687        Ok(())
688    }
689
690    #[test]
691    fn native_trace_computes_42() -> TestResult {
692        let chunk = add_chunk();
693        let mut ctx = JitContext::new(chunk.clone())?;
694        let key = TraceKey {
695            function: 0,
696            entry_pc: 0,
697
698            floats: false,
699        };
700        force_compile(&mut ctx, &chunk, key)?;
701        let trace = ctx
702            .cache
703            .get(&key)
704            .ok_or("trace missing after force_compile")?;
705        let mut slots = vec![0i64; 3];
706        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
707        let exit = ret.into_reason();
708        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
709        assert_eq!(slots[2], 42);
710        Ok(())
711    }
712
713    #[test]
714    fn mul_imm_eq_imm_and_shifts_match_the_interpreter() -> TestResult {
715        let mut b = ChunkBuilder::new("jit-bits");
716        b.begin_function("main", 0, 4);
717        b.emit_load_imm(0, 6);
718        b.emit_mul_imm(1, 0, 7);
719        b.emit_load_imm(2, 1);
720        b.emit_bit_binop(Opcode::Shl, 3, 1, 2);
721        b.emit_bit_binop(Opcode::Shr, 1, 3, 2);
722        b.emit_return(1);
723        let chunk = Arc::new(b.finish());
724        let mut interpreted = Vm::new(chunk.clone(), NativeTable::empty(), 0, &[])?;
725        assert!(matches!(
726            interpreted.run(20),
727            VmResult::Complete(Value::Int(42))
728        ));
729        let mut ctx = JitContext::new(chunk.clone())?;
730        let key = TraceKey {
731            function: 0,
732            entry_pc: 0,
733            floats: false,
734        };
735        force_compile(&mut ctx, &chunk, key)?;
736        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
737        let result = run_vm_with_jit(&mut vm, 20, &mut ctx);
738        assert!(matches!(result, VmResult::Complete(Value::Int(42))));
739
740        let mut b = ChunkBuilder::new("jit-eq-imm");
741        b.begin_function("main", 0, 2);
742        b.emit_load_imm(0, 42);
743        b.emit_eq_imm(1, 0, 42);
744        b.emit_le_imm(0, 0, 41);
745        b.emit_return(1);
746        let chunk = Arc::new(b.finish());
747        let mut interpreted = Vm::new(chunk.clone(), NativeTable::empty(), 0, &[])?;
748        assert!(matches!(
749            interpreted.run(20),
750            VmResult::Complete(Value::Bool(true))
751        ));
752        let mut ctx = JitContext::new(chunk.clone())?;
753        force_compile(&mut ctx, &chunk, key)?;
754        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
755        let result = run_vm_with_jit(&mut vm, 20, &mut ctx);
756        assert!(matches!(result, VmResult::Complete(Value::Bool(true))));
757        Ok(())
758    }
759
760    #[test]
761    fn jit_matches_interpreter_on_scalar_add() -> TestResult {
762        let chunk = add_chunk();
763        let rt = Runtime::new((*chunk).clone())?;
764        let interp = rt.spawn(0, &[])?.join();
765        rt.shutdown();
766        assert!(matches!(interp, FlowOutcome::Completed(Value::Int(42))));
767
768        let mut ctx = JitContext::new(chunk.clone())?;
769        let key = TraceKey {
770            function: 0,
771            entry_pc: 0,
772
773            floats: false,
774        };
775        let mut slots = vec![0i64; 3];
776        force_compile(&mut ctx, &chunk, key)?;
777        let trace = ctx
778            .cache
779            .get(&key)
780            .ok_or("trace missing after force_compile")?;
781        let exit = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3).into_reason();
782        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
783        assert_eq!(slots[2], 42);
784
785        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
786        if let Some(result) = apply_exit_to_vm(&mut vm, &slots, exit)? {
787            assert!(matches!(result, VmResult::Complete(Value::Int(42))));
788        } else {
789            return Err("expected Completed(42)".into());
790        }
791        Ok(())
792    }
793
794    #[test]
795    fn div_by_zero_returns_trap_exit() -> TestResult {
796        let mut b = ChunkBuilder::new("jit-div0");
797        b.begin_function("main", 0, 3);
798        b.emit_load_imm(0, 1);
799        b.emit_load_imm(1, 0);
800        b.emit_binop(Opcode::Div, 2, 0, 1);
801        b.emit_return(2);
802        let chunk = Arc::new(b.finish());
803
804        let mut ctx = JitContext::new(chunk.clone())?;
805        let key = TraceKey {
806            function: 0,
807            entry_pc: 0,
808
809            floats: false,
810        };
811        force_compile(&mut ctx, &chunk, key)?;
812        let trace = ctx
813            .cache
814            .get(&key)
815            .ok_or("trace missing after force_compile")?;
816        let mut slots = vec![0i64; 3];
817        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
818        assert!(matches!(ret.into_reason(), ExitReason::Trap { .. }));
819        Ok(())
820    }
821
822    #[test]
823    fn div_and_mod_of_i64_min_wrap_instead_of_aborting() -> TestResult {
824        let mut b = ChunkBuilder::new("jit-div-overflow");
825        b.begin_function("div", 0, 3);
826        let min = b.const_(Value::Int(i64::MIN));
827        let neg = b.const_(Value::Int(-1));
828        b.emit_load_const(0, min);
829        b.emit_load_const(1, neg);
830        b.emit_binop(Opcode::Div, 2, 0, 1);
831        b.emit_return(2);
832        let rem = b.begin_function("rem", 0, 3);
833        let min = b.const_(Value::Int(i64::MIN));
834        let neg = b.const_(Value::Int(-1));
835        b.emit_load_const(0, min);
836        b.emit_load_const(1, neg);
837        b.emit_binop(Opcode::Mod, 2, 0, 1);
838        b.emit_return(2);
839        let chunk = Arc::new(b.finish());
840        let mut ctx = JitContext::new(chunk.clone())?;
841
842        for (function, expect) in [(0, i64::MIN), (rem, 0)] {
843            let entry = chunk.functions[function as usize].entry;
844            force_compile(
845                &mut ctx,
846                &chunk,
847                TraceKey {
848                    function,
849                    entry_pc: entry,
850
851                    floats: false,
852                },
853            )?;
854            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, &[])?;
855            let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
856            match result {
857                VmResult::Complete(Value::Int(n)) if n == expect => {}
858                other => {
859                    return Err(format!("function {function} finished as {other:?}").into());
860                }
861            }
862        }
863        Ok(())
864    }
865
866    #[test]
867    fn sync_slots_accepts_a_float_register() -> TestResult {
868        let chunk = add_chunk();
869        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
870        vm.set_register(0, Value::Float(1.0))?;
871        let mut slots = vec![0i64; 3];
872        assert_eq!(sync_slots_from_vm(&vm, &mut slots), SyncSlotsResult::Float);
873        assert_eq!(f64::from_bits(slots[0] as u64), 1.0);
874        Ok(())
875    }
876
877    #[test]
878    fn float_trace_matches_the_interpreter() -> TestResult {
879        let mut b = ChunkBuilder::new("jit-float");
880        let zero = b.const_(Value::Float(0.0));
881        let one = b.const_(Value::Float(1.0));
882        let limit = b.const_(Value::Float(4.0));
883        b.begin_function("main", 0, 4);
884        b.emit_load_const(0, zero);
885        b.emit_load_const(1, one);
886        b.emit_load_const(2, limit);
887        let head = b.new_label();
888        let done = b.new_label();
889        b.bind_label(head);
890        b.emit_binop(Opcode::Add, 0, 0, 1);
891        b.emit_binop(Opcode::Lt, 3, 0, 2);
892        b.emit_branch(3, done);
893        b.emit_jump(head);
894        b.bind_label(done);
895        b.emit_return(0);
896        let chunk = Arc::new(b.finish());
897        let mut plain = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
898        let interpreted = plain.run(100);
899        let mut ctx = JitContext::new(Arc::clone(&chunk))?;
900        ctx.hot_threshold = 1;
901        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
902        let compiled = run_vm_with_jit(&mut vm, 100, &mut ctx);
903        if !ctx.cache.has_float_trace() {
904            return Err("float add loop was not compiled".into());
905        }
906        match (interpreted, compiled) {
907            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
908                if a == b && a == 4.0 =>
909            {
910                Ok(())
911            }
912            (left, right) => Err(format!("float trace {right:?} interpreter {left:?}").into()),
913        }
914    }
915
916    fn run_float_chunk(
917        chunk: Arc<Chunk>,
918        budget: u32,
919    ) -> Result<(VmResult, VmResult, JitContext), Box<dyn std::error::Error>> {
920        let mut plain = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
921        let interpreted = plain.run(budget);
922        let mut ctx = JitContext::new(Arc::clone(&chunk))?;
923        ctx.hot_threshold = 1;
924        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
925        let compiled = run_vm_with_jit(&mut vm, budget, &mut ctx);
926        Ok((interpreted, compiled, ctx))
927    }
928
929    #[test]
930    fn float_trace_edges_match_the_interpreter() -> TestResult {
931        let mut nan_lt = ChunkBuilder::new("jit-nan-lt");
932        let nan = nan_lt.const_(Value::Float(f64::NAN));
933        let zero = nan_lt.const_(Value::Float(0.0));
934        nan_lt.begin_function("main", 0, 3);
935        nan_lt.emit_load_const(0, nan);
936        nan_lt.emit_load_const(1, zero);
937        let head = nan_lt.new_label();
938        nan_lt.bind_label(head);
939        nan_lt.emit_binop(Opcode::Lt, 2, 0, 1);
940        nan_lt.emit_return(2);
941        let nan_chunk = Arc::new(nan_lt.finish());
942        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&nan_chunk), 20)?;
943        if !ctx.cache.has_float_trace() {
944            return Err("NaN comparison was not compiled".into());
945        }
946        match (interpreted, compiled) {
947            (VmResult::Complete(Value::Bool(false)), VmResult::Complete(Value::Bool(false))) => {}
948            (left, right) => {
949                return Err(format!("nan lt {right:?} interpreter {left:?}").into());
950            }
951        }
952
953        let mut inf_add = ChunkBuilder::new("jit-inf-add");
954        let pos = inf_add.const_(Value::Float(f64::INFINITY));
955        let neg = inf_add.const_(Value::Float(f64::NEG_INFINITY));
956        inf_add.begin_function("main", 0, 3);
957        inf_add.emit_load_const(0, pos);
958        inf_add.emit_load_const(1, neg);
959        let head = inf_add.new_label();
960        inf_add.bind_label(head);
961        inf_add.emit_binop(Opcode::Add, 2, 0, 1);
962        inf_add.emit_return(2);
963        let inf_chunk = Arc::new(inf_add.finish());
964        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&inf_chunk), 20)?;
965        if !ctx.cache.has_float_trace() {
966            return Err("infinity add was not compiled".into());
967        }
968        match (interpreted, compiled) {
969            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
970                if a.is_nan() && b.is_nan() => {}
971            (left, right) => {
972                return Err(format!("inf add {right:?} interpreter {left:?}").into());
973            }
974        }
975
976        let mut zeros = ChunkBuilder::new("jit-signed-zero");
977        let neg_zero = zeros.const_(Value::Float(-0.0));
978        zeros.begin_function("main", 0, 1);
979        zeros.emit_load_const(0, neg_zero);
980        let head = zeros.new_label();
981        zeros.bind_label(head);
982        zeros.emit_add_imm(0, 0, 0);
983        zeros.emit_return(0);
984        let zero_chunk = Arc::new(zeros.finish());
985        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&zero_chunk), 20)?;
986        if !ctx.cache.has_float_trace() {
987            return Err("signed-zero add was not compiled".into());
988        }
989        match (interpreted, compiled) {
990            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
991                if a.to_bits() == 0.0f64.to_bits() && b.to_bits() == 0.0f64.to_bits() => {}
992            (left, right) => {
993                return Err(format!("signed zero {right:?} interpreter {left:?}").into());
994            }
995        }
996
997        let mut countdown = ChunkBuilder::new("jit-sub-imm");
998        let start = countdown.const_(Value::Float(4.0));
999        countdown.begin_function("main", 0, 2);
1000        countdown.emit_load_const(0, start);
1001        let head = countdown.new_label();
1002        let body = countdown.new_label();
1003        let done = countdown.new_label();
1004        countdown.bind_label(head);
1005        countdown.emit_lt_imm(1, 0, 1);
1006        countdown.emit_branch(1, body);
1007        countdown.emit_jump(done);
1008        countdown.bind_label(body);
1009        countdown.emit_sub_imm(0, 0, 1);
1010        countdown.emit_jump(head);
1011        countdown.bind_label(done);
1012        countdown.emit_return(0);
1013        let sub_chunk = Arc::new(countdown.finish());
1014        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&sub_chunk), 40)?;
1015        if !ctx.cache.has_float_trace() {
1016            return Err("float SubImm loop was not compiled".into());
1017        }
1018        match (interpreted, compiled) {
1019            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1020                if a == 0.0 && b == 0.0 =>
1021            {
1022                Ok(())
1023            }
1024            (left, right) => Err(format!("sub imm {right:?} interpreter {left:?}").into()),
1025        }
1026    }
1027
1028    #[test]
1029    fn runtime_path_compiles_and_runs() -> TestResult {
1030        let chunk = add_chunk();
1031        let runtime = JitRuntime::new(chunk.clone(), 1);
1032        let key = TraceKey {
1033            function: 0,
1034            entry_pc: 0,
1035
1036            floats: false,
1037        };
1038        let mut slots = vec![0i64; 3];
1039        let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
1040            .ok_or("expected jit execution")?;
1041        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
1042        assert_eq!(slots[2], 42);
1043        Ok(())
1044    }
1045
1046    #[test]
1047    fn budget_exit_when_exhausted_mid_trace() -> TestResult {
1048        let mut b = ChunkBuilder::new("jit-budget");
1049        b.begin_function("main", 0, 1);
1050        b.emit_load_imm(0, 1);
1051        b.emit_load_imm(0, 2);
1052        b.emit_load_imm(0, 3);
1053        b.emit_return(0);
1054        let chunk = Arc::new(b.finish());
1055
1056        let mut ctx = JitContext::new(chunk.clone())?;
1057        let key = TraceKey {
1058            function: 0,
1059            entry_pc: 0,
1060
1061            floats: false,
1062        };
1063        force_compile(&mut ctx, &chunk, key)?;
1064        let trace = ctx
1065            .cache
1066            .get(&key)
1067            .ok_or("trace missing after force_compile")?;
1068        let mut slots = vec![0i64; 1];
1069        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 2, 0, 1);
1070        assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 2 }));
1071        Ok(())
1072    }
1073
1074    #[test]
1075    fn interleaved_jit_compiles_mid_quantum() -> TestResult {
1076        let mut b = ChunkBuilder::new("jit-interleave");
1077        b.begin_function("main", 0, 2);
1078        b.emit_load_imm(0, 0);
1079        let head = b.new_label();
1080        b.bind_label(head);
1081        b.emit_load_imm(1, 1);
1082        b.emit_binop(Opcode::Add, 0, 0, 1);
1083        b.emit_load_imm(1, 100);
1084        b.emit_binop(Opcode::Lt, 1, 0, 1);
1085        let done = b.new_label();
1086        b.emit_branch(1, done);
1087        b.emit_jump(head);
1088        b.bind_label(done);
1089        b.emit_return(0);
1090        let chunk = Arc::new(b.finish());
1091        let head_pc = chunk.functions[0].entry + 1;
1092
1093        let mut ctx = JitContext::new(chunk.clone())?;
1094        ctx.hot_threshold = 2;
1095        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1096        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1097        assert!(matches!(result, VmResult::Complete(Value::Int(100))));
1098        assert!(ctx
1099            .cache
1100            .get(&TraceKey {
1101                function: 0,
1102                entry_pc: head_pc,
1103
1104                floats: false,
1105            })
1106            .is_some());
1107        Ok(())
1108    }
1109
1110    #[test]
1111    fn reload_chunk_invalidates_jit_cache() -> TestResult {
1112        let chunk = add_chunk();
1113        let runtime = JitRuntime::new(chunk.clone(), 1);
1114        let key = TraceKey {
1115            function: 0,
1116            entry_pc: 0,
1117
1118            floats: false,
1119        };
1120        let mut slots = vec![0i64; 3];
1121        let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
1122            .ok_or("expected jit execution")?;
1123        assert!(matches!(exit, ExitReason::Return { .. }));
1124
1125        let mut b = ChunkBuilder::new("other");
1126        b.begin_function("main", 0, 1);
1127        b.emit_load_imm(0, 1);
1128        b.emit_return(0);
1129        runtime.reload(Arc::new(b.finish()));
1130        assert!(runtime.get_trace(&key).is_none());
1131        Ok(())
1132    }
1133
1134    /// Budget expiry used to resume past instructions whose results existed
1135    /// only in SSA, and writeback turned every untouched `Unit` into `Int(0)`.
1136    #[test]
1137    fn budget_exit_publishes_assigned_regs_and_keeps_unit() -> TestResult {
1138        let mut b = ChunkBuilder::new("jit-budget");
1139        b.begin_function("main", 0, 2);
1140        b.emit_load_imm(0, 41);
1141        b.emit_load_imm(1, 1);
1142        b.emit_return(0);
1143        let chunk = Arc::new(b.finish());
1144        let mut ctx = JitContext::new(chunk.clone())?;
1145        let key = TraceKey {
1146            function: 0,
1147            entry_pc: 0,
1148
1149            floats: false,
1150        };
1151        force_compile(&mut ctx, &chunk, key)?;
1152        let trace = ctx
1153            .cache
1154            .get(&key)
1155            .ok_or("trace missing after force_compile")?;
1156        let mut slots = vec![0i64; 2];
1157        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 1, 0, 2);
1158        assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 1 }));
1159        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1160        apply_exit_tagged(&mut vm, &slots, ret)?;
1161        let regs = vm.top_registers().ok_or("no frame")?;
1162        assert!(matches!(regs.first(), Some(&Value::Int(41))));
1163        assert!(matches!(regs.get(1), Some(&Value::Unit)));
1164        Ok(())
1165    }
1166
1167    #[test]
1168    fn jit_call_does_not_clobber_the_caller_frame() -> TestResult {
1169        let mut b = ChunkBuilder::new("jit-call-frames");
1170        b.begin_function("callee", 0, 3);
1171        b.emit_load_imm(2, 99);
1172        b.emit_load_imm(0, 1);
1173        b.emit_return(0);
1174        let main = b.begin_function("main", 0, 3);
1175        b.emit_load_imm(2, 7);
1176        b.emit_call(0, 0, 0);
1177        b.emit_return(2);
1178        let chunk = Arc::new(b.finish());
1179        let mut ctx = JitContext::new(chunk.clone())?;
1180        let entry = chunk.functions[main as usize].entry;
1181        force_compile(
1182            &mut ctx,
1183            &chunk,
1184            TraceKey {
1185                function: main,
1186                entry_pc: entry,
1187
1188                floats: false,
1189            },
1190        )?;
1191        let mut vm = Vm::new(chunk, NativeTable::empty(), main, &[])?;
1192        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1193        assert!(matches!(result, VmResult::Complete(Value::Int(7))));
1194        Ok(())
1195    }
1196
1197    #[test]
1198    fn move_keeps_bool_unit_and_a_later_int() -> TestResult {
1199        let mut b = ChunkBuilder::new("jit-move-tags");
1200        b.begin_function("cmp", 0, 4);
1201        b.emit_load_imm(0, 1);
1202        b.emit_load_imm(1, 1);
1203        b.emit_binop(Opcode::Eq, 2, 0, 1);
1204        b.emit_move(3, 2);
1205        b.emit_return(3);
1206        let moved_bool = b.begin_function("moved-bool", 1, 2);
1207        b.emit_move(1, 0);
1208        b.emit_return(1);
1209        let moved_false = b.begin_function("moved-false", 1, 2);
1210        b.emit_move(1, 0);
1211        b.emit_return(1);
1212        let moved_unit = b.begin_function("moved-unit", 0, 2);
1213        b.emit_move(1, 0);
1214        b.emit_return(1);
1215        let overwritten = b.begin_function("overwritten", 1, 2);
1216        b.emit_load_imm(0, 5);
1217        let cont = b.new_label();
1218        b.emit_jump(cont);
1219        b.bind_label(cont);
1220        b.emit_move(1, 0);
1221        b.emit_return(1);
1222        let chunk = Arc::new(b.finish());
1223        let mut ctx = JitContext::new(chunk.clone())?;
1224
1225        let run = |ctx: &mut JitContext, function: u32, args: &[Value]| -> TestResult {
1226            let entry = chunk.functions[function as usize].entry;
1227            force_compile(
1228                ctx,
1229                &chunk,
1230                TraceKey {
1231                    function,
1232                    entry_pc: entry,
1233
1234                    floats: false,
1235                },
1236            )?;
1237            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
1238            let result = run_vm_with_jit(&mut vm, 10_000, ctx);
1239            match (function, result) {
1240                (_, VmResult::Complete(Value::Bool(true))) if function == 0 => Ok(()),
1241                (_, VmResult::Complete(Value::Bool(true))) if function == moved_bool => Ok(()),
1242                (_, VmResult::Complete(Value::Bool(false))) if function == moved_false => Ok(()),
1243                (_, VmResult::Complete(Value::Unit)) if function == moved_unit => Ok(()),
1244                (_, VmResult::Complete(Value::Int(5))) if function == overwritten => Ok(()),
1245                (_, other) => Err(format!("function {function} finished as {other:?}").into()),
1246            }
1247        };
1248
1249        run(&mut ctx, 0, &[])?;
1250        run(&mut ctx, moved_bool, &[Value::Bool(true)])?;
1251        run(&mut ctx, moved_false, &[Value::Bool(false)])?;
1252        run(&mut ctx, moved_unit, &[])?;
1253        run(&mut ctx, overwritten, &[Value::Bool(true)])?;
1254        Ok(())
1255    }
1256
1257    #[test]
1258    fn leaf_call_stays_in_the_trace() -> TestResult {
1259        let mut b = ChunkBuilder::new("jit-call");
1260        let add1 = b.begin_function("add1", 1, 2);
1261        b.emit_load_imm(1, 1);
1262        b.emit_binop(Opcode::Add, 0, 0, 1);
1263        b.emit_return(0);
1264        let main = b.begin_function("main", 0, 1);
1265        b.emit_load_imm(0, 41);
1266        b.emit_call(0, add1, 1);
1267        b.emit_return(0);
1268        let chunk = Arc::new(b.finish());
1269        let mut ctx = JitContext::new(chunk.clone())?;
1270        let entry = chunk.functions[main as usize].entry;
1271        let key = TraceKey {
1272            function: main,
1273            entry_pc: entry,
1274
1275            floats: false,
1276        };
1277        force_compile(&mut ctx, &chunk, key)?;
1278        let trace = ctx
1279            .cache
1280            .get(&key)
1281            .ok_or("trace missing after force_compile")?;
1282        let mut slots = vec![0i64; 2];
1283        let exit = run_compiled_trace_ref(trace, &mut slots, entry, 10_000, main, 1).into_reason();
1284        match exit {
1285            ExitReason::Return { return_reg: 0 } => {}
1286            other => return Err(format!("call left the trace: {other:?}").into()),
1287        }
1288        if slots[0] != 42 {
1289            return Err(format!("leaf call produced {}", slots[0]).into());
1290        }
1291        Ok(())
1292    }
1293
1294    #[test]
1295    fn leaf_call_keeps_bool_unit_and_a_high_dest() -> TestResult {
1296        let mut b = ChunkBuilder::new("jit-call-tags");
1297        let is_true = b.begin_function("is-true", 0, 2);
1298        b.emit_load_imm(0, 1);
1299        b.emit_load_imm(1, 1);
1300        b.emit_binop(Opcode::Eq, 0, 0, 1);
1301        b.emit_return(0);
1302        let blank = b.begin_function("blank", 0, 1);
1303        b.emit_return(0);
1304        let moved = b.begin_function("moved", 1, 2);
1305        b.emit_move(1, 0);
1306        b.emit_return(1);
1307        let add1 = b.begin_function("add1", 1, 2);
1308        b.emit_load_imm(1, 1);
1309        b.emit_binop(Opcode::Add, 0, 0, 1);
1310        b.emit_return(0);
1311
1312        let main_bool = b.begin_function("main-bool", 0, 1);
1313        b.emit_call(0, is_true, 0);
1314        b.emit_return(0);
1315        let main_unit = b.begin_function("main-unit", 0, 1);
1316        b.emit_load_imm(0, 9);
1317        b.emit_call(0, blank, 0);
1318        b.emit_return(0);
1319        let main_moved = b.begin_function("main-moved", 1, 1);
1320        b.emit_call(0, moved, 1);
1321        b.emit_return(0);
1322        let main_high = b.begin_function("main-high", 0, 17);
1323        b.emit_load_imm(16, 41);
1324        b.emit_call(16, add1, 1);
1325        b.emit_return(16);
1326        let chunk = Arc::new(b.finish());
1327        let mut ctx = JitContext::new(chunk.clone())?;
1328
1329        let run = |ctx: &mut JitContext,
1330                   function: u32,
1331                   args: &[Value]|
1332         -> Result<VmResult, Box<dyn std::error::Error>> {
1333            let entry = chunk.functions[function as usize].entry;
1334            force_compile(
1335                ctx,
1336                &chunk,
1337                TraceKey {
1338                    function,
1339                    entry_pc: entry,
1340
1341                    floats: false,
1342                },
1343            )?;
1344            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
1345            Ok(run_vm_with_jit(&mut vm, 10_000, ctx))
1346        };
1347
1348        match run(&mut ctx, main_bool, &[])? {
1349            VmResult::Complete(Value::Bool(true)) => {}
1350            other => return Err(format!("bool leaf finished as {other:?}").into()),
1351        }
1352        match run(&mut ctx, main_unit, &[])? {
1353            VmResult::Complete(Value::Unit) => {}
1354            other => return Err(format!("unread leaf finished as {other:?}").into()),
1355        }
1356        match run(&mut ctx, main_moved, &[Value::Bool(false)])? {
1357            VmResult::Complete(Value::Bool(false)) => {}
1358            other => return Err(format!("bool arg finished as {other:?}").into()),
1359        }
1360        match run(&mut ctx, main_high, &[])? {
1361            VmResult::Complete(Value::Int(42)) => {}
1362            other => return Err(format!("r16 dest finished as {other:?}").into()),
1363        }
1364        Ok(())
1365    }
1366}