Bases: ABC
Base class for performing data flow analyses over a ControlFlowGraph.
This abstract class implements a generic work-list algorithm that can run either
in a "forward" or "backward" direction. Subclasses must provide IR-specific
semantics by implementing the abstract methods: transfer, join, stmt_str and
direction, and may override boundary_state.
only blocks reachable from the boundary block (ENTRY for forward, EXIT for
backward) are visited, and joins skip neighbors that weren't processed yet.
so loops start optimistic and dead blocks (e.g. after a return) never get
joined in. transfer must not mutate its input.
blocks are visited in reverse postorder, so a block is joined after the
neighbors before it.
Key attributes
- cfg: the ControlFlowGraph to analyze.
- input_states: a mapping from basic block id to the state flowing into the
block's transfer (its entry for forward, its exit for backward).
- output_states: a mapping from basic block id to the state the block's
transfer produces.
- reached: ids of the blocks visited by analyze.
Source code in src/finch/symbolic/dataflow.py
| class DataFlowAnalysis(ABC):
"""
Base class for performing data flow analyses over a ControlFlowGraph.
This abstract class implements a generic work-list algorithm that can run either
in a "forward" or "backward" direction. Subclasses must provide IR-specific
semantics by implementing the abstract methods: transfer, join, stmt_str and
direction, and may override boundary_state.
only blocks reachable from the boundary block (ENTRY for forward, EXIT for
backward) are visited, and joins skip neighbors that weren't processed yet.
so loops start optimistic and dead blocks (e.g. after a `return`) never get
joined in. `transfer` must not mutate its input.
blocks are visited in reverse postorder, so a block is joined after the
neighbors before it.
Key attributes
- cfg: the ControlFlowGraph to analyze.
- input_states: a mapping from basic block id to the state flowing into the
block's transfer (its entry for forward, its exit for backward).
- output_states: a mapping from basic block id to the state the block's
transfer produces.
- reached: ids of the blocks visited by `analyze`.
"""
def __init__(self, cfg: ControlFlowGraph):
self.cfg: ControlFlowGraph = cfg
self.input_states: dict[str, dict] = {
block.id: {} for block in cfg.blocks.values()
}
self.output_states: dict[str, dict] = {
block.id: {} for block in cfg.blocks.values()
}
self.reached: set[str] = set()
def __str__(self) -> str:
"""
Return a string representation describing the current dataflow
analysis state over the control-flow graph (CFG).
The output lists each basic block in the order
produced by self.cfg.blocks.values().
For every block the printed form is:
<block.id>: #succs=[<succ_id>, ...]
<stmt_representation_for_first_stmt>
<stmt_representation_for_second_stmt>
...
statements are annotated with the state flowing into their transfer
(before them for forward, after them for backward), statements of
unreached blocks without annotations.
"""
lines: list[str] = []
forward = self.direction() == "forward"
for block in self.cfg.blocks.values():
succ_names = [succ.id for succ in block.successors]
lines.append(f"{block.id}: #succs=[{', '.join(succ_names)}]")
if block.id not in self.reached:
lines.extend(f" {stmt}" for stmt in block.statements)
else:
# deep copy, so printing never changes the stored states
state = copy.deepcopy(self.input_states[block.id])
stmts = block.statements if forward else block.statements[::-1]
annotated = []
for stmt in stmts:
annotated.append(f" {self.stmt_str(stmt, state)}")
state = self.transfer([stmt], state)
lines.extend(annotated if forward else annotated[::-1])
lines.append("")
return "\n".join(lines)
@abstractmethod
def stmt_str(self, stmt, state: dict) -> str:
"""
Format a single statement given the current lattice state.
Implement in subclasses or IR-specific abstract bases.
"""
...
@abstractmethod
def transfer(self, stmts, state: dict) -> dict:
"""
Transfer function for the data flow analysis.
This should be implemented by subclasses.
"""
...
@abstractmethod
def join(self, state_1: dict, state_2: dict) -> dict:
"""
Join function for the data flow analysis.
This should be implemented by subclasses.
"""
...
@abstractmethod
def direction(self) -> str:
"""
Return the direction of the data flow analysis, either "forward" or "backward".
This should be implemented by subclasses.
"""
...
def boundary_state(self) -> dict:
"""state at the cfg boundary: out of ENTRY (forward) or into EXIT (backward)"""
return {}
def analyze(self) -> None:
"""run the work list until the states of all reached blocks are stable"""
forward = self.direction() == "forward"
start = self.cfg.entry_block if forward else self.cfg.exit_block
def upstream(block: BasicBlock) -> list[BasicBlock]:
return block.predecessors if forward else block.successors
def downstream(block: BasicBlock) -> list[BasicBlock]:
return block.successors if forward else block.predecessors
rank = _depth_first(start, downstream)
work_list = [(rank[start.id], start.id)]
queued = {start.id}
while work_list:
_, block_id = heapq.heappop(work_list)
queued.remove(block_id)
block = self.cfg.blocks[block_id]
# join the states of processed upstream neighbors
states = [
self.output_states[b.id]
for b in upstream(block)
if b.id in self.reached
]
if block is start:
states.insert(0, self.boundary_state())
input_state = states[0].copy()
for other in states[1:]:
input_state = self.join(input_state, other)
self.input_states[block.id] = input_state
output_state = self.transfer(block.statements, input_state)
if (
block.id in self.reached
and output_state == self.output_states[block.id]
):
continue
self.reached.add(block.id)
self.output_states[block.id] = output_state
for neighbor in downstream(block):
if neighbor.id not in queued:
queued.add(neighbor.id)
heapq.heappush(work_list, (rank[neighbor.id], neighbor.id))
|
__str__()
Return a string representation describing the current dataflow
analysis state over the control-flow graph (CFG).
The output lists each basic block in the order
produced by self.cfg.blocks.values().
For every block the printed form is:
<block.id>: #succs=[<succ_id>, ...]
<stmt_representation_for_first_stmt>
<stmt_representation_for_second_stmt>
...
statements are annotated with the state flowing into their transfer
(before them for forward, after them for backward), statements of
unreached blocks without annotations.
Source code in src/finch/symbolic/dataflow.py
| def __str__(self) -> str:
"""
Return a string representation describing the current dataflow
analysis state over the control-flow graph (CFG).
The output lists each basic block in the order
produced by self.cfg.blocks.values().
For every block the printed form is:
<block.id>: #succs=[<succ_id>, ...]
<stmt_representation_for_first_stmt>
<stmt_representation_for_second_stmt>
...
statements are annotated with the state flowing into their transfer
(before them for forward, after them for backward), statements of
unreached blocks without annotations.
"""
lines: list[str] = []
forward = self.direction() == "forward"
for block in self.cfg.blocks.values():
succ_names = [succ.id for succ in block.successors]
lines.append(f"{block.id}: #succs=[{', '.join(succ_names)}]")
if block.id not in self.reached:
lines.extend(f" {stmt}" for stmt in block.statements)
else:
# deep copy, so printing never changes the stored states
state = copy.deepcopy(self.input_states[block.id])
stmts = block.statements if forward else block.statements[::-1]
annotated = []
for stmt in stmts:
annotated.append(f" {self.stmt_str(stmt, state)}")
state = self.transfer([stmt], state)
lines.extend(annotated if forward else annotated[::-1])
lines.append("")
return "\n".join(lines)
|
analyze()
run the work list until the states of all reached blocks are stable
Source code in src/finch/symbolic/dataflow.py
| def analyze(self) -> None:
"""run the work list until the states of all reached blocks are stable"""
forward = self.direction() == "forward"
start = self.cfg.entry_block if forward else self.cfg.exit_block
def upstream(block: BasicBlock) -> list[BasicBlock]:
return block.predecessors if forward else block.successors
def downstream(block: BasicBlock) -> list[BasicBlock]:
return block.successors if forward else block.predecessors
rank = _depth_first(start, downstream)
work_list = [(rank[start.id], start.id)]
queued = {start.id}
while work_list:
_, block_id = heapq.heappop(work_list)
queued.remove(block_id)
block = self.cfg.blocks[block_id]
# join the states of processed upstream neighbors
states = [
self.output_states[b.id]
for b in upstream(block)
if b.id in self.reached
]
if block is start:
states.insert(0, self.boundary_state())
input_state = states[0].copy()
for other in states[1:]:
input_state = self.join(input_state, other)
self.input_states[block.id] = input_state
output_state = self.transfer(block.statements, input_state)
if (
block.id in self.reached
and output_state == self.output_states[block.id]
):
continue
self.reached.add(block.id)
self.output_states[block.id] = output_state
for neighbor in downstream(block):
if neighbor.id not in queued:
queued.add(neighbor.id)
heapq.heappush(work_list, (rank[neighbor.id], neighbor.id))
|
boundary_state()
state at the cfg boundary: out of ENTRY (forward) or into EXIT (backward)
Source code in src/finch/symbolic/dataflow.py
| def boundary_state(self) -> dict:
"""state at the cfg boundary: out of ENTRY (forward) or into EXIT (backward)"""
return {}
|
direction()
abstractmethod
Return the direction of the data flow analysis, either "forward" or "backward".
This should be implemented by subclasses.
Source code in src/finch/symbolic/dataflow.py
| @abstractmethod
def direction(self) -> str:
"""
Return the direction of the data flow analysis, either "forward" or "backward".
This should be implemented by subclasses.
"""
...
|
join(state_1, state_2)
abstractmethod
Join function for the data flow analysis.
This should be implemented by subclasses.
Source code in src/finch/symbolic/dataflow.py
| @abstractmethod
def join(self, state_1: dict, state_2: dict) -> dict:
"""
Join function for the data flow analysis.
This should be implemented by subclasses.
"""
...
|
stmt_str(stmt, state)
abstractmethod
Format a single statement given the current lattice state.
Implement in subclasses or IR-specific abstract bases.
Source code in src/finch/symbolic/dataflow.py
| @abstractmethod
def stmt_str(self, stmt, state: dict) -> str:
"""
Format a single statement given the current lattice state.
Implement in subclasses or IR-specific abstract bases.
"""
...
|
transfer(stmts, state)
abstractmethod
Transfer function for the data flow analysis.
This should be implemented by subclasses.
Source code in src/finch/symbolic/dataflow.py
| @abstractmethod
def transfer(self, stmts, state: dict) -> dict:
"""
Transfer function for the data flow analysis.
This should be implemented by subclasses.
"""
...
|