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/// Attempt one native trace at the current `(function, pc)`.
26fn try_jit_step(vm: &mut Vm, ctx: &mut JitContext, budget: u32) -> Option<VmResult> {
27    if !Arc::ptr_eq(&ctx.chunk, &vm.chunk_arc()) {
28        return None;
29    }
30    let pc = vm.current_pc()?;
31    let function = vm.current_function();
32    let register_count = vm.current_num_registers()?;
33
34    let mut slots = vec![0i64; slot_capacity(vm)];
35    match sync_slots_from_vm(vm, &mut slots) {
36        SyncSlotsResult::Ok => {}
37        SyncSlotsResult::Deopt | SyncSlotsResult::Unavailable => return None,
38    }
39
40    let key = TraceKey {
41        function,
42        entry_pc: pc as u32,
43    };
44    let exit = try_run_hot(
45        ctx,
46        vm.chunk_arc().as_ref(),
47        key,
48        &mut slots,
49        budget,
50        register_count,
51        None,
52    )?;
53    match apply_exit_to_vm(vm, &slots, exit) {
54        Ok(Some(result)) => Some(result),
55        Ok(None) => None,
56        Err(fault) => Some(VmResult::Trap(fault)),
57    }
58}
59
60fn try_jit_step_runtime(
61    vm: &mut Vm,
62    runtime: &JitRuntime,
63    budget: u32,
64    metrics: Option<&crate::scheduler::RuntimeMetrics>,
65) -> Option<VmResult> {
66    if !runtime.matches_chunk(&vm.chunk_arc()) {
67        return None;
68    }
69    let pc = vm.current_pc()?;
70    let function = vm.current_function();
71    let register_count = vm.current_num_registers()?;
72
73    let mut slots = vec![0i64; slot_capacity(vm)];
74    match sync_slots_from_vm(vm, &mut slots) {
75        SyncSlotsResult::Ok => {}
76        SyncSlotsResult::Deopt => {
77            if let Some(m) = metrics {
78                crate::scheduler::RuntimeMetrics::inc(&m.jit_deopts);
79            }
80            return None;
81        }
82        SyncSlotsResult::Unavailable => return None,
83    }
84
85    let key = TraceKey {
86        function,
87        entry_pc: pc as u32,
88    };
89    let exit = try_run_hot_runtime(
90        runtime,
91        vm.chunk_arc().as_ref(),
92        key,
93        &mut slots,
94        budget,
95        register_count,
96        metrics,
97    )?;
98    match apply_exit_to_vm(vm, &slots, exit) {
99        Ok(Some(result)) => Some(result),
100        Ok(None) => None,
101        Err(fault) => Some(VmResult::Trap(fault)),
102    }
103}
104
105/// Run at most `budget` instructions, retrying compiled traces after each
106/// interpreter step when a site becomes hot.
107pub fn run_vm_with_jit(vm: &mut Vm, budget: u32, ctx: &mut JitContext) -> VmResult {
108    run_vm_with_jit_loop(vm, budget, |vm, remaining| try_jit_step(vm, ctx, remaining))
109}
110
111/// Runtime path: shared cache, per-thread compilation module.
112pub fn run_vm_with_jit_runtime(
113    vm: &mut Vm,
114    budget: u32,
115    runtime: &JitRuntime,
116    metrics: Option<&crate::scheduler::RuntimeMetrics>,
117) -> VmResult {
118    run_vm_with_jit_loop(vm, budget, |vm, remaining| {
119        try_jit_step_runtime(vm, runtime, remaining, metrics)
120    })
121}
122
123fn run_vm_with_jit_loop(
124    vm: &mut Vm,
125    budget: u32,
126    mut try_step: impl FnMut(&mut Vm, u32) -> Option<VmResult>,
127) -> VmResult {
128    let mut remaining = budget;
129    while remaining > 0 {
130        if let Some(result) = try_step(vm, remaining) {
131            return result;
132        }
133        match vm.run(1) {
134            VmResult::Yield => {
135                remaining -= 1;
136            }
137            other => return other,
138        }
139    }
140    VmResult::Yield
141}
142
143fn slot_capacity(vm: &Vm) -> usize {
144    let chunk = vm.chunk_arc();
145    let max_in_chunk = chunk
146        .functions
147        .iter()
148        .map(|f| f.num_registers as usize)
149        .max();
150    match (max_in_chunk, vm.current_num_registers()) {
151        (Some(max_regs), Some(current)) => max_regs.max(current as usize),
152        (Some(max_regs), None) => max_regs,
153        (None, Some(current)) => current as usize,
154        (None, None) => 0,
155    }
156}
157
158/// Run a compiled trace against the shadow slot table.
159pub fn run_compiled_trace(
160    entry: super::frame::JitEntry,
161    slots: &mut [i64],
162    pc: u32,
163    budget: u32,
164    function: u32,
165    register_count: u32,
166) -> JitReturn {
167    let mut call_stack = [JitCallRecord {
168        return_pc: 0,
169        return_function: 0,
170        dest_reg: 0,
171        caller_register_count: 0,
172    }; MAX_JIT_CALL_DEPTH];
173    let mut frame = JitFrame {
174        slots: slots.as_mut_ptr(),
175        register_count,
176        pc,
177        budget,
178        function,
179        exit_kind: 0,
180        return_reg: 0,
181        call_depth: 0,
182        call_stack: call_stack.as_mut_ptr(),
183    };
184    unsafe { (entry)(&mut frame) };
185    JitReturn {
186        kind: frame.exit_kind,
187        pc: frame.pc,
188        return_reg: frame.return_reg,
189    }
190}
191
192/// Run a cached trace by reference.
193pub fn run_compiled_trace_ref(
194    trace: &CompiledTrace,
195    slots: &mut [i64],
196    pc: u32,
197    budget: u32,
198    function: u32,
199    register_count: u32,
200) -> JitReturn {
201    run_compiled_trace(trace.entry, slots, pc, budget, function, register_count)
202}
203
204/// Compile `key` if needed and execute once. Returns `None` when compilation
205/// fails (caller should fall back to the interpreter).
206pub fn try_run_hot(
207    ctx: &mut JitContext,
208    chunk: &Chunk,
209    key: TraceKey,
210    slots: &mut [i64],
211    budget: u32,
212    register_count: u8,
213    metrics: Option<&crate::scheduler::RuntimeMetrics>,
214) -> Option<ExitReason> {
215    if ctx.cache.get(&key).is_none() {
216        if !ctx.hot.hit(key, ctx.hot_threshold) {
217            if let Some(m) = metrics {
218                crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
219            }
220            return None;
221        }
222        let mut compiler = TraceCompiler::new(ctx.module_mut());
223        match compiler.compile_trace(chunk, key) {
224            Ok(compiled) => {
225                ctx.cache.insert(key, compiled);
226                if let Some(m) = metrics {
227                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
228                }
229            }
230            Err(_) => {
231                if let Some(m) = metrics {
232                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
233                }
234                return None;
235            }
236        }
237    }
238    let trace = ctx.cache.get(&key)?;
239    if let Some(m) = metrics {
240        crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
241    }
242    let ret = run_compiled_trace_ref(
243        trace,
244        slots,
245        key.entry_pc,
246        budget,
247        key.function,
248        u32::from(register_count),
249    );
250    Some(ret.into_reason())
251}
252
253/// Shared-runtime variant (no global lock during execution).
254pub fn try_run_hot_runtime(
255    runtime: &JitRuntime,
256    chunk: &Chunk,
257    key: TraceKey,
258    slots: &mut [i64],
259    budget: u32,
260    register_count: u8,
261    metrics: Option<&crate::scheduler::RuntimeMetrics>,
262) -> Option<ExitReason> {
263    if let Some(copy) = runtime.get_trace(&key) {
264        if let Some(m) = metrics {
265            crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
266        }
267        let ret = run_compiled_trace(
268            copy.entry,
269            slots,
270            key.entry_pc,
271            budget,
272            key.function,
273            u32::from(register_count),
274        );
275        return Some(ret.into_reason());
276    }
277
278    if !runtime.record_hot_hit(key) {
279        if let Some(m) = metrics {
280            crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
281        }
282        return None;
283    }
284
285    // Double-checked compile after hot threshold.
286    if runtime.get_trace(&key).is_some() {
287        return try_run_hot_runtime(runtime, chunk, key, slots, budget, register_count, metrics);
288    }
289
290    let compiled =
291        match with_jit_module(|module| TraceCompiler::new(module).compile_trace(chunk, key)) {
292            Ok(trace) => trace,
293            Err(_) => {
294                if let Some(m) = metrics {
295                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
296                }
297                return None;
298            }
299        };
300
301    runtime.insert_trace(key, compiled);
302    if let Some(m) = metrics {
303        crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
304    }
305
306    try_run_hot_runtime(runtime, chunk, key, slots, budget, register_count, metrics)
307}
308
309/// Apply a native trace exit to a live [`Vm`], producing an optional early
310/// [`VmResult`] when the trace finished the flow.
311pub fn apply_exit_to_vm(
312    vm: &mut Vm,
313    slots: &[i64],
314    exit: ExitReason,
315) -> Result<Option<VmResult>, Fault> {
316    match exit {
317        ExitReason::Return { return_reg } => {
318            let value = Value::Int(slots[return_reg as usize]);
319            vm.set_register(return_reg, value.clone())?;
320            let pc = vm
321                .current_pc()
322                .ok_or(Fault::Invariant("empty frame stack while running"))?;
323            vm.set_pc(pc.saturating_add(1));
324            vm.return_value(value)
325        }
326        ExitReason::Trap { pc } => {
327            vm.set_pc(pc as usize);
328            Ok(Some(VmResult::Trap(Fault::DivideByZero)))
329        }
330        ExitReason::Budget { pc } => {
331            vm.set_pc(pc as usize);
332            sync_slots_to_vm(vm, slots)?;
333            Ok(None)
334        }
335        ExitReason::Continue { pc } | ExitReason::Effect { pc } | ExitReason::Deopt { pc } => {
336            vm.set_pc(pc as usize);
337            if matches!(
338                exit,
339                ExitReason::Continue { .. } | ExitReason::Effect { .. }
340            ) {
341                sync_slots_to_vm(vm, slots)?;
342            }
343            Ok(None)
344        }
345    }
346}
347
348/// Copy int-compatible registers from the VM into JIT shadow slots.
349pub fn sync_slots_from_vm(vm: &Vm, slots: &mut [i64]) -> SyncSlotsResult {
350    let Some(regs) = vm.top_registers() else {
351        return SyncSlotsResult::Unavailable;
352    };
353    for (slot, value) in slots.iter_mut().zip(regs.iter()) {
354        match value {
355            Value::Int(i) => *slot = *i,
356            Value::Bool(b) => *slot = i64::from(*b),
357            Value::Unit => *slot = 0,
358            _ => return SyncSlotsResult::Deopt,
359        }
360    }
361    SyncSlotsResult::Ok
362}
363
364/// Write JIT shadow slots back into the active VM register file.
365pub fn sync_slots_to_vm(vm: &mut Vm, slots: &[i64]) -> Result<(), Fault> {
366    let Some(regs) = vm.top_registers_mut() else {
367        return Err(Fault::Invariant("empty frame stack while syncing slots"));
368    };
369    for (reg, slot) in regs.iter_mut().zip(slots.iter()) {
370        *reg = Value::Int(*slot);
371    }
372    Ok(())
373}
374
375/// Threshold at which a `(function, pc)` pair becomes a compilation candidate.
376pub const fn hot_threshold() -> u32 {
377    HOT_THRESHOLD
378}
379
380/// Force-compile a trace (tests / benchmarks).
381pub fn force_compile(
382    ctx: &mut JitContext,
383    chunk: &Chunk,
384    key: TraceKey,
385) -> Result<(), super::error::CompileError> {
386    if ctx.cache.get(&key).is_none() {
387        let mut compiler = TraceCompiler::new(ctx.module_mut());
388        let compiled = compiler.compile_trace(chunk, key)?;
389        ctx.cache.insert(key, compiled);
390    }
391    Ok(())
392}
393
394#[cfg(test)]
395mod tests {
396    use std::sync::Arc;
397
398    use crate::{
399        bytecode::builder::ChunkBuilder, FlowOutcome, NativeTable, Opcode, Runtime, Value, Vm,
400        VmResult,
401    };
402
403    use super::*;
404    use crate::jit::trace::{JitContext, TraceKey};
405
406    type TestResult = Result<(), Box<dyn std::error::Error>>;
407
408    fn add_chunk() -> std::sync::Arc<crate::Chunk> {
409        let mut b = ChunkBuilder::new("jit-add");
410        b.begin_function("main", 0, 3);
411        b.emit_load_imm(0, 41);
412        b.emit_load_imm(1, 1);
413        b.emit_binop(Opcode::Add, 2, 0, 1);
414        b.emit_return(2);
415        Arc::new(b.finish())
416    }
417
418    #[test]
419    fn run_vm_with_jit_completes_scalar_add() -> TestResult {
420        let chunk = add_chunk();
421        let mut ctx = JitContext::new(chunk.clone())?;
422        let key = TraceKey {
423            function: 0,
424            entry_pc: 0,
425        };
426        force_compile(&mut ctx, &chunk, key)?;
427
428        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
429        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
430        assert!(matches!(result, VmResult::Complete(Value::Int(42))));
431        Ok(())
432    }
433
434    #[test]
435    fn native_trace_computes_42() -> TestResult {
436        let chunk = add_chunk();
437        let mut ctx = JitContext::new(chunk.clone())?;
438        let key = TraceKey {
439            function: 0,
440            entry_pc: 0,
441        };
442        force_compile(&mut ctx, &chunk, key)?;
443        let trace = ctx
444            .cache
445            .get(&key)
446            .ok_or("trace missing after force_compile")?;
447        let mut slots = vec![0i64; 3];
448        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
449        let exit = ret.into_reason();
450        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
451        assert_eq!(slots[2], 42);
452        Ok(())
453    }
454
455    #[test]
456    fn jit_matches_interpreter_on_scalar_add() -> TestResult {
457        let chunk = add_chunk();
458        let rt = Runtime::new((*chunk).clone())?;
459        let interp = rt.spawn(0, &[])?.join();
460        rt.shutdown();
461        assert!(matches!(interp, FlowOutcome::Completed(Value::Int(42))));
462
463        let mut ctx = JitContext::new(chunk.clone())?;
464        let key = TraceKey {
465            function: 0,
466            entry_pc: 0,
467        };
468        let mut slots = vec![0i64; 3];
469        force_compile(&mut ctx, &chunk, key)?;
470        let trace = ctx
471            .cache
472            .get(&key)
473            .ok_or("trace missing after force_compile")?;
474        let exit = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3).into_reason();
475        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
476        assert_eq!(slots[2], 42);
477
478        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
479        if let Some(result) = apply_exit_to_vm(&mut vm, &slots, exit)? {
480            assert!(matches!(result, VmResult::Complete(Value::Int(42))));
481        } else {
482            return Err("expected Completed(42)".into());
483        }
484        Ok(())
485    }
486
487    #[test]
488    fn div_by_zero_returns_trap_exit() -> TestResult {
489        let mut b = ChunkBuilder::new("jit-div0");
490        b.begin_function("main", 0, 3);
491        b.emit_load_imm(0, 1);
492        b.emit_load_imm(1, 0);
493        b.emit_binop(Opcode::Div, 2, 0, 1);
494        b.emit_return(2);
495        let chunk = Arc::new(b.finish());
496
497        let mut ctx = JitContext::new(chunk.clone())?;
498        let key = TraceKey {
499            function: 0,
500            entry_pc: 0,
501        };
502        force_compile(&mut ctx, &chunk, key)?;
503        let trace = ctx
504            .cache
505            .get(&key)
506            .ok_or("trace missing after force_compile")?;
507        let mut slots = vec![0i64; 3];
508        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
509        assert!(matches!(ret.into_reason(), ExitReason::Trap { .. }));
510        Ok(())
511    }
512
513    #[test]
514    fn sync_slots_deopts_on_float() -> TestResult {
515        let chunk = add_chunk();
516        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
517        vm.set_register(0, Value::Float(1.0))?;
518        let mut slots = vec![0i64; 3];
519        assert_eq!(sync_slots_from_vm(&vm, &mut slots), SyncSlotsResult::Deopt);
520        Ok(())
521    }
522
523    #[test]
524    fn runtime_path_compiles_and_runs() -> TestResult {
525        let chunk = add_chunk();
526        let runtime = JitRuntime::new(chunk.clone(), 1);
527        let key = TraceKey {
528            function: 0,
529            entry_pc: 0,
530        };
531        let mut slots = vec![0i64; 3];
532        let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
533            .ok_or("expected jit execution")?;
534        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
535        assert_eq!(slots[2], 42);
536        Ok(())
537    }
538
539    #[test]
540    fn budget_exit_when_exhausted_mid_trace() -> TestResult {
541        let mut b = ChunkBuilder::new("jit-budget");
542        b.begin_function("main", 0, 1);
543        b.emit_load_imm(0, 1);
544        b.emit_load_imm(0, 2);
545        b.emit_load_imm(0, 3);
546        b.emit_return(0);
547        let chunk = Arc::new(b.finish());
548
549        let mut ctx = JitContext::new(chunk.clone())?;
550        let key = TraceKey {
551            function: 0,
552            entry_pc: 0,
553        };
554        force_compile(&mut ctx, &chunk, key)?;
555        let trace = ctx
556            .cache
557            .get(&key)
558            .ok_or("trace missing after force_compile")?;
559        let mut slots = vec![0i64; 1];
560        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 2, 0, 1);
561        assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 2 }));
562        Ok(())
563    }
564
565    #[test]
566    fn interleaved_jit_compiles_mid_quantum() -> TestResult {
567        let mut b = ChunkBuilder::new("jit-interleave");
568        b.begin_function("main", 0, 2);
569        b.emit_load_imm(0, 0);
570        let head = b.new_label();
571        b.bind_label(head);
572        b.emit_load_imm(1, 1);
573        b.emit_binop(Opcode::Add, 0, 0, 1);
574        b.emit_load_imm(1, 100);
575        b.emit_binop(Opcode::Lt, 1, 0, 1);
576        let done = b.new_label();
577        b.emit_branch(1, done);
578        b.emit_jump(head);
579        b.bind_label(done);
580        b.emit_return(0);
581        let chunk = Arc::new(b.finish());
582        let head_pc = chunk.functions[0].entry + 1;
583
584        let mut ctx = JitContext::new(chunk.clone())?;
585        ctx.hot_threshold = 2;
586        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
587        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
588        assert!(matches!(result, VmResult::Complete(Value::Int(100))));
589        assert!(ctx
590            .cache
591            .get(&TraceKey {
592                function: 0,
593                entry_pc: head_pc,
594            })
595            .is_some());
596        Ok(())
597    }
598
599    #[test]
600    fn reload_chunk_invalidates_jit_cache() -> TestResult {
601        let chunk = add_chunk();
602        let runtime = JitRuntime::new(chunk.clone(), 1);
603        let key = TraceKey {
604            function: 0,
605            entry_pc: 0,
606        };
607        let mut slots = vec![0i64; 3];
608        let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
609            .ok_or("expected jit execution")?;
610        assert!(matches!(exit, ExitReason::Return { .. }));
611
612        let mut b = ChunkBuilder::new("other");
613        b.begin_function("main", 0, 1);
614        b.emit_load_imm(0, 1);
615        b.emit_return(0);
616        runtime.reload(Arc::new(b.finish()));
617        assert!(runtime.get_trace(&key).is_none());
618        Ok(())
619    }
620}