1#![allow(unsafe_code)]
3
4use std::sync::Arc;
5
6use crate::{Chunk, Fault, Opcode, Value, Vm, VmResult};
7
8use super::compiler::TraceCompiler;
9use super::exit::{ExitReason, JitReturn, JIT_BUDGET, JIT_DEOPT};
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) -> JitProbe {
70 if !Arc::ptr_eq(&ctx.chunk, &vm.chunk_arc()) {
71 return JitProbe::Miss;
72 }
73 let Some(pc) = vm.current_pc() else {
74 return JitProbe::Miss;
75 };
76 let function = vm.current_function();
77 let Some(register_count) = vm.current_num_registers() else {
78 return JitProbe::Miss;
79 };
80
81 let mut slots = vec![0i64; slot_capacity(vm)];
82 let floats = match sync_slots_from_vm(vm, &mut slots) {
83 SyncSlotsResult::Ok => false,
84 SyncSlotsResult::Float => true,
85 SyncSlotsResult::Deopt | SyncSlotsResult::Unavailable => return JitProbe::Miss,
86 };
87
88 let key = TraceKey {
89 function,
90 entry_pc: pc as u32,
91 floats,
92 };
93 let Some((exit, spent, unwind)) = try_run_hot_tagged(
94 ctx,
95 vm.chunk_arc().as_ref(),
96 key,
97 &mut HotCall {
98 slots: &mut slots,
99 budget,
100 register_count: register_count as u8,
101 metrics: None,
102 tags: EntryTags::from_vm(vm),
103 },
104 ) else {
105 return JitProbe::Miss;
106 };
107 finish_probe(vm, &slots, exit, spent, unwind)
108}
109
110fn try_jit_step_runtime(
111 vm: &mut Vm,
112 runtime: &JitRuntime,
113 budget: u32,
114 metrics: Option<&crate::scheduler::RuntimeMetrics>,
115) -> JitProbe {
116 if !runtime.matches_chunk(&vm.chunk_arc()) {
117 return JitProbe::Miss;
118 }
119 let Some(pc) = vm.current_pc() else {
120 return JitProbe::Miss;
121 };
122 let function = vm.current_function();
123 let Some(register_count) = vm.current_num_registers() else {
124 return JitProbe::Miss;
125 };
126
127 let mut slots = vec![0i64; slot_capacity(vm)];
128 let floats = match sync_slots_from_vm(vm, &mut slots) {
129 SyncSlotsResult::Ok => false,
130 SyncSlotsResult::Float => true,
131 SyncSlotsResult::Deopt => {
132 if let Some(m) = metrics {
133 crate::scheduler::RuntimeMetrics::inc(&m.jit_deopts);
134 }
135 return JitProbe::Miss;
136 }
137 SyncSlotsResult::Unavailable => return JitProbe::Miss,
138 };
139
140 let key = TraceKey {
141 function,
142 entry_pc: pc as u32,
143 floats,
144 };
145 let Some((exit, spent, unwind)) = try_run_hot_runtime_tagged(
146 runtime,
147 vm.chunk_arc().as_ref(),
148 key,
149 &mut HotCall {
150 slots: &mut slots,
151 budget,
152 register_count: register_count as u8,
153 metrics,
154 tags: EntryTags::from_vm(vm),
155 },
156 ) else {
157 return JitProbe::Miss;
158 };
159 finish_probe(vm, &slots, exit, spent, unwind)
160}
161
162enum JitProbe {
164 Miss,
166 Hit { spent: u32, stop: Option<VmResult> },
170}
171
172fn finish_probe(
173 vm: &mut Vm,
174 slots: &[i64],
175 exit: JitReturn,
176 spent: u32,
177 unwind: Option<JitUnwind>,
178) -> JitProbe {
179 if let Some(unwind) = unwind {
180 return match install_unwind(vm, slots, &exit, &unwind) {
181 Ok(()) => match exit.kind {
182 super::exit::JIT_TRAP => JitProbe::Hit {
183 spent,
184 stop: Some(VmResult::Trap(Fault::DivideByZero)),
185 },
186 JIT_BUDGET => JitProbe::Hit {
187 spent,
188 stop: Some(VmResult::Yield),
189 },
190 super::exit::JIT_RETURN => JitProbe::Hit {
191 spent,
192 stop: Some(VmResult::Trap(Fault::Invariant(
193 "jit return left a call stack installed",
194 ))),
195 },
196 _ => JitProbe::Hit { spent, stop: None },
197 },
198 Err(fault) => JitProbe::Hit {
199 spent,
200 stop: Some(VmResult::Trap(fault)),
201 },
202 };
203 }
204 let kind = exit.kind;
205 match apply_exit_tagged(vm, slots, exit) {
206 Ok(Some(result)) => JitProbe::Hit {
207 spent,
208 stop: Some(result),
209 },
210 Ok(None) if kind == JIT_BUDGET => JitProbe::Hit {
211 spent,
212 stop: Some(VmResult::Yield),
213 },
214 Ok(None) if kind == JIT_DEOPT => JitProbe::Miss,
215 Ok(None) => JitProbe::Hit { spent, stop: None },
216 Err(fault) => JitProbe::Hit {
217 spent,
218 stop: Some(VmResult::Trap(fault)),
219 },
220 }
221}
222
223pub fn run_vm_with_jit(vm: &mut Vm, budget: u32, ctx: &mut JitContext) -> VmResult {
226 run_vm_with_jit_loop(vm, budget, |vm, remaining| try_jit_step(vm, ctx, remaining))
227}
228
229pub fn run_vm_with_jit_runtime(
231 vm: &mut Vm,
232 budget: u32,
233 runtime: &JitRuntime,
234 metrics: Option<&crate::scheduler::RuntimeMetrics>,
235) -> VmResult {
236 run_vm_with_jit_loop(vm, budget, |vm, remaining| {
237 try_jit_step_runtime(vm, runtime, remaining, metrics)
238 })
239}
240
241fn run_vm_with_jit_loop(
242 vm: &mut Vm,
243 budget: u32,
244 mut try_step: impl FnMut(&mut Vm, u32) -> JitProbe,
245) -> VmResult {
246 let mut remaining = budget;
247 while remaining > 0 {
248 match try_step(vm, remaining) {
249 JitProbe::Hit { spent, stop } => {
250 let spent = spent.min(remaining);
251 vm.record_instructions(u64::from(spent));
252 remaining -= spent;
253 if let Some(result) = stop {
254 return result;
255 }
256 if remaining == 0 {
257 break;
258 }
259 }
260 JitProbe::Miss => {}
261 }
262 let pc_before = vm.current_pc();
267 match vm.run(1) {
268 VmResult::Yield if explicit_yield(vm, pc_before) => return VmResult::Yield,
269 VmResult::Yield => {
270 remaining -= 1;
271 }
272 other => return other,
273 }
274 }
275 VmResult::Yield
276}
277
278fn explicit_yield(vm: &Vm, pc_before: Option<usize>) -> bool {
283 let Some(pc) = pc_before else {
284 return false;
285 };
286 vm.chunk_arc()
287 .code
288 .get(pc)
289 .is_some_and(|instr| instr.op == Opcode::Yield)
290}
291
292fn slot_capacity(vm: &Vm) -> usize {
293 let chunk = vm.chunk_arc();
294 let max_in_chunk = chunk
295 .functions
296 .iter()
297 .map(|f| f.num_registers as usize)
298 .max();
299 match (max_in_chunk, vm.current_num_registers()) {
300 (Some(max_regs), Some(current)) => max_regs.max(current),
301 (Some(max_regs), None) => max_regs,
302 (None, Some(current)) => current,
303 (None, None) => 0,
304 }
305}
306
307pub fn run_compiled_trace(
312 entry: super::frame::JitEntry,
313 slots: &mut [i64],
314 pc: u32,
315 budget: u32,
316 function: u32,
317 register_count: u32,
318) -> JitReturn {
319 run_compiled_trace_with_tags(
320 entry,
321 slots,
322 pc,
323 budget,
324 function,
325 register_count,
326 EntryTags::INT,
327 )
328 .0
329}
330
331fn run_compiled_trace_with_tags(
332 entry: super::frame::JitEntry,
333 slots: &mut [i64],
334 pc: u32,
335 budget: u32,
336 function: u32,
337 register_count: u32,
338 tags: EntryTags,
339) -> (JitReturn, u32, Option<JitUnwind>) {
340 let mut call_stack = [JitCallRecord {
341 return_pc: 0,
342 return_function: 0,
343 dest_reg: 0,
344 caller_register_count: 0,
345 written: [0; 4],
346 as_bool: [0; 4],
347 as_unit: [0; 4],
348 as_float: [0; 4],
349 }; MAX_JIT_CALL_DEPTH];
350 let stride = slots.len();
351 let mut spill = vec![0i64; stride.saturating_mul(MAX_JIT_CALL_DEPTH)];
352 let mut frame = JitFrame {
353 slots: slots.as_mut_ptr(),
354 register_count,
355 pc,
356 budget,
357 function,
358 exit_kind: 0,
359 return_reg: 0,
360 call_depth: 0,
361 call_stack: call_stack.as_mut_ptr(),
362 spill: spill.as_mut_ptr(),
363 spill_stride: stride as u32,
364 written: [0; 4],
365 as_bool: [0; 4],
366 as_unit: [0; 4],
367 entry_as_bool: tags.as_bool,
368 entry_as_unit: tags.as_unit,
369 as_float: [0; 4],
370 entry_as_float: tags.as_float,
371 };
372 unsafe { (entry)(&mut frame) };
373 let spent = budget.saturating_sub(frame.budget);
374 let ret = JitReturn {
375 kind: frame.exit_kind,
376 pc: frame.pc,
377 return_reg: frame.return_reg,
378 written: frame.written,
379 as_bool: frame.as_bool,
380 as_unit: frame.as_unit,
381 as_float: frame.as_float,
382 };
383 let depth = frame.call_depth as usize;
384 let unwind = if depth == 0 || depth > call_stack.len() {
385 None
386 } else {
387 let stride = slots.len();
388 let spill_len = stride.saturating_mul(depth);
389 let spill_len = spill_len.min(spill.len());
390 Some(JitUnwind {
391 records: call_stack[..depth].to_vec(),
392 spill: spill[..spill_len].to_vec(),
393 stride,
394 function: frame.function,
395 register_count: frame.register_count,
396 })
397 };
398 (ret, spent, unwind)
399}
400
401struct JitUnwind {
404 records: Vec<JitCallRecord>,
405 spill: Vec<i64>,
406 stride: usize,
407 function: u32,
408 register_count: u32,
409}
410
411fn install_unwind(
412 vm: &mut Vm,
413 slots: &[i64],
414 ret: &JitReturn,
415 unwind: &JitUnwind,
416) -> Result<(), Fault> {
417 let Some(caller) = unwind.records.first() else {
418 return Err(Fault::Invariant("jit unwind without a caller"));
419 };
420 let mut frames = Vec::with_capacity(unwind.records.len());
421 for index in 1..unwind.records.len() {
422 let rec = &unwind.records[index];
423 let dest = dest_reg(unwind.records[index - 1].dest_reg)?;
424 frames.push(suspended(unwind, index, rec, dest)?);
425 }
426 let dest = dest_reg(
427 unwind
428 .records
429 .last()
430 .ok_or(Fault::Invariant("jit unwind without a caller"))?
431 .dest_reg,
432 )?;
433 frames.push(live_frame(slots, ret, unwind, dest)?);
434 let window = spill_window(unwind, 0)?;
435 let updates = written_updates(
436 window,
437 caller.caller_register_count as usize,
438 &caller.written,
439 &caller.as_bool,
440 &caller.as_unit,
441 &caller.as_float,
442 );
443 vm.install_jit_frames(caller.return_pc as usize, &updates, frames)
444}
445
446fn suspended(
447 unwind: &JitUnwind,
448 index: usize,
449 rec: &JitCallRecord,
450 dest: u8,
451) -> Result<(u32, u8, usize, Vec<Value>), Fault> {
452 let count = register_len(rec.caller_register_count)?;
453 let window = spill_window(unwind, index)?;
454 let registers = frame_values(
455 window,
456 count,
457 &rec.written,
458 &rec.as_bool,
459 &rec.as_unit,
460 &rec.as_float,
461 );
462 Ok((rec.return_function, dest, rec.return_pc as usize, registers))
463}
464
465fn live_frame(
466 slots: &[i64],
467 ret: &JitReturn,
468 unwind: &JitUnwind,
469 dest: u8,
470) -> Result<(u32, u8, usize, Vec<Value>), Fault> {
471 let count = register_len(unwind.register_count)?;
472 let registers = frame_values(
473 slots,
474 count,
475 &ret.written,
476 &ret.as_bool,
477 &ret.as_unit,
478 &ret.as_float,
479 );
480 Ok((unwind.function, dest, ret.pc as usize, registers))
481}
482
483fn spill_window(unwind: &JitUnwind, index: usize) -> Result<&[i64], Fault> {
484 let start = index
485 .checked_mul(unwind.stride)
486 .ok_or(Fault::Invariant("jit spill index overflow"))?;
487 let end = start
488 .checked_add(unwind.stride)
489 .ok_or(Fault::Invariant("jit spill index overflow"))?;
490 unwind
491 .spill
492 .get(start..end)
493 .ok_or(Fault::Invariant("jit spill is shorter than its call stack"))
494}
495
496fn dest_reg(raw: u32) -> Result<u8, Fault> {
497 u8::try_from(raw).map_err(|_| Fault::Invariant("jit dest register does not fit"))
498}
499
500fn register_len(raw: u32) -> Result<usize, Fault> {
501 let count = usize::try_from(raw).map_err(|_| Fault::Invariant("jit register count"))?;
502 if count > usize::from(u8::MAX) {
503 return Err(Fault::Invariant("jit frame is wider than a register file"));
504 }
505 Ok(count)
506}
507
508fn written_updates(
509 window: &[i64],
510 count: usize,
511 written: &[u64; 4],
512 as_bool: &[u64; 4],
513 as_unit: &[u64; 4],
514 as_float: &[u64; 4],
515) -> Vec<(u8, Value)> {
516 let mut out = Vec::new();
517 for index in 0..count.min(window.len()).min(256) {
518 if !tag_bit(written, index) {
519 continue;
520 }
521 let Some(reg) = u8::try_from(index).ok() else {
522 break;
523 };
524 let Some(bits) = window.get(index).copied() else {
525 break;
526 };
527 out.push((reg, tagged_value(bits, index, as_bool, as_unit, as_float)));
528 }
529 out
530}
531
532fn frame_values(
533 window: &[i64],
534 count: usize,
535 written: &[u64; 4],
536 as_bool: &[u64; 4],
537 as_unit: &[u64; 4],
538 as_float: &[u64; 4],
539) -> Vec<Value> {
540 let mut registers = vec![Value::Unit; count];
541 for (index, reg) in registers.iter_mut().enumerate() {
542 if !tag_bit(written, index) {
543 continue;
544 }
545 let Some(bits) = window.get(index).copied() else {
546 continue;
547 };
548 *reg = tagged_value(bits, index, as_bool, as_unit, as_float);
549 }
550 registers
551}
552
553fn tagged_value(
554 bits: i64,
555 index: usize,
556 as_bool: &[u64; 4],
557 as_unit: &[u64; 4],
558 as_float: &[u64; 4],
559) -> Value {
560 if tag_bit(as_unit, index) {
561 Value::Unit
562 } else if tag_bit(as_bool, index) {
563 Value::Bool(bits != 0)
564 } else if tag_bit(as_float, index) {
565 Value::Float(f64::from_bits(bits as u64))
566 } else {
567 Value::Int(bits)
568 }
569}
570
571pub fn run_compiled_trace_ref(
573 trace: &CompiledTrace,
574 slots: &mut [i64],
575 pc: u32,
576 budget: u32,
577 function: u32,
578 register_count: u32,
579) -> JitReturn {
580 run_compiled_trace(trace.entry, slots, pc, budget, function, register_count)
581}
582
583struct HotCall<'a> {
584 slots: &'a mut [i64],
585 budget: u32,
586 register_count: u8,
587 metrics: Option<&'a crate::scheduler::RuntimeMetrics>,
588 tags: EntryTags,
589}
590
591pub fn try_run_hot(
594 ctx: &mut JitContext,
595 chunk: &Chunk,
596 key: TraceKey,
597 slots: &mut [i64],
598 budget: u32,
599 register_count: u8,
600 metrics: Option<&crate::scheduler::RuntimeMetrics>,
601) -> Option<ExitReason> {
602 try_run_hot_tagged(
603 ctx,
604 chunk,
605 key,
606 &mut HotCall {
607 slots,
608 budget,
609 register_count,
610 metrics,
611 tags: EntryTags::INT,
612 },
613 )
614 .and_then(|(ret, _, unwind)| {
615 if unwind.is_some() {
616 None
617 } else {
618 Some(ret.into_reason())
619 }
620 })
621}
622
623fn try_run_hot_tagged(
624 ctx: &mut JitContext,
625 chunk: &Chunk,
626 key: TraceKey,
627 call: &mut HotCall<'_>,
628) -> Option<(JitReturn, u32, Option<JitUnwind>)> {
629 if ctx.cache.get(&key).is_none() {
630 if ctx.cache.is_failed(&key) {
631 return None;
632 }
633 if !ctx.hot.hit(key, ctx.hot_threshold) {
634 if let Some(m) = call.metrics {
635 crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
636 }
637 return None;
638 }
639 let mut compiler = TraceCompiler::new(ctx.module_mut());
640 match compiler.compile_trace(chunk, key) {
641 Ok(compiled) => {
642 ctx.cache.insert(key, compiled);
643 if let Some(m) = call.metrics {
644 crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
645 }
646 }
647 Err(_) => {
648 ctx.cache.mark_failed(key);
649 if let Some(m) = call.metrics {
650 crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
651 }
652 return None;
653 }
654 }
655 }
656 let trace = ctx.cache.get(&key)?;
657 if let Some(m) = call.metrics {
658 crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
659 }
660 Some(run_compiled_trace_with_tags(
661 trace.entry,
662 call.slots,
663 key.entry_pc,
664 call.budget,
665 key.function,
666 u32::from(call.register_count),
667 call.tags,
668 ))
669}
670
671pub fn try_run_hot_runtime(
673 runtime: &JitRuntime,
674 chunk: &Chunk,
675 key: TraceKey,
676 slots: &mut [i64],
677 budget: u32,
678 register_count: u8,
679 metrics: Option<&crate::scheduler::RuntimeMetrics>,
680) -> Option<ExitReason> {
681 try_run_hot_runtime_tagged(
682 runtime,
683 chunk,
684 key,
685 &mut HotCall {
686 slots,
687 budget,
688 register_count,
689 metrics,
690 tags: EntryTags::INT,
691 },
692 )
693 .and_then(|(ret, _, unwind)| {
694 if unwind.is_some() {
695 None
696 } else {
697 Some(ret.into_reason())
698 }
699 })
700}
701
702fn try_run_hot_runtime_tagged(
703 runtime: &JitRuntime,
704 chunk: &Chunk,
705 key: TraceKey,
706 call: &mut HotCall<'_>,
707) -> Option<(JitReturn, u32, Option<JitUnwind>)> {
708 if runtime.is_failed(&key) {
709 return None;
710 }
711
712 if let Some(copy) = runtime.get_trace(&key) {
713 if let Some(m) = call.metrics {
714 crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
715 }
716 return Some(run_compiled_trace_with_tags(
717 copy.entry,
718 call.slots,
719 key.entry_pc,
720 call.budget,
721 key.function,
722 u32::from(call.register_count),
723 call.tags,
724 ));
725 }
726
727 if !runtime.record_hot_hit(key) {
728 if let Some(m) = call.metrics {
729 crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
730 }
731 return None;
732 }
733
734 if runtime.get_trace(&key).is_some() {
736 return try_run_hot_runtime_tagged(runtime, chunk, key, call);
737 }
738
739 let compiled =
740 match with_jit_module(|module| TraceCompiler::new(module).compile_trace(chunk, key)) {
741 Ok(trace) => trace,
742 Err(_) => {
743 runtime.mark_failed(key);
744 if let Some(m) = call.metrics {
745 crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
746 }
747 return None;
748 }
749 };
750
751 runtime.insert_trace(key, compiled);
752 if let Some(m) = call.metrics {
753 crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
754 }
755
756 try_run_hot_runtime_tagged(runtime, chunk, key, call)
757}
758
759fn tag_bit(words: &[u64; 4], reg: usize) -> bool {
760 if reg >= 256 {
761 return false;
762 }
763 words[reg / 64] & (1u64 << (reg % 64)) != 0
764}
765
766fn sync_slots_tagged(vm: &mut Vm, slots: &[i64], ret: &JitReturn) -> Result<(), Fault> {
770 let Some(regs) = vm.top_registers_mut() else {
771 return Err(Fault::Invariant("empty frame stack while syncing slots"));
772 };
773 for (index, reg) in regs.iter_mut().enumerate() {
774 if !tag_bit(&ret.written, index) {
775 continue;
776 }
777 let Some(slot) = slots.get(index).copied() else {
778 continue;
779 };
780 *reg = if tag_bit(&ret.as_unit, index) {
781 Value::Unit
782 } else if tag_bit(&ret.as_bool, index) {
783 Value::Bool(slot != 0)
784 } else if tag_bit(&ret.as_float, index) {
785 Value::Float(f64::from_bits(slot as u64))
786 } else {
787 Value::Int(slot)
788 };
789 }
790 Ok(())
791}
792
793fn apply_exit_tagged(
794 vm: &mut Vm,
795 slots: &[i64],
796 ret: JitReturn,
797) -> Result<Option<VmResult>, Fault> {
798 match ret.kind {
799 super::exit::JIT_RETURN => {
800 sync_slots_tagged(vm, slots, &ret)?;
801 let return_reg = ret.return_reg as u8;
802 let value = match vm
803 .top_registers()
804 .and_then(|regs| regs.get(usize::from(return_reg)))
805 {
806 Some(v) => v.clone(),
807 None => {
808 let frame_size = match vm.current_num_registers() {
809 Some(n) => n as u8,
810 None => 0,
811 };
812 return Err(Fault::RegisterOutOfRange {
813 reg: return_reg,
814 frame_size,
815 });
816 }
817 };
818 let pc = vm
819 .current_pc()
820 .ok_or(Fault::Invariant("empty frame stack while running"))?;
821 vm.set_pc(pc.saturating_add(1));
822 vm.return_value(value)
823 }
824 super::exit::JIT_TRAP => {
825 vm.set_pc(ret.pc as usize);
826 Ok(Some(VmResult::Trap(Fault::DivideByZero)))
827 }
828 super::exit::JIT_BUDGET => {
829 vm.set_pc(ret.pc as usize);
830 sync_slots_tagged(vm, slots, &ret)?;
831 Ok(None)
832 }
833 super::exit::JIT_CONTINUE | super::exit::JIT_EFFECT => {
834 vm.set_pc(ret.pc as usize);
835 sync_slots_tagged(vm, slots, &ret)?;
836 Ok(None)
837 }
838 _ => {
839 vm.set_pc(ret.pc as usize);
840 Ok(None)
841 }
842 }
843}
844
845pub fn apply_exit_to_vm(
848 vm: &mut Vm,
849 slots: &[i64],
850 exit: ExitReason,
851) -> Result<Option<VmResult>, Fault> {
852 match exit {
853 ExitReason::Return { return_reg } => {
854 let Some(bits) = slots.get(usize::from(return_reg)).copied() else {
855 return Err(Fault::RegisterOutOfRange {
856 reg: return_reg,
857 frame_size: u8::try_from(slots.len()).unwrap_or(u8::MAX),
858 });
859 };
860 let value = Value::Int(bits);
861 vm.set_register(return_reg, value.clone())?;
862 let pc = vm
863 .current_pc()
864 .ok_or(Fault::Invariant("empty frame stack while running"))?;
865 vm.set_pc(pc.saturating_add(1));
866 vm.return_value(value)
867 }
868 ExitReason::Trap { pc } => {
869 vm.set_pc(pc as usize);
870 Ok(Some(VmResult::Trap(Fault::DivideByZero)))
871 }
872 ExitReason::Budget { pc } => {
873 vm.set_pc(pc as usize);
874 sync_slots_to_vm(vm, slots)?;
875 Ok(None)
876 }
877 ExitReason::Continue { pc } | ExitReason::Effect { pc } | ExitReason::Deopt { pc } => {
878 vm.set_pc(pc as usize);
879 if matches!(
880 exit,
881 ExitReason::Continue { .. } | ExitReason::Effect { .. }
882 ) {
883 sync_slots_to_vm(vm, slots)?;
884 }
885 Ok(None)
886 }
887 }
888}
889
890pub fn sync_slots_from_vm(vm: &Vm, slots: &mut [i64]) -> SyncSlotsResult {
892 let Some(regs) = vm.top_registers() else {
893 return SyncSlotsResult::Unavailable;
894 };
895 let mut saw_float = false;
896 let mut saw_int = false;
897 for value in regs.iter().take(slots.len()) {
898 match value {
899 Value::Int(_) => saw_int = true,
900 Value::Float(_) => saw_float = true,
901 Value::Bool(_) | Value::Unit => {}
902 _ => return SyncSlotsResult::Deopt,
903 }
904 }
905 if saw_int && saw_float {
906 return SyncSlotsResult::Deopt;
907 }
908 for (slot, value) in slots.iter_mut().zip(regs.iter()) {
909 *slot = match value {
910 Value::Int(i) => *i,
911 Value::Bool(b) => i64::from(*b),
912 Value::Unit => 0,
913 Value::Float(n) => n.to_bits() as i64,
914 _ => 0,
915 };
916 }
917 if saw_float {
918 SyncSlotsResult::Float
919 } else {
920 SyncSlotsResult::Ok
921 }
922}
923
924pub fn sync_slots_to_vm(vm: &mut Vm, slots: &[i64]) -> Result<(), Fault> {
926 let Some(regs) = vm.top_registers_mut() else {
927 return Err(Fault::Invariant("empty frame stack while syncing slots"));
928 };
929 for (reg, slot) in regs.iter_mut().zip(slots.iter()) {
930 *reg = Value::Int(*slot);
931 }
932 Ok(())
933}
934
935pub const fn hot_threshold() -> u32 {
937 HOT_THRESHOLD
938}
939
940pub fn force_compile(
942 ctx: &mut JitContext,
943 chunk: &Chunk,
944 key: TraceKey,
945) -> Result<(), super::error::CompileError> {
946 if ctx.cache.get(&key).is_none() {
947 let mut compiler = TraceCompiler::new(ctx.module_mut());
948 let compiled = compiler.compile_trace(chunk, key)?;
949 ctx.cache.insert(key, compiled);
950 }
951 Ok(())
952}
953
954#[cfg(test)]
955mod tests {
956 use std::sync::Arc;
957
958 use crate::{
959 bytecode::builder::ChunkBuilder, FlowOutcome, NativeTable, Opcode, Runtime, Value, Vm,
960 VmResult,
961 };
962
963 use super::*;
964 use crate::jit::trace::{JitContext, TraceKey};
965
966 type TestResult = Result<(), Box<dyn std::error::Error>>;
967
968 fn add_chunk() -> std::sync::Arc<crate::Chunk> {
969 let mut b = ChunkBuilder::new("jit-add");
970 b.begin_function("main", 0, 3);
971 b.emit_load_imm(0, 41);
972 b.emit_load_imm(1, 1);
973 b.emit_binop(Opcode::Add, 2, 0, 1);
974 b.emit_return(2);
975 Arc::new(b.finish())
976 }
977
978 #[test]
979 fn run_vm_with_jit_completes_scalar_add() -> TestResult {
980 let chunk = add_chunk();
981 let mut ctx = JitContext::new(chunk.clone())?;
982 let key = TraceKey {
983 function: 0,
984 entry_pc: 0,
985
986 floats: false,
987 };
988 force_compile(&mut ctx, &chunk, key)?;
989
990 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
991 let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
992 assert!(matches!(result, VmResult::Complete(Value::Int(42))));
993 Ok(())
994 }
995
996 #[test]
997 fn native_trace_computes_42() -> TestResult {
998 let chunk = add_chunk();
999 let mut ctx = JitContext::new(chunk.clone())?;
1000 let key = TraceKey {
1001 function: 0,
1002 entry_pc: 0,
1003
1004 floats: false,
1005 };
1006 force_compile(&mut ctx, &chunk, key)?;
1007 let trace = ctx
1008 .cache
1009 .get(&key)
1010 .ok_or("trace missing after force_compile")?;
1011 let mut slots = vec![0i64; 3];
1012 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
1013 let exit = ret.into_reason();
1014 assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
1015 assert_eq!(slots[2], 42);
1016 Ok(())
1017 }
1018
1019 #[test]
1020 fn mul_imm_eq_imm_and_shifts_match_the_interpreter() -> TestResult {
1021 let mut b = ChunkBuilder::new("jit-bits");
1022 b.begin_function("main", 0, 4);
1023 b.emit_load_imm(0, 6);
1024 b.emit_mul_imm(1, 0, 7);
1025 b.emit_load_imm(2, 1);
1026 b.emit_bit_binop(Opcode::Shl, 3, 1, 2);
1027 b.emit_bit_binop(Opcode::Shr, 1, 3, 2);
1028 b.emit_return(1);
1029 let chunk = Arc::new(b.finish());
1030 let mut interpreted = Vm::new(chunk.clone(), NativeTable::empty(), 0, &[])?;
1031 assert!(matches!(
1032 interpreted.run(20),
1033 VmResult::Complete(Value::Int(42))
1034 ));
1035 let mut ctx = JitContext::new(chunk.clone())?;
1036 let key = TraceKey {
1037 function: 0,
1038 entry_pc: 0,
1039 floats: false,
1040 };
1041 force_compile(&mut ctx, &chunk, key)?;
1042 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1043 let result = run_vm_with_jit(&mut vm, 20, &mut ctx);
1044 assert!(matches!(result, VmResult::Complete(Value::Int(42))));
1045
1046 let mut b = ChunkBuilder::new("jit-eq-imm");
1047 b.begin_function("main", 0, 2);
1048 b.emit_load_imm(0, 42);
1049 b.emit_eq_imm(1, 0, 42);
1050 b.emit_le_imm(0, 0, 41);
1051 b.emit_return(1);
1052 let chunk = Arc::new(b.finish());
1053 let mut interpreted = Vm::new(chunk.clone(), NativeTable::empty(), 0, &[])?;
1054 assert!(matches!(
1055 interpreted.run(20),
1056 VmResult::Complete(Value::Bool(true))
1057 ));
1058 let mut ctx = JitContext::new(chunk.clone())?;
1059 let eq_key = TraceKey {
1060 function: 0,
1061 entry_pc: 0,
1062 floats: false,
1063 };
1064 force_compile(&mut ctx, &chunk, eq_key)?;
1065 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1066 let result = run_vm_with_jit(&mut vm, 20, &mut ctx);
1067 assert!(matches!(result, VmResult::Complete(Value::Bool(true))));
1068 Ok(())
1069 }
1070
1071 #[test]
1072 fn jit_matches_interpreter_on_scalar_add() -> TestResult {
1073 let chunk = add_chunk();
1074 let rt = Runtime::new((*chunk).clone())?;
1075 let interp = rt.spawn(0, &[])?.join();
1076 rt.shutdown();
1077 assert!(matches!(interp, FlowOutcome::Completed(Value::Int(42))));
1078
1079 let mut ctx = JitContext::new(chunk.clone())?;
1080 let key = TraceKey {
1081 function: 0,
1082 entry_pc: 0,
1083
1084 floats: false,
1085 };
1086 let mut slots = vec![0i64; 3];
1087 force_compile(&mut ctx, &chunk, key)?;
1088 let trace = ctx
1089 .cache
1090 .get(&key)
1091 .ok_or("trace missing after force_compile")?;
1092 let exit = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3).into_reason();
1093 assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
1094 assert_eq!(slots[2], 42);
1095
1096 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1097 if let Some(result) = apply_exit_to_vm(&mut vm, &slots, exit)? {
1098 assert!(matches!(result, VmResult::Complete(Value::Int(42))));
1099 } else {
1100 return Err("expected Completed(42)".into());
1101 }
1102 Ok(())
1103 }
1104
1105 #[test]
1106 fn div_by_zero_returns_trap_exit() -> TestResult {
1107 let mut b = ChunkBuilder::new("jit-div0");
1108 b.begin_function("main", 0, 3);
1109 b.emit_load_imm(0, 1);
1110 b.emit_load_imm(1, 0);
1111 b.emit_binop(Opcode::Div, 2, 0, 1);
1112 b.emit_return(2);
1113 let chunk = Arc::new(b.finish());
1114
1115 let mut ctx = JitContext::new(chunk.clone())?;
1116 let key = TraceKey {
1117 function: 0,
1118 entry_pc: 0,
1119
1120 floats: false,
1121 };
1122 force_compile(&mut ctx, &chunk, key)?;
1123 let trace = ctx
1124 .cache
1125 .get(&key)
1126 .ok_or("trace missing after force_compile")?;
1127 let mut slots = vec![0i64; 3];
1128 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
1129 assert!(matches!(ret.into_reason(), ExitReason::Trap { .. }));
1130 Ok(())
1131 }
1132
1133 #[test]
1134 fn div_and_mod_of_i64_min_wrap_instead_of_aborting() -> TestResult {
1135 let mut b = ChunkBuilder::new("jit-div-overflow");
1136 b.begin_function("div", 0, 3);
1137 let min = b.const_(Value::Int(i64::MIN));
1138 let neg = b.const_(Value::Int(-1));
1139 b.emit_load_const(0, min);
1140 b.emit_load_const(1, neg);
1141 b.emit_binop(Opcode::Div, 2, 0, 1);
1142 b.emit_return(2);
1143 let rem = b.begin_function("rem", 0, 3);
1144 let min = b.const_(Value::Int(i64::MIN));
1145 let neg = b.const_(Value::Int(-1));
1146 b.emit_load_const(0, min);
1147 b.emit_load_const(1, neg);
1148 b.emit_binop(Opcode::Mod, 2, 0, 1);
1149 b.emit_return(2);
1150 let chunk = Arc::new(b.finish());
1151 let mut ctx = JitContext::new(chunk.clone())?;
1152
1153 for (function, expect) in [(0, i64::MIN), (rem, 0)] {
1154 let entry = chunk.functions[function as usize].entry;
1155 force_compile(
1156 &mut ctx,
1157 &chunk,
1158 TraceKey {
1159 function,
1160 entry_pc: entry,
1161
1162 floats: false,
1163 },
1164 )?;
1165 let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, &[])?;
1166 let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1167 match result {
1168 VmResult::Complete(Value::Int(n)) if n == expect => {}
1169 other => {
1170 return Err(format!("function {function} finished as {other:?}").into());
1171 }
1172 }
1173 }
1174 Ok(())
1175 }
1176
1177 #[test]
1178 fn sync_slots_accepts_a_float_register() -> TestResult {
1179 let chunk = add_chunk();
1180 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1181 vm.set_register(0, Value::Float(1.0))?;
1182 let mut slots = vec![0i64; 3];
1183 assert_eq!(sync_slots_from_vm(&vm, &mut slots), SyncSlotsResult::Float);
1184 assert_eq!(f64::from_bits(slots[0] as u64), 1.0);
1185 Ok(())
1186 }
1187
1188 #[test]
1189 fn float_trace_matches_the_interpreter() -> TestResult {
1190 let mut b = ChunkBuilder::new("jit-float");
1191 let zero = b.const_(Value::Float(0.0));
1192 let one = b.const_(Value::Float(1.0));
1193 let limit = b.const_(Value::Float(4.0));
1194 b.begin_function("main", 0, 4);
1195 b.emit_load_const(0, zero);
1196 b.emit_load_const(1, one);
1197 b.emit_load_const(2, limit);
1198 let head = b.new_label();
1199 let done = b.new_label();
1200 b.bind_label(head);
1201 b.emit_binop(Opcode::Add, 0, 0, 1);
1202 b.emit_binop(Opcode::Lt, 3, 0, 2);
1203 b.emit_branch(3, done);
1204 b.emit_jump(head);
1205 b.bind_label(done);
1206 b.emit_return(0);
1207 let chunk = Arc::new(b.finish());
1208 let mut plain = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
1209 let interpreted = plain.run(100);
1210 let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1211 ctx.hot_threshold = 1;
1212 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1213 let compiled = run_vm_with_jit(&mut vm, 100, &mut ctx);
1214 if !ctx.cache.has_float_trace() {
1215 return Err("float add loop was not compiled".into());
1216 }
1217 match (interpreted, compiled) {
1218 (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1219 if a == b && a == 4.0 =>
1220 {
1221 Ok(())
1222 }
1223 (left, right) => Err(format!("float trace {right:?} interpreter {left:?}").into()),
1224 }
1225 }
1226
1227 fn run_float_chunk(
1228 chunk: Arc<Chunk>,
1229 budget: u32,
1230 ) -> Result<(VmResult, VmResult, JitContext), Box<dyn std::error::Error>> {
1231 let mut plain = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
1232 let interpreted = plain.run(budget);
1233 let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1234 ctx.hot_threshold = 1;
1235 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1236 let compiled = run_vm_with_jit(&mut vm, budget, &mut ctx);
1237 Ok((interpreted, compiled, ctx))
1238 }
1239
1240 #[test]
1241 fn float_trace_edges_match_the_interpreter() -> TestResult {
1242 let mut nan_lt = ChunkBuilder::new("jit-nan-lt");
1243 let nan = nan_lt.const_(Value::Float(f64::NAN));
1244 let zero = nan_lt.const_(Value::Float(0.0));
1245 nan_lt.begin_function("main", 0, 3);
1246 nan_lt.emit_load_const(0, nan);
1247 nan_lt.emit_load_const(1, zero);
1248 let head = nan_lt.new_label();
1249 nan_lt.bind_label(head);
1250 nan_lt.emit_binop(Opcode::Lt, 2, 0, 1);
1251 nan_lt.emit_return(2);
1252 let nan_chunk = Arc::new(nan_lt.finish());
1253 let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&nan_chunk), 20)?;
1254 if !ctx.cache.has_float_trace() {
1255 return Err("NaN comparison was not compiled".into());
1256 }
1257 match (interpreted, compiled) {
1258 (VmResult::Complete(Value::Bool(false)), VmResult::Complete(Value::Bool(false))) => {}
1259 (left, right) => {
1260 return Err(format!("nan lt {right:?} interpreter {left:?}").into());
1261 }
1262 }
1263
1264 let mut inf_add = ChunkBuilder::new("jit-inf-add");
1265 let pos = inf_add.const_(Value::Float(f64::INFINITY));
1266 let neg = inf_add.const_(Value::Float(f64::NEG_INFINITY));
1267 inf_add.begin_function("main", 0, 3);
1268 inf_add.emit_load_const(0, pos);
1269 inf_add.emit_load_const(1, neg);
1270 let head = inf_add.new_label();
1271 inf_add.bind_label(head);
1272 inf_add.emit_binop(Opcode::Add, 2, 0, 1);
1273 inf_add.emit_return(2);
1274 let inf_chunk = Arc::new(inf_add.finish());
1275 let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&inf_chunk), 20)?;
1276 if !ctx.cache.has_float_trace() {
1277 return Err("infinity add was not compiled".into());
1278 }
1279 match (interpreted, compiled) {
1280 (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1281 if a.is_nan() && b.is_nan() => {}
1282 (left, right) => {
1283 return Err(format!("inf add {right:?} interpreter {left:?}").into());
1284 }
1285 }
1286
1287 let mut zeros = ChunkBuilder::new("jit-signed-zero");
1288 let neg_zero = zeros.const_(Value::Float(-0.0));
1289 zeros.begin_function("main", 0, 1);
1290 zeros.emit_load_const(0, neg_zero);
1291 let head = zeros.new_label();
1292 zeros.bind_label(head);
1293 zeros.emit_add_imm(0, 0, 0);
1294 zeros.emit_return(0);
1295 let zero_chunk = Arc::new(zeros.finish());
1296 let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&zero_chunk), 20)?;
1297 if !ctx.cache.has_float_trace() {
1298 return Err("signed-zero add was not compiled".into());
1299 }
1300 match (interpreted, compiled) {
1301 (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1302 if a.to_bits() == 0.0f64.to_bits() && b.to_bits() == 0.0f64.to_bits() => {}
1303 (left, right) => {
1304 return Err(format!("signed zero {right:?} interpreter {left:?}").into());
1305 }
1306 }
1307
1308 let mut countdown = ChunkBuilder::new("jit-sub-imm");
1309 let start = countdown.const_(Value::Float(4.0));
1310 countdown.begin_function("main", 0, 2);
1311 countdown.emit_load_const(0, start);
1312 let head = countdown.new_label();
1313 let body = countdown.new_label();
1314 let done = countdown.new_label();
1315 countdown.bind_label(head);
1316 countdown.emit_lt_imm(1, 0, 1);
1317 countdown.emit_branch(1, body);
1318 countdown.emit_jump(done);
1319 countdown.bind_label(body);
1320 countdown.emit_sub_imm(0, 0, 1);
1321 countdown.emit_jump(head);
1322 countdown.bind_label(done);
1323 countdown.emit_return(0);
1324 let sub_chunk = Arc::new(countdown.finish());
1325 let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&sub_chunk), 40)?;
1326 if !ctx.cache.has_float_trace() {
1327 return Err("float SubImm loop was not compiled".into());
1328 }
1329 match (interpreted, compiled) {
1330 (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1331 if a == 0.0 && b == 0.0 =>
1332 {
1333 Ok(())
1334 }
1335 (left, right) => Err(format!("sub imm {right:?} interpreter {left:?}").into()),
1336 }
1337 }
1338
1339 #[test]
1340 fn runtime_path_compiles_and_runs() -> TestResult {
1341 let chunk = add_chunk();
1342 let runtime = JitRuntime::new(chunk.clone(), 1);
1343 let key = TraceKey {
1344 function: 0,
1345 entry_pc: 0,
1346
1347 floats: false,
1348 };
1349 let mut slots = vec![0i64; 3];
1350 let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
1351 .ok_or("expected jit execution")?;
1352 assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
1353 assert_eq!(slots[2], 42);
1354 Ok(())
1355 }
1356
1357 #[test]
1358 fn budget_exit_when_exhausted_mid_trace() -> TestResult {
1359 let mut b = ChunkBuilder::new("jit-budget");
1360 b.begin_function("main", 0, 1);
1361 b.emit_load_imm(0, 1);
1362 b.emit_load_imm(0, 2);
1363 b.emit_load_imm(0, 3);
1364 b.emit_return(0);
1365 let chunk = Arc::new(b.finish());
1366
1367 let mut ctx = JitContext::new(chunk.clone())?;
1368 let key = TraceKey {
1369 function: 0,
1370 entry_pc: 0,
1371
1372 floats: false,
1373 };
1374 force_compile(&mut ctx, &chunk, key)?;
1375 let trace = ctx
1376 .cache
1377 .get(&key)
1378 .ok_or("trace missing after force_compile")?;
1379 let mut slots = vec![0i64; 1];
1380 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 2, 0, 1);
1381 assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 2 }));
1382 Ok(())
1383 }
1384
1385 #[test]
1386 fn explicit_yield_stops_the_quantum() -> TestResult {
1387 let mut b = ChunkBuilder::new("jit-yield");
1388 b.begin_function("main", 0, 1);
1389 b.emit_load_imm(0, 1);
1390 b.emit_yield();
1391 b.emit_load_imm(0, 2);
1392 b.emit_return(0);
1393 let chunk = Arc::new(b.finish());
1394
1395 let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1396 ctx.hot_threshold = u32::MAX;
1397 let mut vm = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
1398 let first = run_vm_with_jit(&mut vm, 100, &mut ctx);
1399 if !matches!(first, VmResult::Yield) {
1400 return Err(format!("yield was swallowed, got {first:?}").into());
1401 }
1402 match vm.top_registers().and_then(|regs| regs.first().cloned()) {
1403 Some(Value::Int(1)) => {}
1404 other => return Err(format!("register after yield is {other:?}").into()),
1405 }
1406 let second = run_vm_with_jit(&mut vm, 100, &mut ctx);
1407 if !matches!(second, VmResult::Complete(Value::Int(2))) {
1408 return Err(format!("resume after yield finished as {second:?}").into());
1409 }
1410
1411 force_compile(
1412 &mut ctx,
1413 &chunk,
1414 TraceKey {
1415 function: 0,
1416 entry_pc: 0,
1417 floats: false,
1418 },
1419 )?;
1420 let mut compiled = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1421 let stopped = run_vm_with_jit(&mut compiled, 100, &mut ctx);
1422 if !matches!(stopped, VmResult::Yield) {
1423 return Err(format!("compiled prefix ran through yield, got {stopped:?}").into());
1424 }
1425 match compiled
1426 .top_registers()
1427 .and_then(|regs| regs.first().cloned())
1428 {
1429 Some(Value::Int(1)) => Ok(()),
1430 other => Err(format!("compiled prefix left {other:?}").into()),
1431 }
1432 }
1433
1434 #[test]
1435 fn budget_end_still_runs_the_rest_of_the_quantum() -> TestResult {
1436 let mut b = ChunkBuilder::new("jit-budget-step");
1437 b.begin_function("main", 0, 1);
1438 b.emit_load_imm(0, 1);
1439 b.emit_load_imm(0, 2);
1440 b.emit_load_imm(0, 3);
1441 b.emit_return(0);
1442 let chunk = Arc::new(b.finish());
1443 let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1444 ctx.hot_threshold = u32::MAX;
1445 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1446 let result = run_vm_with_jit(&mut vm, 2, &mut ctx);
1447 if !matches!(result, VmResult::Yield) {
1448 return Err(format!("budget 2 finished as {result:?}").into());
1449 }
1450 if vm.instructions_executed() != 2 {
1451 return Err(format!("ran {} instructions", vm.instructions_executed()).into());
1452 }
1453 match vm.top_registers().and_then(|regs| regs.first().cloned()) {
1454 Some(Value::Int(2)) => Ok(()),
1455 other => Err(format!("expected the second load, got {other:?}").into()),
1456 }
1457 }
1458
1459 #[test]
1460 fn compiled_trace_counts_the_instructions_it_ran() -> TestResult {
1461 let mut b = ChunkBuilder::new("jit-count");
1462 b.begin_function("main", 0, 1);
1463 b.emit_load_imm(0, 1);
1464 b.emit_load_imm(0, 2);
1465 b.emit_load_imm(0, 3);
1466 b.emit_return(0);
1467 let chunk = Arc::new(b.finish());
1468 let mut ctx = JitContext::new(chunk.clone())?;
1469 force_compile(
1470 &mut ctx,
1471 &chunk,
1472 TraceKey {
1473 function: 0,
1474 entry_pc: 0,
1475 floats: false,
1476 },
1477 )?;
1478 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1479 let result = run_vm_with_jit(&mut vm, 10, &mut ctx);
1480 assert!(matches!(result, VmResult::Complete(Value::Int(3))));
1481 assert_eq!(vm.instructions_executed(), 4);
1482 Ok(())
1483 }
1484
1485 #[test]
1486 fn interleaved_jit_compiles_mid_quantum() -> TestResult {
1487 let mut b = ChunkBuilder::new("jit-interleave");
1488 b.begin_function("main", 0, 2);
1489 b.emit_load_imm(0, 0);
1490 let head = b.new_label();
1491 b.bind_label(head);
1492 b.emit_load_imm(1, 1);
1493 b.emit_binop(Opcode::Add, 0, 0, 1);
1494 b.emit_load_imm(1, 100);
1495 b.emit_binop(Opcode::Lt, 1, 0, 1);
1496 let done = b.new_label();
1497 b.emit_branch(1, done);
1498 b.emit_jump(head);
1499 b.bind_label(done);
1500 b.emit_return(0);
1501 let chunk = Arc::new(b.finish());
1502 let head_pc = chunk.functions[0].entry + 1;
1503
1504 let mut ctx = JitContext::new(chunk.clone())?;
1505 ctx.hot_threshold = 2;
1506 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1507 let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1508 assert!(matches!(result, VmResult::Complete(Value::Int(100))));
1509 assert!(ctx
1510 .cache
1511 .get(&TraceKey {
1512 function: 0,
1513 entry_pc: head_pc,
1514
1515 floats: false,
1516 })
1517 .is_some());
1518 Ok(())
1519 }
1520
1521 #[test]
1522 fn reload_chunk_invalidates_jit_cache() -> TestResult {
1523 let chunk = add_chunk();
1524 let runtime = JitRuntime::new(chunk.clone(), 1);
1525 let key = TraceKey {
1526 function: 0,
1527 entry_pc: 0,
1528
1529 floats: false,
1530 };
1531 let mut slots = vec![0i64; 3];
1532 let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
1533 .ok_or("expected jit execution")?;
1534 assert!(matches!(exit, ExitReason::Return { .. }));
1535
1536 let mut b = ChunkBuilder::new("other");
1537 b.begin_function("main", 0, 1);
1538 b.emit_load_imm(0, 1);
1539 b.emit_return(0);
1540 runtime.reload(Arc::new(b.finish()));
1541 assert!(runtime.get_trace(&key).is_none());
1542 Ok(())
1543 }
1544
1545 #[test]
1548 fn budget_exit_publishes_assigned_regs_and_keeps_unit() -> TestResult {
1549 let mut b = ChunkBuilder::new("jit-budget");
1550 b.begin_function("main", 0, 2);
1551 b.emit_load_imm(0, 41);
1552 b.emit_load_imm(1, 1);
1553 b.emit_return(0);
1554 let chunk = Arc::new(b.finish());
1555 let mut ctx = JitContext::new(chunk.clone())?;
1556 let key = TraceKey {
1557 function: 0,
1558 entry_pc: 0,
1559
1560 floats: false,
1561 };
1562 force_compile(&mut ctx, &chunk, key)?;
1563 let trace = ctx
1564 .cache
1565 .get(&key)
1566 .ok_or("trace missing after force_compile")?;
1567 let mut slots = vec![0i64; 2];
1568 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 1, 0, 2);
1569 assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 1 }));
1570 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1571 apply_exit_tagged(&mut vm, &slots, ret)?;
1572 let regs = vm.top_registers().ok_or("no frame")?;
1573 assert!(matches!(regs.first(), Some(&Value::Int(41))));
1574 assert!(matches!(regs.get(1), Some(&Value::Unit)));
1575 Ok(())
1576 }
1577
1578 #[test]
1579 fn jit_call_does_not_clobber_the_caller_frame() -> TestResult {
1580 let mut b = ChunkBuilder::new("jit-call-frames");
1581 b.begin_function("callee", 0, 3);
1582 b.emit_load_imm(2, 99);
1583 b.emit_load_imm(0, 1);
1584 b.emit_return(0);
1585 let main = b.begin_function("main", 0, 3);
1586 b.emit_load_imm(2, 7);
1587 b.emit_call(0, 0, 0);
1588 b.emit_return(2);
1589 let chunk = Arc::new(b.finish());
1590 let mut ctx = JitContext::new(chunk.clone())?;
1591 let entry = chunk.functions[main as usize].entry;
1592 force_compile(
1593 &mut ctx,
1594 &chunk,
1595 TraceKey {
1596 function: main,
1597 entry_pc: entry,
1598
1599 floats: false,
1600 },
1601 )?;
1602 let mut vm = Vm::new(chunk, NativeTable::empty(), main, &[])?;
1603 let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1604 assert!(matches!(result, VmResult::Complete(Value::Int(7))));
1605 Ok(())
1606 }
1607
1608 #[test]
1609 fn move_keeps_bool_unit_and_a_later_int() -> TestResult {
1610 let mut b = ChunkBuilder::new("jit-move-tags");
1611 b.begin_function("cmp", 0, 4);
1612 b.emit_load_imm(0, 1);
1613 b.emit_load_imm(1, 1);
1614 b.emit_binop(Opcode::Eq, 2, 0, 1);
1615 b.emit_move(3, 2);
1616 b.emit_return(3);
1617 let moved_bool = b.begin_function("moved-bool", 1, 2);
1618 b.emit_move(1, 0);
1619 b.emit_return(1);
1620 let moved_false = b.begin_function("moved-false", 1, 2);
1621 b.emit_move(1, 0);
1622 b.emit_return(1);
1623 let moved_unit = b.begin_function("moved-unit", 0, 2);
1624 b.emit_move(1, 0);
1625 b.emit_return(1);
1626 let overwritten = b.begin_function("overwritten", 1, 2);
1627 b.emit_load_imm(0, 5);
1628 let cont = b.new_label();
1629 b.emit_jump(cont);
1630 b.bind_label(cont);
1631 b.emit_move(1, 0);
1632 b.emit_return(1);
1633 let chunk = Arc::new(b.finish());
1634 let mut ctx = JitContext::new(chunk.clone())?;
1635
1636 let run = |ctx: &mut JitContext, function: u32, args: &[Value]| -> TestResult {
1637 let entry = chunk.functions[function as usize].entry;
1638 force_compile(
1639 ctx,
1640 &chunk,
1641 TraceKey {
1642 function,
1643 entry_pc: entry,
1644
1645 floats: false,
1646 },
1647 )?;
1648 let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
1649 let result = run_vm_with_jit(&mut vm, 10_000, ctx);
1650 match (function, result) {
1651 (_, VmResult::Complete(Value::Bool(true))) if function == 0 => Ok(()),
1652 (_, VmResult::Complete(Value::Bool(true))) if function == moved_bool => Ok(()),
1653 (_, VmResult::Complete(Value::Bool(false))) if function == moved_false => Ok(()),
1654 (_, VmResult::Complete(Value::Unit)) if function == moved_unit => Ok(()),
1655 (_, VmResult::Complete(Value::Int(5))) if function == overwritten => Ok(()),
1656 (_, other) => Err(format!("function {function} finished as {other:?}").into()),
1657 }
1658 };
1659
1660 run(&mut ctx, 0, &[])?;
1661 run(&mut ctx, moved_bool, &[Value::Bool(true)])?;
1662 run(&mut ctx, moved_false, &[Value::Bool(false)])?;
1663 run(&mut ctx, moved_unit, &[])?;
1664 run(&mut ctx, overwritten, &[Value::Bool(true)])?;
1665 Ok(())
1666 }
1667
1668 #[test]
1669 fn leaf_call_stays_in_the_trace() -> TestResult {
1670 let mut b = ChunkBuilder::new("jit-call");
1671 let add1 = b.begin_function("add1", 1, 2);
1672 b.emit_load_imm(1, 1);
1673 b.emit_binop(Opcode::Add, 0, 0, 1);
1674 b.emit_return(0);
1675 let main = b.begin_function("main", 0, 1);
1676 b.emit_load_imm(0, 41);
1677 b.emit_call(0, add1, 1);
1678 b.emit_return(0);
1679 let chunk = Arc::new(b.finish());
1680 let mut ctx = JitContext::new(chunk.clone())?;
1681 let entry = chunk.functions[main as usize].entry;
1682 let key = TraceKey {
1683 function: main,
1684 entry_pc: entry,
1685
1686 floats: false,
1687 };
1688 force_compile(&mut ctx, &chunk, key)?;
1689 let trace = ctx
1690 .cache
1691 .get(&key)
1692 .ok_or("trace missing after force_compile")?;
1693 let mut slots = vec![0i64; 2];
1694 let exit = run_compiled_trace_ref(trace, &mut slots, entry, 10_000, main, 1).into_reason();
1695 match exit {
1696 ExitReason::Return { return_reg: 0 } => {}
1697 other => return Err(format!("call left the trace: {other:?}").into()),
1698 }
1699 if slots[0] != 42 {
1700 return Err(format!("leaf call produced {}", slots[0]).into());
1701 }
1702 Ok(())
1703 }
1704
1705 #[test]
1706 fn leaf_call_keeps_bool_unit_and_a_high_dest() -> TestResult {
1707 let mut b = ChunkBuilder::new("jit-call-tags");
1708 let is_true = b.begin_function("is-true", 0, 2);
1709 b.emit_load_imm(0, 1);
1710 b.emit_load_imm(1, 1);
1711 b.emit_binop(Opcode::Eq, 0, 0, 1);
1712 b.emit_return(0);
1713 let blank = b.begin_function("blank", 0, 1);
1714 b.emit_return(0);
1715 let moved = b.begin_function("moved", 1, 2);
1716 b.emit_move(1, 0);
1717 b.emit_return(1);
1718 let add1 = b.begin_function("add1", 1, 2);
1719 b.emit_load_imm(1, 1);
1720 b.emit_binop(Opcode::Add, 0, 0, 1);
1721 b.emit_return(0);
1722
1723 let main_bool = b.begin_function("main-bool", 0, 1);
1724 b.emit_call(0, is_true, 0);
1725 b.emit_return(0);
1726 let main_unit = b.begin_function("main-unit", 0, 1);
1727 b.emit_load_imm(0, 9);
1728 b.emit_call(0, blank, 0);
1729 b.emit_return(0);
1730 let main_moved = b.begin_function("main-moved", 1, 1);
1731 b.emit_call(0, moved, 1);
1732 b.emit_return(0);
1733 let main_high = b.begin_function("main-high", 0, 17);
1734 b.emit_load_imm(16, 41);
1735 b.emit_call(16, add1, 1);
1736 b.emit_return(16);
1737 let chunk = Arc::new(b.finish());
1738 let mut ctx = JitContext::new(chunk.clone())?;
1739
1740 let run = |ctx: &mut JitContext,
1741 function: u32,
1742 args: &[Value]|
1743 -> Result<VmResult, Box<dyn std::error::Error>> {
1744 let entry = chunk.functions[function as usize].entry;
1745 force_compile(
1746 ctx,
1747 &chunk,
1748 TraceKey {
1749 function,
1750 entry_pc: entry,
1751
1752 floats: false,
1753 },
1754 )?;
1755 let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
1756 Ok(run_vm_with_jit(&mut vm, 10_000, ctx))
1757 };
1758
1759 match run(&mut ctx, main_bool, &[])? {
1760 VmResult::Complete(Value::Bool(true)) => {}
1761 other => return Err(format!("bool leaf finished as {other:?}").into()),
1762 }
1763 match run(&mut ctx, main_unit, &[])? {
1764 VmResult::Complete(Value::Unit) => {}
1765 other => return Err(format!("unread leaf finished as {other:?}").into()),
1766 }
1767 match run(&mut ctx, main_moved, &[Value::Bool(false)])? {
1768 VmResult::Complete(Value::Bool(false)) => {}
1769 other => return Err(format!("bool arg finished as {other:?}").into()),
1770 }
1771 match run(&mut ctx, main_high, &[])? {
1772 VmResult::Complete(Value::Int(42)) => {}
1773 other => return Err(format!("r16 dest finished as {other:?}").into()),
1774 }
1775 Ok(())
1776 }
1777}