Skip to main content

logicaffeine_compile/analysis/
liveness.rs

1use std::collections::{HashMap, HashSet};
2
3use logicaffeine_base::Symbol;
4use logicaffeine_language::ast::stmt::Pattern;
5use logicaffeine_language::ast::{Expr, Stmt};
6
7use crate::optimize::Mentions;
8
9/// Liveness analysis result for a whole program.
10///
11/// For every statement of every user-defined function and of the top-level (`## Main`) statement list — nested
12/// statements included — the set of variables live immediately *after* it. Each function also keeps the table of its
13/// top-level statements by position (`live_after[i]`).
14///
15/// Used by codegen to decide when a value can be *moved* (into a call, into a constructed record) instead of cloned:
16/// if a variable is not live after the statement, the old value is never read again and ownership can be
17/// transferred. A move on a variable wrongly thought dead breaks the program, so the analysis errs toward "live": a
18/// statement kind it has no case for uses every name it touches (the optimizer's one exhaustive walk,
19/// `crate::optimize::Mentions`), foreign code uses every name, and a loop body's end sees what the next iteration
20/// needs.
21pub struct LivenessResult {
22    functions: HashMap<Symbol, FunctionLiveness>,
23    /// Every analysed statement's live-after set, keyed by the statement's address in the arena it was analysed in.
24    by_stmt: HashMap<usize, HashSet<Symbol>>,
25}
26
27/// Per-function liveness table.
28pub struct FunctionLiveness {
29    /// `live_after[i]` = variables live after top-level statement `i`.
30    pub live_after: Vec<HashSet<Symbol>>,
31}
32
33impl LivenessResult {
34    /// Compute liveness for every `FunctionDef` in `stmts`, and for `stmts` themselves as the `## Main` body.
35    ///
36    /// Algorithm: backward dataflow over each body. `Return` is treated as a terminator — variables used in
37    /// subsequent (dead-code) statements do not affect liveness before the `Return`.
38    pub fn analyze(stmts: &[Stmt<'_>]) -> Self {
39        let mut functions = HashMap::new();
40        let mut by_stmt = HashMap::new();
41        let none_pinned = HashSet::new();
42        for stmt in stmts {
43            if let Stmt::FunctionDef { name, body, .. } = stmt {
44                functions.insert(*name, analyze_body(body, &none_pinned, &mut by_stmt));
45            }
46        }
47        // A function reaches Main's variables by name (they are its globals), so a call can read one no Main
48        // statement names: every name a function body speaks of stays live throughout Main.
49        let reached: HashSet<Symbol> = stmts
50            .iter()
51            .filter_map(|s| match s {
52                Stmt::FunctionDef { body, .. } => {
53                    Some(Mentions::of_block(body).symbols().collect::<Vec<_>>())
54                }
55                _ => None,
56            })
57            .flatten()
58            .collect();
59        analyze_body(stmts, &reached, &mut by_stmt);
60        Self { functions, by_stmt }
61    }
62
63    /// The variables live after `stmt`, when the analysis saw it (a statement the compiler synthesized later has
64    /// no entry).
65    pub fn after(&self, stmt: &Stmt<'_>) -> Option<&HashSet<Symbol>> {
66        self.by_stmt.get(&stmt_key(stmt))
67    }
68
69    /// Every analysed statement's live-after set, by [`stmt_key`].
70    pub fn into_statement_table(self) -> HashMap<usize, HashSet<Symbol>> {
71        self.by_stmt
72    }
73
74    /// Returns `true` if `var` is live immediately after top-level statement
75    /// `stmt_idx` in function `fn_sym`.
76    ///
77    /// Returns `false` for unknown functions, out-of-bounds indices, or when
78    /// the variable is definitely dead.
79    pub fn is_live_after(&self, fn_sym: Symbol, stmt_idx: usize, var: Symbol) -> bool {
80        self.functions
81            .get(&fn_sym)
82            .and_then(|fl| fl.live_after.get(stmt_idx))
83            .map(|s| s.contains(&var))
84            .unwrap_or(false)
85    }
86
87    /// Returns the live-after set for statement `stmt_idx` in `fn_sym`.
88    ///
89    /// Returns a reference to an empty set when the function or index is
90    /// unknown.
91    pub fn live_after(&self, fn_sym: Symbol, stmt_idx: usize) -> &HashSet<Symbol> {
92        static EMPTY: std::sync::OnceLock<HashSet<Symbol>> = std::sync::OnceLock::new();
93        self.functions
94            .get(&fn_sym)
95            .and_then(|fl| fl.live_after.get(stmt_idx))
96            .unwrap_or_else(|| EMPTY.get_or_init(HashSet::new))
97    }
98}
99
100/// The key a statement's liveness is recorded under: its address in the arena the analysis walked.
101pub fn stmt_key(stmt: &Stmt<'_>) -> usize {
102    stmt as *const Stmt<'_> as *const () as usize
103}
104
105// =============================================================================
106// Per-body analysis
107// =============================================================================
108
109/// The backward walk over one body: what foreign code may read, the names live throughout it, and where each
110/// statement's live-after set is written.
111struct Walk<'r> {
112    /// Every name the body speaks of — what foreign code may read.
113    every: HashSet<Symbol>,
114    /// Names live at every point of the body (Main's variables that a function reads by name).
115    pinned: &'r HashSet<Symbol>,
116    /// What is live where a `Break` goes: after the nearest loop or zone.
117    break_exit: Option<HashSet<Symbol>>,
118    /// What is live where a `Return` goes when a zone encloses it: after the nearest zone, which the `Return` leaves.
119    return_exit: Option<HashSet<Symbol>>,
120    by_stmt: &'r mut HashMap<usize, HashSet<Symbol>>,
121}
122
123fn analyze_body(
124    body: &[Stmt<'_>],
125    pinned: &HashSet<Symbol>,
126    by_stmt: &mut HashMap<usize, HashSet<Symbol>>,
127) -> FunctionLiveness {
128    let mut walk = Walk {
129        every: Mentions::of_block(body).symbols().collect(),
130        pinned,
131        break_exit: None,
132        return_exit: None,
133        by_stmt,
134    };
135    let n = body.len();
136    let mut live_after = vec![HashSet::<Symbol>::new(); n];
137    let mut current: HashSet<Symbol> = pinned.clone();
138
139    for i in (0..n).rev() {
140        if is_terminator(&body[i]) {
141            // Return (or similar terminator): nothing is live after it,
142            // and dead code that follows does not influence pre-Return liveness.
143            live_after[i] = pinned.clone();
144            walk.record(&body[i], &live_after[i]);
145            current = walk.gen_stmt(&body[i]);
146        } else {
147            live_after[i] = current.clone();
148            current = walk.live_before_stmt(&body[i], &current);
149        }
150    }
151
152    FunctionLiveness { live_after }
153}
154
155fn is_terminator(stmt: &Stmt<'_>) -> bool {
156    matches!(stmt, Stmt::Return { .. })
157}
158
159impl Walk<'_> {
160    /// Record `live_out` as what is live after `stmt`. A loop body is walked once per fixpoint round; the last
161    /// round, at the fixpoint, writes last.
162    fn record(&mut self, stmt: &Stmt<'_>, live_out: &HashSet<Symbol>) {
163        let mut live = live_out.clone();
164        live.extend(self.pinned.iter().copied());
165        self.by_stmt.insert(stmt_key(stmt), live);
166    }
167
168    /// Variables generated (used) by a terminator.
169    fn gen_stmt(&self, stmt: &Stmt<'_>) -> HashSet<Symbol> {
170        let mut out = self.pinned.clone();
171        if let Stmt::Return { value: Some(v) } = stmt {
172            self.gen_expr(v, &mut out);
173        }
174        out
175    }
176
177    /// Compute the live-before set for a single statement given what is live after it, recording what is live
178    /// after it and after every statement nested in it.
179    fn live_before_stmt(&mut self, stmt: &Stmt<'_>, live_out: &HashSet<Symbol>) -> HashSet<Symbol> {
180        // A `Break` goes to the nearest loop's or zone's exit, whatever follows it; one with no exit known keeps every
181        // name live.
182        if matches!(stmt, Stmt::Break) {
183            let exit = self.break_exit.clone().unwrap_or_else(|| self.every.clone());
184            self.record(stmt, &exit);
185            return exit;
186        }
187        // A `Return` inside a zone leaves the zone and goes on after it.
188        if let (Stmt::Return { value }, Some(exit)) = (stmt, self.return_exit.clone()) {
189            self.record(stmt, &exit);
190            let mut before = exit;
191            if let Some(value) = value {
192                self.gen_expr(value, &mut before);
193            }
194            return before;
195        }
196        self.record(stmt, live_out);
197        match stmt {
198            Stmt::Return { .. } => self.gen_stmt(stmt),
199
200            Stmt::Let { var, value, .. } => {
201                let mut result = live_out.clone();
202                result.remove(var);
203                self.gen_expr(value, &mut result);
204                result
205            }
206
207            Stmt::Set { target, value } => {
208                let mut result = live_out.clone();
209                result.remove(target);
210                self.gen_expr(value, &mut result);
211                result
212            }
213
214            Stmt::Call { function, args } => {
215                let mut result = live_out.clone();
216                // A callee named by a binding (a closure held in a variable) is a use of it.
217                result.insert(*function);
218                for a in args.iter() {
219                    self.gen_expr(a, &mut result);
220                }
221                result
222            }
223
224            Stmt::Push { value, collection } => {
225                let mut result = live_out.clone();
226                self.gen_expr(value, &mut result);
227                self.gen_expr(collection, &mut result);
228                result
229            }
230
231            Stmt::Pop { collection, into } => {
232                let mut result = live_out.clone();
233                if let Some(v) = into {
234                    result.remove(v);
235                }
236                self.gen_expr(collection, &mut result);
237                result
238            }
239
240            Stmt::Add { value, collection } | Stmt::Remove { value, collection } => {
241                let mut result = live_out.clone();
242                self.gen_expr(value, &mut result);
243                self.gen_expr(collection, &mut result);
244                result
245            }
246
247            Stmt::SetIndex {
248                collection,
249                index,
250                value,
251            } => {
252                let mut result = live_out.clone();
253                self.gen_expr(collection, &mut result);
254                self.gen_expr(index, &mut result);
255                self.gen_expr(value, &mut result);
256                result
257            }
258
259            Stmt::SetField { object, value, .. } => {
260                let mut result = live_out.clone();
261                self.gen_expr(object, &mut result);
262                self.gen_expr(value, &mut result);
263                result
264            }
265
266            Stmt::If {
267                cond,
268                then_block,
269                else_block,
270            } => {
271                let then_lb = self.live_before_block(then_block, live_out);
272                let else_lb = match else_block {
273                    Some(b) => self.live_before_block(b, live_out),
274                    None => live_out.clone(),
275                };
276                let mut result = HashSet::new();
277                self.gen_expr(cond, &mut result);
278                result.extend(then_lb);
279                result.extend(else_lb);
280                result
281            }
282
283            Stmt::While {
284                cond,
285                body,
286                decreasing,
287            } => {
288                // Fixed-point: loop_live = live_out ∪ gen(cond, decreasing) ∪ body_live_before(loop_live)
289                let mut loop_live: HashSet<Symbol> = live_out.clone();
290                self.gen_expr(cond, &mut loop_live);
291                if let Some(d) = decreasing {
292                    self.gen_expr(d, &mut loop_live);
293                }
294                let enclosing = self.break_exit.replace(live_out.clone());
295                loop {
296                    let body_before = self.live_before_block(body, &loop_live);
297                    let mut new_live = live_out.clone();
298                    self.gen_expr(cond, &mut new_live);
299                    if let Some(d) = decreasing {
300                        self.gen_expr(d, &mut new_live);
301                    }
302                    new_live.extend(body_before);
303                    if new_live == loop_live {
304                        break;
305                    }
306                    loop_live = new_live;
307                }
308                self.break_exit = enclosing;
309                loop_live
310            }
311
312            Stmt::Repeat {
313                pattern,
314                iterable,
315                body,
316            } => {
317                // Fixed-point: what the top of an iteration needs is live at the end of the one before it; the
318                // pattern's names are bound afresh at each top.
319                let pattern_syms: HashSet<Symbol> = match pattern {
320                    Pattern::Identifier(s) => [*s].into_iter().collect(),
321                    Pattern::Tuple(syms) => syms.iter().copied().collect(),
322                };
323                let mut loop_live: HashSet<Symbol> = live_out.clone();
324                let enclosing = self.break_exit.replace(live_out.clone());
325                loop {
326                    let body_before = self.live_before_block(body, &loop_live);
327                    let mut new_live = live_out.clone();
328                    new_live.extend(
329                        body_before
330                            .into_iter()
331                            .filter(|s| !pattern_syms.contains(s)),
332                    );
333                    if new_live == loop_live {
334                        break;
335                    }
336                    loop_live = new_live;
337                }
338                self.break_exit = enclosing;
339                let mut result = loop_live;
340                self.gen_expr(iterable, &mut result);
341                result
342            }
343
344            Stmt::Inspect { target, arms, .. } => {
345                let mut result = HashSet::new();
346                for arm in arms.iter() {
347                    let arm_lb = self.live_before_block(arm.body, live_out);
348                    result.extend(arm_lb);
349                }
350                self.gen_expr(target, &mut result);
351                result
352            }
353
354            Stmt::Zone { body, .. } => {
355                let enclosing_break = self.break_exit.replace(live_out.clone());
356                let enclosing_return = self.return_exit.replace(live_out.clone());
357                let before = self.live_before_block(body, live_out);
358                self.break_exit = enclosing_break;
359                self.return_exit = enclosing_return;
360                before
361            }
362
363            // Any other statement uses every name it touches (a `Swap` reads both names; a `Show`, a `Give`, a
364            // splice, a select arm, a concurrent task reads what it names), and foreign code uses every name.
365            // Nothing nested in it is recorded, so nothing inside it moves.
366            _ => {
367                let touched = Mentions::of_stmt(stmt);
368                let mut result = live_out.clone();
369                result.extend(touched.symbols());
370                if touched.is_opaque() {
371                    result.extend(self.every.iter().copied());
372                }
373                result
374            }
375        }
376    }
377
378    /// Compute live-before for a block of statements.
379    fn live_before_block(
380        &mut self,
381        stmts: &[Stmt<'_>],
382        live_out: &HashSet<Symbol>,
383    ) -> HashSet<Symbol> {
384        let mut current = live_out.clone();
385        for stmt in stmts.iter().rev() {
386            if is_terminator(stmt) && self.return_exit.is_none() {
387                let after = self.pinned.clone();
388                self.record(stmt, &after);
389                current = self.gen_stmt(stmt);
390            } else {
391                current = self.live_before_stmt(stmt, &current);
392            }
393        }
394        current
395    }
396
397    /// Every variable an expression uses: each identifier it reads, what a closure in it captures, and — for foreign
398    /// code — every name the body speaks of. From the optimizer's one exhaustive walk, so no expression form is
399    /// overlooked.
400    fn gen_expr(&self, expr: &Expr<'_>, out: &mut HashSet<Symbol>) {
401        let touched = Mentions::of_expr(expr);
402        out.extend(touched.symbols());
403        if touched.is_opaque() {
404            out.extend(self.every.iter().copied());
405        }
406    }
407}
408
409#[cfg(test)]
410#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/analysis/liveness/tests.rs"]
411mod tests;