graphity_core/dominators.rs
1use crate::error::check_index;
2use crate::graph::{SharedArray, share};
3use crate::{BiAdjacentGraph, NONE, dfs_preorder::DfsPreorder};
4
5/// Unlinked marker in the ancestor lane of the path-compression forest.
6const UNLINKED: u32 = NONE;
7
8/// The dominators of a graph with one or more entries, such as the control flow of a method, given
9/// by the immediate dominator of every node.
10///
11/// A node `d` dominates a node `n` if every path from an entry to `n` passes through `d`; every node
12/// dominates itself. The immediate dominator of `n` is the dominator closest to `n` other than `n`
13/// itself. The immediate dominators form the dominator tree, which
14/// [`graphs::dominator_tree`](crate::graphs::dominator_tree) returns as a graph. Several entries act
15/// like one virtual root above all of them. A node that only this virtual root dominates, such as an
16/// entry, has no immediate dominator and is a root of the dominator tree, which is then a forest. A
17/// node that no entry reaches has no immediate dominator either; [`is_reachable`](Self::is_reachable)
18/// tells the two apart.
19///
20/// Whether one node dominates another is an ancestor query on the dominator tree.
21/// [`Ancestry::of_dominators`](crate::Ancestry::of_dominators) answers it in O(log node_count) and
22/// [`PreorderAncestry`](crate::PreorderAncestry) in O(1). The analysis follows the edges against their
23/// direction, so it takes a [`BiAdjacentGraph`]. Here, the dominators of the basic blocks of the
24/// method `load` from its `entry`, and whether `body` and `then` dominate `next`:
25///
26/// <!-- example: dominance.rs#dominators -->
27/// ```
28/// # use graphity_core::{Ancestry, BiAdjacentGraph, Dominators};
29/// # let cfg = graphity_core::Graph::of(&[0, 1, 3, 5, 6, 7, 7], &[1, 2, 5, 3, 4, 4, 1]).unwrap();
30/// # let (entry, body, then, next) = (0, 2, 3, 4);
31/// let dominators = Dominators::of(&BiAdjacentGraph::of(&cfg), entry);
32/// let idom = dominators.immediate_dominator_of(next); // Some(2) - the block body
33/// let dominance = Ancestry::of_dominators(&dominators);
34/// let body_dominates_next = dominance.is_ancestor_of(body, next); // true
35/// let then_dominates_next = dominance.is_ancestor_of(then, next); // false
36/// # assert_eq!(idom, Some(2));
37/// # assert!(body_dominates_next);
38/// # assert!(!then_dominates_next);
39/// ```
40///
41/// The post-dominators are the dominators of the transposed graph, with the exits as entries. A node
42/// `p` post-dominates `n` if every path from `n` to an exit passes through `p`. Here, `next` is the
43/// first block that every path from `body` to the `exit` of `load` passes through:
44///
45/// <!-- example: dominance.rs#postDominators -->
46/// ```
47/// # use graphity_core::{BiAdjacentGraph, Dominators};
48/// # let cfg = graphity_core::Graph::of(&[0, 1, 3, 5, 6, 7, 7], &[1, 2, 5, 3, 4, 4, 1]).unwrap();
49/// # let (body, exit) = (2, 5);
50/// let post_dominators = Dominators::of(&BiAdjacentGraph::of(&cfg).transposed(), exit);
51/// let join = post_dominators.immediate_dominator_of(body); // Some(4) - the block next
52/// # assert_eq!(join, Some(4));
53/// ```
54///
55/// A node from which no exit can be reached, such as one in an endless loop, has no post-dominator,
56/// unless an extra exit with an edge from that loop is added to the graph first.
57///
58/// Uses [the algorithm of Lengauer and Tarjan](https://en.wikipedia.org/wiki/Dominator_(graph_theory)),
59/// without recursion. Dominance frontiers and control dependence are in the crate
60/// `graphity-controlflow`.
61///
62/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
63///
64/// **Memory:** 4 x node_count bytes and 1 bit per node, plus the graph, which stays reachable as long
65/// as the dominators are.
66#[derive(Debug, Clone)]
67pub struct Dominators {
68 graph: BiAdjacentGraph,
69 /// Immediate dominator of each node, [`NONE`] for a root of the forest and when unreachable.
70 pub(crate) immediate_dominator: SharedArray,
71 /// Bit set of the nodes reachable from at least one entry.
72 reachable: Box<[u64]>,
73}
74
75impl Dominators {
76 /// Returns the dominators of `graph` with the single entry `entry`. Equivalent to
77 /// [`of_entries(graph, &[entry])`](Self::of_entries) - Java's overload `of(BiAdjacentGraph, int)`.
78 ///
79 /// **Time:** O((node_count + edge_count) log node_count).
80 /// **Memory:** 4 x node_count bytes and 1 bit per node for the result; while it runs, up to
81 /// 32 x node_count bytes more.
82 ///
83 /// # Panics
84 /// With an `index out of bounds` message if `entry` is not in `0..node_count`; with an
85 /// `invalid argument` message if `graph` has more than `2^30 - 6` nodes.
86 #[track_caller]
87 pub fn of(graph: &BiAdjacentGraph, entry: u32) -> Dominators {
88 Self::of_entries(graph, &[entry])
89 }
90
91 /// Returns the dominators of `graph` with the given entries - Java's overload
92 /// `of(BiAdjacentGraph, IntList)`.
93 ///
94 /// Several entries act like one virtual root above all of them, as the type documentation describes.
95 /// Their order does not matter. An entry given twice counts once, and with no entries, no node is
96 /// reachable.
97 ///
98 /// **Time:** O(entries.len() + (node_count + edge_count) log node_count).
99 /// **Memory:** 4 x node_count bytes and 1 bit per node for the result; while it runs, up to
100 /// 32 x node_count bytes more.
101 ///
102 /// # Panics
103 /// With an `index out of bounds` message if an entry is not in `0..node_count`; with an
104 /// `invalid argument` message if `graph` has more than `2^30 - 6` nodes.
105 #[track_caller]
106 pub fn of_entries(graph: &BiAdjacentGraph, entries: &[u32]) -> Dominators {
107 let n = graph.node_count() as usize;
108 let dfs = DfsPreorder::of(graph, entries, "Dominators");
109 let idom = lengauer_tarjan(
110 &dfs,
111 graph.in_adjacency_start(),
112 graph.in_adjacency(),
113 false,
114 );
115
116 // Back to node IDs; the virtual root becomes NONE.
117 let order = &dfs.order;
118 let mut immediate_dominator = vec![NONE; n];
119 let mut reachable = vec![0u64; (n >> 6) + 1];
120 for v in 1..=dfs.reached_count as usize {
121 let node = order[v] as usize;
122 reachable[node >> 6] |= 1 << (node & 63);
123 if idom[v] != 0 {
124 immediate_dominator[node] = order[idom[v] as usize];
125 }
126 }
127 Dominators {
128 graph: graph.clone(),
129 immediate_dominator: share(immediate_dominator),
130 reachable: reachable.into_boxed_slice(),
131 }
132 }
133
134 /// Immediate dominators of each block's induced subgraph, as node IDs, [`NONE`] for the entry
135 /// of a block. A block is the set of nodes the search numbers from one entry. No entry may be
136 /// reached by the search from an earlier one, and every node must be reached. One node of
137 /// every strongly connected component, sink components first, satisfies this: each search
138 /// stays inside its component, so the blocks are the components and the edges between them are
139 /// ignored.
140 pub(crate) fn within_blocks(graph: &BiAdjacentGraph, entries: &[u32]) -> Vec<u32> {
141 let dfs = DfsPreorder::of(graph, entries, "Dominators");
142 let idom = lengauer_tarjan(&dfs, graph.in_adjacency_start(), graph.in_adjacency(), true);
143 let mut immediate_dominator = vec![NONE; graph.node_count() as usize];
144 for v in 1..=dfs.reached_count as usize {
145 if idom[v] != 0 {
146 immediate_dominator[dfs.order[v] as usize] = dfs.order[idom[v] as usize];
147 }
148 }
149 immediate_dominator
150 }
151
152 /// Returns the graph these dominators were computed on, for analyses that need both, such as
153 /// dominance frontiers. It shares its arrays with the graph passed in.
154 ///
155 /// **Time:** O(1).
156 pub fn graph(&self) -> &BiAdjacentGraph {
157 &self.graph
158 }
159
160 /// Returns the immediate dominator of `node`, or `None` if it has none - Java's `-1`.
161 ///
162 /// A node has none if it is an entry, if only the virtual root above several entries dominates it,
163 /// or if no entry reaches it.
164 ///
165 /// **Time:** O(1).
166 ///
167 /// # Panics
168 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
169 #[inline]
170 #[track_caller]
171 pub fn immediate_dominator_of(&self, node: u32) -> Option<u32> {
172 check_index(node, self.immediate_dominator.len() as u32);
173 let idom = self.immediate_dominator[node as usize];
174 (idom != NONE).then_some(idom)
175 }
176
177 /// Returns whether `node` is reachable from an entry.
178 ///
179 /// **Time:** O(1).
180 ///
181 /// # Panics
182 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
183 #[inline]
184 #[track_caller]
185 pub fn is_reachable(&self, node: u32) -> bool {
186 check_index(node, self.immediate_dominator.len() as u32);
187 let v = node as usize;
188 self.reachable[v >> 6] & (1 << (v & 63)) != 0
189 }
190}
191
192/// Immediate dominators by preorder number, 0 for the virtual root. `in_start` and `inn` are the
193/// in-adjacency over node IDs, translated per edge into preorder numbers (0 = unreachable).
194///
195/// Step 1 settles a node once the search path from its semidominator down to it is linked: the
196/// node then gets its immediate dominator, or a node with the same one, which step 2 resolves.
197///
198/// With `within_blocks`, predecessors outside the block of the node are ignored, as described at
199/// [`Dominators::within_blocks`]. A block is a contiguous range of preorder numbers that starts at
200/// its entry, and every predecessor in another block comes from a later one.
201fn lengauer_tarjan(
202 dfs: &DfsPreorder,
203 in_start: &[u32],
204 inn: &[u32],
205 within_blocks: bool,
206) -> Vec<u32> {
207 let size = dfs.reached_count as usize + 1;
208 let parent = &dfs.parent;
209 let order = &dfs.order;
210 let number = &dfs.preorder_number;
211 let mut semi: Vec<u32> = (0..size as u32).collect();
212 // Two lanes per preorder number, ancestor and label of the path-compression forest: one cache
213 // line serves both reads of a compression step.
214 let mut lanes = vec![0u32; 2 * size];
215 for v in 0..size {
216 lanes[2 * v] = UNLINKED;
217 lanes[2 * v + 1] = v as u32;
218 }
219 // While a node waits in a bucket, its idom slot links it to the next node of the same bucket.
220 let mut idom = vec![0u32; size];
221 let mut bucket = vec![NONE; size];
222
223 // 1) Reverse preorder: semidominator, link to the search parent, settle the parent's bucket.
224 let mut block_end = size as u32 - 1;
225 for v in (1..size).rev() {
226 let v32 = v as u32;
227 let mut best = v32;
228 let node = order[v] as usize;
229 let preds = &inn[in_start[node] as usize..in_start[node + 1] as usize];
230 if within_blocks {
231 for &pred in preds {
232 let u = number[pred as usize];
233 if u > block_end {
234 continue;
235 }
236 let candidate = if u < v32 {
237 u
238 } else {
239 semi[eval(&mut lanes, &semi, u) as usize]
240 };
241 best = best.min(candidate);
242 }
243 if dfs.is_entry(v32) {
244 block_end = v32 - 1;
245 }
246 } else {
247 for &pred in preds {
248 let u = number[pred as usize];
249 if u == 0 {
250 continue;
251 }
252 let candidate = if u < v32 {
253 u
254 } else {
255 semi[eval(&mut lanes, &semi, u) as usize]
256 };
257 best = best.min(candidate);
258 }
259 }
260 let s = if dfs.is_entry(v32) { 0 } else { best };
261 semi[v] = s;
262 idom[v] = bucket[s as usize];
263 bucket[s as usize] = v32;
264 let p = parent[v];
265 lanes[2 * v] = p;
266 let mut w = bucket[p as usize];
267 while w != NONE {
268 let next = idom[w as usize];
269 let u = eval(&mut lanes, &semi, w);
270 idom[w as usize] = if semi[u as usize] < semi[w as usize] {
271 u
272 } else {
273 p
274 };
275 w = next;
276 }
277 bucket[p as usize] = NONE;
278 }
279
280 // 2) Preorder: a node settled with a deferred dominator takes that node's, already final.
281 for v in 1..size {
282 if idom[v] != semi[v] {
283 idom[v] = idom[idom[v] as usize];
284 }
285 }
286 idom
287}
288
289/// The node of least semidominator on the forest path from `v` up to, but excluding, its tree
290/// root, compressing the path on the way.
291#[inline]
292fn eval(lanes: &mut [u32], semi: &[u32], v: u32) -> u32 {
293 let ancestor = lanes[2 * v as usize];
294 if ancestor == UNLINKED {
295 return v;
296 }
297 if lanes[2 * ancestor as usize] != UNLINKED {
298 compress(lanes, semi, v);
299 }
300 lanes[2 * v as usize + 1]
301}
302
303/// Path compression without recursion and without a stack: the way up reverses the ancestor
304/// pointers, the way down restores them pointing at the tree root and carries the best label
305/// along.
306fn compress(lanes: &mut [u32], semi: &[u32], v: u32) {
307 let mut below = UNLINKED;
308 let mut x = v as usize;
309 while lanes[2 * lanes[2 * x] as usize] != UNLINKED {
310 let up = lanes[2 * x] as usize;
311 lanes[2 * x] = below;
312 below = x as u32;
313 x = up;
314 }
315 while below != UNLINKED {
316 let y = below as usize;
317 below = lanes[2 * y];
318 let x_label = lanes[2 * x + 1];
319 if semi[x_label as usize] < semi[lanes[2 * y + 1] as usize] {
320 lanes[2 * y + 1] = x_label;
321 }
322 lanes[2 * y] = lanes[2 * x];
323 x = y;
324 }
325}