Skip to main content

byteflow/jit/
trace.rs

1// Docs ratchet: public items here predate `missing_docs`. Delete this
2// allow once they are documented; new files get the lint by default.
3#![allow(missing_docs)]
4
5use std::collections::{HashMap, HashSet};
6use std::ops::Range;
7use std::sync::Arc;
8
9use cranelift_codegen::settings::Configurable;
10
11use crate::Chunk;
12
13use super::frame::JitEntry;
14
15/// Maximum instructions recorded into a single trace.
16pub const MAX_TRACE_LENGTH: usize = 256;
17
18/// How many times `(function, pc)` must run before compilation is attempted.
19pub const HOT_THRESHOLD: u32 = 1_000;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub struct TraceKey {
23    pub function: u32,
24    pub entry_pc: u32,
25    /// `true` when every live register at entry was `Float`, `Bool`, or
26    /// `Unit`. Arithmetic in the trace is IEEE `f64`, not wrapping `i64`.
27    pub floats: bool,
28}
29
30#[derive(Debug, Clone)]
31pub struct TraceSpan {
32    pub function: u32,
33    pub range: Range<u32>,
34}
35
36#[derive(Debug)]
37pub struct CompiledTrace {
38    pub span: TraceSpan,
39    pub entry: JitEntry,
40}
41
42pub struct TraceCache {
43    traces: HashMap<TraceKey, CompiledTrace>,
44    failed: HashSet<TraceKey>,
45}
46
47impl TraceCache {
48    pub fn new() -> Self {
49        Self {
50            traces: HashMap::new(),
51            failed: HashSet::new(),
52        }
53    }
54
55    pub fn get(&self, key: &TraceKey) -> Option<&CompiledTrace> {
56        self.traces.get(key)
57    }
58
59    pub fn is_failed(&self, key: &TraceKey) -> bool {
60        self.failed.contains(key)
61    }
62
63    pub fn mark_failed(&mut self, key: TraceKey) {
64        self.failed.insert(key);
65    }
66
67    pub fn insert(&mut self, key: TraceKey, trace: CompiledTrace) {
68        self.traces.insert(key, trace);
69    }
70
71    pub fn clear(&mut self) {
72        self.traces.clear();
73        self.failed.clear();
74    }
75
76    #[cfg(test)]
77    pub(crate) fn has_float_trace(&self) -> bool {
78        self.traces.keys().any(|key| key.floats)
79    }
80
81    /// `pc` lies in a trace compiled with `TraceKey::floats`.
82    #[cfg(test)]
83    pub(crate) fn float_trace_covers(&self, pc: u32) -> bool {
84        self.traces.iter().any(|(key, trace)| {
85            key.floats && trace.span.function == key.function && trace.span.range.contains(&pc)
86        })
87    }
88}
89
90impl Default for TraceCache {
91    fn default() -> Self {
92        Self::new()
93    }
94}
95
96#[derive(Default)]
97pub struct HotCounter {
98    counters: HashMap<TraceKey, u32>,
99}
100
101impl HotCounter {
102    pub fn hit(&mut self, key: TraceKey, threshold: u32) -> bool {
103        let counter = self.counters.entry(key).or_insert(0);
104        *counter = counter.saturating_add(1);
105        *counter >= threshold
106    }
107
108    pub fn reset(&mut self, key: TraceKey) {
109        self.counters.remove(&key);
110    }
111
112    pub fn clear(&mut self) {
113        self.counters.clear();
114    }
115}
116
117pub struct JitContext {
118    pub chunk: Arc<Chunk>,
119    pub cache: TraceCache,
120    pub hot: HotCounter,
121    pub hot_threshold: u32,
122    module: cranelift_jit::JITModule,
123}
124
125pub(crate) fn cranelift_flags() -> cranelift_codegen::settings::Flags {
126    let mut flag_builder = cranelift_codegen::settings::builder();
127    if !cfg!(debug_assertions) {
128        // Debug compiles stay at Cranelift's default (`none`). Release
129        // traces pay for the speed pipeline once per hot region.
130        let _ = flag_builder.set("opt_level", "speed");
131    }
132    cranelift_codegen::settings::Flags::new(flag_builder)
133}
134
135impl JitContext {
136    pub fn new(chunk: Arc<Chunk>) -> Result<Self, super::error::CompileError> {
137        let flags = cranelift_flags();
138        let isa = cranelift_native::builder()
139            .map_err(|e| super::error::CompileError::Backend(e.to_string()))?
140            .finish(flags)
141            .map_err(|e| super::error::CompileError::Backend(e.to_string()))?;
142        let builder =
143            cranelift_jit::JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
144        let module = cranelift_jit::JITModule::new(builder);
145        Ok(Self {
146            chunk,
147            cache: TraceCache::new(),
148            hot: HotCounter::default(),
149            hot_threshold: HOT_THRESHOLD,
150            module,
151        })
152    }
153
154    pub fn module_mut(&mut self) -> &mut cranelift_jit::JITModule {
155        &mut self.module
156    }
157
158    /// Drop compiled traces and hot counters after the bytecode image changes.
159    pub fn reload(&mut self, chunk: Arc<Chunk>) {
160        self.chunk = chunk;
161        self.cache.clear();
162        self.hot.clear();
163    }
164}