1use std::collections::HashMap;
2use std::ops::Range;
3use std::sync::Arc;
4
5use cranelift_codegen::settings::Configurable;
6
7use crate::Chunk;
8
9use super::frame::JitEntry;
10
11pub const MAX_TRACE_LENGTH: usize = 256;
13
14pub const HOT_THRESHOLD: u32 = 1_000;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub struct TraceKey {
19 pub function: u32,
20 pub entry_pc: u32,
21 pub floats: bool,
24}
25
26#[derive(Debug, Clone)]
27pub struct TraceSpan {
28 pub function: u32,
29 pub range: Range<u32>,
30}
31
32#[derive(Debug)]
33pub struct CompiledTrace {
34 pub span: TraceSpan,
35 pub entry: JitEntry,
36}
37
38pub struct TraceCache {
39 traces: HashMap<TraceKey, CompiledTrace>,
40}
41
42impl TraceCache {
43 pub fn new() -> Self {
44 Self {
45 traces: HashMap::new(),
46 }
47 }
48
49 pub fn get(&self, key: &TraceKey) -> Option<&CompiledTrace> {
50 self.traces.get(key)
51 }
52
53 pub fn insert(&mut self, key: TraceKey, trace: CompiledTrace) {
54 self.traces.insert(key, trace);
55 }
56
57 pub fn clear(&mut self) {
58 self.traces.clear();
59 }
60
61 #[cfg(test)]
62 pub(crate) fn has_float_trace(&self) -> bool {
63 self.traces.keys().any(|key| key.floats)
64 }
65
66 #[cfg(test)]
68 pub(crate) fn float_trace_covers(&self, pc: u32) -> bool {
69 self.traces.iter().any(|(key, trace)| {
70 key.floats && trace.span.function == key.function && trace.span.range.contains(&pc)
71 })
72 }
73}
74
75impl Default for TraceCache {
76 fn default() -> Self {
77 Self::new()
78 }
79}
80
81#[derive(Default)]
82pub struct HotCounter {
83 counters: HashMap<TraceKey, u32>,
84}
85
86impl HotCounter {
87 pub fn hit(&mut self, key: TraceKey, threshold: u32) -> bool {
88 let counter = self.counters.entry(key).or_insert(0);
89 *counter = counter.saturating_add(1);
90 *counter >= threshold
91 }
92
93 pub fn reset(&mut self, key: TraceKey) {
94 self.counters.remove(&key);
95 }
96
97 pub fn clear(&mut self) {
98 self.counters.clear();
99 }
100}
101
102pub struct JitContext {
103 pub chunk: Arc<Chunk>,
104 pub cache: TraceCache,
105 pub hot: HotCounter,
106 pub hot_threshold: u32,
107 module: cranelift_jit::JITModule,
108}
109
110pub(crate) fn cranelift_flags() -> cranelift_codegen::settings::Flags {
111 let mut flag_builder = cranelift_codegen::settings::builder();
112 if !cfg!(debug_assertions) {
113 let _ = flag_builder.set("opt_level", "speed");
116 }
117 cranelift_codegen::settings::Flags::new(flag_builder)
118}
119
120impl JitContext {
121 pub fn new(chunk: Arc<Chunk>) -> Result<Self, super::error::CompileError> {
122 let flags = cranelift_flags();
123 let isa = cranelift_native::builder()
124 .map_err(|e| super::error::CompileError::Backend(e.to_string()))?
125 .finish(flags)
126 .map_err(|e| super::error::CompileError::Backend(e.to_string()))?;
127 let builder =
128 cranelift_jit::JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
129 let module = cranelift_jit::JITModule::new(builder);
130 Ok(Self {
131 chunk,
132 cache: TraceCache::new(),
133 hot: HotCounter::default(),
134 hot_threshold: HOT_THRESHOLD,
135 module,
136 })
137 }
138
139 pub fn module_mut(&mut self) -> &mut cranelift_jit::JITModule {
140 &mut self.module
141 }
142
143 pub fn reload(&mut self, chunk: Arc<Chunk>) {
145 self.chunk = chunk;
146 self.cache.clear();
147 self.hot.clear();
148 }
149}