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    /// A register held a non-int type — interpreter must resume.
20    Deopt,
21    /// Frame unavailable.
22    Unavailable,
23}
24
25/// Tags of the active frame at the moment a trace is entered.
26///
27/// The public slot runners pass [`EntryTags::INT`]: every inherited `Move`
28/// writes an `Int`. The VM runners fill the real `Bool` and `Unit` bits.
29#[derive(Clone, Copy)]
30struct EntryTags {
31    as_bool: [u64; 4],
32    as_unit: [u64; 4],
33}
34
35impl EntryTags {
36    const INT: Self = Self {
37        as_bool: [0; 4],
38        as_unit: [0; 4],
39    };
40
41    fn from_vm(vm: &Vm) -> Self {
42        let mut tags = Self::INT;
43        let Some(regs) = vm.top_registers() else {
44            return tags;
45        };
46        for (index, value) in regs.iter().enumerate() {
47            if index >= 256 {
48                break;
49            }
50            let bit = 1u64 << (index % 64);
51            let word = index / 64;
52            match value {
53                Value::Bool(_) => tags.as_bool[word] |= bit,
54                Value::Unit => tags.as_unit[word] |= bit,
55                _ => {}
56            }
57        }
58        tags
59    }
60}
61
62/// Attempt one native trace at the current `(function, pc)`.
63fn try_jit_step(vm: &mut Vm, ctx: &mut JitContext, budget: u32) -> Option<VmResult> {
64    if !Arc::ptr_eq(&ctx.chunk, &vm.chunk_arc()) {
65        return None;
66    }
67    let pc = vm.current_pc()?;
68    let function = vm.current_function();
69    let register_count = vm.current_num_registers()?;
70
71    let mut slots = vec![0i64; slot_capacity(vm)];
72    match sync_slots_from_vm(vm, &mut slots) {
73        SyncSlotsResult::Ok => {}
74        SyncSlotsResult::Deopt | SyncSlotsResult::Unavailable => return None,
75    }
76
77    let key = TraceKey {
78        function,
79        entry_pc: pc as u32,
80    };
81    let exit = try_run_hot_tagged(
82        ctx,
83        vm.chunk_arc().as_ref(),
84        key,
85        &mut HotCall {
86            slots: &mut slots,
87            budget,
88            register_count,
89            metrics: None,
90            tags: EntryTags::from_vm(vm),
91        },
92    )?;
93    match apply_exit_tagged(vm, &slots, exit) {
94        Ok(Some(result)) => Some(result),
95        Ok(None) => None,
96        Err(fault) => Some(VmResult::Trap(fault)),
97    }
98}
99
100fn try_jit_step_runtime(
101    vm: &mut Vm,
102    runtime: &JitRuntime,
103    budget: u32,
104    metrics: Option<&crate::scheduler::RuntimeMetrics>,
105) -> Option<VmResult> {
106    if !runtime.matches_chunk(&vm.chunk_arc()) {
107        return None;
108    }
109    let pc = vm.current_pc()?;
110    let function = vm.current_function();
111    let register_count = vm.current_num_registers()?;
112
113    let mut slots = vec![0i64; slot_capacity(vm)];
114    match sync_slots_from_vm(vm, &mut slots) {
115        SyncSlotsResult::Ok => {}
116        SyncSlotsResult::Deopt => {
117            if let Some(m) = metrics {
118                crate::scheduler::RuntimeMetrics::inc(&m.jit_deopts);
119            }
120            return None;
121        }
122        SyncSlotsResult::Unavailable => return None,
123    }
124
125    let key = TraceKey {
126        function,
127        entry_pc: pc as u32,
128    };
129    let exit = try_run_hot_runtime_tagged(
130        runtime,
131        vm.chunk_arc().as_ref(),
132        key,
133        &mut HotCall {
134            slots: &mut slots,
135            budget,
136            register_count,
137            metrics,
138            tags: EntryTags::from_vm(vm),
139        },
140    )?;
141    match apply_exit_tagged(vm, &slots, exit) {
142        Ok(Some(result)) => Some(result),
143        Ok(None) => None,
144        Err(fault) => Some(VmResult::Trap(fault)),
145    }
146}
147
148/// Run at most `budget` instructions, retrying compiled traces after each
149/// interpreter step when a site becomes hot.
150pub fn run_vm_with_jit(vm: &mut Vm, budget: u32, ctx: &mut JitContext) -> VmResult {
151    run_vm_with_jit_loop(vm, budget, |vm, remaining| try_jit_step(vm, ctx, remaining))
152}
153
154/// Runtime path: shared cache, per-thread compilation module.
155pub fn run_vm_with_jit_runtime(
156    vm: &mut Vm,
157    budget: u32,
158    runtime: &JitRuntime,
159    metrics: Option<&crate::scheduler::RuntimeMetrics>,
160) -> VmResult {
161    run_vm_with_jit_loop(vm, budget, |vm, remaining| {
162        try_jit_step_runtime(vm, runtime, remaining, metrics)
163    })
164}
165
166fn run_vm_with_jit_loop(
167    vm: &mut Vm,
168    budget: u32,
169    mut try_step: impl FnMut(&mut Vm, u32) -> Option<VmResult>,
170) -> VmResult {
171    let mut remaining = budget;
172    while remaining > 0 {
173        if let Some(result) = try_step(vm, remaining) {
174            return result;
175        }
176        match vm.run(1) {
177            VmResult::Yield => {
178                remaining -= 1;
179            }
180            other => return other,
181        }
182    }
183    VmResult::Yield
184}
185
186fn slot_capacity(vm: &Vm) -> usize {
187    let chunk = vm.chunk_arc();
188    let max_in_chunk = chunk
189        .functions
190        .iter()
191        .map(|f| f.num_registers as usize)
192        .max();
193    match (max_in_chunk, vm.current_num_registers()) {
194        (Some(max_regs), Some(current)) => max_regs.max(current as usize),
195        (Some(max_regs), None) => max_regs,
196        (None, Some(current)) => current as usize,
197        (None, None) => 0,
198    }
199}
200
201/// Run a compiled trace against the shadow slot table.
202///
203/// Inherited `Move`s are written back as `Int`. The VM entry path records
204/// the real `Bool` and `Unit` bits before calling the trace.
205pub fn run_compiled_trace(
206    entry: super::frame::JitEntry,
207    slots: &mut [i64],
208    pc: u32,
209    budget: u32,
210    function: u32,
211    register_count: u32,
212) -> JitReturn {
213    run_compiled_trace_with_tags(
214        entry,
215        slots,
216        pc,
217        budget,
218        function,
219        register_count,
220        EntryTags::INT,
221    )
222}
223
224fn run_compiled_trace_with_tags(
225    entry: super::frame::JitEntry,
226    slots: &mut [i64],
227    pc: u32,
228    budget: u32,
229    function: u32,
230    register_count: u32,
231    tags: EntryTags,
232) -> JitReturn {
233    let mut call_stack = [JitCallRecord {
234        return_pc: 0,
235        return_function: 0,
236        dest_reg: 0,
237        caller_register_count: 0,
238    }; MAX_JIT_CALL_DEPTH];
239    let mut frame = JitFrame {
240        slots: slots.as_mut_ptr(),
241        register_count,
242        pc,
243        budget,
244        function,
245        exit_kind: 0,
246        return_reg: 0,
247        call_depth: 0,
248        call_stack: call_stack.as_mut_ptr(),
249        written: [0; 4],
250        as_bool: [0; 4],
251        as_unit: [0; 4],
252        entry_as_bool: tags.as_bool,
253        entry_as_unit: tags.as_unit,
254    };
255    unsafe { (entry)(&mut frame) };
256    JitReturn {
257        kind: frame.exit_kind,
258        pc: frame.pc,
259        return_reg: frame.return_reg,
260        written: frame.written,
261        as_bool: frame.as_bool,
262        as_unit: frame.as_unit,
263    }
264}
265
266/// Run a cached trace by reference.
267pub fn run_compiled_trace_ref(
268    trace: &CompiledTrace,
269    slots: &mut [i64],
270    pc: u32,
271    budget: u32,
272    function: u32,
273    register_count: u32,
274) -> JitReturn {
275    run_compiled_trace(trace.entry, slots, pc, budget, function, register_count)
276}
277
278struct HotCall<'a> {
279    slots: &'a mut [i64],
280    budget: u32,
281    register_count: u8,
282    metrics: Option<&'a crate::scheduler::RuntimeMetrics>,
283    tags: EntryTags,
284}
285
286/// Compile `key` if needed and execute once. Returns `None` when compilation
287/// fails (caller should fall back to the interpreter).
288pub fn try_run_hot(
289    ctx: &mut JitContext,
290    chunk: &Chunk,
291    key: TraceKey,
292    slots: &mut [i64],
293    budget: u32,
294    register_count: u8,
295    metrics: Option<&crate::scheduler::RuntimeMetrics>,
296) -> Option<ExitReason> {
297    try_run_hot_tagged(
298        ctx,
299        chunk,
300        key,
301        &mut HotCall {
302            slots,
303            budget,
304            register_count,
305            metrics,
306            tags: EntryTags::INT,
307        },
308    )
309    .map(JitReturn::into_reason)
310}
311
312fn try_run_hot_tagged(
313    ctx: &mut JitContext,
314    chunk: &Chunk,
315    key: TraceKey,
316    call: &mut HotCall<'_>,
317) -> Option<JitReturn> {
318    if ctx.cache.get(&key).is_none() {
319        if !ctx.hot.hit(key, ctx.hot_threshold) {
320            if let Some(m) = call.metrics {
321                crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
322            }
323            return None;
324        }
325        let mut compiler = TraceCompiler::new(ctx.module_mut());
326        match compiler.compile_trace(chunk, key) {
327            Ok(compiled) => {
328                ctx.cache.insert(key, compiled);
329                if let Some(m) = call.metrics {
330                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
331                }
332            }
333            Err(_) => {
334                if let Some(m) = call.metrics {
335                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
336                }
337                return None;
338            }
339        }
340    }
341    let trace = ctx.cache.get(&key)?;
342    if let Some(m) = call.metrics {
343        crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
344    }
345    Some(run_compiled_trace_with_tags(
346        trace.entry,
347        call.slots,
348        key.entry_pc,
349        call.budget,
350        key.function,
351        u32::from(call.register_count),
352        call.tags,
353    ))
354}
355
356/// Shared-runtime variant (no global lock during execution).
357pub fn try_run_hot_runtime(
358    runtime: &JitRuntime,
359    chunk: &Chunk,
360    key: TraceKey,
361    slots: &mut [i64],
362    budget: u32,
363    register_count: u8,
364    metrics: Option<&crate::scheduler::RuntimeMetrics>,
365) -> Option<ExitReason> {
366    try_run_hot_runtime_tagged(
367        runtime,
368        chunk,
369        key,
370        &mut HotCall {
371            slots,
372            budget,
373            register_count,
374            metrics,
375            tags: EntryTags::INT,
376        },
377    )
378    .map(JitReturn::into_reason)
379}
380
381fn try_run_hot_runtime_tagged(
382    runtime: &JitRuntime,
383    chunk: &Chunk,
384    key: TraceKey,
385    call: &mut HotCall<'_>,
386) -> Option<JitReturn> {
387    if let Some(copy) = runtime.get_trace(&key) {
388        if let Some(m) = call.metrics {
389            crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
390        }
391        return Some(run_compiled_trace_with_tags(
392            copy.entry,
393            call.slots,
394            key.entry_pc,
395            call.budget,
396            key.function,
397            u32::from(call.register_count),
398            call.tags,
399        ));
400    }
401
402    if !runtime.record_hot_hit(key) {
403        if let Some(m) = call.metrics {
404            crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
405        }
406        return None;
407    }
408
409    // Double-checked compile after hot threshold.
410    if runtime.get_trace(&key).is_some() {
411        return try_run_hot_runtime_tagged(runtime, chunk, key, call);
412    }
413
414    let compiled =
415        match with_jit_module(|module| TraceCompiler::new(module).compile_trace(chunk, key)) {
416            Ok(trace) => trace,
417            Err(_) => {
418                if let Some(m) = call.metrics {
419                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
420                }
421                return None;
422            }
423        };
424
425    runtime.insert_trace(key, compiled);
426    if let Some(m) = call.metrics {
427        crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
428    }
429
430    try_run_hot_runtime_tagged(runtime, chunk, key, call)
431}
432
433fn tag_bit(words: &[u64; 4], reg: usize) -> bool {
434    if reg >= 256 {
435        return false;
436    }
437    words[reg / 64] & (1u64 << (reg % 64)) != 0
438}
439
440/// Write back only registers the trace assigned. Untouched `Unit` / `Bool`
441/// values stay as they were. A `Move` of either tag is written back as that
442/// tag. Comparison results come back as `Bool`.
443fn sync_slots_tagged(vm: &mut Vm, slots: &[i64], ret: &JitReturn) -> Result<(), Fault> {
444    let Some(regs) = vm.top_registers_mut() else {
445        return Err(Fault::Invariant("empty frame stack while syncing slots"));
446    };
447    for (index, reg) in regs.iter_mut().enumerate() {
448        if !tag_bit(&ret.written, index) {
449            continue;
450        }
451        let Some(slot) = slots.get(index).copied() else {
452            continue;
453        };
454        *reg = if tag_bit(&ret.as_unit, index) {
455            Value::Unit
456        } else if tag_bit(&ret.as_bool, index) {
457            Value::Bool(slot != 0)
458        } else {
459            Value::Int(slot)
460        };
461    }
462    Ok(())
463}
464
465fn apply_exit_tagged(
466    vm: &mut Vm,
467    slots: &[i64],
468    ret: JitReturn,
469) -> Result<Option<VmResult>, Fault> {
470    match ret.kind {
471        super::exit::JIT_RETURN => {
472            sync_slots_tagged(vm, slots, &ret)?;
473            let return_reg = ret.return_reg as u8;
474            let value = match vm
475                .top_registers()
476                .and_then(|regs| regs.get(usize::from(return_reg)))
477            {
478                Some(v) => v.clone(),
479                None => {
480                    let frame_size = match vm.current_num_registers() {
481                        Some(n) => n,
482                        None => 0,
483                    };
484                    return Err(Fault::RegisterOutOfRange {
485                        reg: return_reg,
486                        frame_size,
487                    });
488                }
489            };
490            let pc = vm
491                .current_pc()
492                .ok_or(Fault::Invariant("empty frame stack while running"))?;
493            vm.set_pc(pc.saturating_add(1));
494            vm.return_value(value)
495        }
496        super::exit::JIT_TRAP => {
497            vm.set_pc(ret.pc as usize);
498            Ok(Some(VmResult::Trap(Fault::DivideByZero)))
499        }
500        super::exit::JIT_BUDGET => {
501            vm.set_pc(ret.pc as usize);
502            sync_slots_tagged(vm, slots, &ret)?;
503            Ok(None)
504        }
505        super::exit::JIT_CONTINUE | super::exit::JIT_EFFECT => {
506            vm.set_pc(ret.pc as usize);
507            sync_slots_tagged(vm, slots, &ret)?;
508            Ok(None)
509        }
510        _ => {
511            vm.set_pc(ret.pc as usize);
512            Ok(None)
513        }
514    }
515}
516
517/// Apply a native trace exit to a live [`Vm`], producing an optional early
518/// [`VmResult`] when the trace finished the flow.
519pub fn apply_exit_to_vm(
520    vm: &mut Vm,
521    slots: &[i64],
522    exit: ExitReason,
523) -> Result<Option<VmResult>, Fault> {
524    match exit {
525        ExitReason::Return { return_reg } => {
526            let Some(bits) = slots.get(usize::from(return_reg)).copied() else {
527                return Err(Fault::RegisterOutOfRange {
528                    reg: return_reg,
529                    frame_size: u8::try_from(slots.len()).unwrap_or(u8::MAX),
530                });
531            };
532            let value = Value::Int(bits);
533            vm.set_register(return_reg, value.clone())?;
534            let pc = vm
535                .current_pc()
536                .ok_or(Fault::Invariant("empty frame stack while running"))?;
537            vm.set_pc(pc.saturating_add(1));
538            vm.return_value(value)
539        }
540        ExitReason::Trap { pc } => {
541            vm.set_pc(pc as usize);
542            Ok(Some(VmResult::Trap(Fault::DivideByZero)))
543        }
544        ExitReason::Budget { pc } => {
545            vm.set_pc(pc as usize);
546            sync_slots_to_vm(vm, slots)?;
547            Ok(None)
548        }
549        ExitReason::Continue { pc } | ExitReason::Effect { pc } | ExitReason::Deopt { pc } => {
550            vm.set_pc(pc as usize);
551            if matches!(
552                exit,
553                ExitReason::Continue { .. } | ExitReason::Effect { .. }
554            ) {
555                sync_slots_to_vm(vm, slots)?;
556            }
557            Ok(None)
558        }
559    }
560}
561
562/// Copy int-compatible registers from the VM into JIT shadow slots.
563pub fn sync_slots_from_vm(vm: &Vm, slots: &mut [i64]) -> SyncSlotsResult {
564    let Some(regs) = vm.top_registers() else {
565        return SyncSlotsResult::Unavailable;
566    };
567    for (slot, value) in slots.iter_mut().zip(regs.iter()) {
568        match value {
569            Value::Int(i) => *slot = *i,
570            Value::Bool(b) => *slot = i64::from(*b),
571            Value::Unit => *slot = 0,
572            _ => return SyncSlotsResult::Deopt,
573        }
574    }
575    SyncSlotsResult::Ok
576}
577
578/// Write JIT shadow slots back into the active VM register file.
579pub fn sync_slots_to_vm(vm: &mut Vm, slots: &[i64]) -> Result<(), Fault> {
580    let Some(regs) = vm.top_registers_mut() else {
581        return Err(Fault::Invariant("empty frame stack while syncing slots"));
582    };
583    for (reg, slot) in regs.iter_mut().zip(slots.iter()) {
584        *reg = Value::Int(*slot);
585    }
586    Ok(())
587}
588
589/// Threshold at which a `(function, pc)` pair becomes a compilation candidate.
590pub const fn hot_threshold() -> u32 {
591    HOT_THRESHOLD
592}
593
594/// Force-compile a trace (tests / benchmarks).
595pub fn force_compile(
596    ctx: &mut JitContext,
597    chunk: &Chunk,
598    key: TraceKey,
599) -> Result<(), super::error::CompileError> {
600    if ctx.cache.get(&key).is_none() {
601        let mut compiler = TraceCompiler::new(ctx.module_mut());
602        let compiled = compiler.compile_trace(chunk, key)?;
603        ctx.cache.insert(key, compiled);
604    }
605    Ok(())
606}
607
608#[cfg(test)]
609mod tests {
610    use std::sync::Arc;
611
612    use crate::{
613        bytecode::builder::ChunkBuilder, FlowOutcome, NativeTable, Opcode, Runtime, Value, Vm,
614        VmResult,
615    };
616
617    use super::*;
618    use crate::jit::trace::{JitContext, TraceKey};
619
620    type TestResult = Result<(), Box<dyn std::error::Error>>;
621
622    fn add_chunk() -> std::sync::Arc<crate::Chunk> {
623        let mut b = ChunkBuilder::new("jit-add");
624        b.begin_function("main", 0, 3);
625        b.emit_load_imm(0, 41);
626        b.emit_load_imm(1, 1);
627        b.emit_binop(Opcode::Add, 2, 0, 1);
628        b.emit_return(2);
629        Arc::new(b.finish())
630    }
631
632    #[test]
633    fn run_vm_with_jit_completes_scalar_add() -> TestResult {
634        let chunk = add_chunk();
635        let mut ctx = JitContext::new(chunk.clone())?;
636        let key = TraceKey {
637            function: 0,
638            entry_pc: 0,
639        };
640        force_compile(&mut ctx, &chunk, key)?;
641
642        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
643        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
644        assert!(matches!(result, VmResult::Complete(Value::Int(42))));
645        Ok(())
646    }
647
648    #[test]
649    fn native_trace_computes_42() -> TestResult {
650        let chunk = add_chunk();
651        let mut ctx = JitContext::new(chunk.clone())?;
652        let key = TraceKey {
653            function: 0,
654            entry_pc: 0,
655        };
656        force_compile(&mut ctx, &chunk, key)?;
657        let trace = ctx
658            .cache
659            .get(&key)
660            .ok_or("trace missing after force_compile")?;
661        let mut slots = vec![0i64; 3];
662        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
663        let exit = ret.into_reason();
664        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
665        assert_eq!(slots[2], 42);
666        Ok(())
667    }
668
669    #[test]
670    fn jit_matches_interpreter_on_scalar_add() -> TestResult {
671        let chunk = add_chunk();
672        let rt = Runtime::new((*chunk).clone())?;
673        let interp = rt.spawn(0, &[])?.join();
674        rt.shutdown();
675        assert!(matches!(interp, FlowOutcome::Completed(Value::Int(42))));
676
677        let mut ctx = JitContext::new(chunk.clone())?;
678        let key = TraceKey {
679            function: 0,
680            entry_pc: 0,
681        };
682        let mut slots = vec![0i64; 3];
683        force_compile(&mut ctx, &chunk, key)?;
684        let trace = ctx
685            .cache
686            .get(&key)
687            .ok_or("trace missing after force_compile")?;
688        let exit = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3).into_reason();
689        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
690        assert_eq!(slots[2], 42);
691
692        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
693        if let Some(result) = apply_exit_to_vm(&mut vm, &slots, exit)? {
694            assert!(matches!(result, VmResult::Complete(Value::Int(42))));
695        } else {
696            return Err("expected Completed(42)".into());
697        }
698        Ok(())
699    }
700
701    #[test]
702    fn div_by_zero_returns_trap_exit() -> TestResult {
703        let mut b = ChunkBuilder::new("jit-div0");
704        b.begin_function("main", 0, 3);
705        b.emit_load_imm(0, 1);
706        b.emit_load_imm(1, 0);
707        b.emit_binop(Opcode::Div, 2, 0, 1);
708        b.emit_return(2);
709        let chunk = Arc::new(b.finish());
710
711        let mut ctx = JitContext::new(chunk.clone())?;
712        let key = TraceKey {
713            function: 0,
714            entry_pc: 0,
715        };
716        force_compile(&mut ctx, &chunk, key)?;
717        let trace = ctx
718            .cache
719            .get(&key)
720            .ok_or("trace missing after force_compile")?;
721        let mut slots = vec![0i64; 3];
722        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
723        assert!(matches!(ret.into_reason(), ExitReason::Trap { .. }));
724        Ok(())
725    }
726
727    #[test]
728    fn div_and_mod_of_i64_min_wrap_instead_of_aborting() -> TestResult {
729        let mut b = ChunkBuilder::new("jit-div-overflow");
730        b.begin_function("div", 0, 3);
731        let min = b.const_(Value::Int(i64::MIN));
732        let neg = b.const_(Value::Int(-1));
733        b.emit_load_const(0, min);
734        b.emit_load_const(1, neg);
735        b.emit_binop(Opcode::Div, 2, 0, 1);
736        b.emit_return(2);
737        let rem = b.begin_function("rem", 0, 3);
738        let min = b.const_(Value::Int(i64::MIN));
739        let neg = b.const_(Value::Int(-1));
740        b.emit_load_const(0, min);
741        b.emit_load_const(1, neg);
742        b.emit_binop(Opcode::Mod, 2, 0, 1);
743        b.emit_return(2);
744        let chunk = Arc::new(b.finish());
745        let mut ctx = JitContext::new(chunk.clone())?;
746
747        for (function, expect) in [(0, i64::MIN), (rem, 0)] {
748            let entry = chunk.functions[function as usize].entry;
749            force_compile(
750                &mut ctx,
751                &chunk,
752                TraceKey {
753                    function,
754                    entry_pc: entry,
755                },
756            )?;
757            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, &[])?;
758            let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
759            match result {
760                VmResult::Complete(Value::Int(n)) if n == expect => {}
761                other => {
762                    return Err(format!("function {function} finished as {other:?}").into());
763                }
764            }
765        }
766        Ok(())
767    }
768
769    #[test]
770    fn sync_slots_deopts_on_float() -> TestResult {
771        let chunk = add_chunk();
772        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
773        vm.set_register(0, Value::Float(1.0))?;
774        let mut slots = vec![0i64; 3];
775        assert_eq!(sync_slots_from_vm(&vm, &mut slots), SyncSlotsResult::Deopt);
776        Ok(())
777    }
778
779    #[test]
780    fn runtime_path_compiles_and_runs() -> TestResult {
781        let chunk = add_chunk();
782        let runtime = JitRuntime::new(chunk.clone(), 1);
783        let key = TraceKey {
784            function: 0,
785            entry_pc: 0,
786        };
787        let mut slots = vec![0i64; 3];
788        let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
789            .ok_or("expected jit execution")?;
790        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
791        assert_eq!(slots[2], 42);
792        Ok(())
793    }
794
795    #[test]
796    fn budget_exit_when_exhausted_mid_trace() -> TestResult {
797        let mut b = ChunkBuilder::new("jit-budget");
798        b.begin_function("main", 0, 1);
799        b.emit_load_imm(0, 1);
800        b.emit_load_imm(0, 2);
801        b.emit_load_imm(0, 3);
802        b.emit_return(0);
803        let chunk = Arc::new(b.finish());
804
805        let mut ctx = JitContext::new(chunk.clone())?;
806        let key = TraceKey {
807            function: 0,
808            entry_pc: 0,
809        };
810        force_compile(&mut ctx, &chunk, key)?;
811        let trace = ctx
812            .cache
813            .get(&key)
814            .ok_or("trace missing after force_compile")?;
815        let mut slots = vec![0i64; 1];
816        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 2, 0, 1);
817        assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 2 }));
818        Ok(())
819    }
820
821    #[test]
822    fn interleaved_jit_compiles_mid_quantum() -> TestResult {
823        let mut b = ChunkBuilder::new("jit-interleave");
824        b.begin_function("main", 0, 2);
825        b.emit_load_imm(0, 0);
826        let head = b.new_label();
827        b.bind_label(head);
828        b.emit_load_imm(1, 1);
829        b.emit_binop(Opcode::Add, 0, 0, 1);
830        b.emit_load_imm(1, 100);
831        b.emit_binop(Opcode::Lt, 1, 0, 1);
832        let done = b.new_label();
833        b.emit_branch(1, done);
834        b.emit_jump(head);
835        b.bind_label(done);
836        b.emit_return(0);
837        let chunk = Arc::new(b.finish());
838        let head_pc = chunk.functions[0].entry + 1;
839
840        let mut ctx = JitContext::new(chunk.clone())?;
841        ctx.hot_threshold = 2;
842        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
843        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
844        assert!(matches!(result, VmResult::Complete(Value::Int(100))));
845        assert!(ctx
846            .cache
847            .get(&TraceKey {
848                function: 0,
849                entry_pc: head_pc,
850            })
851            .is_some());
852        Ok(())
853    }
854
855    #[test]
856    fn reload_chunk_invalidates_jit_cache() -> TestResult {
857        let chunk = add_chunk();
858        let runtime = JitRuntime::new(chunk.clone(), 1);
859        let key = TraceKey {
860            function: 0,
861            entry_pc: 0,
862        };
863        let mut slots = vec![0i64; 3];
864        let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
865            .ok_or("expected jit execution")?;
866        assert!(matches!(exit, ExitReason::Return { .. }));
867
868        let mut b = ChunkBuilder::new("other");
869        b.begin_function("main", 0, 1);
870        b.emit_load_imm(0, 1);
871        b.emit_return(0);
872        runtime.reload(Arc::new(b.finish()));
873        assert!(runtime.get_trace(&key).is_none());
874        Ok(())
875    }
876
877    /// Budget expiry used to resume past instructions whose results existed
878    /// only in SSA, and writeback turned every untouched `Unit` into `Int(0)`.
879    #[test]
880    fn budget_exit_publishes_assigned_regs_and_keeps_unit() -> TestResult {
881        let mut b = ChunkBuilder::new("jit-budget");
882        b.begin_function("main", 0, 2);
883        b.emit_load_imm(0, 41);
884        b.emit_load_imm(1, 1);
885        b.emit_return(0);
886        let chunk = Arc::new(b.finish());
887        let mut ctx = JitContext::new(chunk.clone())?;
888        let key = TraceKey {
889            function: 0,
890            entry_pc: 0,
891        };
892        force_compile(&mut ctx, &chunk, key)?;
893        let trace = ctx
894            .cache
895            .get(&key)
896            .ok_or("trace missing after force_compile")?;
897        let mut slots = vec![0i64; 2];
898        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 1, 0, 2);
899        assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 1 }));
900        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
901        apply_exit_tagged(&mut vm, &slots, ret)?;
902        let regs = vm.top_registers().ok_or("no frame")?;
903        assert!(matches!(regs.first(), Some(&Value::Int(41))));
904        assert!(matches!(regs.get(1), Some(&Value::Unit)));
905        Ok(())
906    }
907
908    #[test]
909    fn jit_call_does_not_clobber_the_caller_frame() -> TestResult {
910        let mut b = ChunkBuilder::new("jit-call-frames");
911        b.begin_function("callee", 0, 3);
912        b.emit_load_imm(2, 99);
913        b.emit_load_imm(0, 1);
914        b.emit_return(0);
915        let main = b.begin_function("main", 0, 3);
916        b.emit_load_imm(2, 7);
917        b.emit_call(0, 0, 0);
918        b.emit_return(2);
919        let chunk = Arc::new(b.finish());
920        let mut ctx = JitContext::new(chunk.clone())?;
921        let entry = chunk.functions[main as usize].entry;
922        force_compile(
923            &mut ctx,
924            &chunk,
925            TraceKey {
926                function: main,
927                entry_pc: entry,
928            },
929        )?;
930        let mut vm = Vm::new(chunk, NativeTable::empty(), main, &[])?;
931        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
932        assert!(matches!(result, VmResult::Complete(Value::Int(7))));
933        Ok(())
934    }
935
936    #[test]
937    fn move_keeps_bool_unit_and_a_later_int() -> TestResult {
938        let mut b = ChunkBuilder::new("jit-move-tags");
939        b.begin_function("cmp", 0, 4);
940        b.emit_load_imm(0, 1);
941        b.emit_load_imm(1, 1);
942        b.emit_binop(Opcode::Eq, 2, 0, 1);
943        b.emit_move(3, 2);
944        b.emit_return(3);
945        let moved_bool = b.begin_function("moved-bool", 1, 2);
946        b.emit_move(1, 0);
947        b.emit_return(1);
948        let moved_false = b.begin_function("moved-false", 1, 2);
949        b.emit_move(1, 0);
950        b.emit_return(1);
951        let moved_unit = b.begin_function("moved-unit", 0, 2);
952        b.emit_move(1, 0);
953        b.emit_return(1);
954        let overwritten = b.begin_function("overwritten", 1, 2);
955        b.emit_load_imm(0, 5);
956        let cont = b.new_label();
957        b.emit_jump(cont);
958        b.bind_label(cont);
959        b.emit_move(1, 0);
960        b.emit_return(1);
961        let chunk = Arc::new(b.finish());
962        let mut ctx = JitContext::new(chunk.clone())?;
963
964        let run = |ctx: &mut JitContext, function: u32, args: &[Value]| -> TestResult {
965            let entry = chunk.functions[function as usize].entry;
966            force_compile(
967                ctx,
968                &chunk,
969                TraceKey {
970                    function,
971                    entry_pc: entry,
972                },
973            )?;
974            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
975            let result = run_vm_with_jit(&mut vm, 10_000, ctx);
976            match (function, result) {
977                (_, VmResult::Complete(Value::Bool(true))) if function == 0 => Ok(()),
978                (_, VmResult::Complete(Value::Bool(true))) if function == moved_bool => Ok(()),
979                (_, VmResult::Complete(Value::Bool(false))) if function == moved_false => Ok(()),
980                (_, VmResult::Complete(Value::Unit)) if function == moved_unit => Ok(()),
981                (_, VmResult::Complete(Value::Int(5))) if function == overwritten => Ok(()),
982                (_, other) => Err(format!("function {function} finished as {other:?}").into()),
983            }
984        };
985
986        run(&mut ctx, 0, &[])?;
987        run(&mut ctx, moved_bool, &[Value::Bool(true)])?;
988        run(&mut ctx, moved_false, &[Value::Bool(false)])?;
989        run(&mut ctx, moved_unit, &[])?;
990        run(&mut ctx, overwritten, &[Value::Bool(true)])?;
991        Ok(())
992    }
993}