Data structureadvanced
Loop nesting forest
Also called loop tree.
A forest whose nodes are the loops of a flow graph, with each loop below the loops that contain it, defined for irreducible graphs too.
- Evidence
- Full proofCode in 1 languages
A loop nesting forest describes the loops of a control flow graph and how they nest. Each node of the forest is a loop, a set of blocks, with a set of headers, and each loop lies below the smallest loop that contains it. On a reducible flow graph the loops are the natural loops merged by header, and the forest is the usual loop tree of a compiler. The forest is also defined when the graph is irreducible: a loop that can be entered at several blocks gets several headers. This page builds the forest of Steensgaard. The outer loops are the nontrivial strongly connected components of the graph. The headers of a loop are its blocks with a predecessor outside the loop, and the inner loops are found again in the loop with its headers removed. Removing the edges from each loop into its headers leaves a graph with no cycle.
In plain words
A program often has loops inside loops. A compiler wants a map of them: which blocks belong to each loop, where each loop starts, and which loop is inside which. The loop nesting forest is that map. To build it, find each group of blocks in which every block can get to every other block. Each such group is a loop. The blocks where control can come into the group from outside are its headers, the doors of the loop. Take the doors away, and look for groups again inside what is left. These are the inner loops. Go on until no group is left. In a well-structured program every loop has one door, at its top. In other programs a loop can have two or more doors, and the map shows all of them.
The abstract type
The input is a flow graph with a root . Only the part that reaches counts. The structure holds a family of loops. Each loop is a set of vertices with a nonempty set of headers and a parent loop or none. The operations are:
loop_forest(G, r): build the structure.headers(L),parent(L),children(L): read the forest.innermost(v): the smallest loop that contains , or none.depth(L): the number of loops from up to its root, with counted.
The laws:
- Nesting. Two loops are disjoint or one contains the other, and the loops that contain are and its ancestors.
- Children avoid the headers. A child of lies in .
- Loops are cycles. Each loop is strongly connected and holds a cycle, and every cycle of the graph lies in some loop.
- The headers break the cycles. If the edges from inside each loop into are removed, the graph has no cycle.
- Reducible graphs. If is reducible, each loop has one header . dominates the loop, and the loop is the union of the natural loops of the back edges into . There is one loop for each vertex that is the target of a back edge.
Representation
The Python code returns a list of loops. Each loop is a dict with the sorted list nodes, the sorted list headers and the index parent, which is at a root of the forest. A parent comes before its children in the list. innermost(n, loops) gives each vertex its innermost loop, and depth(loops, i) follows the parent indices. cfg_loops(prog) does the same for a program in the toy IR and uses block labels.
A compiler does not store the full vertex set of every loop, because a vertex at depth would be stored times. It keeps one record per loop with its headers, its parent and its children, and one pointer per block to the innermost loop. Then the loops of a block are found by following parents, and the blocks of a loop by walking its subtree. This uses space for blocks.
Operations
LOOP-NESTING-FOREST(G, r)- 1
R0 <- the vertices that r reaches; T <- the stack [(R0, none)] - 2
while T is not empty do - 3
(R, p) <- pop(T) - 4
for each strongly connected component S of G[R] do - 5
skip S if it has one vertex and no self-loop - 6
H <- {v in S : v = r or v has a predecessor in R0 outside S} - 7
record the loop S with headers H and parent p - 8
push (S \ H, the new loop) on T - 9
return the loops
Line L1 drops the unreachable part, and line L6 looks only at predecessors that reaches, so dead code cannot create a header. The root has no predecessor, so line L6 counts it as an entry, as if control came into it from outside. A loop always has a header: if it does not hold , a path from into the loop must enter it somewhere. So each region on the stack is smaller than the loop above it, and the loop stops. The code finds the components with Tarjan's algorithm, with an explicit stack, so deep nesting does not use Python recursion.
innermost walks the list once and keeps, for each vertex, the last loop that contains it. This is the innermost one, because the loops that contain a vertex form a chain and a parent comes before its children.
Example
Take the blocks B0 to B6 with the edges B0→B1, B1→B2, B2→B1, B2→B3, B3→B4, B4→B3, B4→B5, B5→B1 and B5→B6. This is a loop at B1 with a loop at B3 inside it.
| step | region | components | loop found | headers |
|---|---|---|---|---|
| 1 | B0 to B6 | {B0}, {B1, B2, B3, B4, B5}, {B6} | {B1, B2, B3, B4, B5} | B1, entered from B0 |
| 2 | {B2, B3, B4, B5} | {B2}, {B3, B4}, {B5} | {B3, B4}, parent 0 | B3, entered from B2 |
| 3 | {B4} | {B4} | none, B4 has no self-loop |
The innermost loops are: B0 none, B1 loop 0, B2 loop 0, B3 loop 1, B4 loop 1, B5 loop 0, B6 none. The edges into headers from inside their loops are B2→B1, B5→B1 and B4→B3. Without them the graph has no cycle. The graph is reducible, and loop 0 is the union of the natural loops of B2→B1 and B5→B1.
Now take an irreducible graph: r→A, r→B, A→B, B→A and A→C. The only nontrivial component is {A, B}. Both blocks have the predecessor r outside it, so the loop {A, B} has the headers A and B, and nothing is left inside. No block of the cycle dominates the other, so the graph has no back edge at all, and no natural loop finds this cycle. The forest still shows it.
Correctness
The proof file shows four things. First, every loop has a header, so the regions shrink and the construction stops, with at most loops and depth at most . Second, the loops nest: loops made from one region are disjoint, and everything below a loop lies in it. Third, a cycle that avoids all the removed edges would lie in one component of some region, would have to avoid its headers, and so would lie in a smaller region, which gives a contradiction by induction. Fourth, for a reducible graph, take the first vertex of a top loop in a topological order of the graph without back edges. Every edge into from the loop is then a back edge, dominates the loop and is its only header, and the loop is the union of the natural loops into . Inside the loop, delete the edges into and make the root. This smaller graph is reducible, has the same dominators and natural loops, and gives the same inner loops with the same headers, so induction on the number of edges finishes the proof. The component step is Tarjan's algorithm and is cited.
Proof: The loops of repeated strongly connected components form a forest that breaks every cycle, and on a reducible graph they are the natural loopsfull
Setting. A flow graph is with a root . Let be the set of vertices that reaches, and keep only the edges whose source is in ; their targets are then in too. All paths, cycles and predecessors below are in this graph. A path may have length 0. For , is the subgraph induced by . A strongly connected component of is nontrivial if or with a self-loop . Note that a set is nontrivial exactly when it holds a cycle.
Definition. The forest is built by , where does this for each nontrivial strongly connected component of : it makes a loop with parent and header set
and then calls . Lines L1 to L9 of the code do exactly this, with a stack of pending regions in place of the recursion. The regions are handled one at a time and the result for one region does not depend on the others, so the order of the stack does not matter. The components come from Tarjan's algorithm, which is cited, not proved here; the tests check them against mutual reachability.
Lemma 1 (termination and size). Every loop has . So every call works on a smaller region than its parent call, the recursion stops, and the depth of the forest is at most . Each vertex is a header of at most one loop, so there are at most loops.
Proof. If then . Otherwise take and a path from to . It starts outside and ends in , so it has an edge with and , and . So . A header of is not in , so no loop below contains it, and loops made in the same call are disjoint, as components are.
Lemma 2 (laminar family). Any two loops are disjoint or one contains the other. The loops that contain a loop are exactly and its ancestors, so the parent of is the smallest loop that strictly contains it. A child of lies in .
Proof. By the definition, every loop below lies in . Take two loops . If one is an ancestor of the other, it contains the other. Otherwise take the deepest call that lies on both of their paths from the top call. lies in (or is) one component of that call and in another, so they are disjoint. Now let with . is not disjoint from , so it is an ancestor or a descendant of , and a descendant lies in , which is strictly smaller than . So is an ancestor.
Theorem 1 (the forest breaks every cycle). Let be the set of edges such that and for some loop . Then the graph has no cycle. Each loop also holds a cycle through each of its headers, so every loop is used.
Proof. We show, by induction on , that for every region on which is called, without the edges of has no cycle. With this is the theorem. Let be a cycle in . Its vertices reach each other inside , so they lie in one component of , and is nontrivial because it holds a cycle. So is a loop. If passes a header , the edge of into comes from a vertex of , so it is in , which is false. So lies in , and is called on this smaller region, where by induction no such cycle exists. For the last claim: is strongly connected and nontrivial, so each lies on a cycle inside .
Reducible graphs. An edge is a back edge if dominates ; let be the set of back edges. is reducible if has no cycle. A self-loop is a back edge. The natural loop of a back edge is .
Lemma 3 (the top loops of a reducible graph). Let be reducible and let be a nontrivial component of . Let be the first vertex of in a topological order of . Then:
(a) every edge with is a back edge; (b) dominates every vertex of ; (c) ; (d) every back edge has , and is the union of over these back edges.
Proof. (a) If were not a back edge, would come before in the order, but is the first vertex of . (A self-loop is a back edge anyway.)
(b) Let , , and suppose a path from to avoids . Take a path from to inside and let be the vertex just before the first on . Then , and followed by the part of up to is a path from to that avoids . But is a back edge by (a), so dominates , which is false.
(c) First, is not empty by Lemma 1. Let . If , then dominates and dominates by (b), so . Otherwise has a predecessor . Suppose . A path from to , followed by the edge , passes by (b), and , so lies on the part up to . Then reaches , reaches , and reaches inside , so , which is false. So .
(d) Let be a back edge. Every path from to passes , so reaches , and reaches by the edge, so . Let with , and let be a path from to that avoids . If a path from to avoided , then with it would give a path from to that avoids ; so dominates , reaches , and reaches through . So . Conversely, let , , take a path from to inside , and let be the vertex just before its first . Then is a back edge by (a), and the path up to avoids , so .
Lemma 4 (the graph inside a top loop). In the setting of Lemma 3, let have the vertices , the edges of except those that end at , and the root . Then:
(a) reaches every vertex of in ; (b) for , dominates in if and only if dominates in ; (c) is reducible, its back edges are the back edges of inside that do not end at , and for such a back edge the natural loop in equals the natural loop in ; (d) the loops of are exactly the loops of below , with the same header sets.
Proof. (a) Let . A path from to passes by Lemma 3(b). Its part after the last does not return to , and each of its vertices is reached from and reaches , which reaches , so . So this part is a path of .
(b) Suppose dominates in , and let be a path in from to . As in (a), the part of after its last is a path of from to , so it passes , and so does . Conversely, suppose dominates in , and let be a path in from to . If , passes . Otherwise take a path in from to the first it meets. followed by is a path of to , so it passes . If were on , it would be before , and the part of up to would reach without passing , against Lemma 3(b). So is on .
(c) By (b), an edge of is a back edge of exactly when it is a back edge of . By Lemma 3(a), all the removed edges are back edges, so the edges of that are not back edges are edges of , and they have no cycle. So is reducible. Every back edge of with has , because dominates and so reaches it, and reaches . Now let . A path of is a path of , so the natural loop in lies in the one in . Conversely, let be a path in from to that avoids . Each vertex of is dominated by , since a path from to that avoids would, with the rest of , reach without . So reaches , and reaches through , so . If passed , then would dominate , while dominates by Lemma 3(b), so , which is false. So is a path of .
(d) In no edge ends at , so is a trivial component, and the other components of are the components of , the region of the call in . So both build the same loops at their top level. For the headers, let be such a loop and . The root of is , and the root of is not in either, since would mean by Lemma 3(c). A predecessor of in lies in , since otherwise would be in , against Lemma 3(c). So has the same predecessors in and in , and is the same in both. The calls below then see the same regions and the same predecessors, so the whole subtree is the same.
Theorem 2 (reducible graphs). Let be reducible. Then every loop of the forest has exactly one header , dominates every vertex of , and is the union of the natural loops of all the back edges that end at . The map from a loop to its header is a one-to-one map from the loops onto the targets of the back edges.
Proof. By induction on the number of edges. The loops at the top level satisfy the claims by Lemma 3. A loop below a top loop is a loop of with the same headers (Lemma 4(d)). is reducible and has fewer edges, since holds an edge into by Lemma 3(a) and the nontriviality of . So by induction has one header , dominates in , and is the union of the natural loops in of the back edges of into . By Lemma 4(b) and (c), the same holds in , and since , the back edges of into are all the back edges of into .
For the map: each loop with header holds an edge from into , which is a back edge (Lemma 3(a), in or in ), so is a back edge target. Different loops have different headers by Lemma 1. Let be the target of a back edge . Then and lie on a cycle, so is in a top loop . If is the header of we are done. Otherwise is a back edge of by Lemma 4(c), and by induction is the header of a loop of , which is a loop of by Lemma 4(d).
Cost. Let , and let be the depth of the forest. The regions of the calls at one depth are disjoint, so all the calls at one depth cost for the components, the header sets and the new regions, counting each edge from its source and from its target. There are at most depths, so the total is , which is in the worst case by Lemma 1. The Python code also sorts each region and each loop for a fixed output order, which adds per depth. The bound is reached: the path with the back edges for has nested loops, and the call at depth works on about vertices, so the work is for a graph with edges.
What is proved and what is measured. Lemmas 1 to 4 and Theorems 1 and 2 are proved here, given that the component step is correct. The almost-linear algorithms of Ramalingam for other forests are cited, not proved. The tests compare the code with a direct reading of the definition that finds components by mutual reachability, with the merged natural loops of brute-force dominators on reducible graphs, and with the properties of Lemma 2 and Theorem 1. The running times in the tests and on the page are measurements.
Complexity
Let be the number of vertices, the number of edges and the depth of the forest.
| operation | time | space |
|---|---|---|
| build (lines L1 to L9) | , so in the worst case | working space |
| the loops as vertex lists | , at most | |
innermost for all vertices |
||
parent, headers |
||
depth(L) |
Proved. The regions at one depth of the forest are disjoint, so one depth costs , and there are at most depths. The bound is tight: the path with the back edges for has nested loops, and the work is for edges. The Python code also sorts each region and each loop for a fixed output, which adds per depth.
Cited, not proved. Ramalingam showed that Havlak's algorithm is quadratic in the worst case, not almost linear as first stated, and gave almost-linear versions of it and of the algorithm of Sreedhar, Gao and Lee. He later defined the reduced Havlak forest, which a bottom-up algorithm builds in almost linear time. Those algorithms build other forests, not the one of this page.
Measured, not proved. On the nested path above, the Python code took about 0.04 s for , 0.17 s for , 0.71 s for and 3.0 s for on one laptop, about four times as long for each doubling. Over 2,000 seeded random graphs with up to 9 vertices, 1,749 were reducible, and the loops had 1 header in 2,140 cases, 2 in 223, 3 in 49 and 4 in 14.
Variants
- Havlak's forest. Do a depth-first search and give each loop one header, its first vertex in the search. On an irreducible graph the result can depend on the order of the search.
- Sreedhar, Gao and Lee. Find the loops with the dominator tree and the join edges of the flow graph, the DJ graph.
- Reduced Havlak forest. Ramalingam's forest, built bottom-up in almost linear time.
- The loop tree of a reducible graph. Find the back edges with dominators, build each natural loop by a backward search from the tail, and merge the loops that share a header. On a reducible graph this gives the forest of this page, as the proof file shows.
- A virtual root. Many compilers add one more node above the forest for the whole function, so the forest becomes a tree.
When to use it
Use the forest when an optimization needs the loop structure: loop invariant code motion, induction variable analysis, unrolling and other loop transformations, block placement, and register allocation that weights spill costs by loop depth. It is also a good order for iterative data-flow analysis, since an inner loop can settle before its outer loop. Use this construction when the input can be irreducible, for example code from a goto, from a decompiler or from a JIT that enters a loop in the middle. If the graph is known to be reducible, the natural loops from a dominator tree give the same forest and often come for free.
Pitfalls
- One header is not always true. An irreducible loop has two or more headers. An optimization that puts a preheader before "the" header must skip such a loop or first make it reducible, for example by node splitting.
- The forests differ. On an irreducible graph, Steensgaard's, Havlak's and other forests can give different headers and different inner loops. Do not mix results from two of them.
- The root. The entry block has no predecessor. If it lies on a cycle, it must still count as a header, or the loop through it gets no header and the construction does not stop.
- Unreachable code. An edge from a block that the entry cannot reach must be ignored. Otherwise it can turn a block of a real loop into a header.
- Self-loops. A block with an edge to itself is a loop with one vertex. A block on no cycle is not a loop.
- Recursion depth. Loop nests from generated code can be hundreds deep. Use explicit stacks for the components and for the regions.
- Stale forests. A transformation that adds or removes blocks or edges can change the loops. Rebuild the forest or update it.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/loop-nesting-forest/. The authors are listed in prov/EMNP01.jsonl.
"""A loop nesting forest by repeated strongly connected components.
loop_forest(n, edges, root) returns a list of loops. Each loop is a dict
with "nodes" (the sorted vertices of the loop, inner loops included),
"headers" (its entry vertices, sorted) and "parent" (the index of the
smallest loop that contains it, or -1). The loops are the nontrivial
strongly connected components of the part that root reaches; inside each
loop, the headers are removed and the rest is split again. The headers of a
loop are its vertices with a predecessor outside the loop, and root, if the
loop contains it. This choice of headers is the one of Steensgaard; on a
reducible graph each loop then has one header and is the union of the
natural loops of that header.
innermost(n, loops) gives, for each vertex, the index of the innermost loop
that contains it, or -1. cfg_loops(prog) works on the blocks of a toy IR
program and uses labels.
"""
import toyir
def _sccs(nodes, succ):
"""Tarjan's algorithm with an explicit stack, on the subgraph induced by
the set nodes. Returns the components as lists."""
index = {}
low = {}
on = set()
stack = []
out = []
counter = 0
for s in sorted(nodes):
if s in index:
continue
index[s] = low[s] = counter
counter += 1
stack.append(s)
on.add(s)
work = [(s, iter(succ[s]))]
while work:
v, it = work[-1]
advanced = False
for w in it:
if w not in nodes:
continue
if w not in index:
index[w] = low[w] = counter
counter += 1
stack.append(w)
on.add(w)
work.append((w, iter(succ[w])))
advanced = True
break
if w in on and index[w] < low[v]:
low[v] = index[w]
if advanced:
continue
work.pop()
if work:
u = work[-1][0]
if low[v] < low[u]:
low[u] = low[v]
if low[v] == index[v]:
comp = []
while True:
w = stack.pop()
on.discard(w)
comp.append(w)
if w == v:
break
out.append(comp)
return out
def loop_forest(n, edges, root):
if n < 1 or not 0 <= root < n:
raise ValueError("a flow graph needs n >= 1 vertices and a root in range")
succ = [[] for _ in range(n)]
for a, b in edges:
if not (0 <= a < n and 0 <= b < n):
raise ValueError("edge endpoint out of range")
succ[a].append(b)
seen = {root} # @line L1
stack = [root]
while stack:
v = stack.pop()
for w in succ[v]:
if w not in seen:
seen.add(w)
stack.append(w)
pred = [[] for _ in range(n)]
for a, b in edges:
if a in seen:
pred[b].append(a)
loops = []
regions = [(seen, -1)]
while regions: # @line L2
region, parent = regions.pop() # @line L3
for comp in _sccs(region, succ): # @line L4
body = set(comp)
v = comp[0]
if len(comp) == 1 and v not in succ[v]: # @line L5
continue
heads = {x for x in body if x == root or any(p not in body for p in pred[x])} # @line L6
loops.append({"nodes": sorted(body), "headers": sorted(heads), "parent": parent}) # @line L7
regions.append((body - heads, len(loops) - 1)) # @line L8
return loops # @line L9
def innermost(n, loops):
"""The innermost loop of each vertex, or -1. A loop comes after its
parent in the list, so the last loop that contains a vertex is the
innermost one."""
out = [-1] * n
for i, loop in enumerate(loops):
for v in loop["nodes"]:
out[v] = i
return out
def depth(loops, i):
"""The number of loops on the path from loop i up to its root."""
d = 0
while i != -1:
d += 1
i = loops[i]["parent"]
return d
def cfg_loops(prog):
"""The loops of a toy IR program, with block labels instead of numbers."""
labels = list(prog.blocks)
index = {lab: i for i, lab in enumerate(labels)}
edges = [(index[a], index[b]) for a, b in toyir.edges(prog)]
loops = loop_forest(len(labels), edges, 0)
return [
{
"nodes": [labels[v] for v in loop["nodes"]],
"headers": [labels[v] for v in loop["headers"]],
"parent": loop["parent"],
}
for loop in loops
]
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.
A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:
("const", x, k) x = k
("copy", x, a) x = y
("op", x, op, a, b) x = a op b
("phi", x, {pred: a}) x = phi [pred: a, ...]
("addr", p, x) p = &x
("load", x, p) x = *p
("store", p, a) *p = a
("alloc", p) p = alloc
("call", x, f, args) x = call f(a, b) (args is a list)
Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""
from dataclasses import dataclass, field
import re
OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")
@dataclass
class Block:
instrs: list = field(default_factory=list)
term: tuple = ("ret", 0)
@dataclass
class Program:
params: list
blocks: dict
@property
def entry(self):
return next(iter(self.blocks))
class UndefinedName(Exception):
"""A name was read before any definition."""
# ---------------------------------------------------------------- text form
_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"
def _operand(tok):
if re.fullmatch(_INT, tok):
return int(tok)
if re.fullmatch(_NAME, tok):
return tok
raise ValueError("bad operand: %r" % tok)
def _name(tok):
if not re.fullmatch(_NAME, tok):
raise ValueError("bad name: %r" % tok)
return tok
def _parse_instr(line):
toks = line.split()
if toks[0] == "jump" and len(toks) == 2:
return "term", ("jump", _name(toks[1]))
if toks[0] == "br" and len(toks) == 4:
return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
if toks[0] == "ret" and len(toks) == 2:
return "term", ("ret", _operand(toks[1]))
lhs, eq, rhs = line.partition("=")
if not eq:
raise ValueError("bad line: %r" % line)
lhs, rhs = lhs.strip(), rhs.strip()
if lhs.startswith("*"):
return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
x = _name(lhs)
if rhs.startswith("phi"):
body = rhs[3:].strip()
if not (body.startswith("[") and body.endswith("]")):
raise ValueError("bad phi: %r" % line)
args = {}
inner = body[1:-1].strip()
if inner:
for part in inner.split(","):
pred, colon, a = part.partition(":")
if not colon:
raise ValueError("bad phi: %r" % line)
args[_name(pred.strip())] = _operand(a.strip())
return "instr", ("phi", x, args)
if rhs.startswith("call "):
m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
if not m:
raise ValueError("bad call: %r" % line)
inner = m.group(2).strip()
args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
return "instr", ("call", x, m.group(1), args)
if rhs == "alloc":
return "instr", ("alloc", x)
if rhs.startswith("&"):
return "instr", ("addr", x, _name(rhs[1:].strip()))
if rhs.startswith("*"):
return "instr", ("load", x, _name(rhs[1:].strip()))
parts = rhs.split()
if len(parts) == 1:
a = _operand(parts[0])
if isinstance(a, int):
return "instr", ("const", x, a)
return "instr", ("copy", x, a)
if len(parts) == 3 and parts[1] in OPS:
return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
raise ValueError("bad instruction: %r" % line)
def parse(text):
"""Parse the text form. A line "# params: a, b" gives the parameters;
without it, the parameters are the names that are read and never
defined, in the order of their first use."""
params = None
blocks = {}
cur = None
for raw in text.splitlines():
line = raw.strip()
if not line:
continue
if line.startswith("#"):
m = re.fullmatch(r"#\s*params:(.*)", line)
if m:
inner = m.group(1).strip()
params = [_name(p.strip()) for p in inner.split(",")] if inner else []
continue
if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
label = line[:-1]
if label in blocks:
raise ValueError("duplicate label: %r" % label)
cur = label
blocks[label] = Block([], None)
continue
if cur is None:
raise ValueError("instruction outside a block: %r" % line)
if blocks[cur].term is not None:
raise ValueError("instruction after the terminator in %r" % cur)
kind, item = _parse_instr(line)
if kind == "term":
blocks[cur].term = item
else:
blocks[cur].instrs.append(item)
for label, b in blocks.items():
if b.term is None:
raise ValueError("block %r has no terminator" % label)
if not blocks:
raise ValueError("empty program")
prog = Program([], blocks)
if params is None:
params = _free_names(prog)
prog.params = params
return prog
def _free_names(prog):
defined = set()
for b in prog.blocks.values():
for ins in b.instrs:
d = defs(ins)
if d is not None:
defined.add(d)
out = []
for b in prog.blocks.values():
for ins in b.instrs:
for a in uses(ins):
if a not in defined and a not in out:
out.append(a)
for a in term_uses(b.term):
if a not in defined and a not in out:
out.append(a)
return out
def _show_instr(ins):
k = ins[0]
if k == "const":
return "%s = %d" % (ins[1], ins[2])
if k == "copy":
return "%s = %s" % (ins[1], ins[2])
if k == "op":
return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
if k == "phi":
return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
if k == "addr":
return "%s = &%s" % (ins[1], ins[2])
if k == "load":
return "%s = *%s" % (ins[1], ins[2])
if k == "store":
return "*%s = %s" % (ins[1], ins[2])
if k == "alloc":
return "%s = alloc" % ins[1]
if k == "call":
return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
raise ValueError("bad instruction: %r" % (ins,))
def _show_term(t):
if t[0] == "jump":
return "jump %s" % t[1]
if t[0] == "br":
return "br %s %s %s" % (t[1], t[2], t[3])
if t[0] == "ret":
return "ret %s" % (t[1],)
raise ValueError("bad terminator: %r" % (t,))
def show(prog):
lines = ["# params: " + ", ".join(prog.params)]
for label, b in prog.blocks.items():
lines.append(label + ":")
for ins in b.instrs:
lines.append(" " + _show_instr(ins))
lines.append(" " + _show_term(b.term))
return "\n".join(lines) + "\n"
# ---------------------------------------------------------- names and graph
def defs(ins):
"""The name an instruction defines, or None for a store."""
return None if ins[0] == "store" else ins[1]
def uses(ins):
"""The names an instruction reads, in order (phi operands included)."""
k = ins[0]
if k == "const" or k == "alloc" or k == "addr":
ops = []
elif k == "copy":
ops = [ins[2]]
elif k == "op":
ops = [ins[3], ins[4]]
elif k == "phi":
ops = list(ins[2].values())
elif k == "load":
ops = [ins[2]]
elif k == "store":
ops = [ins[1], ins[2]]
elif k == "call":
ops = list(ins[3])
else:
raise ValueError("bad instruction: %r" % (ins,))
return [a for a in ops if isinstance(a, str)]
def term_uses(t):
if t[0] == "br" or t[0] == "ret":
return [t[1]] if isinstance(t[1], str) else []
return []
def succs(prog, label):
"""Successor labels of a block, without repeats, in terminator order."""
t = prog.blocks[label].term
if t[0] == "jump":
return [t[1]]
if t[0] == "br":
return [t[2]] if t[2] == t[3] else [t[2], t[3]]
return []
def edges(prog):
return [(a, b) for a in prog.blocks for b in succs(prog, a)]
def preds(prog):
"""Dict from label to the list of predecessor labels, in block order."""
out = {label: [] for label in prog.blocks}
for a, b in edges(prog):
out[b].append(a)
return out
def is_acyclic(prog):
color = {label: 0 for label in prog.blocks}
for root in prog.blocks:
if color[root]:
continue
color[root] = 1
stack = [(root, iter(succs(prog, root)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
color[v] = 2
stack.pop()
elif color[w] == 1:
return False
elif color[w] == 0:
color[w] = 1
stack.append((w, iter(succs(prog, w))))
return True
def paths(prog):
"""Every path from the entry to a ret block, as a list of labels.
The CFG must be acyclic."""
if not is_acyclic(prog):
raise ValueError("paths needs an acyclic CFG")
out = []
def walk(path):
last = path[-1]
s = succs(prog, last)
if not s:
out.append(list(path))
for w in s:
path.append(w)
walk(path)
path.pop()
walk([prog.entry])
return out
# ------------------------------------------------------------------ running
class _Trap(Exception):
pass
class _Fuel(Exception):
pass
def _binop(op, a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("arithmetic on a pointer")
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/" or op == "%":
if b == 0:
raise _Trap()
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if op == "/" else a - b * q
if op == "&":
return a & b
if op == "|":
return a | b
if op == "^":
return a ^ b
if op == "<<" or op == ">>":
if b < 0 or b > 63:
raise _Trap()
return a << b if op == "<<" else a >> b
if op == "<":
return int(a < b)
if op == "<=":
return int(a <= b)
if op == "==":
return int(a == b)
if op == "!=":
return int(a != b)
raise ValueError("bad operator: %r" % op)
class _Frame:
"""One activation: its program, its variables and its position."""
def __init__(self, prog, args, fid):
if len(args) != len(prog.params):
raise ValueError("expected %d arguments" % len(prog.params))
self.prog = prog
self.env = dict(zip(prog.params, args))
self.fid = fid
self.label = prog.entry
self.prev = None
self.pc = 0 # 0 means: the phis of the block have not run yet
self.dest = None # the name that receives the value of a pending call
def val(self, a):
if isinstance(a, int):
return a
if a not in self.env:
raise UndefinedName(a)
return self.env[a]
def _run(prog, args, fuel, funcs):
"""Run with an explicit stack of frames, so deep recursion in the toy
program does not use Python recursion."""
heap = {}
envs = {}
stack = []
fr = _Frame(prog, args, 0)
envs[0] = fr.env
nframes = 1
def tick():
nonlocal fuel
if fuel <= 0:
raise _Fuel()
fuel -= 1
while True:
block = fr.prog.blocks[fr.label]
instrs = block.instrs
if fr.pc == 0:
# Phis at the top of the block read all operands first, then assign.
incoming = []
i = 0
while i < len(instrs) and instrs[i][0] == "phi":
tick()
ins = instrs[i]
if fr.prev not in ins[2]:
raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
incoming.append((ins[1], fr.val(ins[2][fr.prev])))
i += 1
for x, v in incoming:
fr.env[x] = v
fr.pc = i if i > 0 else -1
start = fr.pc if fr.pc > 0 else 0
called = False
env = fr.env
for j in range(start, len(instrs)):
ins = instrs[j]
tick()
k = ins[0]
if k == "const":
env[ins[1]] = ins[2]
elif k == "copy":
env[ins[1]] = fr.val(ins[2])
elif k == "op":
env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
elif k == "addr":
env[ins[1]] = ("var", fr.fid, ins[2])
elif k == "alloc":
cell = ("heap", len(heap))
heap[cell] = None
env[ins[1]] = cell
elif k == "load":
p = fr.val(ins[2])
if p[0] == "var":
if p[2] not in envs[p[1]]:
raise UndefinedName(p[2])
env[ins[1]] = envs[p[1]][p[2]]
else:
if heap[p] is None:
raise UndefinedName(repr(p))
env[ins[1]] = heap[p]
elif k == "store":
p = fr.val(ins[1])
if p[0] == "var":
envs[p[1]][p[2]] = fr.val(ins[2])
else:
heap[p] = fr.val(ins[2])
elif k == "call":
if funcs is None or ins[2] not in funcs:
raise ValueError("unknown function %r" % ins[2])
vals = [fr.val(a) for a in ins[3]]
fr.pc = j + 1
fr.dest = ins[1]
stack.append(fr)
fr = _Frame(funcs[ins[2]], vals, nframes)
envs[nframes] = fr.env
nframes += 1
called = True
break
elif k == "phi":
raise ValueError("phi after a non-phi instruction")
else:
raise ValueError("bad instruction: %r" % (ins,))
if called:
continue
tick()
t = block.term
if t[0] == "jump" or t[0] == "br":
if t[0] == "jump":
nxt = t[1]
else:
nxt = t[2] if fr.val(t[1]) != 0 else t[3]
fr.prev, fr.label, fr.pc = fr.label, nxt, 0
continue
v = fr.val(t[1])
if not stack:
return ("ret", v), fuel
fr = stack.pop()
fr.env[fr.dest] = v
def run(prog, args, fuel=10000, funcs=None):
"""Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
Each instruction, phi and terminator uses one unit of fuel. funcs is an
optional dict from function name to Program, used by call; deep
recursion in the toy program is fine, because the frames are kept on an
explicit stack."""
try:
out, _ = _run(prog, list(args), fuel, funcs)
return out
except _Trap:
return ("trap",)
except _Fuel:
return ("fuel",)
# ------------------------------------------------------------ random programs
_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")
def random_program(rng, nvars, nblocks, acyclic):
"""A random program with blocks B0 .. B(nblocks-1) and variables
x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
others, so no run reads an undefined name. A division by a variable can
trap. Every block is reachable from
B0 and B0 has no predecessor. With acyclic=False, each loop has its own
counter c that is set to 0 in B0 and never reset, and the back edge is
taken only while c < m and c < 4, where m is the first parameter. So the
whole run takes each back edge at most 3 times."""
nvars = max(nvars, 1)
nblocks = max(nblocks, 1)
xs = ["x%d" % i for i in range(nvars)]
params = xs[:2]
labels = ["B%d" % i for i in range(nblocks)]
def operand():
if rng.random() < 0.25:
return rng.randint(-3, 9)
return rng.choice(xs)
def instr():
x = rng.choice(xs)
r = rng.random()
if r < 0.15:
return ("const", x, rng.randint(-5, 9))
if r < 0.25:
return ("copy", x, rng.choice(xs))
if r < 0.3:
# A division by a variable may trap.
return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
if r < 0.4:
op = rng.choice(_CONST_RIGHT)
k = rng.randint(1, 5)
return ("op", x, op, rng.choice(xs), k)
return ("op", x, rng.choice(_SAFE), operand(), operand())
blocks = {}
has_pred = [False] * nblocks
has_pred[0] = True
for i in range(nblocks):
instrs = [instr() for _ in range(rng.randint(1, 3))]
if i == 0:
instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
if i == nblocks - 1:
term = ("ret", rng.choice(xs))
elif has_pred[i + 1] and rng.random() < 0.2:
term = ("ret", rng.choice(xs))
else:
first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
if rng.random() < 0.5:
term = ("jump", labels[first])
has_pred[first] = True
else:
second = rng.randrange(i + 1, nblocks)
if second == first:
term = ("jump", labels[first])
else:
term = ("br", rng.choice(xs), labels[first], labels[second])
has_pred[second] = True
has_pred[first] = True
blocks[labels[i]] = Block(instrs, term)
if not acyclic and nblocks > 1:
nloops = rng.randint(1, max(1, nblocks // 3))
for k in range(nloops):
latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
if not latches:
break
t = rng.choice(latches)
h = labels[rng.randint(1, labels.index(t))]
c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
out = blocks[t].term[1]
blocks[t].instrs += [
("op", c, "+", c, 1),
("op", w1, "<", c, m),
("op", w2, "<", c, 4),
("op", w, "&", w1, w2),
]
blocks[t].term = ("br", w, h, out)
return Program(list(params), blocks)
test_loop_nesting_forest.py 267 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/loop-nesting-forest/. The authors are listed in prov/EMNP01.jsonl.
import random
import time
import pytest
import toyir
from loop_nesting_forest import cfg_loops, depth, innermost, loop_forest
# ------------------------------------------------------------ brute force
def reach_in(allowed, succ, s):
"""The vertices of allowed that s reaches inside allowed (s included)."""
seen = {s}
stack = [s]
while stack:
v = stack.pop()
for w in succ[v]:
if w in allowed and w not in seen:
seen.add(w)
stack.append(w)
return seen
def adjacency(n, edges):
succ = [[] for _ in range(n)]
for a, b in edges:
succ[a].append(b)
return succ
def by_definition(n, edges, root):
"""The forest from its recursive definition, with mutual reachability in
place of a strongly connected components algorithm."""
succ = adjacency(n, edges)
reach = reach_in(set(range(n)), succ, root)
pred = [[] for _ in range(n)]
for a, b in edges:
if a in reach:
pred[b].append(a)
out = set()
def split(region):
r = {v: reach_in(region, succ, v) for v in region}
done = set()
for v in sorted(region):
if v in done:
continue
comp = {w for w in r[v] if v in r[w]}
done |= comp
if len(comp) == 1 and v not in succ[v]:
continue
heads = {x for x in comp if x == root or any(p not in comp for p in pred[x])}
out.add((frozenset(comp), frozenset(heads)))
split(comp - heads)
split(reach)
return out
def natural_loops(n, edges, root):
"""(reducible, loops) where loops are the natural loops, merged by
header, with dominators from their definition: d dominates v when v
cannot be reached from root once d is removed."""
succ = adjacency(n, edges)
reach = reach_in(set(range(n)), succ, root)
def dominates(d, v):
if d == v or d == root:
return True
return v not in reach_in(reach - {d}, succ, root)
pred = [[] for _ in range(n)]
for a, b in edges:
if a in reach:
pred[b].append(a)
live = [(a, b) for a, b in edges if a in reach]
back = [(a, b) for a, b in live if dominates(b, a)]
forward = adjacency(n, [(a, b) for a, b in live if not dominates(b, a)])
reducible = not has_cycle(reach, forward)
loops = {}
for a, h in back:
body = loops.setdefault(h, {h})
if a in body:
continue
body.add(a)
stack = [a]
while stack:
v = stack.pop()
for p in pred[v]:
if p not in body:
body.add(p)
stack.append(p)
return reducible, {(frozenset(b), frozenset([h])) for h, b in loops.items()}
def has_cycle(vertices, succ):
indeg = {v: 0 for v in vertices}
for v in vertices:
for w in succ[v]:
if w in indeg:
indeg[w] += 1
ready = [v for v in vertices if indeg[v] == 0]
count = 0
while ready:
v = ready.pop()
count += 1
for w in succ[v]:
if w in indeg:
indeg[w] -= 1
if indeg[w] == 0:
ready.append(w)
return count != len(vertices)
def as_set(loops):
return {(frozenset(x["nodes"]), frozenset(x["headers"])) for x in loops}
def random_graph(rng):
n = rng.randint(1, 9)
m = rng.randint(0, 3 * n)
edges = [(rng.randrange(n), rng.randrange(n)) for _ in range(m)]
return n, edges, rng.randrange(n)
# ------------------------------------------------------------------ tests
def test_nested_loops_example():
# B0 -> B1 -> B2 -> B3 -> B4 -> B5 -> B6, with back edges B2 -> B1,
# B4 -> B3 and B5 -> B1.
edges = [(0, 1), (1, 2), (2, 1), (2, 3), (3, 4), (4, 3), (4, 5), (5, 1), (5, 6)]
loops = loop_forest(7, edges, 0)
assert loops == [
{"nodes": [1, 2, 3, 4, 5], "headers": [1], "parent": -1},
{"nodes": [3, 4], "headers": [3], "parent": 0},
]
assert innermost(7, loops) == [-1, 0, 0, 1, 1, 0, -1]
assert [depth(loops, i) for i in range(2)] == [1, 2]
def test_irreducible_loop_has_two_headers():
# r -> A, r -> B, A <-> B, A -> C. The cycle can be entered at A or at B.
loops = loop_forest(4, [(0, 1), (0, 2), (1, 2), (2, 1), (1, 3)], 0)
assert loops == [{"nodes": [1, 2], "headers": [1, 2], "parent": -1}]
def test_small_cases():
assert loop_forest(1, [], 0) == []
assert loop_forest(1, [(0, 0)], 0) == [{"nodes": [0], "headers": [0], "parent": -1}]
assert loop_forest(2, [(0, 1), (1, 1)], 0) == [{"nodes": [1], "headers": [1], "parent": -1}]
# A loop through the root has the root as a header.
assert loop_forest(2, [(0, 1), (1, 0)], 0) == [{"nodes": [0, 1], "headers": [0], "parent": -1}]
assert loop_forest(3, [(0, 1), (1, 0), (1, 2), (2, 1)], 0) == [
{"nodes": [0, 1, 2], "headers": [0], "parent": -1},
{"nodes": [1, 2], "headers": [1], "parent": 0},
]
# Repeated edges change nothing.
assert loop_forest(2, [(0, 1), (1, 1), (1, 1), (0, 1)], 0) == [{"nodes": [1], "headers": [1], "parent": -1}]
def test_unreachable_part_is_ignored():
# 2 <-> 3 is a cycle that 0 cannot reach, and 3 -> 1 is an edge from it
# into the loop 1 <-> 4; that edge must not make 1 or 4 a header.
edges = [(0, 1), (1, 4), (4, 1), (2, 3), (3, 2), (3, 4)]
assert loop_forest(5, edges, 0) == [{"nodes": [1, 4], "headers": [1], "parent": -1}]
def test_bad_input():
with pytest.raises(ValueError):
loop_forest(0, [], 0)
with pytest.raises(ValueError):
loop_forest(2, [], 2)
with pytest.raises(ValueError):
loop_forest(2, [(0, 2)], 0)
def test_random_graphs_match_the_definition():
rng = random.Random(97)
multi = 0
for _ in range(2000):
n, edges, root = random_graph(rng)
got = loop_forest(n, edges, root)
assert as_set(got) == by_definition(n, edges, root), (n, edges, root)
multi += sum(1 for x in got if len(x["headers"]) > 1)
assert multi > 100
def test_reducible_graphs_give_merged_natural_loops():
rng = random.Random(101)
seen = [0, 0]
for _ in range(2000):
n, edges, root = random_graph(rng)
reducible, nat = natural_loops(n, edges, root)
seen[reducible] += 1
if reducible:
assert as_set(loop_forest(n, edges, root)) == nat, (n, edges, root)
assert min(seen) > 100
def test_forest_properties():
rng = random.Random(103)
for _ in range(1500):
n, edges, root = random_graph(rng)
loops = loop_forest(n, edges, root)
succ = adjacency(n, edges)
reach = reach_in(set(range(n)), succ, root)
sets = [set(x["nodes"]) for x in loops]
for i, x in enumerate(loops):
assert x["headers"] and set(x["headers"]) <= sets[i] <= reach
p = x["parent"]
assert p < i
if p != -1:
assert sets[i] <= sets[p] - set(loops[p]["headers"])
for j in range(i):
assert sets[i] <= sets[j] or not (sets[i] & sets[j])
if sets[i] <= sets[j]:
# The parent is the smallest loop above.
assert p != -1 and sets[p] <= sets[j]
inner = innermost(n, loops)
for v in range(n):
holding = [i for i in range(len(loops)) if v in sets[i]]
assert inner[v] == (max(holding, key=lambda i: depth(loops, i)) if holding else -1)
# Remove the edges from inside each loop to its headers: no cycle is left.
cut = set()
for x, s in zip(loops, sets):
cut |= {(a, b) for a, b in edges if a in s and b in x["headers"]}
rest = adjacency(n, [(a, b) for a, b in edges if (a, b) not in cut])
assert not has_cycle(reach, rest)
def test_toy_programs():
rng = random.Random(107)
multi = 0
for _ in range(300):
prog = toyir.random_program(rng, 4, rng.randint(1, 14), rng.random() < 0.2)
labels = list(prog.blocks)
index = {lab: i for i, lab in enumerate(labels)}
edges = [(index[a], index[b]) for a, b in toyir.edges(prog)]
got = cfg_loops(prog)
want = by_definition(len(labels), edges, 0)
named = {(frozenset(index[v] for v in x["nodes"]), frozenset(index[v] for v in x["headers"])) for x in got}
assert named == want
multi += sum(1 for x in got if len(x["headers"]) > 1)
if toyir.is_acyclic(prog):
assert got == []
assert multi > 0
def test_deep_nesting():
# The path 0 .. 2k with the back edges 2k - i -> i gives k nested loops.
k = 500
n = 2 * k + 1
edges = [(i, i + 1) for i in range(2 * k)] + [(2 * k - i, i) for i in range(k)]
start = time.perf_counter()
loops = loop_forest(n, edges, 0)
assert time.perf_counter() - start < 5
assert len(loops) == k
for i, x in enumerate(loops):
assert x["headers"] == [i] and x["nodes"] == list(range(i, 2 * k - i + 1))
assert x["parent"] == i - 1
assert depth(loops, k - 1) == k
assert innermost(n, loops)[k] == k - 1
History
Early optimizing compilers found loops through intervals and dominators, in the work of Allen and Cocke around 1970, and the natural loops of a reducible graph give the loop tree that textbooks describe. Irreducible graphs needed more. Steensgaard's technical report of 1993 defined loops as nested strongly connected components with entry nodes, for program dependence graphs of irreducible programs. Sreedhar, Gao and Lee found loops with DJ graphs in 1996, and Havlak described a forest from a depth-first search in 1997. Ramalingam showed in 1999 that Havlak's algorithm can take quadratic time and gave almost-linear versions, and in 2002 he described a common frame for these forests and the reduced Havlak forest.
References
- G. Ramalingam, On loops, dominators, and dominance frontiers, ACM Transactions on Programming Languages and Systems 24(5), 2002, pages 455-490, loop nesting forests in general, the construction that finds strongly connected components, picks headers, removes the edges into the headers and repeats, the forests of Steensgaard, Havlak and Sreedhar, Gao and Lee as cases of it, and the reduced Havlak forest
- G. Ramalingam, Identifying loops in almost linear time, ACM Transactions on Programming Languages and Systems 21(2), 1999, pages 175-188, Steensgaard's top-down algorithm with generalized entry nodes and generalized back edges, the quadratic worst case of Havlak's algorithm, and almost-linear versions of the Havlak and Sreedhar, Gao and Lee algorithms
- Paul Havlak, Nesting of reducible and irreducible loops, ACM Transactions on Programming Languages and Systems 19(4), 1997, pages 557-567, a loop nesting forest for reducible and irreducible loops built from a depth-first search
- Vugranam C. Sreedhar, Guang R. Gao and Yong-Fong Lee, Identifying loops using DJ graphs, ACM Transactions on Programming Languages and Systems 18(6), 1996, pages 649-658, reducible and irreducible loops found with the dominator tree and the join edges of the flow graph
- Bjarne Steensgaard, Sequentializing program dependence graphs for irreducible programs, Technical Report MSR-TR-93-14, Microsoft Research, 1993, the loops of irreducible programs as nested strongly connected components with entry nodes
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag EMNP01 Edit this page History Report an error Markdown