Skip to content

Commit e6a062f

Browse files
committed
feat: add dominance, SSA construction and def-use chains
1 parent 70924d4 commit e6a062f

9 files changed

Lines changed: 689 additions & 46 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ Currently supported inside functions: arguments, assignments, names, constants,
3636
operations, unary operations, comparisons, calls, attribute access, indexing, returns,
3737
`if`/`elif`/`else`, `while`, `for`, `break`, `continue` and `raise`. Each function is
3838
emitted as its control-flow graph: one block per basic block, ending in an explicit
39-
terminator (`branch`, `jump`, `return`, `raise`, `for_next`).
39+
terminator (`branch`, `jump`, `return`, `raise`, `for_next`). Add `--ssa` to print the
40+
static single assignment form: locals become numbered values, merges get `phi`
41+
instructions and unassigned paths read an explicit `undefined` value.
4042
Unsupported syntax produces a source-located diagnostic and a non-zero exit status.
4143

4244
Names are resolved to canonical symbols through lexical scopes, imports and builtins.

‎src/coretrace_python/cfg/__init__.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
"""Per-function control-flow graphs over PyHIR (architecture §5)."""
22

33
from coretrace_python.cfg.builder import CFGAnalysis, build_cfg
4+
from coretrace_python.cfg.dominance import (
5+
EXIT,
6+
DominanceAnalysis,
7+
DominatorTree,
8+
PostDominanceAnalysis,
9+
dominator_tree,
10+
post_dominator_tree,
11+
)
412
from coretrace_python.cfg.model import (
513
CFG,
614
BasicBlock,
@@ -17,16 +25,22 @@
1725

1826
__all__ = [
1927
"CFG",
28+
"EXIT",
2029
"BasicBlock",
2130
"BlockId",
2231
"Branch",
2332
"CFGAnalysis",
2433
"CFGError",
34+
"DominanceAnalysis",
35+
"DominatorTree",
2536
"ForEach",
2637
"Jump",
38+
"PostDominanceAnalysis",
2739
"Raise",
2840
"Return",
2941
"Terminator",
3042
"build_cfg",
43+
"dominator_tree",
44+
"post_dominator_tree",
3145
"targets",
3246
]
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
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))

‎src/coretrace_python/cli.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ def build_parser() -> argparse.ArgumentParser:
2323
action="store_true",
2424
help="print the lowered Python intermediate representation",
2525
)
26+
parser.add_argument(
27+
"--ssa",
28+
action="store_true",
29+
help="with --emit-ir, print the static single assignment form",
30+
)
2631
return parser
2732

2833

@@ -34,7 +39,7 @@ def main(argv: list[str] | None = None) -> int:
3439

3540
try:
3641
source = SourceManager().load_file(args.path)
37-
module = lower_module(build_hir(source))
42+
module = lower_module(build_hir(source), ssa=args.ssa)
3843
except (
3944
OSError,
4045
UnicodeError,

‎src/coretrace_python/ir/defuse.py‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""Def-use and use-def chains over SSA values (architecture §7)."""
2+
3+
from __future__ import annotations
4+
5+
from collections.abc import Mapping
6+
from dataclasses import dataclass
7+
from types import MappingProxyType
8+
from typing import ClassVar
9+
10+
from coretrace_python.analysis import AnalysisContext, AnyAnalysis, FunctionAnalysis
11+
from coretrace_python.cfg import BlockId
12+
from coretrace_python.hir import nodes
13+
from coretrace_python.ir.model import ForNext, FunctionIR, Value
14+
from coretrace_python.ir.ssa import SSAAnalysis
15+
16+
17+
@dataclass(frozen=True)
18+
class Definition:
19+
"""Where a value is defined: a parameter (no block), an instruction, or a terminator."""
20+
21+
block: BlockId | None
22+
index: int | None
23+
24+
25+
@dataclass(frozen=True)
26+
class Use:
27+
"""Where a value is used: an instruction index, or ``None`` for the terminator."""
28+
29+
block: BlockId
30+
index: int | None
31+
32+
33+
class DefUse:
34+
def __init__(
35+
self,
36+
definitions: Mapping[Value, Definition],
37+
uses: Mapping[Value, tuple[Use, ...]],
38+
) -> None:
39+
self._definitions = MappingProxyType(dict(definitions))
40+
self._uses = MappingProxyType(dict(uses))
41+
42+
def definition(self, value: Value) -> Definition:
43+
return self._definitions[value]
44+
45+
def uses(self, value: Value) -> tuple[Use, ...]:
46+
return self._uses.get(value, ())
47+
48+
49+
def def_use(function: FunctionIR) -> DefUse:
50+
definitions: dict[Value, Definition] = {}
51+
uses: dict[Value, list[Use]] = {}
52+
for parameter in function.parameters:
53+
definitions[parameter] = Definition(None, None)
54+
for block in function.blocks:
55+
for index, instruction in enumerate(block.instructions):
56+
if instruction.result is not None:
57+
definitions[instruction.result] = Definition(block.id, index)
58+
for operand in instruction.operands():
59+
uses.setdefault(operand, []).append(Use(block.id, index))
60+
terminator = block.terminator
61+
if isinstance(terminator, ForNext) and terminator.result is not None:
62+
definitions[terminator.result] = Definition(block.id, None)
63+
for operand in terminator.operands():
64+
uses.setdefault(operand, []).append(Use(block.id, None))
65+
return DefUse(definitions, {value: tuple(found) for value, found in uses.items()})
66+
67+
68+
class DefUseAnalysis(FunctionAnalysis[DefUse]):
69+
name: ClassVar[str] = "ir.defuse"
70+
requires: ClassVar[frozenset[AnyAnalysis]] = frozenset({SSAAnalysis})
71+
72+
@classmethod
73+
def compute(cls, ctx: AnalysisContext, function: nodes.Function) -> DefUse:
74+
return def_use(ctx.get(SSAAnalysis, function))

0 commit comments

Comments
 (0)