1#![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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum SyncSlotsResult {
18 Ok,
19 Float,
22 Deopt,
24 Unavailable,
26}
27
28#[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
68fn 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
158pub 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
164pub 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
211pub 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
286pub 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
306pub 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
376pub 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 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
460fn 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
539pub 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
584pub 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
618pub 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
629pub const fn hot_threshold() -> u32 {
631 HOT_THRESHOLD
632}
633
634pub 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 jit_matches_interpreter_on_scalar_add() -> TestResult {
715 let chunk = add_chunk();
716 let rt = Runtime::new((*chunk).clone())?;
717 let interp = rt.spawn(0, &[])?.join();
718 rt.shutdown();
719 assert!(matches!(interp, FlowOutcome::Completed(Value::Int(42))));
720
721 let mut ctx = JitContext::new(chunk.clone())?;
722 let key = TraceKey {
723 function: 0,
724 entry_pc: 0,
725
726 floats: false,
727 };
728 let mut slots = vec![0i64; 3];
729 force_compile(&mut ctx, &chunk, key)?;
730 let trace = ctx
731 .cache
732 .get(&key)
733 .ok_or("trace missing after force_compile")?;
734 let exit = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3).into_reason();
735 assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
736 assert_eq!(slots[2], 42);
737
738 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
739 if let Some(result) = apply_exit_to_vm(&mut vm, &slots, exit)? {
740 assert!(matches!(result, VmResult::Complete(Value::Int(42))));
741 } else {
742 return Err("expected Completed(42)".into());
743 }
744 Ok(())
745 }
746
747 #[test]
748 fn div_by_zero_returns_trap_exit() -> TestResult {
749 let mut b = ChunkBuilder::new("jit-div0");
750 b.begin_function("main", 0, 3);
751 b.emit_load_imm(0, 1);
752 b.emit_load_imm(1, 0);
753 b.emit_binop(Opcode::Div, 2, 0, 1);
754 b.emit_return(2);
755 let chunk = Arc::new(b.finish());
756
757 let mut ctx = JitContext::new(chunk.clone())?;
758 let key = TraceKey {
759 function: 0,
760 entry_pc: 0,
761
762 floats: false,
763 };
764 force_compile(&mut ctx, &chunk, key)?;
765 let trace = ctx
766 .cache
767 .get(&key)
768 .ok_or("trace missing after force_compile")?;
769 let mut slots = vec![0i64; 3];
770 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
771 assert!(matches!(ret.into_reason(), ExitReason::Trap { .. }));
772 Ok(())
773 }
774
775 #[test]
776 fn div_and_mod_of_i64_min_wrap_instead_of_aborting() -> TestResult {
777 let mut b = ChunkBuilder::new("jit-div-overflow");
778 b.begin_function("div", 0, 3);
779 let min = b.const_(Value::Int(i64::MIN));
780 let neg = b.const_(Value::Int(-1));
781 b.emit_load_const(0, min);
782 b.emit_load_const(1, neg);
783 b.emit_binop(Opcode::Div, 2, 0, 1);
784 b.emit_return(2);
785 let rem = b.begin_function("rem", 0, 3);
786 let min = b.const_(Value::Int(i64::MIN));
787 let neg = b.const_(Value::Int(-1));
788 b.emit_load_const(0, min);
789 b.emit_load_const(1, neg);
790 b.emit_binop(Opcode::Mod, 2, 0, 1);
791 b.emit_return(2);
792 let chunk = Arc::new(b.finish());
793 let mut ctx = JitContext::new(chunk.clone())?;
794
795 for (function, expect) in [(0, i64::MIN), (rem, 0)] {
796 let entry = chunk.functions[function as usize].entry;
797 force_compile(
798 &mut ctx,
799 &chunk,
800 TraceKey {
801 function,
802 entry_pc: entry,
803
804 floats: false,
805 },
806 )?;
807 let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, &[])?;
808 let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
809 match result {
810 VmResult::Complete(Value::Int(n)) if n == expect => {}
811 other => {
812 return Err(format!("function {function} finished as {other:?}").into());
813 }
814 }
815 }
816 Ok(())
817 }
818
819 #[test]
820 fn sync_slots_accepts_a_float_register() -> TestResult {
821 let chunk = add_chunk();
822 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
823 vm.set_register(0, Value::Float(1.0))?;
824 let mut slots = vec![0i64; 3];
825 assert_eq!(sync_slots_from_vm(&vm, &mut slots), SyncSlotsResult::Float);
826 assert_eq!(f64::from_bits(slots[0] as u64), 1.0);
827 Ok(())
828 }
829
830 #[test]
831 fn float_trace_matches_the_interpreter() -> TestResult {
832 let mut b = ChunkBuilder::new("jit-float");
833 let zero = b.const_(Value::Float(0.0));
834 let one = b.const_(Value::Float(1.0));
835 let limit = b.const_(Value::Float(4.0));
836 b.begin_function("main", 0, 4);
837 b.emit_load_const(0, zero);
838 b.emit_load_const(1, one);
839 b.emit_load_const(2, limit);
840 let head = b.new_label();
841 let done = b.new_label();
842 b.bind_label(head);
843 b.emit_binop(Opcode::Add, 0, 0, 1);
844 b.emit_binop(Opcode::Lt, 3, 0, 2);
845 b.emit_branch(3, done);
846 b.emit_jump(head);
847 b.bind_label(done);
848 b.emit_return(0);
849 let chunk = Arc::new(b.finish());
850 let mut plain = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
851 let interpreted = plain.run(100);
852 let mut ctx = JitContext::new(Arc::clone(&chunk))?;
853 ctx.hot_threshold = 1;
854 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
855 let compiled = run_vm_with_jit(&mut vm, 100, &mut ctx);
856 if !ctx.cache.has_float_trace() {
857 return Err("float add loop was not compiled".into());
858 }
859 match (interpreted, compiled) {
860 (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
861 if a == b && a == 4.0 =>
862 {
863 Ok(())
864 }
865 (left, right) => Err(format!("float trace {right:?} interpreter {left:?}").into()),
866 }
867 }
868
869 fn run_float_chunk(
870 chunk: Arc<Chunk>,
871 budget: u32,
872 ) -> Result<(VmResult, VmResult, JitContext), Box<dyn std::error::Error>> {
873 let mut plain = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
874 let interpreted = plain.run(budget);
875 let mut ctx = JitContext::new(Arc::clone(&chunk))?;
876 ctx.hot_threshold = 1;
877 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
878 let compiled = run_vm_with_jit(&mut vm, budget, &mut ctx);
879 Ok((interpreted, compiled, ctx))
880 }
881
882 #[test]
883 fn float_trace_edges_match_the_interpreter() -> TestResult {
884 let mut nan_lt = ChunkBuilder::new("jit-nan-lt");
885 let nan = nan_lt.const_(Value::Float(f64::NAN));
886 let zero = nan_lt.const_(Value::Float(0.0));
887 nan_lt.begin_function("main", 0, 3);
888 nan_lt.emit_load_const(0, nan);
889 nan_lt.emit_load_const(1, zero);
890 let head = nan_lt.new_label();
891 nan_lt.bind_label(head);
892 nan_lt.emit_binop(Opcode::Lt, 2, 0, 1);
893 nan_lt.emit_return(2);
894 let nan_chunk = Arc::new(nan_lt.finish());
895 let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&nan_chunk), 20)?;
896 if !ctx.cache.has_float_trace() {
897 return Err("NaN comparison was not compiled".into());
898 }
899 match (interpreted, compiled) {
900 (VmResult::Complete(Value::Bool(false)), VmResult::Complete(Value::Bool(false))) => {}
901 (left, right) => {
902 return Err(format!("nan lt {right:?} interpreter {left:?}").into());
903 }
904 }
905
906 let mut inf_add = ChunkBuilder::new("jit-inf-add");
907 let pos = inf_add.const_(Value::Float(f64::INFINITY));
908 let neg = inf_add.const_(Value::Float(f64::NEG_INFINITY));
909 inf_add.begin_function("main", 0, 3);
910 inf_add.emit_load_const(0, pos);
911 inf_add.emit_load_const(1, neg);
912 let head = inf_add.new_label();
913 inf_add.bind_label(head);
914 inf_add.emit_binop(Opcode::Add, 2, 0, 1);
915 inf_add.emit_return(2);
916 let inf_chunk = Arc::new(inf_add.finish());
917 let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&inf_chunk), 20)?;
918 if !ctx.cache.has_float_trace() {
919 return Err("infinity add was not compiled".into());
920 }
921 match (interpreted, compiled) {
922 (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
923 if a.is_nan() && b.is_nan() => {}
924 (left, right) => {
925 return Err(format!("inf add {right:?} interpreter {left:?}").into());
926 }
927 }
928
929 let mut zeros = ChunkBuilder::new("jit-signed-zero");
930 let neg_zero = zeros.const_(Value::Float(-0.0));
931 zeros.begin_function("main", 0, 1);
932 zeros.emit_load_const(0, neg_zero);
933 let head = zeros.new_label();
934 zeros.bind_label(head);
935 zeros.emit_add_imm(0, 0, 0);
936 zeros.emit_return(0);
937 let zero_chunk = Arc::new(zeros.finish());
938 let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&zero_chunk), 20)?;
939 if !ctx.cache.has_float_trace() {
940 return Err("signed-zero add was not compiled".into());
941 }
942 match (interpreted, compiled) {
943 (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
944 if a.to_bits() == 0.0f64.to_bits() && b.to_bits() == 0.0f64.to_bits() => {}
945 (left, right) => {
946 return Err(format!("signed zero {right:?} interpreter {left:?}").into());
947 }
948 }
949
950 let mut countdown = ChunkBuilder::new("jit-sub-imm");
951 let start = countdown.const_(Value::Float(4.0));
952 countdown.begin_function("main", 0, 2);
953 countdown.emit_load_const(0, start);
954 let head = countdown.new_label();
955 let body = countdown.new_label();
956 let done = countdown.new_label();
957 countdown.bind_label(head);
958 countdown.emit_lt_imm(1, 0, 1);
959 countdown.emit_branch(1, body);
960 countdown.emit_jump(done);
961 countdown.bind_label(body);
962 countdown.emit_sub_imm(0, 0, 1);
963 countdown.emit_jump(head);
964 countdown.bind_label(done);
965 countdown.emit_return(0);
966 let sub_chunk = Arc::new(countdown.finish());
967 let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&sub_chunk), 40)?;
968 if !ctx.cache.has_float_trace() {
969 return Err("float SubImm loop was not compiled".into());
970 }
971 match (interpreted, compiled) {
972 (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
973 if a == 0.0 && b == 0.0 =>
974 {
975 Ok(())
976 }
977 (left, right) => Err(format!("sub imm {right:?} interpreter {left:?}").into()),
978 }
979 }
980
981 #[test]
982 fn runtime_path_compiles_and_runs() -> TestResult {
983 let chunk = add_chunk();
984 let runtime = JitRuntime::new(chunk.clone(), 1);
985 let key = TraceKey {
986 function: 0,
987 entry_pc: 0,
988
989 floats: false,
990 };
991 let mut slots = vec![0i64; 3];
992 let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
993 .ok_or("expected jit execution")?;
994 assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
995 assert_eq!(slots[2], 42);
996 Ok(())
997 }
998
999 #[test]
1000 fn budget_exit_when_exhausted_mid_trace() -> TestResult {
1001 let mut b = ChunkBuilder::new("jit-budget");
1002 b.begin_function("main", 0, 1);
1003 b.emit_load_imm(0, 1);
1004 b.emit_load_imm(0, 2);
1005 b.emit_load_imm(0, 3);
1006 b.emit_return(0);
1007 let chunk = Arc::new(b.finish());
1008
1009 let mut ctx = JitContext::new(chunk.clone())?;
1010 let key = TraceKey {
1011 function: 0,
1012 entry_pc: 0,
1013
1014 floats: false,
1015 };
1016 force_compile(&mut ctx, &chunk, key)?;
1017 let trace = ctx
1018 .cache
1019 .get(&key)
1020 .ok_or("trace missing after force_compile")?;
1021 let mut slots = vec![0i64; 1];
1022 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 2, 0, 1);
1023 assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 2 }));
1024 Ok(())
1025 }
1026
1027 #[test]
1028 fn interleaved_jit_compiles_mid_quantum() -> TestResult {
1029 let mut b = ChunkBuilder::new("jit-interleave");
1030 b.begin_function("main", 0, 2);
1031 b.emit_load_imm(0, 0);
1032 let head = b.new_label();
1033 b.bind_label(head);
1034 b.emit_load_imm(1, 1);
1035 b.emit_binop(Opcode::Add, 0, 0, 1);
1036 b.emit_load_imm(1, 100);
1037 b.emit_binop(Opcode::Lt, 1, 0, 1);
1038 let done = b.new_label();
1039 b.emit_branch(1, done);
1040 b.emit_jump(head);
1041 b.bind_label(done);
1042 b.emit_return(0);
1043 let chunk = Arc::new(b.finish());
1044 let head_pc = chunk.functions[0].entry + 1;
1045
1046 let mut ctx = JitContext::new(chunk.clone())?;
1047 ctx.hot_threshold = 2;
1048 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1049 let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1050 assert!(matches!(result, VmResult::Complete(Value::Int(100))));
1051 assert!(ctx
1052 .cache
1053 .get(&TraceKey {
1054 function: 0,
1055 entry_pc: head_pc,
1056
1057 floats: false,
1058 })
1059 .is_some());
1060 Ok(())
1061 }
1062
1063 #[test]
1064 fn reload_chunk_invalidates_jit_cache() -> TestResult {
1065 let chunk = add_chunk();
1066 let runtime = JitRuntime::new(chunk.clone(), 1);
1067 let key = TraceKey {
1068 function: 0,
1069 entry_pc: 0,
1070
1071 floats: false,
1072 };
1073 let mut slots = vec![0i64; 3];
1074 let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
1075 .ok_or("expected jit execution")?;
1076 assert!(matches!(exit, ExitReason::Return { .. }));
1077
1078 let mut b = ChunkBuilder::new("other");
1079 b.begin_function("main", 0, 1);
1080 b.emit_load_imm(0, 1);
1081 b.emit_return(0);
1082 runtime.reload(Arc::new(b.finish()));
1083 assert!(runtime.get_trace(&key).is_none());
1084 Ok(())
1085 }
1086
1087 #[test]
1090 fn budget_exit_publishes_assigned_regs_and_keeps_unit() -> TestResult {
1091 let mut b = ChunkBuilder::new("jit-budget");
1092 b.begin_function("main", 0, 2);
1093 b.emit_load_imm(0, 41);
1094 b.emit_load_imm(1, 1);
1095 b.emit_return(0);
1096 let chunk = Arc::new(b.finish());
1097 let mut ctx = JitContext::new(chunk.clone())?;
1098 let key = TraceKey {
1099 function: 0,
1100 entry_pc: 0,
1101
1102 floats: false,
1103 };
1104 force_compile(&mut ctx, &chunk, key)?;
1105 let trace = ctx
1106 .cache
1107 .get(&key)
1108 .ok_or("trace missing after force_compile")?;
1109 let mut slots = vec![0i64; 2];
1110 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 1, 0, 2);
1111 assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 1 }));
1112 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1113 apply_exit_tagged(&mut vm, &slots, ret)?;
1114 let regs = vm.top_registers().ok_or("no frame")?;
1115 assert!(matches!(regs.first(), Some(&Value::Int(41))));
1116 assert!(matches!(regs.get(1), Some(&Value::Unit)));
1117 Ok(())
1118 }
1119
1120 #[test]
1121 fn jit_call_does_not_clobber_the_caller_frame() -> TestResult {
1122 let mut b = ChunkBuilder::new("jit-call-frames");
1123 b.begin_function("callee", 0, 3);
1124 b.emit_load_imm(2, 99);
1125 b.emit_load_imm(0, 1);
1126 b.emit_return(0);
1127 let main = b.begin_function("main", 0, 3);
1128 b.emit_load_imm(2, 7);
1129 b.emit_call(0, 0, 0);
1130 b.emit_return(2);
1131 let chunk = Arc::new(b.finish());
1132 let mut ctx = JitContext::new(chunk.clone())?;
1133 let entry = chunk.functions[main as usize].entry;
1134 force_compile(
1135 &mut ctx,
1136 &chunk,
1137 TraceKey {
1138 function: main,
1139 entry_pc: entry,
1140
1141 floats: false,
1142 },
1143 )?;
1144 let mut vm = Vm::new(chunk, NativeTable::empty(), main, &[])?;
1145 let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1146 assert!(matches!(result, VmResult::Complete(Value::Int(7))));
1147 Ok(())
1148 }
1149
1150 #[test]
1151 fn move_keeps_bool_unit_and_a_later_int() -> TestResult {
1152 let mut b = ChunkBuilder::new("jit-move-tags");
1153 b.begin_function("cmp", 0, 4);
1154 b.emit_load_imm(0, 1);
1155 b.emit_load_imm(1, 1);
1156 b.emit_binop(Opcode::Eq, 2, 0, 1);
1157 b.emit_move(3, 2);
1158 b.emit_return(3);
1159 let moved_bool = b.begin_function("moved-bool", 1, 2);
1160 b.emit_move(1, 0);
1161 b.emit_return(1);
1162 let moved_false = b.begin_function("moved-false", 1, 2);
1163 b.emit_move(1, 0);
1164 b.emit_return(1);
1165 let moved_unit = b.begin_function("moved-unit", 0, 2);
1166 b.emit_move(1, 0);
1167 b.emit_return(1);
1168 let overwritten = b.begin_function("overwritten", 1, 2);
1169 b.emit_load_imm(0, 5);
1170 let cont = b.new_label();
1171 b.emit_jump(cont);
1172 b.bind_label(cont);
1173 b.emit_move(1, 0);
1174 b.emit_return(1);
1175 let chunk = Arc::new(b.finish());
1176 let mut ctx = JitContext::new(chunk.clone())?;
1177
1178 let run = |ctx: &mut JitContext, function: u32, args: &[Value]| -> TestResult {
1179 let entry = chunk.functions[function as usize].entry;
1180 force_compile(
1181 ctx,
1182 &chunk,
1183 TraceKey {
1184 function,
1185 entry_pc: entry,
1186
1187 floats: false,
1188 },
1189 )?;
1190 let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
1191 let result = run_vm_with_jit(&mut vm, 10_000, ctx);
1192 match (function, result) {
1193 (_, VmResult::Complete(Value::Bool(true))) if function == 0 => Ok(()),
1194 (_, VmResult::Complete(Value::Bool(true))) if function == moved_bool => Ok(()),
1195 (_, VmResult::Complete(Value::Bool(false))) if function == moved_false => Ok(()),
1196 (_, VmResult::Complete(Value::Unit)) if function == moved_unit => Ok(()),
1197 (_, VmResult::Complete(Value::Int(5))) if function == overwritten => Ok(()),
1198 (_, other) => Err(format!("function {function} finished as {other:?}").into()),
1199 }
1200 };
1201
1202 run(&mut ctx, 0, &[])?;
1203 run(&mut ctx, moved_bool, &[Value::Bool(true)])?;
1204 run(&mut ctx, moved_false, &[Value::Bool(false)])?;
1205 run(&mut ctx, moved_unit, &[])?;
1206 run(&mut ctx, overwritten, &[Value::Bool(true)])?;
1207 Ok(())
1208 }
1209
1210 #[test]
1211 fn leaf_call_stays_in_the_trace() -> TestResult {
1212 let mut b = ChunkBuilder::new("jit-call");
1213 let add1 = b.begin_function("add1", 1, 2);
1214 b.emit_load_imm(1, 1);
1215 b.emit_binop(Opcode::Add, 0, 0, 1);
1216 b.emit_return(0);
1217 let main = b.begin_function("main", 0, 1);
1218 b.emit_load_imm(0, 41);
1219 b.emit_call(0, add1, 1);
1220 b.emit_return(0);
1221 let chunk = Arc::new(b.finish());
1222 let mut ctx = JitContext::new(chunk.clone())?;
1223 let entry = chunk.functions[main as usize].entry;
1224 let key = TraceKey {
1225 function: main,
1226 entry_pc: entry,
1227
1228 floats: false,
1229 };
1230 force_compile(&mut ctx, &chunk, key)?;
1231 let trace = ctx
1232 .cache
1233 .get(&key)
1234 .ok_or("trace missing after force_compile")?;
1235 let mut slots = vec![0i64; 2];
1236 let exit = run_compiled_trace_ref(trace, &mut slots, entry, 10_000, main, 1).into_reason();
1237 match exit {
1238 ExitReason::Return { return_reg: 0 } => {}
1239 other => return Err(format!("call left the trace: {other:?}").into()),
1240 }
1241 if slots[0] != 42 {
1242 return Err(format!("leaf call produced {}", slots[0]).into());
1243 }
1244 Ok(())
1245 }
1246
1247 #[test]
1248 fn leaf_call_keeps_bool_unit_and_a_high_dest() -> TestResult {
1249 let mut b = ChunkBuilder::new("jit-call-tags");
1250 let is_true = b.begin_function("is-true", 0, 2);
1251 b.emit_load_imm(0, 1);
1252 b.emit_load_imm(1, 1);
1253 b.emit_binop(Opcode::Eq, 0, 0, 1);
1254 b.emit_return(0);
1255 let blank = b.begin_function("blank", 0, 1);
1256 b.emit_return(0);
1257 let moved = b.begin_function("moved", 1, 2);
1258 b.emit_move(1, 0);
1259 b.emit_return(1);
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
1265 let main_bool = b.begin_function("main-bool", 0, 1);
1266 b.emit_call(0, is_true, 0);
1267 b.emit_return(0);
1268 let main_unit = b.begin_function("main-unit", 0, 1);
1269 b.emit_load_imm(0, 9);
1270 b.emit_call(0, blank, 0);
1271 b.emit_return(0);
1272 let main_moved = b.begin_function("main-moved", 1, 1);
1273 b.emit_call(0, moved, 1);
1274 b.emit_return(0);
1275 let main_high = b.begin_function("main-high", 0, 17);
1276 b.emit_load_imm(16, 41);
1277 b.emit_call(16, add1, 1);
1278 b.emit_return(16);
1279 let chunk = Arc::new(b.finish());
1280 let mut ctx = JitContext::new(chunk.clone())?;
1281
1282 let run = |ctx: &mut JitContext,
1283 function: u32,
1284 args: &[Value]|
1285 -> Result<VmResult, Box<dyn std::error::Error>> {
1286 let entry = chunk.functions[function as usize].entry;
1287 force_compile(
1288 ctx,
1289 &chunk,
1290 TraceKey {
1291 function,
1292 entry_pc: entry,
1293
1294 floats: false,
1295 },
1296 )?;
1297 let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
1298 Ok(run_vm_with_jit(&mut vm, 10_000, ctx))
1299 };
1300
1301 match run(&mut ctx, main_bool, &[])? {
1302 VmResult::Complete(Value::Bool(true)) => {}
1303 other => return Err(format!("bool leaf finished as {other:?}").into()),
1304 }
1305 match run(&mut ctx, main_unit, &[])? {
1306 VmResult::Complete(Value::Unit) => {}
1307 other => return Err(format!("unread leaf finished as {other:?}").into()),
1308 }
1309 match run(&mut ctx, main_moved, &[Value::Bool(false)])? {
1310 VmResult::Complete(Value::Bool(false)) => {}
1311 other => return Err(format!("bool arg finished as {other:?}").into()),
1312 }
1313 match run(&mut ctx, main_high, &[])? {
1314 VmResult::Complete(Value::Int(42)) => {}
1315 other => return Err(format!("r16 dest finished as {other:?}").into()),
1316 }
1317 Ok(())
1318 }
1319}