1use crate::dominator_tree::{ChildIter, DomTreeGraph, DominatorTree};
25use crate::flowgraph::{BlockPredecessor, ControlFlowGraph};
26use crate::ir::{Block, Layout, ProgramPoint};
27use core::cmp::Ordering;
28
29struct ReverseGraph<'a> {
33 cfg: &'a ControlFlowGraph,
34}
35
36impl DomTreeGraph for ReverseGraph<'_> {
37 fn num_blocks(&self) -> usize {
38 self.cfg.num_blocks()
39 }
40
41 fn roots(&self) -> impl Iterator<Item = Block> {
42 self.cfg
53 .blocks()
54 .filter(|&block| self.cfg.succ_iter(block).next().is_none())
55 }
56
57 fn successors(&self, block: Block) -> impl Iterator<Item = Block> {
58 self.cfg
61 .pred_iter(block)
62 .map(|pred: BlockPredecessor| pred.block)
63 }
64
65 fn predecessors(&self, block: Block) -> impl Iterator<Item = Block> {
66 self.cfg.succ_iter(block)
69 }
70}
71
72pub struct PostDominatorTree {
74 dom_tree: DominatorTree,
77}
78
79impl Default for PostDominatorTree {
80 fn default() -> Self {
81 Self::new()
82 }
83}
84
85impl PostDominatorTree {
86 pub fn new() -> Self {
90 Self {
91 dom_tree: DominatorTree::new(),
92 }
93 }
94
95 pub fn with_cfg(cfg: &ControlFlowGraph) -> Self {
97 let mut post_domtree = Self::new();
98 post_domtree.compute(cfg);
99 post_domtree
100 }
101
102 pub fn compute(&mut self, cfg: &ControlFlowGraph) {
105 debug_assert!(cfg.is_valid());
106 self.dom_tree.compute_from_graph(&ReverseGraph { cfg });
107 }
108
109 pub fn clear(&mut self) {
114 self.dom_tree.clear();
115 }
116
117 pub fn is_valid(&self) -> bool {
124 self.dom_tree.is_valid()
125 }
126
127 pub fn immediate_post_dominator(&self, block: Block) -> Option<Block> {
140 self.dom_tree.idom(block)
141 }
142
143 pub fn post_dominates<A, B>(&self, a: A, b: B, layout: &Layout) -> bool
146 where
147 A: Into<ProgramPoint>,
148 B: Into<ProgramPoint>,
149 {
150 let a = a.into();
151 let b = b.into();
152 match a {
153 ProgramPoint::Block(block_a) => match b {
154 ProgramPoint::Block(block_b) => self.block_post_dominates(block_a, block_b),
155 ProgramPoint::Inst(inst_b) => {
156 let block_b = layout
157 .inst_block(inst_b)
158 .expect("instruction not in layout");
159 block_a != block_b && self.block_post_dominates(block_a, block_b)
163 }
164 },
165 ProgramPoint::Inst(inst_a) => {
166 let block_a: Block = layout
167 .inst_block(inst_a)
168 .expect("Instruction not in layout.");
169 match b {
170 ProgramPoint::Block(block_b) => {
171 self.block_post_dominates(block_a, block_b)
175 }
176 ProgramPoint::Inst(inst_b) => {
177 let block_b = layout
178 .inst_block(inst_b)
179 .expect("instruction not in layout");
180 if block_a == block_b {
181 layout.pp_cmp(a, b) != Ordering::Less
184 } else {
185 self.block_post_dominates(block_a, block_b)
186 }
187 }
188 }
189 }
190 }
191 }
192
193 pub fn block_post_dominates(&self, block_a: Block, block_b: Block) -> bool {
199 self.dom_tree.block_dominates(block_a, block_b)
200 }
201
202 pub fn children(&self, block: Block) -> ChildIter<'_> {
207 self.dom_tree.children(block)
208 }
209
210 pub fn diverges(&self, block: Block) -> bool {
212 !self.dom_tree.is_reachable(block)
216 }
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use crate::cursor::{Cursor, FuncCursor};
223 use crate::ir::types::*;
224 use crate::ir::{Function, InstBuilder, TrapCode};
225 use alloc::string::String;
226 use alloc::vec::Vec;
227 use mutatis::{Mutate, check::Check, mutators as m};
228
229 #[test]
230 fn empty() {
231 let func = Function::new();
232 let cfg = ControlFlowGraph::with_function(&func);
233 let pdt = PostDominatorTree::with_cfg(&cfg);
234 assert!(pdt.is_valid());
235 }
236
237 #[test]
238 fn lifecycle() {
239 let mut func = Function::new();
240 let block0 = func.dfg.make_block();
241 let mut cur = FuncCursor::new(&mut func);
242 cur.insert_block(block0);
243 cur.ins().return_(&[]);
244 let cfg = ControlFlowGraph::with_function(cur.func);
245
246 let mut pdt = PostDominatorTree::new();
247 assert!(!pdt.is_valid());
248 pdt.compute(&cfg);
249 assert!(pdt.is_valid());
250 pdt.clear();
251 assert!(!pdt.is_valid());
252 pdt.compute(&cfg);
254 assert!(pdt.is_valid());
255 }
256
257 #[test]
258 fn straight_line() {
259 let mut func = Function::new();
260 let block0 = func.dfg.make_block();
261 let mut cur = FuncCursor::new(&mut func);
262 cur.insert_block(block0);
263 let v0 = cur.ins().iconst(I32, 1);
264 let v1 = cur.ins().iadd(v0, v0);
265 cur.ins().return_(&[]);
266
267 let cfg = ControlFlowGraph::with_function(cur.func);
268 let pdt = PostDominatorTree::with_cfg(&cfg);
269
270 assert_eq!(pdt.immediate_post_dominator(block0), None);
273 assert!(pdt.block_post_dominates(block0, block0));
274 assert!(!pdt.diverges(block0));
275
276 let v0_def = cur.func.dfg.value_def(v0).unwrap_inst();
278 let v1_def = cur.func.dfg.value_def(v1).unwrap_inst();
279 assert!(pdt.post_dominates(v1_def, v0_def, &cur.func.layout));
280 assert!(!pdt.post_dominates(v0_def, v1_def, &cur.func.layout));
281 assert!(pdt.post_dominates(v0_def, v0_def, &cur.func.layout));
282 }
283
284 #[test]
285 fn if_else_diamond() {
286 let mut func = Function::new();
287 let block0 = func.dfg.make_block();
288 let block1 = func.dfg.make_block();
289 let block2 = func.dfg.make_block();
290 let join = func.dfg.make_block();
291
292 let mut cur = FuncCursor::new(&mut func);
293
294 cur.insert_block(block0);
295 let v0 = cur.ins().iconst(I32, 0);
296 cur.ins().brif(v0, block1, &[], block2, &[]);
297
298 cur.insert_block(block1);
299 cur.ins().jump(join, &[]);
300
301 cur.insert_block(block2);
302 cur.ins().jump(join, &[]);
303
304 cur.insert_block(join);
305 cur.ins().return_(&[]);
306
307 let cfg = ControlFlowGraph::with_function(cur.func);
308 let pdt = PostDominatorTree::with_cfg(&cfg);
309
310 assert_eq!(pdt.immediate_post_dominator(block0), Some(join));
312 assert_eq!(pdt.immediate_post_dominator(block1), Some(join));
313 assert_eq!(pdt.immediate_post_dominator(block2), Some(join));
314 assert_eq!(pdt.immediate_post_dominator(join), None);
315
316 assert!(pdt.block_post_dominates(join, block0));
317 assert!(pdt.block_post_dominates(join, block1));
318 assert!(!pdt.block_post_dominates(block1, block0));
320 assert!(!pdt.block_post_dominates(block2, block0));
321 assert!(!pdt.block_post_dominates(block0, join));
323
324 for block in [block0, block1, block2, join] {
325 assert!(!pdt.diverges(block));
326 }
327
328 let layout = &cur.func.layout;
330 let entry_term = layout.last_inst(block0).unwrap();
331 let join_term = layout.last_inst(join).unwrap();
332 assert!(pdt.post_dominates(join_term, entry_term, layout));
334 assert!(!pdt.post_dominates(entry_term, join_term, layout));
336 assert!(pdt.post_dominates(join, entry_term, layout));
338 assert!(!pdt.post_dominates(entry_term, join, layout));
339
340 let mut kids = pdt.children(join).collect::<alloc::vec::Vec<_>>();
342 kids.sort();
343 assert_eq!(kids, [block0, block1, block2]);
344 }
345
346 #[test]
347 fn terminating_loop() {
348 let mut func = Function::new();
349 let entry = func.dfg.make_block();
350 let header = func.dfg.make_block();
351 let body = func.dfg.make_block();
352 let exit = func.dfg.make_block();
353
354 let mut cur = FuncCursor::new(&mut func);
355
356 cur.insert_block(entry);
357 cur.ins().jump(header, &[]);
358 cur.insert_block(header);
359 let v0 = cur.ins().iconst(I32, 0);
360 cur.ins().brif(v0, body, &[], exit, &[]);
361
362 cur.insert_block(body);
363 cur.ins().jump(header, &[]);
364 cur.insert_block(exit);
365 cur.ins().return_(&[]);
366
367 let cfg = ControlFlowGraph::with_function(cur.func);
368 let pdt = PostDominatorTree::with_cfg(&cfg);
369
370 assert_eq!(pdt.immediate_post_dominator(entry), Some(header));
371 assert_eq!(pdt.immediate_post_dominator(header), Some(exit));
372 assert_eq!(pdt.immediate_post_dominator(body), Some(header));
373 assert_eq!(pdt.immediate_post_dominator(exit), None);
374
375 assert!(pdt.block_post_dominates(exit, entry));
376 assert!(pdt.block_post_dominates(exit, body));
377 assert!(pdt.block_post_dominates(header, body));
378 assert!(!pdt.block_post_dominates(body, header));
379
380 for block in [entry, header, body, exit] {
382 assert!(!pdt.diverges(block));
383 }
384 }
385
386 #[test]
387 fn infinite_loop() {
388 let mut func = Function::new();
389 let block0 = func.dfg.make_block();
390 let mut cur = FuncCursor::new(&mut func);
391 cur.insert_block(block0);
392 cur.ins().jump(block0, &[]);
393
394 let cfg = ControlFlowGraph::with_function(cur.func);
395 let pdt = PostDominatorTree::with_cfg(&cfg);
396
397 assert!(pdt.is_valid());
400 assert!(pdt.diverges(block0));
401 assert_eq!(pdt.immediate_post_dominator(block0), None);
402 }
403
404 #[test]
405 fn infinite_loop_with_side_exit() {
406 let mut func = Function::new();
407 let entry = func.dfg.make_block();
408 let header = func.dfg.make_block();
409 let body = func.dfg.make_block();
410 let exit = func.dfg.make_block();
411
412 let mut cur = FuncCursor::new(&mut func);
413
414 cur.insert_block(entry);
415 cur.ins().jump(header, &[]);
416
417 cur.insert_block(header);
418 let v0 = cur.ins().iconst(I32, 0);
419 cur.ins().brif(v0, exit, &[], body, &[]);
420
421 cur.insert_block(body);
423 cur.ins().jump(body, &[]);
424
425 cur.insert_block(exit);
426 cur.ins().return_(&[]);
427
428 let cfg = ControlFlowGraph::with_function(cur.func);
429 let pdt = PostDominatorTree::with_cfg(&cfg);
430
431 assert!(pdt.diverges(body));
433 assert_eq!(pdt.immediate_post_dominator(body), None);
434
435 assert!(!pdt.diverges(entry));
436 assert!(!pdt.diverges(header));
437 assert!(!pdt.diverges(exit));
438 assert_eq!(pdt.immediate_post_dominator(header), Some(exit));
439 assert_eq!(pdt.immediate_post_dominator(entry), Some(header));
440 assert_eq!(pdt.immediate_post_dominator(exit), None);
441 }
442
443 #[test]
444 fn multiple_returns() {
445 let mut func = Function::new();
446 let entry = func.dfg.make_block();
447 let block1 = func.dfg.make_block();
448 let block2 = func.dfg.make_block();
449
450 let mut cur = FuncCursor::new(&mut func);
451
452 cur.insert_block(entry);
453 let v0 = cur.ins().iconst(I32, 0);
454 cur.ins().brif(v0, block1, &[], block2, &[]);
455
456 cur.insert_block(block1);
457 cur.ins().return_(&[]);
458
459 cur.insert_block(block2);
460 cur.ins().return_(&[]);
461
462 let cfg = ControlFlowGraph::with_function(cur.func);
463 let pdt = PostDominatorTree::with_cfg(&cfg);
464
465 assert_eq!(pdt.immediate_post_dominator(block1), None);
468 assert_eq!(pdt.immediate_post_dominator(block2), None);
469 assert_eq!(pdt.immediate_post_dominator(entry), None);
470
471 assert!(!pdt.block_post_dominates(block1, entry));
472 assert!(!pdt.block_post_dominates(block2, entry));
473
474 assert!(!pdt.block_post_dominates(block1, block2));
476 assert!(!pdt.block_post_dominates(block2, block1));
477
478 for block in [entry, block1, block2] {
479 assert!(!pdt.diverges(block));
480 }
481 }
482
483 #[test]
484 fn trap_as_exit() {
485 let mut func = Function::new();
486 let entry = func.dfg.make_block();
487 let ret_block = func.dfg.make_block();
488 let trap_block = func.dfg.make_block();
489
490 let mut cur = FuncCursor::new(&mut func);
491
492 cur.insert_block(entry);
493 let v0 = cur.ins().iconst(I32, 0);
494 cur.ins().brif(v0, ret_block, &[], trap_block, &[]);
495
496 cur.insert_block(ret_block);
497 cur.ins().return_(&[]);
498
499 cur.insert_block(trap_block);
500 cur.ins().trap(TrapCode::unwrap_user(1));
501
502 let cfg = ControlFlowGraph::with_function(cur.func);
503 let pdt = PostDominatorTree::with_cfg(&cfg);
504
505 assert_eq!(pdt.immediate_post_dominator(trap_block), None);
508 assert_eq!(pdt.immediate_post_dominator(ret_block), None);
509 assert_eq!(pdt.immediate_post_dominator(entry), None);
510
511 assert!(!pdt.diverges(trap_block));
512 assert!(!pdt.diverges(ret_block));
513 assert!(!pdt.diverges(entry));
514 }
515
516 #[test]
517 fn insts_post_dominate_same_block() {
518 let mut func = Function::new();
519 let block0 = func.dfg.make_block();
520
521 let mut cur = FuncCursor::new(&mut func);
522 cur.insert_block(block0);
523 let v1 = cur.ins().iconst(I32, 1);
524 let v2 = cur.ins().iadd(v1, v1);
525 let v3 = cur.ins().iadd(v2, v2);
526 cur.ins().return_(&[]);
527
528 let cfg = ControlFlowGraph::with_function(cur.func);
529 let pdt = PostDominatorTree::with_cfg(&cfg);
530
531 let v1_def = cur.func.dfg.value_def(v1).unwrap_inst();
532 let v2_def = cur.func.dfg.value_def(v2).unwrap_inst();
533 let v3_def = cur.func.dfg.value_def(v3).unwrap_inst();
534 let layout = &cur.func.layout;
535
536 assert!(pdt.post_dominates(v2_def, v1_def, layout));
538 assert!(pdt.post_dominates(v3_def, v1_def, layout));
539 assert!(pdt.post_dominates(v3_def, v2_def, layout));
540
541 assert!(!pdt.post_dominates(v1_def, v2_def, layout));
543 assert!(!pdt.post_dominates(v1_def, v3_def, layout));
544
545 assert!(pdt.post_dominates(v2_def, v2_def, layout));
547
548 assert!(pdt.post_dominates(v1_def, block0, layout));
550 assert!(!pdt.post_dominates(block0, v1_def, layout));
553
554 assert!(pdt.post_dominates(block0, block0, layout));
556 }
557
558 #[test]
565 fn post_dominators_match_oracle() -> mutatis::check::CheckResult<GraphSpec> {
566 use Terminator::*;
567
568 let corpus = [
569 GraphSpec {
571 blocks: alloc::vec![Return],
572 },
573 GraphSpec {
575 blocks: alloc::vec![Jump(1), Jump(2), Return],
576 },
577 GraphSpec {
579 blocks: alloc::vec![Brif(1, 2), Jump(3), Jump(3), Return],
580 },
581 GraphSpec {
583 blocks: alloc::vec![Jump(1), Brif(1, 2), Return],
584 },
585 GraphSpec {
587 blocks: alloc::vec![Jump(1), Jump(0)],
588 },
589 ];
590
591 Check::new()
592 .iters(10_000)
593 .run_with(m::default::<GraphSpec>(), corpus, check_post_dominance)
594 }
595
596 const MAX_BLOCKS: usize = 12;
599
600 #[derive(Clone, Debug, Default, Mutate)]
602 struct GraphSpec {
603 blocks: Vec<Terminator>,
604 }
605
606 impl GraphSpec {
607 fn fixup(&self) -> Option<Self> {
608 let n = self.blocks.len().min(MAX_BLOCKS);
609 if n == 0 {
610 return None;
611 }
612 let mut graph = GraphSpec {
613 blocks: self.blocks[..n].to_vec(),
614 };
615 for terminator in &mut graph.blocks {
616 terminator.fixup(n);
617 }
618 Some(graph)
619 }
620
621 fn build(&self) -> (Function, Vec<Block>) {
623 let mut func = Function::new();
624
625 let blocks: Vec<Block> = (0..self.blocks.len())
626 .map(|_| func.dfg.make_block())
627 .collect();
628
629 let mut cur = FuncCursor::new(&mut func);
630 for (i, terminator) in self.blocks.iter().enumerate() {
631 cur.insert_block(blocks[i]);
632 match *terminator {
633 Terminator::Return => {
634 cur.ins().return_(&[]);
635 }
636 Terminator::Jump(t) => {
637 cur.ins().jump(blocks[t], &[]);
638 }
639 Terminator::Brif(t1, t2) => {
640 let c = cur.ins().iconst(I32, 0);
641 cur.ins().brif(c, blocks[t1], &[], blocks[t2], &[]);
642 }
643 }
644 }
645 (func, blocks)
646 }
647 }
648
649 #[derive(Clone, Copy, Debug, Default, Mutate)]
651 enum Terminator {
652 #[default]
653 Return,
654 Jump(usize),
655 Brif(usize, usize),
656 }
657
658 impl Terminator {
659 fn fixup(&mut self, n: usize) {
660 match self {
661 Self::Return => {}
662 Self::Jump(a) => {
663 *a %= n;
664 }
665 Self::Brif(a, b) => {
666 *a %= n;
667 *b %= n;
668 }
669 }
670 }
671 }
672
673 fn check_post_dominance(graph: &GraphSpec) -> Result<(), String> {
676 let Some(graph) = graph.fixup() else {
677 return Ok(());
678 };
679
680 let (func, blocks) = graph.build();
681 let cfg = ControlFlowGraph::with_function(&func);
682 let pdt = PostDominatorTree::with_cfg(&cfg);
683
684 let sink = graph.blocks.len();
686 let succ: Vec<Vec<usize>> = graph
687 .blocks
688 .iter()
689 .map(|t| match *t {
690 Terminator::Return => alloc::vec![sink],
691 Terminator::Jump(x) => alloc::vec![x],
692 Terminator::Brif(x, y) => alloc::vec![x, y],
693 })
694 .collect();
695
696 let mut reaches = alloc::vec![false; graph.blocks.len() + 1];
699 reaches[sink] = true;
700 loop {
701 let mut changed = false;
702 for i in 0..graph.blocks.len() {
703 if !reaches[i] && succ[i].iter().any(|&s| reaches[s]) {
704 reaches[i] = true;
705 changed = true;
706 }
707 }
708 if !changed {
709 break;
710 }
711 }
712
713 let bit = |x: usize| 1u64 << x;
716 let universe = bit(graph.blocks.len() + 1) - 1;
717 let mut pdom = alloc::vec![universe; graph.blocks.len() + 1];
718 pdom[sink] = bit(sink);
719 loop {
720 let mut changed = false;
721 for i in 0..graph.blocks.len() {
722 let mut inter = u64::MAX;
723 for &s in &succ[i] {
724 inter &= pdom[s];
725 }
726 let next = bit(i) | inter;
727 if next != pdom[i] {
728 pdom[i] = next;
729 changed = true;
730 }
731 }
732 if !changed {
733 break;
734 }
735 }
736
737 for i in 0..graph.blocks.len() {
738 let expect_diverges = !reaches[i];
739 if pdt.diverges(blocks[i]) != expect_diverges {
740 return Err(format!(
741 "diverges({i}) = {}, expected {expect_diverges}",
742 pdt.diverges(blocks[i]),
743 ));
744 }
745
746 for a in 0..graph.blocks.len() {
749 let expect = if expect_diverges {
750 a == i
751 } else {
752 pdom[i] & bit(a) != 0
753 };
754 if pdt.block_post_dominates(blocks[a], blocks[i]) != expect {
755 return Err(format!(
756 "block_post_dominates({a}, {i}) = {}, expected {expect}",
757 pdt.block_post_dominates(blocks[a], blocks[i]),
758 ));
759 }
760 }
761
762 if expect_diverges {
763 if pdt.immediate_post_dominator(blocks[i]).is_some() {
764 return Err(format!(
765 "immediate_post_dominator({i}) should be None for a diverging block;",
766 ));
767 }
768 continue;
769 }
770
771 let strict = pdom[i] & !bit(i);
776 let mut best: Option<(u32, usize)> = None;
777 for x in 0..=graph.blocks.len() {
778 if strict & bit(x) != 0 {
779 let size = pdom[x].count_ones();
780 if best.map_or(true, |(best_size, _)| size > best_size) {
781 best = Some((size, x));
782 }
783 }
784 }
785 let expect_ipdom = match best {
786 Some((_, x)) if x != sink => Some(blocks[x]),
787 _ => None,
788 };
789 if pdt.immediate_post_dominator(blocks[i]) != expect_ipdom {
790 return Err(format!(
791 "immediate_post_dominator({i}) = {:?}, expected {expect_ipdom:?}",
792 pdt.immediate_post_dominator(blocks[i]),
793 ));
794 }
795 }
796
797 Ok(())
798 }
799}