Skip to main content

ruxla_core/
trace.rs

1//! The tracing context of the `Trace` backend.
2//!
3//! Values of the `Trace` backend are [`TraceRef`]s: two integers naming an
4//! entry of a trace frame. The frames live on a thread-local stack, so the
5//! values can be `Copy`. A frame records the
6//! equations of one function being traced; nested functions (the branches of
7//! `cond`, the body of `while`, ...) push frames of their own, and values of
8//! enclosing frames that they use are captured as extra inputs.
9
10use std::cell::RefCell;
11use std::collections::HashMap;
12use std::sync::atomic::{AtomicU32, Ordering};
13
14use ruxla_ir::{AVal, Atom, Eqn, Function, HostArray, Literal, Params, Prim, Var};
15
16/// A value of the `Trace` backend: an entry of a trace frame.
17#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
18pub struct TraceRef {
19    frame: u32,
20    index: u32,
21}
22
23/// What a frame entry is.
24#[derive(Clone, Debug)]
25enum Entry {
26    /// A variable defined in the frame (an input or an equation's output).
27    Var(Var),
28    /// A scalar literal.
29    Lit(Literal),
30    /// A constant array (a `constvar` of the function).
31    Const(Var, HostArray),
32}
33
34#[derive(Debug)]
35struct Frame {
36    id: u32,
37    entries: Vec<Entry>,
38    invars: Vec<Var>,
39    eqns: Vec<Eqn>,
40    constvars: Vec<(Var, HostArray)>,
41    /// Values of the enclosing frame captured as inputs: the value in the
42    /// enclosing frame, and the input variable in this frame.
43    captured: Vec<(TraceRef, Var)>,
44    /// Entries of other frames already resolved in this frame.
45    resolved: HashMap<TraceRef, Atom>,
46}
47
48thread_local! {
49    static STACK: RefCell<Vec<Frame>> = const { RefCell::new(Vec::new()) };
50}
51
52static NEXT_FRAME: AtomicU32 = AtomicU32::new(1);
53
54/// Returns whether a trace is in progress on this thread.
55pub fn is_tracing() -> bool {
56    STACK.with(|s| !s.borrow().is_empty())
57}
58
59fn push_entry(frame: &mut Frame, entry: Entry) -> TraceRef {
60    frame.entries.push(entry);
61    TraceRef {
62        frame: frame.id,
63        index: (frame.entries.len() - 1) as u32,
64    }
65}
66
67/// Returns the atom for `r` in frame `level`, capturing it from enclosing
68/// frames if needed.
69fn resolve(stack: &mut [Frame], level: usize, r: TraceRef) -> Atom {
70    if stack[level].id == r.frame {
71        return match &stack[level].entries[r.index as usize] {
72            Entry::Var(v) | Entry::Const(v, _) => Atom::Var(v.clone()),
73            Entry::Lit(l) => Atom::Lit(l.clone()),
74        };
75    }
76    if let Some(a) = stack[level].resolved.get(&r) {
77        return a.clone();
78    }
79    let Some(owner) = stack[..level].iter().position(|f| f.id == r.frame) else {
80        panic!(
81            "a traced value was used after its trace ended (or in another thread); \
82             traced values must not escape the function being traced"
83        );
84    };
85    let atom = match &stack[owner].entries[r.index as usize] {
86        Entry::Lit(l) => Atom::Lit(l.clone()),
87        // Constants are copied rather than captured.
88        Entry::Const(_, value) => {
89            let value = value.clone();
90            let v = Var::new(value.aval());
91            stack[level].constvars.push((v.clone(), value));
92            Atom::Var(v)
93        }
94        Entry::Var(_) => {
95            // Capture from the enclosing frame, which may itself capture.
96            let outer = resolve(stack, level - 1, r);
97            let Atom::Var(outer_var) = outer else {
98                unreachable!("variables resolve to variables")
99            };
100            let parent = &mut stack[level - 1];
101            let outer_ref = push_entry(parent, Entry::Var(outer_var.clone()));
102            let v = Var::new(outer_var.aval().clone());
103            stack[level].captured.push((outer_ref, v.clone()));
104            Atom::Var(v)
105        }
106    };
107    stack[level].resolved.insert(r, atom.clone());
108    atom
109}
110
111/// Returns the abstract value of a traced value.
112pub(crate) fn aval(r: TraceRef) -> AVal {
113    STACK.with(|s| {
114        let s = s.borrow();
115        let Some(frame) = s.iter().find(|f| f.id == r.frame) else {
116            panic!("a traced value was used after its trace ended");
117        };
118        match &frame.entries[r.index as usize] {
119            Entry::Var(v) | Entry::Const(v, _) => v.aval().clone(),
120            Entry::Lit(l) => l.value().aval(),
121        }
122    })
123}
124
125/// Returns the value of a traced literal, if it is one (for constant
126/// folding of static checks).
127pub(crate) fn literal_value(r: TraceRef) -> Option<HostArray> {
128    STACK.with(|s| {
129        let s = s.borrow();
130        let frame = s.iter().find(|f| f.id == r.frame)?;
131        match &frame.entries[r.index as usize] {
132            Entry::Lit(l) => Some(l.value().clone()),
133            _ => None,
134        }
135    })
136}
137
138/// Adds a scalar literal to the current frame.
139///
140/// # Panics
141///
142/// Panics if no trace is in progress.
143pub(crate) fn literal(value: HostArray) -> TraceRef {
144    STACK.with(|s| {
145        let mut s = s.borrow_mut();
146        let top = s
147            .last_mut()
148            .expect("Trace values can only be created while tracing");
149        push_entry(top, Entry::Lit(Literal::new(value)))
150    })
151}
152
153/// Adds a constant array to the current frame.
154pub(crate) fn constant(value: HostArray) -> TraceRef {
155    if value.shape().rank() == 0 {
156        return literal(value);
157    }
158    STACK.with(|s| {
159        let mut s = s.borrow_mut();
160        let top = s
161            .last_mut()
162            .expect("Trace values can only be created while tracing");
163        let v = Var::new(value.aval());
164        top.constvars.push((v.clone(), value.clone()));
165        push_entry(top, Entry::Const(v, value))
166    })
167}
168
169/// Records an equation in the current frame and returns its outputs.
170///
171/// # Panics
172///
173/// Panics if no trace is in progress, or with the primitive's message if it
174/// rejects the inputs.
175#[track_caller]
176pub(crate) fn bind(prim: Prim, inputs: &[TraceRef], params: Params) -> Vec<TraceRef> {
177    let loc = std::panic::Location::caller();
178    STACK.with(|s| {
179        let mut s = s.borrow_mut();
180        let level = s
181            .len()
182            .checked_sub(1)
183            .expect("Trace operations need a trace in progress");
184        let atoms: Vec<Atom> = inputs.iter().map(|&r| resolve(&mut s, level, r)).collect();
185        let avals: Vec<AVal> = atoms.iter().map(Atom::aval).collect();
186        let outs = prim
187            .abstract_eval(&avals, &params)
188            .unwrap_or_else(|e| panic!("{e}"));
189        let outputs: Vec<Var> = outs.into_iter().map(Var::new).collect();
190        let top = &mut s[level];
191        top.eqns.push(Eqn {
192            prim,
193            inputs: atoms,
194            params,
195            outputs: outputs.clone(),
196            loc: Some(loc),
197        });
198        outputs
199            .into_iter()
200            .map(|v| push_entry(top, Entry::Var(v)))
201            .collect()
202    })
203}
204
205/// The result of [`trace_function`].
206#[derive(Debug)]
207pub(crate) struct Traced {
208    /// The function. Its inputs are the captured values followed by the
209    /// arguments.
210    pub(crate) function: Function,
211    /// The captured values, in the enclosing frame, to pass as the first
212    /// arguments.
213    pub(crate) captured: Vec<TraceRef>,
214}
215
216/// Pops the frame when dropped, so that a panic while tracing does not
217/// leave it on the stack.
218struct PopOnDrop;
219
220impl Drop for PopOnDrop {
221    fn drop(&mut self) {
222        STACK.with(|s| {
223            s.borrow_mut().pop();
224        });
225    }
226}
227
228/// Traces `f` as a function with inputs of `in_avals`.
229pub(crate) fn trace_function(
230    in_avals: &[AVal],
231    f: impl FnOnce(&[TraceRef]) -> Vec<TraceRef>,
232) -> Traced {
233    let id = NEXT_FRAME.fetch_add(1, Ordering::Relaxed);
234    let args: Vec<TraceRef> = STACK.with(|s| {
235        let mut s = s.borrow_mut();
236        let mut frame = Frame {
237            id,
238            entries: Vec::new(),
239            invars: Vec::new(),
240            eqns: Vec::new(),
241            constvars: Vec::new(),
242            captured: Vec::new(),
243            resolved: HashMap::new(),
244        };
245        let args = in_avals
246            .iter()
247            .map(|a| {
248                let v = Var::new(a.clone());
249                frame.invars.push(v.clone());
250                push_entry(&mut frame, Entry::Var(v))
251            })
252            .collect();
253        s.push(frame);
254        args
255    });
256    let guard = PopOnDrop;
257    let outs = f(&args);
258    let traced = STACK.with(|s| {
259        let mut s = s.borrow_mut();
260        let level = s.len() - 1;
261        assert_eq!(s[level].id, id, "trace frames were not properly nested");
262        let outvars: Vec<Atom> = outs.iter().map(|&r| resolve(&mut s, level, r)).collect();
263        let frame = &mut s[level];
264        let (captured, captured_vars): (Vec<TraceRef>, Vec<Var>) = frame.captured.drain(..).unzip();
265        let mut invars = captured_vars;
266        invars.append(&mut frame.invars);
267        Traced {
268            function: Function {
269                constvars: std::mem::take(&mut frame.constvars),
270                invars,
271                eqns: std::mem::take(&mut frame.eqns),
272                outvars,
273            },
274            captured,
275        }
276    });
277    drop(guard);
278    traced
279}