Skip to main content

psync_check/
pdg.rs

1//! Control dependence for a function's program dependence graph (Ferrante, Ottenstein and
2//! Warren, 1987).
3//!
4//! A node `n` is **control dependent** on the edge `a -> b` when `b` leads to `n` on every path to
5//! the exit (`n` post-dominates `b`), but `a` does not (`n` does not post-dominate `a`): the branch
6//! at `a` decides whether `n` runs. Post-dominators are dominators of the reversed graph, from a
7//! virtual exit that every exit block leads to (Cooper, Harvey and Kennedy's iterative algorithm).
8
9use serde::{Deserialize, Serialize};
10
11/// A control-flow graph: `succ[n]` are the blocks `n` may jump to, each with a label for the edge
12/// (`true`, `Err`, `otherwise`). Blocks without successors are exits.
13#[derive(Clone, Debug, Default)]
14pub struct Cfg {
15    pub succ: Vec<Vec<(usize, String)>>,
16}
17
18/// The immediate post-dominator of each block: `Some(n)` for a block, `None` for the virtual exit
19/// (the block is an exit, or every path from it ends there directly) or for a block from which no
20/// exit is reachable.
21pub fn post_dominators(cfg: &Cfg) -> Vec<Option<usize>> {
22    let n = cfg.succ.len();
23    let exit = n; // virtual
24    // Reverse postorder of the reversed graph, from the exit: predecessors in the reversed graph
25    // are successors in the original.
26    let mut preds_rev: Vec<Vec<usize>> = vec![Vec::new(); n + 1]; // reversed-graph successors
27    for (a, s) in cfg.succ.iter().enumerate() {
28        if s.is_empty() {
29            preds_rev[exit].push(a);
30        }
31        for (b, _) in s {
32            preds_rev[*b].push(a);
33        }
34    }
35    let mut order = Vec::new();
36    let mut seen = vec![false; n + 1];
37    let mut stack = vec![(exit, 0usize)];
38    seen[exit] = true;
39    while let Some((v, i)) = stack.pop() {
40        if i < preds_rev[v].len() {
41            stack.push((v, i + 1));
42            let w = preds_rev[v][i];
43            if !seen[w] {
44                seen[w] = true;
45                stack.push((w, 0));
46            }
47        } else {
48            order.push(v);
49        }
50    }
51    order.reverse(); // reverse postorder, exit first
52    let mut rpo = vec![usize::MAX; n + 1];
53    for (k, &v) in order.iter().enumerate() {
54        rpo[v] = k;
55    }
56    let mut idom: Vec<Option<usize>> = vec![None; n + 1];
57    idom[exit] = Some(exit);
58    let intersect = |idom: &[Option<usize>], mut a: usize, mut b: usize| {
59        while a != b {
60            while rpo[a] > rpo[b] {
61                a = idom[a].unwrap();
62            }
63            while rpo[b] > rpo[a] {
64                b = idom[b].unwrap();
65            }
66        }
67        a
68    };
69    let mut changed = true;
70    while changed {
71        changed = false;
72        for &v in order.iter().skip(1) {
73            // Predecessors of `v` in the reversed graph: its successors, or the exit.
74            let ps: Vec<usize> = if cfg.succ[v].is_empty() {
75                vec![exit]
76            } else {
77                cfg.succ[v].iter().map(|(b, _)| *b).collect()
78            };
79            let mut new: Option<usize> = None;
80            for p in ps {
81                if idom[p].is_some() {
82                    new = Some(match new {
83                        None => p,
84                        Some(x) => intersect(&idom, p, x),
85                    });
86                }
87            }
88            if new.is_some() && idom[v] != new {
89                idom[v] = new;
90                changed = true;
91            }
92        }
93    }
94    (0..n).map(|v| idom[v].filter(|&d| d != exit)).collect()
95}
96
97/// One control dependence: the block runs only when the branch at `branch` takes the edge
98/// labelled `label`.
99#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
100pub struct Guard {
101    pub branch: usize,
102    pub label: String,
103}
104
105/// The guards of each block: the branches it is control dependent on.
106pub fn control_dependence(cfg: &Cfg) -> Vec<Vec<Guard>> {
107    let ipdom = post_dominators(cfg);
108    let n = cfg.succ.len();
109    let mut out: Vec<Vec<Guard>> = vec![Vec::new(); n];
110    for (a, s) in cfg.succ.iter().enumerate() {
111        if s.len() < 2 {
112            continue;
113        }
114        for (b, label) in s {
115            // Walk up the post-dominator tree from `b` to `a`'s immediate post-dominator: those
116            // blocks run exactly when this edge is taken.
117            let mut runner = Some(*b);
118            let mut steps = 0;
119            while let Some(r) = runner {
120                if Some(r) == ipdom[a] || steps > n {
121                    break;
122                }
123                let g = Guard {
124                    branch: a,
125                    label: label.clone(),
126                };
127                if !out[r].contains(&g) {
128                    out[r].push(g);
129                }
130                runner = ipdom[r];
131                steps += 1;
132            }
133        }
134    }
135    out
136}
137
138/// A natural loop: the blocks that can reach a back edge `latch -> header` without passing
139/// through `header`.
140#[derive(Clone, Debug, PartialEq, Eq)]
141pub struct NaturalLoop {
142    pub header: usize,
143    /// Every block of the loop, the header included, in increasing order.
144    pub blocks: Vec<usize>,
145}
146
147/// The natural loops of `cfg` reachable from `root`, one per header (loops that share a header
148/// are merged), outermost first.
149///
150/// A back edge is an edge to a block on the depth-first search stack. In a reducible graph, which
151/// is what structured code (Rust without `goto`) compiles to, these are exactly the edges to a
152/// dominator, so this finds the same loops as dominator analysis.
153pub fn natural_loops(cfg: &Cfg, root: usize) -> Vec<NaturalLoop> {
154    let n = cfg.succ.len();
155    if root >= n {
156        return Vec::new();
157    }
158    let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
159    for (a, s) in cfg.succ.iter().enumerate() {
160        for (b, _) in s {
161            preds[*b].push(a);
162        }
163    }
164    // Back edges, by an iterative depth-first search.
165    let mut back: Vec<(usize, usize)> = Vec::new();
166    let mut state = vec![0u8; n]; // 0 new, 1 on the stack, 2 done
167    let mut stack = vec![(root, 0usize)];
168    state[root] = 1;
169    while let Some((v, i)) = stack.pop() {
170        if let Some((w, _)) = cfg.succ[v].get(i) {
171            stack.push((v, i + 1));
172            match state[*w] {
173                0 => {
174                    state[*w] = 1;
175                    stack.push((*w, 0));
176                }
177                1 => back.push((v, *w)),
178                _ => {}
179            }
180        } else {
181            state[v] = 2;
182        }
183    }
184    let mut loops: Vec<NaturalLoop> = Vec::new();
185    for (latch, header) in back {
186        let mut body = std::collections::BTreeSet::from([header]);
187        let mut work = vec![latch];
188        while let Some(v) = work.pop() {
189            if body.insert(v) {
190                work.extend(preds[v].iter().copied());
191            }
192        }
193        match loops.iter_mut().find(|l| l.header == header) {
194            Some(l) => {
195                let mut all: std::collections::BTreeSet<usize> = l.blocks.iter().copied().collect();
196                all.extend(body);
197                l.blocks = all.into_iter().collect();
198            }
199            None => loops.push(NaturalLoop {
200                header,
201                blocks: body.into_iter().collect(),
202            }),
203        }
204    }
205    loops.sort_by_key(|l| std::cmp::Reverse(l.blocks.len()));
206    loops
207}
208
209/// A loop of a body: how often it runs, what runs inside it, and where it is left.
210#[derive(Clone, Debug, Serialize, Deserialize)]
211pub struct PdgLoop {
212    pub header: usize,
213    pub line: usize,
214    /// For a loop over an iterator, the iterator's type: the body runs once per item it yields.
215    /// Empty for a `loop` or `while`, which runs until a branch leaves it.
216    pub per_item_of: String,
217    /// The calls and awaits inside the loop, by block.
218    pub nodes: Vec<usize>,
219    /// The branches that leave the loop, with the label of the edge that leaves.
220    pub exits: Vec<Guard>,
221    /// The header of the innermost loop around this one, if any.
222    pub inside: Option<usize>,
223}
224
225/// A point of interest in a function: a call with effects or a call of the crate's own code, an
226/// await, or a return.
227#[derive(Clone, Debug, Serialize, Deserialize)]
228pub struct PdgNode {
229    pub block: usize,
230    pub line: usize,
231    /// `call`, `await` or `return`.
232    pub kind: String,
233    /// The callee, for a call.
234    pub callee: String,
235    /// What the call does, as the summaries describe it (`write file arg 0`).
236    pub effects: Vec<String>,
237    pub guards: Vec<Guard>,
238    /// The calls (by block) whose results flow into this call's arguments.
239    #[serde(default)]
240    pub uses: Vec<usize>,
241}
242
243/// A branch: where it is and what it tests.
244#[derive(Clone, Debug, Serialize, Deserialize)]
245pub struct PdgBranch {
246    pub block: usize,
247    pub line: usize,
248    pub test: String,
249    /// The calls (by block) whose results the test depends on.
250    #[serde(default)]
251    pub uses: Vec<usize>,
252}
253
254/// One chain of a join the macro generated: a closure or async block of its own, whose graph is
255/// listed under `path`.
256#[derive(Clone, Debug, Serialize, Deserialize)]
257pub struct PdgChain {
258    pub path: String,
259    /// Its first and last statements, by position in the rewritten block.
260    pub first: u64,
261    pub last: u64,
262    pub exits: bool,
263    pub speculate: bool,
264    pub independent: bool,
265    /// A job on a thread (Phase II), not a future.
266    pub sync: bool,
267}
268
269/// Chains that run concurrently: one join of the rewritten function.
270#[derive(Clone, Debug, Serialize, Deserialize)]
271pub struct PdgJoin {
272    pub level: u64,
273    pub chains: Vec<PdgChain>,
274}
275
276/// A prefetched loop: `path` (the prefix) runs for later items while earlier ones finish.
277#[derive(Clone, Debug, Serialize, Deserialize)]
278pub struct PdgPrefetch {
279    pub path: String,
280    pub terminates: bool,
281    pub speculate: bool,
282}
283
284/// A `select!` or `join!` written in the body: futures polled together at one await. For
285/// `select!`, the first to finish wins and the others are dropped where they stopped.
286#[derive(Clone, Debug, Serialize, Deserialize)]
287pub struct PdgSelect {
288    /// The macro's name (`select`, `join`, ...) and the line it is called on.
289    pub name: String,
290    pub line: usize,
291    /// The block of the await that polls the futures.
292    pub at: usize,
293    /// Calls inside the macro that run before that await: they build the futures.
294    pub futures: Vec<usize>,
295    /// Calls inside the macro that run only after it: the arms' handlers.
296    pub handlers: Vec<usize>,
297}
298
299/// The dependence graph of one body (a function, closure or async block).
300#[derive(Clone, Debug, Default, Serialize, Deserialize)]
301pub struct FnPdg {
302    pub path: String,
303    pub nodes: Vec<PdgNode>,
304    pub branches: Vec<PdgBranch>,
305    /// The joins the macro generated in this body.
306    #[serde(default)]
307    pub joins: Vec<PdgJoin>,
308    #[serde(default)]
309    pub prefetches: Vec<PdgPrefetch>,
310    /// The loops of this body, outermost first.
311    #[serde(default)]
312    pub loops: Vec<PdgLoop>,
313    /// The `select!`s and `join!`s of this body.
314    #[serde(default)]
315    pub selects: Vec<PdgSelect>,
316}
317
318#[derive(Clone, Debug, Default, Serialize, Deserialize)]
319pub struct CratePdg {
320    pub crate_name: String,
321    pub functions: Vec<FnPdg>,
322    /// Where requests, commands or events enter the crate: `main`, and the handlers registered
323    /// with a web framework.
324    #[serde(default)]
325    pub entries: Vec<PdgEntry>,
326}
327
328/// An entry point: a function the outside world calls, so the place to start tracing from.
329#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
330pub struct PdgEntry {
331    /// `main`, `axum` or `actix_web`.
332    pub framework: String,
333    /// The registering call (`get`, `post`, `to`), empty for `main`.
334    pub method: String,
335    /// The route it is registered under (`/users/{id}`), when a string literal names it.
336    pub route: String,
337    /// The handler, as the graphs name it (`api::list_users`).
338    pub handler: String,
339    /// The handler's line, and the line of the call that registers it (0 for `main`).
340    pub line: usize,
341    pub registered_at: usize,
342}
343
344/// An entry as one line: `axum get /users -> api::list_users (line 12, registered at line 40)`.
345pub fn render_entry(e: &PdgEntry) -> String {
346    if e.framework == "main" {
347        return format!("main -> {} (line {})", e.handler, e.line);
348    }
349    let route = if e.route.is_empty() {
350        "(route not a literal)".to_string()
351    } else {
352        e.route.clone()
353    };
354    format!(
355        "{} {} {route} -> {} (line {}, registered at line {})",
356        e.framework, e.method, e.handler, e.line, e.registered_at
357    )
358}
359
360/// A function's graph as text: each node with the branches it depends on.
361///
362/// ```text
363/// app::keep::{closure#0}
364///   b2  line 61  await
365///   b5  line 62  call std::fs::write  [write file arg 1]  if b3 (line 60, match on `Result`) = Ok
366/// ```
367pub fn render(f: &FnPdg) -> String {
368    let blocks = |bs: &[usize]| {
369        bs.iter()
370            .map(|b| format!("b{b}"))
371            .collect::<Vec<_>>()
372            .join(", ")
373    };
374    let mut out = format!("{}\n", f.path);
375    for j in &f.joins {
376        let chains: Vec<String> = j
377            .chains
378            .iter()
379            .map(|c| {
380                let mut tags = vec![if c.first == c.last {
381                    format!("statement {}", c.first)
382                } else {
383                    format!("statements {}-{}", c.first, c.last)
384                }];
385                for (on, tag) in [
386                    (c.exits, "may exit"),
387                    (c.speculate, "speculate"),
388                    (c.independent, "independent"),
389                    (c.sync, "thread"),
390                ] {
391                    if on {
392                        tags.push(tag.into());
393                    }
394                }
395                format!("{} ({})", c.path, tags.join(", "))
396            })
397            .collect();
398        out += &format!("  join {}: {}\n", j.level, chains.join(" || "));
399    }
400    for p in &f.prefetches {
401        let mut tags = Vec::new();
402        if p.terminates {
403            tags.push("the body may end the loop");
404        }
405        if p.speculate {
406            tags.push("speculate");
407        }
408        let tags = if tags.is_empty() {
409            String::new()
410        } else {
411            format!(" ({})", tags.join(", "))
412        };
413        out += &format!("  prefetch: {}{tags}\n", p.path);
414    }
415    for l in &f.loops {
416        let runs = if l.per_item_of.is_empty() {
417            "until a branch leaves it".to_string()
418        } else {
419            format!("once per item of `{}`", l.per_item_of)
420        };
421        let inside = l
422            .inside
423            .map_or(String::new(), |h| format!(", inside loop b{h}"));
424        let body = if l.nodes.is_empty() {
425            "no calls".to_string()
426        } else {
427            blocks(&l.nodes)
428        };
429        let exits: Vec<String> = l
430            .exits
431            .iter()
432            .map(|g| format!("b{} = {}", g.branch, g.label))
433            .collect();
434        let exits = if exits.is_empty() {
435            String::new()
436        } else {
437            format!("; leaves at {}", exits.join(", "))
438        };
439        out += &format!(
440            "  loop b{} (line {}{inside}): runs {runs}: {body}{exits}\n",
441            l.header, l.line
442        );
443    }
444    for x in &f.selects {
445        let what = if x.name.contains("select") {
446            "the first to finish wins, the others are dropped"
447        } else {
448            "all run to the end"
449        };
450        let list = |bs: &[usize]| {
451            if bs.is_empty() {
452                "none".to_string()
453            } else {
454                blocks(bs)
455            }
456        };
457        out += &format!(
458            "  {}! b{} (line {}): futures {}; handlers {}; {what}\n",
459            x.name,
460            x.at,
461            x.line,
462            list(&x.futures),
463            list(&x.handlers)
464        );
465    }
466    for n in &f.nodes {
467        let what = match n.kind.as_str() {
468            "call" => format!("call {}", n.callee),
469            k => k.to_string(),
470        };
471        let effects = if n.effects.is_empty() {
472            String::new()
473        } else {
474            format!("  [{}]", n.effects.join("; "))
475        };
476        let guards: Vec<String> = n
477            .guards
478            .iter()
479            .map(|g| {
480                let b = f.branches.iter().find(|b| b.block == g.branch);
481                match b {
482                    Some(b) if !b.uses.is_empty() => format!(
483                        "b{} (line {}, {} on {}) = {}",
484                        g.branch,
485                        b.line,
486                        b.test,
487                        blocks(&b.uses),
488                        g.label
489                    ),
490                    Some(b) => format!("b{} (line {}, {}) = {}", g.branch, b.line, b.test, g.label),
491                    None => format!("b{} = {}", g.branch, g.label),
492                }
493            })
494            .collect();
495        let guards = if guards.is_empty() {
496            String::new()
497        } else {
498            format!("  if {}", guards.join(" and "))
499        };
500        let uses = if n.uses.is_empty() {
501            String::new()
502        } else {
503            format!("  uses {}", blocks(&n.uses))
504        };
505        out += &format!(
506            "  b{:<3} line {:<4} {what}{effects}{uses}{guards}\n",
507            n.block, n.line
508        );
509    }
510    out
511}
512
513#[cfg(test)]
514mod tests {
515    use super::*;
516
517    fn cfg(edges: &[&[(usize, &str)]]) -> Cfg {
518        Cfg {
519            succ: edges
520                .iter()
521                .map(|s| s.iter().map(|(b, l)| (*b, l.to_string())).collect())
522                .collect(),
523        }
524    }
525
526    #[test]
527    fn diamond() {
528        // 0: if c { 1 } else { 2 }; 3
529        let g = cfg(&[&[(1, "true"), (2, "false")], &[(3, "")], &[(3, "")], &[]]);
530        assert_eq!(post_dominators(&g), [Some(3), Some(3), Some(3), None]);
531        let cd = control_dependence(&g);
532        assert_eq!(
533            cd[1],
534            [Guard {
535                branch: 0,
536                label: "true".into()
537            }]
538        );
539        assert_eq!(
540            cd[2],
541            [Guard {
542                branch: 0,
543                label: "false".into()
544            }]
545        );
546        assert!(cd[0].is_empty() && cd[3].is_empty());
547    }
548
549    #[test]
550    fn early_return() {
551        // 0: let x = f()?  (Err -> 1: return); 2: g(); 3: return
552        let g = cfg(&[&[(2, "Ok"), (1, "Err")], &[], &[(3, "")], &[]]);
553        let cd = control_dependence(&g);
554        // `g()` runs only when `f()` succeeded.
555        assert_eq!(
556            cd[2],
557            [Guard {
558                branch: 0,
559                label: "Ok".into()
560            }]
561        );
562        assert_eq!(
563            cd[3],
564            [Guard {
565                branch: 0,
566                label: "Ok".into()
567            }]
568        );
569        assert_eq!(
570            cd[1],
571            [Guard {
572                branch: 0,
573                label: "Err".into()
574            }]
575        );
576    }
577
578    #[test]
579    fn loop_body() {
580        // 0 -> 1: while c { 2 -> 1 }; 3
581        let g = cfg(&[&[(1, "")], &[(2, "true"), (3, "false")], &[(1, "")], &[]]);
582        let cd = control_dependence(&g);
583        assert_eq!(
584            cd[2],
585            [Guard {
586                branch: 1,
587                label: "true".into()
588            }]
589        );
590        // The loop head runs again only when the body ran: it depends on its own branch.
591        assert_eq!(
592            cd[1],
593            [Guard {
594                branch: 1,
595                label: "true".into()
596            }]
597        );
598        assert!(cd[3].is_empty());
599    }
600
601    #[test]
602    fn finds_nested_natural_loops() {
603        // 0 -> 1 (outer header) -> 2 (inner header) -> 3 -> 2, 2 -> 4 -> 1, 1 -> 5 (exit).
604        let cfg = Cfg {
605            succ: vec![
606                vec![(1, String::new())],
607                vec![(2, "Some".into()), (5, "None".into())],
608                vec![(3, "true".into()), (4, "false".into())],
609                vec![(2, String::new())],
610                vec![(1, String::new())],
611                vec![],
612            ],
613        };
614        let loops = natural_loops(&cfg, 0);
615        assert_eq!(
616            loops,
617            vec![
618                NaturalLoop {
619                    header: 1,
620                    blocks: vec![1, 2, 3, 4]
621                },
622                NaturalLoop {
623                    header: 2,
624                    blocks: vec![2, 3]
625                },
626            ]
627        );
628        // No cycle, no loop.
629        let line = Cfg {
630            succ: vec![vec![(1, String::new())], vec![]],
631        };
632        assert!(natural_loops(&line, 0).is_empty());
633    }
634
635    #[test]
636    fn renders_loops() {
637        let f = FnPdg {
638            path: "f".into(),
639            loops: vec![
640                PdgLoop {
641                    header: 4,
642                    line: 10,
643                    per_item_of: "std::slice::Iter<'_, u32>".into(),
644                    nodes: vec![7, 9],
645                    exits: vec![Guard {
646                        branch: 8,
647                        label: "exits".into(),
648                    }],
649                    inside: None,
650                },
651                PdgLoop {
652                    header: 12,
653                    line: 14,
654                    per_item_of: String::new(),
655                    nodes: vec![],
656                    exits: vec![],
657                    inside: Some(4),
658                },
659            ],
660            ..Default::default()
661        };
662        assert_eq!(
663            render(&f),
664            "f\n  loop b4 (line 10): runs once per item of `std::slice::Iter<'_, u32>`: b7, b9; \
665             leaves at b8 = exits\n  loop b12 (line 14, inside loop b4): runs until a branch \
666             leaves it: no calls\n"
667        );
668    }
669
670    #[test]
671    fn renders_joins_and_prefetches() {
672        let f = FnPdg {
673            path: "f::{closure#0}".into(),
674            joins: vec![PdgJoin {
675                level: 1,
676                chains: vec![
677                    PdgChain {
678                        path: "f::{closure#0}::{closure#0}".into(),
679                        first: 0,
680                        last: 2,
681                        exits: true,
682                        speculate: false,
683                        independent: false,
684                        sync: false,
685                    },
686                    PdgChain {
687                        path: "f::{closure#0}::{closure#1}".into(),
688                        first: 1,
689                        last: 1,
690                        exits: false,
691                        speculate: true,
692                        independent: false,
693                        sync: false,
694                    },
695                ],
696            }],
697            prefetches: vec![PdgPrefetch {
698                path: "f::{closure#0}::{closure#2}".into(),
699                terminates: true,
700                speculate: false,
701            }],
702            ..Default::default()
703        };
704        assert_eq!(
705            render(&f),
706            "f::{closure#0}\n  join 1: f::{closure#0}::{closure#0} (statements 0-2, may exit) || \
707             f::{closure#0}::{closure#1} (statement 1, speculate)\n  prefetch: \
708             f::{closure#0}::{closure#2} (the body may end the loop)\n"
709        );
710    }
711
712    #[test]
713    fn unreachable_exit_is_tolerated() {
714        // 0: loop {} with no exit; 1 unreachable from 0.
715        let g = cfg(&[&[(0, "")], &[]]);
716        assert_eq!(post_dominators(&g), [None, None]);
717        assert!(control_dependence(&g).iter().all(Vec::is_empty));
718    }
719}