graphity_controlflow/control_flow.rs
1//! Relations of control flow that follow from [`Dominators`], returned as graphs: the dominance
2//! frontiers and, from them, control dependence - Java's class `ControlFlow`.
3//!
4//! A block is control dependent on another if that block decides whether it runs. Control dependence
5//! is the transposed graph of the dominance frontiers of the post-dominators. The post-dominators are
6//! the dominators of the transposed graph with the exits as entries. Here, for a method `load` with a
7//! for loop and an if in it, whose control flow `cfg` ends in the block `exit`:
8//!
9//! <!-- example: analyzing_control_flow.rs#controlDependence -->
10//! ```
11//! # use graphity_core::{BiAdjacentGraph, Dominators};
12//! # use graphity_controlflow::control_flow;
13//! # let cfg = graphity_core::Graph::of(&[0, 1, 3, 5, 6, 7, 7], &[1, 2, 5, 3, 4, 4, 1]).unwrap();
14//! # let exit = 5;
15//! let post_dominators = Dominators::of(&BiAdjacentGraph::of(&cfg).transposed(), exit);
16//! let control_dependence =
17//! BiAdjacentGraph::of(&control_flow::dominance_frontiers(&post_dominators))
18//! .transposed();
19//! // header -> [header, body, next]: the loop condition decides whether they run
20//! // body -> [then]: the if decides whether then runs
21//! # assert_eq!(control_dependence.out_nodes(1), [1, 2, 4]);
22//! # assert_eq!(control_dependence.out_nodes(2), [3]);
23//! # assert_eq!(control_dependence.edge_count(), 4);
24//! ```
25//!
26//! For the placement of phi-nodes, [`IteratedDominanceFrontier`](crate::IteratedDominanceFrontier)
27//! answers without building the dominance frontiers.
28
29use graphity_core::{Dominators, Graph, NONE, csr};
30
31use crate::error::invalid_argument;
32
33/// The JDK's soft maximum array length, `2^31 - 9`, the one array limit of the library; the crate
34/// derives its other limits from it. Follows the core's limit, which this crate cannot see.
35pub(crate) const MAX_ARRAY_LENGTH: u32 = i32::MAX as u32 - 8;
36
37/// Returns the dominance frontiers as a graph: an edge `n -> m` for every node `m` in the dominance
38/// frontier of `n`.
39///
40/// The dominance frontier of `n` holds the nodes where its dominance ends: `m` is in it if `n`
41/// dominates an in-node of `m` but does not strictly dominate `m`. A node can be in its own dominance
42/// frontier, as the header of a natural loop is, so the result can have self-loops. Nodes that the
43/// entries do not reach have empty dominance frontiers and are in none. The result has the node IDs of
44/// the graph of `dominators`.
45///
46/// Uses the algorithm of Cooper, Harvey and Kennedy. The result is computed anew on every call, not
47/// cached: keep it to use it more than once. It can grow quadratically with the node count, for
48/// example on deeply nested do-while loops.
49///
50/// **Time:** O(node_count + edge_count + frontier_count), where frontier_count is the number of edges
51/// of the result.
52/// **Memory:** 4 x (node_count + frontier_count) bytes for the result; while it runs, 8 x node_count
53/// bytes more. The result takes over the arrays built here ([`Graph::from_csr`]). Java copies them,
54/// which takes as much again.
55///
56/// # Panics
57/// With an `invalid argument` message if the result would have more edges than a graph can have.
58#[track_caller]
59pub fn dominance_frontiers(dominators: &Dominators) -> Graph {
60 let graph = dominators.graph();
61 let n = graph.node_count() as usize;
62 let in_start = csr::in_adjacency_start(graph);
63 let inn = csr::in_adjacency(graph);
64 let idom: Vec<u32> = (0..n as u32)
65 .map(|node| dominators.immediate_dominator_of(node).unwrap_or(NONE))
66 .collect();
67
68 // Walk up from every predecessor of m to just below idom(m), adding m on the way (Cooper,
69 // Harvey and Kennedy). A node already holding m means the rest of the walk is done, so every
70 // step adds a new pair. Run twice - count, then fill - so that each frontier comes out sorted
71 // without an intermediate pair buffer.
72 let mut last_added = vec![NONE; n];
73 let mut start = vec![0u32; n + 1];
74 let mut total = 0u64;
75 for m in 0..n as u32 {
76 if !dominators.is_reachable(m) {
77 continue;
78 }
79 let stop = idom[m as usize];
80 for &pred in &inn[in_start[m as usize] as usize..in_start[m as usize + 1] as usize] {
81 if !dominators.is_reachable(pred) {
82 continue;
83 }
84 let mut runner = pred;
85 while runner != stop && last_added[runner as usize] != m {
86 last_added[runner as usize] = m;
87 start[runner as usize] += 1;
88 total += 1;
89 runner = idom[runner as usize];
90 }
91 }
92 }
93 if total > u64::from(MAX_ARRAY_LENGTH) {
94 invalid_argument!(
95 "the dominance frontier relation has more than {MAX_ARRAY_LENGTH} pairs, the largest \
96 array length"
97 );
98 }
99 let mut next = 0u32;
100 for s in &mut start[..n] {
101 let count = *s;
102 *s = next;
103 next += count;
104 }
105 start[n] = next;
106 let mut frontier = vec![0u32; next as usize];
107 last_added.fill(NONE);
108 // start[runner] doubles as write pointer and is shifted back afterwards.
109 for m in 0..n as u32 {
110 if !dominators.is_reachable(m) {
111 continue;
112 }
113 let stop = idom[m as usize];
114 for &pred in &inn[in_start[m as usize] as usize..in_start[m as usize + 1] as usize] {
115 if !dominators.is_reachable(pred) {
116 continue;
117 }
118 let mut runner = pred;
119 while runner != stop && last_added[runner as usize] != m {
120 last_added[runner as usize] = m;
121 frontier[start[runner as usize] as usize] = m;
122 start[runner as usize] += 1;
123 runner = idom[runner as usize];
124 }
125 }
126 }
127 start.copy_within(0..n, 1);
128 start[0] = 0;
129 Graph::from_csr(start, frontier).expect("each frontier is strictly ascending")
130}