Skip to main content

cranelift_codegen/
dominator_tree.rs

1//! A Dominator Tree represented as mappings of Blocks to their immediate dominator.
2
3use crate::entity::SecondaryMap;
4use crate::flowgraph::{BlockPredecessor, ControlFlowGraph};
5use crate::ir::{Block, Function, Layout, ProgramPoint};
6use crate::packed_option::PackedOption;
7use crate::timing;
8use alloc::vec::Vec;
9use core::cmp;
10use core::cmp::Ordering;
11use core::mem;
12
13mod simple;
14
15pub use simple::SimpleDominatorTree;
16
17/// A directed graph over a function's basic blocks, used to drive the generic
18/// (post-)dominator tree computation shared by [`DominatorTree`] and
19/// `PostDominatorTree`.
20///
21/// The `successors`/`predecessors` methods are in the *analysis* direction:
22/// `successors` is the direction the spanning-tree DFS walks away from the
23/// roots, and `predecessors` is the direction used while computing
24/// semidominators. For the forward dominator tree (see `ForwardGraph`) this is
25/// just the control-flow graph. For the post-dominator tree it is the
26/// *reversed* control-flow graph, augmented with a virtual sink that sits above
27/// the function's exit blocks; the spanning tree's existing virtual root (node
28/// 0) plays the role of that sink.
29pub(crate) trait DomTreeGraph {
30    /// The number of blocks in the underlying function, used to size the
31    /// per-block maps.
32    fn num_blocks(&self) -> usize;
33
34    /// The roots of the (post-)dominator forest: the blocks that are direct
35    /// children of the virtual root/sink.
36    ///
37    /// For the dominator tree this is the entry block; for the post-dominator
38    /// tree these are the function's exit blocks.
39    fn roots(&self) -> impl Iterator<Item = Block>;
40
41    /// The successors of `block`.
42    fn successors(&self, block: Block) -> impl Iterator<Item = Block>;
43
44    /// The predecessors of `block`.
45    fn predecessors(&self, block: Block) -> impl Iterator<Item = Block>;
46}
47
48/// The forward control-flow graph, used to compute the standard
49/// `DominatorTree`.
50struct ForwardGraph<'a> {
51    func: &'a Function,
52    cfg: &'a ControlFlowGraph,
53}
54
55impl DomTreeGraph for ForwardGraph<'_> {
56    fn num_blocks(&self) -> usize {
57        self.func.dfg.num_blocks()
58    }
59
60    fn roots(&self) -> impl Iterator<Item = Block> {
61        self.func.layout.entry_block().into_iter()
62    }
63
64    fn successors(&self, block: Block) -> impl Iterator<Item = Block> {
65        // Heuristic: chase the children in reverse. This puts the first
66        // successor block first in the postorder, all other things being equal,
67        // which tends to prioritize loop backedges over out-edges, putting the
68        // edge-block closer to the loop body and minimizing live-ranges in
69        // linear instruction space. This heuristic doesn't have any effect on
70        // the computation of dominators, and is purely for other consumers of
71        // the postorder we cache here.
72        self.func.block_successors(block).rev()
73    }
74
75    fn predecessors(&self, block: Block) -> impl Iterator<Item = Block> {
76        self.cfg
77            .pred_iter(block)
78            .map(|pred: BlockPredecessor| pred.block)
79    }
80}
81
82/// Spanning tree node, used during domtree computation.
83#[derive(Clone, Default)]
84struct SpanningTreeNode {
85    /// This node's block in function CFG.
86    block: PackedOption<Block>,
87    /// Node's ancestor in the spanning tree.
88    /// Gets invalidated during semi-dominator computation.
89    ancestor: u32,
90    /// The smallest semi value discovered on any semi-dominator path
91    /// that went through the node up till the moment.
92    /// Gets updated in the course of semi-dominator computation.
93    label: u32,
94    /// Semidominator value for the node.
95    semi: u32,
96    /// Immediate dominator value for the node.
97    /// Initialized to node's ancestor in the spanning tree.
98    idom: u32,
99}
100
101/// DFS preorder number for unvisited nodes and the virtual root in the spanning tree.
102const NOT_VISITED: u32 = 0;
103
104/// Spanning tree, in CFG preorder.
105/// Node 0 is the virtual root and doesn't have a corresponding block.
106/// It's not required because function's CFG in Cranelift always have
107/// a singular root, but helps to avoid additional checks.
108/// Numbering nodes from 0 also follows the convention in
109/// `SimpleDominatorTree`.
110#[derive(Clone, Default)]
111struct SpanningTree {
112    nodes: Vec<SpanningTreeNode>,
113}
114
115impl SpanningTree {
116    fn new() -> Self {
117        // Include the virtual root.
118        Self {
119            nodes: vec![Default::default()],
120        }
121    }
122
123    fn with_capacity(capacity: usize) -> Self {
124        // Include the virtual root.
125        let mut nodes = Vec::with_capacity(capacity + 1);
126        nodes.push(Default::default());
127        Self { nodes }
128    }
129
130    fn len(&self) -> usize {
131        self.nodes.len()
132    }
133
134    fn reserve(&mut self, capacity: usize) {
135        // Virtual root should be already included.
136        self.nodes.reserve(capacity);
137    }
138
139    fn clear(&mut self) {
140        self.nodes.resize(1, Default::default());
141    }
142
143    /// Returns pre_number for the new node.
144    fn push(&mut self, ancestor: u32, block: Block) -> u32 {
145        // Virtual root should be already included.
146        debug_assert!(!self.nodes.is_empty());
147
148        let pre_number = self.nodes.len() as u32;
149
150        self.nodes.push(SpanningTreeNode {
151            block: block.into(),
152            ancestor,
153            label: pre_number,
154            semi: pre_number,
155            idom: ancestor,
156        });
157
158        pre_number
159    }
160}
161
162impl core::ops::Index<u32> for SpanningTree {
163    type Output = SpanningTreeNode;
164
165    fn index(&self, idx: u32) -> &Self::Output {
166        &self.nodes[idx as usize]
167    }
168}
169
170impl core::ops::IndexMut<u32> for SpanningTree {
171    fn index_mut(&mut self, idx: u32) -> &mut Self::Output {
172        &mut self.nodes[idx as usize]
173    }
174}
175
176/// Traversal event to compute both preorder spanning tree
177/// and postorder block list. Can't use `Dfs` from traversals.rs
178/// here because of the need for parent links.
179enum TraversalEvent {
180    Enter(u32, Block),
181    Exit(Block),
182}
183
184/// Dominator tree node. We keep one of these per block.
185#[derive(Clone, Default)]
186struct DominatorTreeNode {
187    /// Immediate dominator for the block, `None` for unreachable blocks.
188    idom: PackedOption<Block>,
189    /// Preorder traversal number, zero for unreachable blocks.
190    pre_number: u32,
191    /// This block's index in the CFG post-order, meaningless for unreachable
192    /// blocks.
193    post_number: u32,
194
195    /// First child node in the domtree.
196    child: PackedOption<Block>,
197
198    /// Next sibling node in the domtree. This linked list is ordered according to the CFG RPO
199    /// (i.e. decreasing CFG post-order number).
200    sibling: PackedOption<Block>,
201
202    /// Sequence number for this node in a pre-order traversal of the dominator tree.
203    /// Unreachable blocks have number 0, the entry block is 1.
204    dom_pre_number: u32,
205
206    /// Maximum `dom_pre_number` for the sub-tree of the dominator tree that is rooted at this node.
207    /// This is always >= `dom_pre_number`.
208    dom_pre_max: u32,
209}
210
211/// The dominator tree for a single function,
212/// computed using Semi-NCA algorithm.
213pub struct DominatorTree {
214    /// DFS spanning tree.
215    stree: SpanningTree,
216    /// List of CFG blocks in postorder.
217    postorder: Vec<Block>,
218    /// Dominator tree nodes.
219    nodes: SecondaryMap<Block, DominatorTreeNode>,
220
221    /// Stack for building the spanning tree.
222    dfs_worklist: Vec<TraversalEvent>,
223    /// Stack used for processing semidominator paths
224    /// in link-eval procedure.
225    eval_worklist: Vec<u32>,
226
227    valid: bool,
228}
229
230impl core::fmt::Debug for DominatorTree {
231    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
232        if !self.is_valid() {
233            return f.write_str("DominatorTree { <invalid> }");
234        }
235
236        let mut s = f.debug_tuple("DominatorTree");
237
238        if let Some((mut root, _)) = self.nodes.iter().find(|n| n.1.pre_number != NOT_VISITED) {
239            loop {
240                if let Some(b) = self.idom(root)
241                    && b != root
242                {
243                    root = b;
244                } else {
245                    break;
246                }
247            }
248
249            fn fmt_block(domtree: &DominatorTree, block: Block) -> impl core::fmt::Debug {
250                core::fmt::from_fn(move |f| {
251                    let children = domtree
252                        .children(block)
253                        .map(|c| fmt_block(domtree, c))
254                        .collect::<Vec<_>>();
255                    let mut s = f.debug_tuple(&format!("{block}"));
256                    if !children.is_empty() {
257                        s.field(&children);
258                    }
259                    s.finish()
260                })
261            }
262
263            s.field(&fmt_block(self, root));
264        }
265
266        s.finish()
267    }
268}
269
270/// Methods for querying the dominator tree.
271impl DominatorTree {
272    /// Is `block` reachable from the entry block?
273    pub fn is_reachable(&self, block: Block) -> bool {
274        self.nodes[block].pre_number != NOT_VISITED
275    }
276
277    /// Get the CFG post-order of blocks that was used to compute the dominator tree.
278    ///
279    /// Note that this post-order is not updated automatically when the CFG is modified. It is
280    /// computed from scratch and cached by `compute()`.
281    pub fn cfg_postorder(&self) -> &[Block] {
282        debug_assert!(self.is_valid());
283        &self.postorder
284    }
285
286    /// Get an iterator over CFG reverse post-order of blocks used to compute the dominator tree.
287    ///
288    /// Note that the post-order is not updated automatically when the CFG is modified. It is
289    /// computed from scratch and cached by `compute()`.
290    pub fn cfg_rpo(&self) -> impl Iterator<Item = &Block> {
291        debug_assert!(self.is_valid());
292        self.postorder.iter().rev()
293    }
294
295    /// Returns the immediate dominator of `block`.
296    ///
297    /// `block_a` is said to *dominate* `block_b` if all control flow paths from the function
298    /// entry to `block_b` must go through `block_a`.
299    ///
300    /// The *immediate dominator* is the dominator that is closest to `block`. All other dominators
301    /// also dominate the immediate dominator.
302    ///
303    /// This returns `None` if `block` is not reachable from the entry block, or if it is the entry block
304    /// which has no dominators.
305    pub fn idom(&self, block: Block) -> Option<Block> {
306        self.nodes[block].idom.into()
307    }
308
309    /// Returns `true` if `a` dominates `b`.
310    ///
311    /// This means that every control-flow path from the function entry to `b` must go through `a`.
312    ///
313    /// Dominance is ill defined for unreachable blocks. This function can always determine
314    /// dominance for instructions in the same block, but otherwise returns `false` if either block
315    /// is unreachable.
316    ///
317    /// An instruction is considered to dominate itself.
318    /// A block is also considered to dominate itself.
319    pub fn dominates<A, B>(&self, a: A, b: B, layout: &Layout) -> bool
320    where
321        A: Into<ProgramPoint>,
322        B: Into<ProgramPoint>,
323    {
324        let a = a.into();
325        let b = b.into();
326        match a {
327            ProgramPoint::Block(block_a) => match b {
328                ProgramPoint::Block(block_b) => self.block_dominates(block_a, block_b),
329                ProgramPoint::Inst(inst_b) => {
330                    let block_b = layout
331                        .inst_block(inst_b)
332                        .expect("Instruction not in layout.");
333                    self.block_dominates(block_a, block_b)
334                }
335            },
336            ProgramPoint::Inst(inst_a) => {
337                let block_a: Block = layout
338                    .inst_block(inst_a)
339                    .expect("Instruction not in layout.");
340                match b {
341                    ProgramPoint::Block(block_b) => {
342                        block_a != block_b && self.block_dominates(block_a, block_b)
343                    }
344                    ProgramPoint::Inst(inst_b) => {
345                        let block_b = layout
346                            .inst_block(inst_b)
347                            .expect("Instruction not in layout.");
348                        if block_a == block_b {
349                            layout.pp_cmp(a, b) != Ordering::Greater
350                        } else {
351                            self.block_dominates(block_a, block_b)
352                        }
353                    }
354                }
355            }
356        }
357    }
358
359    /// Returns `true` if `block_a` dominates `block_b`.
360    ///
361    /// Every block dominates itself. If `block_a != block_b` and either block
362    /// is unreachable, returns `false`.
363    ///
364    /// This uses preorder numbers for O(1) constant time performance.
365    pub fn block_dominates(&self, block_a: Block, block_b: Block) -> bool {
366        let na = &self.nodes[block_a];
367        let nb = &self.nodes[block_b];
368        block_a == block_b
369            // Unreachable blocks have dom_pre_number == dom_pre_max == 0.
370            || (na.dom_pre_number != 0
371                && na.dom_pre_number <= nb.dom_pre_number
372                && na.dom_pre_max >= nb.dom_pre_max)
373    }
374
375    /// Returns `true` if the CFG edge `from -> to` is a retreating edge.
376    ///
377    /// A retreating edge is one that goes from a block to one of its ancestors
378    /// in the depth-first spanning tree used to compute this dominator tree, or
379    /// to itself. Every cycle in the CFG contains at least one retreating edge,
380    /// including irreducible cycles, which have no back edge whose target
381    /// dominates its source. In a reducible CFG, the retreating edges are
382    /// exactly its back edges.
383    ///
384    /// Both blocks must be reachable.
385    pub fn is_retreating_edge(&self, from: Block, to: Block) -> bool {
386        debug_assert!(self.is_reachable(from));
387        debug_assert!(self.is_reachable(to));
388        self.nodes[to].post_number >= self.nodes[from].post_number
389    }
390
391    /// Get an iterator over the direct children of `block` in the dominator tree.
392    ///
393    /// These are the blocks whose immediate dominator is `block`, ordered by
394    /// decreasing CFG post-order number.
395    pub fn children(&self, block: Block) -> ChildIter<'_> {
396        ChildIter {
397            domtree: self,
398            next: self.nodes[block].child,
399        }
400    }
401}
402
403impl DominatorTree {
404    /// Allocate a new blank dominator tree. Use `compute` to compute the dominator tree for a
405    /// function.
406    pub fn new() -> Self {
407        Self {
408            stree: SpanningTree::new(),
409            nodes: SecondaryMap::new(),
410            postorder: Vec::new(),
411            dfs_worklist: Vec::new(),
412            eval_worklist: Vec::new(),
413            valid: false,
414        }
415    }
416
417    /// Allocate and compute a dominator tree.
418    pub fn with_function(func: &Function, cfg: &ControlFlowGraph) -> Self {
419        let block_capacity = func.layout.block_capacity();
420        let mut domtree = Self {
421            stree: SpanningTree::with_capacity(block_capacity),
422            nodes: SecondaryMap::with_capacity(block_capacity),
423            postorder: Vec::with_capacity(block_capacity),
424            dfs_worklist: Vec::new(),
425            eval_worklist: Vec::new(),
426            valid: false,
427        };
428        domtree.compute(func, cfg);
429        domtree
430    }
431
432    /// Reset and compute a CFG post-order and dominator tree,
433    /// using Semi-NCA algorithm, described in the paper:
434    ///
435    /// Linear-Time Algorithms for Dominators and Related Problems.
436    /// Loukas Georgiadis, Princeton University, November 2005.
437    ///
438    /// The same algorithm is used by Julia, SpiderMonkey and LLVM,
439    /// the implementation is heavily inspired by them.
440    pub fn compute(&mut self, func: &Function, cfg: &ControlFlowGraph) {
441        let _tt = timing::domtree();
442        debug_assert!(cfg.is_valid());
443        self.compute_from_graph(&ForwardGraph { func, cfg });
444    }
445
446    /// Reset and compute a post-order and dominator tree over an arbitrary
447    /// `DomTreeGraph`.
448    ///
449    /// This is the shared core used both by `DominatorTree::compute` (over the
450    /// control-flow graph) and by `PostDominatorTree` (over the reversed
451    /// control-flow graph augmented with a virtual sink).
452    pub(crate) fn compute_from_graph(&mut self, graph: &impl DomTreeGraph) {
453        self.clear();
454        self.compute_spanning_tree(graph);
455        self.compute_domtree(graph);
456        self.compute_domtree_preorder();
457
458        self.valid = true;
459    }
460
461    /// Clear the data structures used to represent the dominator tree. This will leave the tree in
462    /// a state where `is_valid()` returns false.
463    pub fn clear(&mut self) {
464        self.stree.clear();
465        self.nodes.clear();
466        self.postorder.clear();
467        self.valid = false;
468    }
469
470    /// Check if the dominator tree is in a valid state.
471    ///
472    /// Note that this doesn't perform any kind of validity checks. It simply checks if the
473    /// `compute()` method has been called since the last `clear()`. It does not check that the
474    /// dominator tree is consistent with the CFG.
475    pub fn is_valid(&self) -> bool {
476        self.valid
477    }
478
479    /// Reset all internal data structures, build spanning tree
480    /// and compute a post-order of the control flow graph.
481    fn compute_spanning_tree(&mut self, graph: &impl DomTreeGraph) {
482        self.nodes.resize(graph.num_blocks());
483        self.stree.reserve(graph.num_blocks());
484
485        for root in graph.roots() {
486            self.dfs_worklist.push(TraversalEvent::Enter(0, root));
487        }
488
489        loop {
490            match self.dfs_worklist.pop() {
491                Some(TraversalEvent::Enter(parent, block)) => {
492                    let node = &mut self.nodes[block];
493                    if node.pre_number != NOT_VISITED {
494                        continue;
495                    }
496
497                    self.dfs_worklist.push(TraversalEvent::Exit(block));
498
499                    let pre_number = self.stree.push(parent, block);
500                    node.pre_number = pre_number;
501
502                    // Push successors in the analysis direction. Any ordering
503                    // heuristic (such as the forward graph's `.rev()`) lives in
504                    // the `DomTreeGraph` implementation.
505                    self.dfs_worklist.extend(
506                        graph
507                            .successors(block)
508                            // A simple optimization: push less items to the stack.
509                            .filter(|successor| self.nodes[*successor].pre_number == NOT_VISITED)
510                            .map(|successor| TraversalEvent::Enter(pre_number, successor)),
511                    );
512                }
513                Some(TraversalEvent::Exit(block)) => {
514                    self.nodes[block].post_number = u32::try_from(self.postorder.len()).unwrap();
515                    self.postorder.push(block);
516                }
517                None => break,
518            }
519        }
520    }
521
522    /// Eval-link procedure from the paper.
523    /// For a predecessor V of node W returns V if V < W, otherwise the minimum of sdom(U),
524    /// where U > W and U is on a semi-dominator path for W in CFG.
525    /// Use path compression to bring complexity down to O(m*log(n)).
526    fn eval(&mut self, v: u32, last_linked: u32) -> u32 {
527        if self.stree[v].ancestor < last_linked {
528            return self.stree[v].label;
529        }
530
531        // Follow semi-dominator path.
532        let mut root = v;
533        loop {
534            self.eval_worklist.push(root);
535            root = self.stree[root].ancestor;
536
537            if self.stree[root].ancestor < last_linked {
538                break;
539            }
540        }
541
542        let mut prev = root;
543        let root = self.stree[prev].ancestor;
544
545        // Perform path compression. Point all ancestors to the root
546        // and propagate minimal sdom(U) value from ancestors to children.
547        while let Some(curr) = self.eval_worklist.pop() {
548            if self.stree[prev].label < self.stree[curr].label {
549                self.stree[curr].label = self.stree[prev].label;
550            }
551
552            self.stree[curr].ancestor = root;
553            prev = curr;
554        }
555
556        self.stree[v].label
557    }
558
559    fn compute_domtree(&mut self, graph: &impl DomTreeGraph) {
560        // Compute semi-dominators.
561        for w in (1..self.stree.len() as u32).rev() {
562            let w_node = &mut self.stree[w];
563            let block = w_node.block.expect("Virtual root must have been excluded");
564            let mut semi = w_node.ancestor;
565
566            let last_linked = w + 1;
567
568            for pred in graph.predecessors(block) {
569                // Skip unreachable nodes.
570                if self.nodes[pred].pre_number == NOT_VISITED {
571                    continue;
572                }
573
574                let semi_candidate = self.eval(self.nodes[pred].pre_number, last_linked);
575                semi = core::cmp::min(semi, semi_candidate);
576            }
577
578            let w_node = &mut self.stree[w];
579            w_node.label = semi;
580            w_node.semi = semi;
581        }
582
583        // Compute immediate dominators.
584        for v in 1..self.stree.len() as u32 {
585            let semi = self.stree[v].semi;
586            let block = self.stree[v]
587                .block
588                .expect("Virtual root must have been excluded");
589            let mut idom = self.stree[v].idom;
590
591            while idom > semi {
592                idom = self.stree[idom].idom;
593            }
594
595            self.stree[v].idom = idom;
596
597            self.nodes[block].idom = self.stree[idom].block;
598        }
599    }
600
601    /// Compute dominator tree preorder information.
602    ///
603    /// This populates child/sibling links and preorder numbers for fast dominance checks.
604    fn compute_domtree_preorder(&mut self) {
605        // Populate the child and sibling links.
606        //
607        // By following the CFG post-order and pushing to the front of the lists, we make sure that
608        // sibling lists are ordered according to the CFG reverse post-order (i.e. decreasing CFG
609        // post-order number).
610        for &block in &self.postorder {
611            if let Some(idom) = self.idom(block) {
612                let sib = mem::replace(&mut self.nodes[idom].child, block.into());
613                self.nodes[block].sibling = sib;
614            } else {
615                // Blocks without an immediate dominator are the roots of the
616                // (post-)dominator forest: the entry block for the forward tree,
617                // or the exit blocks for a post-dominator tree.
618                self.dfs_worklist.push(TraversalEvent::Enter(0, block));
619            }
620        }
621
622        // Assign pre-order numbers from a DFS of the dominator tree.
623        //
624        // The worklist now holds every root of the (post-)dominator forest: a
625        // single entry block for the forward `DominatorTree`, but possibly many
626        // (one per exit block) for a post-dominator forest. Each root begins a
627        // disjoint subtree, so the numbering below assigns each its own
628        // contiguous `dom_pre_number` range.
629        let mut n = 0;
630        while let Some(event) = self.dfs_worklist.pop() {
631            if let TraversalEvent::Enter(_, block) = event {
632                n += 1;
633                let node = &mut self.nodes[block];
634                node.dom_pre_number = n;
635                node.dom_pre_max = n;
636                if let Some(sibling) = node.sibling.expand() {
637                    self.dfs_worklist.push(TraversalEvent::Enter(0, sibling));
638                }
639                if let Some(child) = node.child.expand() {
640                    self.dfs_worklist.push(TraversalEvent::Enter(0, child));
641                }
642            }
643        }
644
645        // Propagate the `dom_pre_max` numbers up the tree.
646        // The CFG post-order is topologically ordered w.r.t. dominance so a node comes after all
647        // its dominator tree children.
648        for &block in &self.postorder {
649            if let Some(idom) = self.idom(block) {
650                let pre_max = cmp::max(self.nodes[block].dom_pre_max, self.nodes[idom].dom_pre_max);
651                self.nodes[idom].dom_pre_max = pre_max;
652            }
653        }
654    }
655}
656
657/// An iterator that enumerates the direct children of a block in the dominator tree.
658pub struct ChildIter<'a> {
659    domtree: &'a DominatorTree,
660    next: PackedOption<Block>,
661}
662
663impl<'a> Iterator for ChildIter<'a> {
664    type Item = Block;
665
666    fn next(&mut self) -> Option<Block> {
667        let n = self.next.expand();
668        if let Some(block) = n {
669            self.next = self.domtree.nodes[block].sibling;
670        }
671        n
672    }
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678    use crate::cursor::{Cursor, FuncCursor};
679    use crate::ir::types::*;
680    use crate::ir::{InstBuilder, TrapCode};
681
682    #[test]
683    fn empty() {
684        let func = Function::new();
685        let cfg = ControlFlowGraph::with_function(&func);
686        debug_assert!(cfg.is_valid());
687        let dtree = DominatorTree::with_function(&func, &cfg);
688        assert_eq!(0, dtree.nodes.keys().count());
689        assert_eq!(dtree.cfg_postorder(), &[]);
690    }
691
692    #[test]
693    fn unreachable_node() {
694        let mut func = Function::new();
695        let block0 = func.dfg.make_block();
696        let v0 = func.dfg.append_block_param(block0, I32);
697        let block1 = func.dfg.make_block();
698        let block2 = func.dfg.make_block();
699        let trap_block = func.dfg.make_block();
700
701        let mut cur = FuncCursor::new(&mut func);
702
703        cur.insert_block(block0);
704        cur.ins().brif(v0, block2, &[], trap_block, &[]);
705
706        cur.insert_block(trap_block);
707        cur.ins().trap(TrapCode::unwrap_user(1));
708
709        cur.insert_block(block1);
710        let v1 = cur.ins().iconst(I32, 1);
711        let v2 = cur.ins().iadd(v0, v1);
712        cur.ins().jump(block0, &[v2.into()]);
713
714        cur.insert_block(block2);
715        cur.ins().return_(&[v0]);
716
717        let cfg = ControlFlowGraph::with_function(cur.func);
718        let dt = DominatorTree::with_function(cur.func, &cfg);
719
720        // Fall-through-first, prune-at-source DFT:
721        //
722        // block0 {
723        //   brif block2 {
724        //     trap
725        //     block2 {
726        //       return
727        //     } block2
728        // } block0
729        assert_eq!(dt.cfg_postorder(), &[block2, trap_block, block0]);
730
731        let v2_def = cur.func.dfg.value_def(v2).unwrap_inst();
732        assert!(!dt.dominates(v2_def, block0, &cur.func.layout));
733        assert!(!dt.dominates(block0, v2_def, &cur.func.layout));
734
735        assert!(dt.block_dominates(block0, block0));
736        assert!(!dt.block_dominates(block0, block1));
737        assert!(dt.block_dominates(block0, block2));
738        assert!(!dt.block_dominates(block1, block0));
739        assert!(dt.block_dominates(block1, block1));
740        assert!(!dt.block_dominates(block1, block2));
741        assert!(!dt.block_dominates(block2, block0));
742        assert!(!dt.block_dominates(block2, block1));
743        assert!(dt.block_dominates(block2, block2));
744    }
745
746    #[test]
747    fn unreachable_blocks_do_not_dominate_each_other() {
748        let mut func = Function::new();
749        let block0 = func.dfg.make_block();
750        let block1 = func.dfg.make_block();
751        let block2 = func.dfg.make_block();
752
753        let mut cur = FuncCursor::new(&mut func);
754
755        cur.insert_block(block0);
756        cur.ins().return_(&[]);
757
758        // Two unreachable blocks.
759        cur.insert_block(block1);
760        let jmp12 = cur.ins().jump(block2, &[]);
761
762        cur.insert_block(block2);
763        let jmp21 = cur.ins().jump(block1, &[]);
764
765        let cfg = ControlFlowGraph::with_function(cur.func);
766        let dt = DominatorTree::with_function(cur.func, &cfg);
767
768        assert!(!dt.is_reachable(block1));
769        assert!(!dt.is_reachable(block2));
770
771        // Unreachable blocks dominate themselves but nothing else.
772        assert!(dt.block_dominates(block1, block1));
773        assert!(dt.block_dominates(block2, block2));
774        assert!(!dt.block_dominates(block1, block2));
775        assert!(!dt.block_dominates(block2, block1));
776        assert!(!dt.block_dominates(block1, block0));
777        assert!(!dt.dominates(block1, block2, &cur.func.layout));
778        assert!(!dt.dominates(jmp12, jmp21, &cur.func.layout));
779        assert!(!dt.dominates(jmp21, jmp12, &cur.func.layout));
780    }
781
782    #[test]
783    fn non_zero_entry_block() {
784        let mut func = Function::new();
785        let block0 = func.dfg.make_block();
786        let block1 = func.dfg.make_block();
787        let block2 = func.dfg.make_block();
788        let block3 = func.dfg.make_block();
789        let cond = func.dfg.append_block_param(block3, I32);
790
791        let mut cur = FuncCursor::new(&mut func);
792
793        cur.insert_block(block3);
794        let jmp_block3_block1 = cur.ins().jump(block1, &[]);
795
796        cur.insert_block(block1);
797        let br_block1_block0_block2 = cur.ins().brif(cond, block0, &[], block2, &[]);
798
799        cur.insert_block(block2);
800        cur.ins().jump(block0, &[]);
801
802        cur.insert_block(block0);
803
804        let cfg = ControlFlowGraph::with_function(cur.func);
805        let dt = DominatorTree::with_function(cur.func, &cfg);
806
807        // Fall-through-first, prune-at-source DFT:
808        //
809        // block3 {
810        //   block3:jump block1 {
811        //     block1 {
812        //       block1:brif block0 {
813        //         block1:jump block2 {
814        //           block2 {
815        //             block2:jump block0 (seen)
816        //           } block2
817        //         } block1:jump block2
818        //         block0 {
819        //         } block0
820        //       } block1:brif block0
821        //     } block1
822        //   } block3:jump block1
823        // } block3
824
825        assert_eq!(dt.cfg_postorder(), &[block0, block2, block1, block3]);
826
827        assert_eq!(cur.func.layout.entry_block().unwrap(), block3);
828        assert_eq!(dt.idom(block3), None);
829        assert_eq!(dt.idom(block1).unwrap(), block3);
830        assert_eq!(dt.idom(block2).unwrap(), block1);
831        assert_eq!(dt.idom(block0).unwrap(), block1);
832
833        assert!(dt.dominates(
834            br_block1_block0_block2,
835            br_block1_block0_block2,
836            &cur.func.layout
837        ));
838        assert!(!dt.dominates(br_block1_block0_block2, jmp_block3_block1, &cur.func.layout));
839        assert!(dt.dominates(jmp_block3_block1, br_block1_block0_block2, &cur.func.layout));
840    }
841
842    #[test]
843    fn backwards_layout() {
844        let mut func = Function::new();
845        let block0 = func.dfg.make_block();
846        let block1 = func.dfg.make_block();
847        let block2 = func.dfg.make_block();
848
849        let mut cur = FuncCursor::new(&mut func);
850
851        cur.insert_block(block0);
852        let jmp02 = cur.ins().jump(block2, &[]);
853
854        cur.insert_block(block1);
855        let trap = cur.ins().trap(TrapCode::unwrap_user(5));
856
857        cur.insert_block(block2);
858        let jmp21 = cur.ins().jump(block1, &[]);
859
860        let cfg = ControlFlowGraph::with_function(cur.func);
861        let dt = DominatorTree::with_function(cur.func, &cfg);
862
863        assert_eq!(cur.func.layout.entry_block(), Some(block0));
864        assert_eq!(dt.idom(block0), None);
865        assert_eq!(dt.idom(block1), Some(block2));
866        assert_eq!(dt.idom(block2), Some(block0));
867
868        assert!(dt.dominates(block0, block0, &cur.func.layout));
869        assert!(dt.dominates(block0, jmp02, &cur.func.layout));
870        assert!(dt.dominates(block0, block1, &cur.func.layout));
871        assert!(dt.dominates(block0, trap, &cur.func.layout));
872        assert!(dt.dominates(block0, block2, &cur.func.layout));
873        assert!(dt.dominates(block0, jmp21, &cur.func.layout));
874
875        assert!(!dt.dominates(jmp02, block0, &cur.func.layout));
876        assert!(dt.dominates(jmp02, jmp02, &cur.func.layout));
877        assert!(dt.dominates(jmp02, block1, &cur.func.layout));
878        assert!(dt.dominates(jmp02, trap, &cur.func.layout));
879        assert!(dt.dominates(jmp02, block2, &cur.func.layout));
880        assert!(dt.dominates(jmp02, jmp21, &cur.func.layout));
881
882        assert!(!dt.dominates(block1, block0, &cur.func.layout));
883        assert!(!dt.dominates(block1, jmp02, &cur.func.layout));
884        assert!(dt.dominates(block1, block1, &cur.func.layout));
885        assert!(dt.dominates(block1, trap, &cur.func.layout));
886        assert!(!dt.dominates(block1, block2, &cur.func.layout));
887        assert!(!dt.dominates(block1, jmp21, &cur.func.layout));
888
889        assert!(!dt.dominates(trap, block0, &cur.func.layout));
890        assert!(!dt.dominates(trap, jmp02, &cur.func.layout));
891        assert!(!dt.dominates(trap, block1, &cur.func.layout));
892        assert!(dt.dominates(trap, trap, &cur.func.layout));
893        assert!(!dt.dominates(trap, block2, &cur.func.layout));
894        assert!(!dt.dominates(trap, jmp21, &cur.func.layout));
895
896        assert!(!dt.dominates(block2, block0, &cur.func.layout));
897        assert!(!dt.dominates(block2, jmp02, &cur.func.layout));
898        assert!(dt.dominates(block2, block1, &cur.func.layout));
899        assert!(dt.dominates(block2, trap, &cur.func.layout));
900        assert!(dt.dominates(block2, block2, &cur.func.layout));
901        assert!(dt.dominates(block2, jmp21, &cur.func.layout));
902
903        assert!(!dt.dominates(jmp21, block0, &cur.func.layout));
904        assert!(!dt.dominates(jmp21, jmp02, &cur.func.layout));
905        assert!(dt.dominates(jmp21, block1, &cur.func.layout));
906        assert!(dt.dominates(jmp21, trap, &cur.func.layout));
907        assert!(!dt.dominates(jmp21, block2, &cur.func.layout));
908        assert!(dt.dominates(jmp21, jmp21, &cur.func.layout));
909    }
910
911    #[test]
912    fn retreating_edges() {
913        let mut func = Function::new();
914        let block0 = func.dfg.make_block();
915        let v0 = func.dfg.append_block_param(block0, I32);
916        let block1 = func.dfg.make_block();
917        let block2 = func.dfg.make_block();
918        let block3 = func.dfg.make_block();
919        let block4 = func.dfg.make_block();
920        let block5 = func.dfg.make_block();
921
922        let mut cur = FuncCursor::new(&mut func);
923
924        // An irreducible cycle between `block1` and `block2`, each of which can
925        // be entered directly from `block0`.
926        cur.insert_block(block0);
927        cur.ins().brif(v0, block1, &[], block2, &[]);
928
929        cur.insert_block(block1);
930        cur.ins().brif(v0, block2, &[], block3, &[]);
931
932        cur.insert_block(block2);
933        cur.ins().jump(block1, &[]);
934
935        // A natural loop with header `block3` and back edge `block4 -> block3`.
936        cur.insert_block(block3);
937        cur.ins().jump(block4, &[]);
938
939        cur.insert_block(block4);
940        cur.ins().brif(v0, block3, &[], block5, &[]);
941
942        // A self-loop.
943        cur.insert_block(block5);
944        cur.ins().brif(v0, block5, &[], block1, &[]);
945
946        let cfg = ControlFlowGraph::with_function(cur.func);
947        let dt = DominatorTree::with_function(cur.func, &cfg);
948
949        // Exactly one edge of the irreducible cycle retreats, depending on which
950        // of its blocks the DFS entered first. Neither block dominates the
951        // other.
952        assert!(!dt.block_dominates(block1, block2));
953        assert!(!dt.block_dominates(block2, block1));
954        assert_ne!(
955            dt.is_retreating_edge(block1, block2),
956            dt.is_retreating_edge(block2, block1),
957        );
958
959        assert!(dt.is_retreating_edge(block4, block3));
960        assert!(dt.is_retreating_edge(block5, block5));
961        assert!(dt.is_retreating_edge(block5, block1));
962
963        assert!(!dt.is_retreating_edge(block0, block1));
964        assert!(!dt.is_retreating_edge(block0, block2));
965        assert!(!dt.is_retreating_edge(block1, block3));
966        assert!(!dt.is_retreating_edge(block3, block4));
967        assert!(!dt.is_retreating_edge(block4, block5));
968    }
969
970    #[test]
971    fn insts_same_block() {
972        let mut func = Function::new();
973        let block0 = func.dfg.make_block();
974
975        let mut cur = FuncCursor::new(&mut func);
976
977        cur.insert_block(block0);
978        let v1 = cur.ins().iconst(I32, 1);
979        let v2 = cur.ins().iadd(v1, v1);
980        let v3 = cur.ins().iadd(v2, v2);
981        cur.ins().return_(&[]);
982
983        let cfg = ControlFlowGraph::with_function(cur.func);
984        let dt = DominatorTree::with_function(cur.func, &cfg);
985
986        let v1_def = cur.func.dfg.value_def(v1).unwrap_inst();
987        let v2_def = cur.func.dfg.value_def(v2).unwrap_inst();
988        let v3_def = cur.func.dfg.value_def(v3).unwrap_inst();
989
990        assert!(dt.dominates(v1_def, v2_def, &cur.func.layout));
991        assert!(dt.dominates(v2_def, v3_def, &cur.func.layout));
992        assert!(dt.dominates(v1_def, v3_def, &cur.func.layout));
993
994        assert!(!dt.dominates(v2_def, v1_def, &cur.func.layout));
995        assert!(!dt.dominates(v3_def, v2_def, &cur.func.layout));
996        assert!(!dt.dominates(v3_def, v1_def, &cur.func.layout));
997
998        assert!(dt.dominates(v2_def, v2_def, &cur.func.layout));
999        assert!(dt.dominates(block0, block0, &cur.func.layout));
1000
1001        assert!(dt.dominates(block0, v1_def, &cur.func.layout));
1002        assert!(dt.dominates(block0, v2_def, &cur.func.layout));
1003        assert!(dt.dominates(block0, v3_def, &cur.func.layout));
1004
1005        assert!(!dt.dominates(v1_def, block0, &cur.func.layout));
1006        assert!(!dt.dominates(v2_def, block0, &cur.func.layout));
1007        assert!(!dt.dominates(v3_def, block0, &cur.func.layout));
1008    }
1009}