|
| 1 | +"""Dominance and post-dominance over control-flow graphs (architecture §5). |
| 2 | +
|
| 3 | +Both trees come from the same iterative algorithm (Cooper, Harvey and Kennedy) run on |
| 4 | +the forward graph from the entry, or on the reversed graph from a virtual ``EXIT`` |
| 5 | +that follows every returning or raising block. The post-dominance frontier is the |
| 6 | +control-dependence relation. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +from collections.abc import Callable, Iterable, Mapping |
| 12 | +from dataclasses import dataclass, field |
| 13 | +from types import MappingProxyType |
| 14 | +from typing import ClassVar |
| 15 | + |
| 16 | +from coretrace_python.analysis import AnalysisContext, AnyAnalysis, FunctionAnalysis |
| 17 | +from coretrace_python.cfg.builder import CFGAnalysis |
| 18 | +from coretrace_python.cfg.model import CFG, BlockId |
| 19 | +from coretrace_python.hir import nodes |
| 20 | + |
| 21 | +EXIT = BlockId("<exit>") |
| 22 | + |
| 23 | + |
| 24 | +@dataclass(frozen=True) |
| 25 | +class DominatorTree: |
| 26 | + root: BlockId |
| 27 | + blocks: tuple[BlockId, ...] |
| 28 | + _idom: Mapping[BlockId, BlockId | None] |
| 29 | + _children: Mapping[BlockId, tuple[BlockId, ...]] |
| 30 | + _frontier: Mapping[BlockId, frozenset[BlockId]] |
| 31 | + _depth: Mapping[BlockId, int] = field(init=False, repr=False, compare=False) |
| 32 | + |
| 33 | + def __post_init__(self) -> None: |
| 34 | + depth: dict[BlockId, int] = {} |
| 35 | + for block in self.blocks: |
| 36 | + parent = self._idom[block] |
| 37 | + depth[block] = 0 if parent is None else depth[parent] + 1 |
| 38 | + object.__setattr__(self, "_depth", MappingProxyType(depth)) |
| 39 | + |
| 40 | + def idom(self, block: BlockId) -> BlockId | None: |
| 41 | + return self._idom[block] |
| 42 | + |
| 43 | + def children(self, block: BlockId) -> tuple[BlockId, ...]: |
| 44 | + return self._children[block] |
| 45 | + |
| 46 | + def frontier(self, block: BlockId) -> frozenset[BlockId]: |
| 47 | + return self._frontier[block] |
| 48 | + |
| 49 | + def dominates(self, dominator: BlockId, block: BlockId) -> bool: |
| 50 | + if dominator not in self._idom or block not in self._idom: |
| 51 | + return False |
| 52 | + current: BlockId | None = block |
| 53 | + while current is not None and self._depth[current] >= self._depth[dominator]: |
| 54 | + if current == dominator: |
| 55 | + return True |
| 56 | + current = self._idom[current] |
| 57 | + return False |
| 58 | + |
| 59 | + def iterated_frontier(self, blocks: Iterable[BlockId]) -> frozenset[BlockId]: |
| 60 | + result: set[BlockId] = set() |
| 61 | + pending = list(blocks) |
| 62 | + while pending: |
| 63 | + for candidate in self._frontier[pending.pop()]: |
| 64 | + if candidate not in result: |
| 65 | + result.add(candidate) |
| 66 | + pending.append(candidate) |
| 67 | + return frozenset(result) |
| 68 | + |
| 69 | + |
| 70 | +def _build( |
| 71 | + root: BlockId, |
| 72 | + successors: Callable[[BlockId], tuple[BlockId, ...]], |
| 73 | + order: Callable[[BlockId], int], |
| 74 | +) -> DominatorTree: |
| 75 | + # Reverse postorder over the reachable nodes. |
| 76 | + postorder: list[BlockId] = [] |
| 77 | + seen: set[BlockId] = set() |
| 78 | + |
| 79 | + def visit(node: BlockId) -> None: |
| 80 | + seen.add(node) |
| 81 | + for successor in successors(node): |
| 82 | + if successor not in seen: |
| 83 | + visit(successor) |
| 84 | + postorder.append(node) |
| 85 | + |
| 86 | + visit(root) |
| 87 | + rpo = list(reversed(postorder)) |
| 88 | + index = {node: position for position, node in enumerate(rpo)} |
| 89 | + predecessors: dict[BlockId, list[BlockId]] = {node: [] for node in rpo} |
| 90 | + for node in rpo: |
| 91 | + for successor in successors(node): |
| 92 | + predecessors[successor].append(node) |
| 93 | + |
| 94 | + idom: dict[BlockId, BlockId | None] = {root: None} |
| 95 | + |
| 96 | + def intersect(a: BlockId, b: BlockId) -> BlockId: |
| 97 | + while a != b: |
| 98 | + while index[a] > index[b]: |
| 99 | + a = idom[a] # type: ignore[assignment] |
| 100 | + while index[b] > index[a]: |
| 101 | + b = idom[b] # type: ignore[assignment] |
| 102 | + return a |
| 103 | + |
| 104 | + changed = True |
| 105 | + while changed: |
| 106 | + changed = False |
| 107 | + for node in rpo[1:]: |
| 108 | + candidates = [p for p in predecessors[node] if p in idom] |
| 109 | + new_idom = candidates[0] |
| 110 | + for other in candidates[1:]: |
| 111 | + new_idom = intersect(other, new_idom) |
| 112 | + if idom.get(node) != new_idom: |
| 113 | + idom[node] = new_idom |
| 114 | + changed = True |
| 115 | + |
| 116 | + children: dict[BlockId, list[BlockId]] = {node: [] for node in rpo} |
| 117 | + for node in sorted(rpo, key=order): |
| 118 | + parent = idom[node] |
| 119 | + if parent is not None: |
| 120 | + children[parent].append(node) |
| 121 | + |
| 122 | + frontier: dict[BlockId, set[BlockId]] = {node: set() for node in rpo} |
| 123 | + for node in rpo: |
| 124 | + if node == root or len(predecessors[node]) < 2: |
| 125 | + continue |
| 126 | + for predecessor in predecessors[node]: |
| 127 | + runner: BlockId | None = predecessor |
| 128 | + while runner is not None and runner != idom[node]: |
| 129 | + frontier[runner].add(node) |
| 130 | + runner = idom[runner] |
| 131 | + |
| 132 | + preorder: list[BlockId] = [] |
| 133 | + |
| 134 | + def walk(node: BlockId) -> None: |
| 135 | + preorder.append(node) |
| 136 | + for child in children[node]: |
| 137 | + walk(child) |
| 138 | + |
| 139 | + walk(root) |
| 140 | + return DominatorTree( |
| 141 | + root=root, |
| 142 | + blocks=tuple(preorder), |
| 143 | + _idom=MappingProxyType(dict(idom)), |
| 144 | + _children=MappingProxyType({k: tuple(v) for k, v in children.items()}), |
| 145 | + _frontier=MappingProxyType({k: frozenset(v) for k, v in frontier.items()}), |
| 146 | + ) |
| 147 | + |
| 148 | + |
| 149 | +def dominator_tree(cfg: CFG) -> DominatorTree: |
| 150 | + order = {block_id: position for position, block_id in enumerate(cfg.blocks)} |
| 151 | + return _build(cfg.entry, cfg.successors, lambda block: order[block]) |
| 152 | + |
| 153 | + |
| 154 | +def post_dominator_tree(cfg: CFG) -> DominatorTree: |
| 155 | + reachable = cfg.reachable() |
| 156 | + order = {block_id: position for position, block_id in enumerate(cfg.blocks)} |
| 157 | + order[EXIT] = -1 |
| 158 | + leaves = tuple(b for b in cfg.blocks if b in reachable and not cfg.successors(b)) |
| 159 | + |
| 160 | + def reversed_successors(block: BlockId) -> tuple[BlockId, ...]: |
| 161 | + if block == EXIT: |
| 162 | + return leaves |
| 163 | + return tuple(p for p in cfg.predecessors(block) if p in reachable) |
| 164 | + |
| 165 | + return _build(EXIT, reversed_successors, lambda block: order[block]) |
| 166 | + |
| 167 | + |
| 168 | +class DominanceAnalysis(FunctionAnalysis[DominatorTree]): |
| 169 | + name: ClassVar[str] = "cfg.dominance" |
| 170 | + requires: ClassVar[frozenset[AnyAnalysis]] = frozenset({CFGAnalysis}) |
| 171 | + |
| 172 | + @classmethod |
| 173 | + def compute(cls, ctx: AnalysisContext, function: nodes.Function) -> DominatorTree: |
| 174 | + return dominator_tree(ctx.get(CFGAnalysis, function)) |
| 175 | + |
| 176 | + |
| 177 | +class PostDominanceAnalysis(FunctionAnalysis[DominatorTree]): |
| 178 | + name: ClassVar[str] = "cfg.post_dominance" |
| 179 | + requires: ClassVar[frozenset[AnyAnalysis]] = frozenset({CFGAnalysis}) |
| 180 | + |
| 181 | + @classmethod |
| 182 | + def compute(cls, ctx: AnalysisContext, function: nodes.Function) -> DominatorTree: |
| 183 | + return post_dominator_tree(ctx.get(CFGAnalysis, function)) |
0 commit comments