Algorithmcore
Iterated register coalescing
Also called George-Appel allocator.
Interleaves simplification with conservative coalescing of move-related nodes and freezes moves when stuck, removing many copies safely.
- Time
- O(r (l + s n + n^2 (c + 1))) worst
- Space
- O(n + m + s + c) extra
- Where
- c = the number of copies; l = the time of one liveness analysis; m = the number of interference edges; n = the number of names; r = the number of rounds (at most n + 1); s = the number of instructions
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Lal George, Andrew W. Appel, 1996
Iterated register coalescing is the graph-coloring allocator of George and Appel (1996). It adds the removal of copies to optimistic coloring. A copy x = y is free if and get the same register, because it becomes r = r and is deleted. So the allocator coalesces the two names: it merges their vertices in the interference graph. A merge can make the graph harder to color, so the allocator merges only when the Briggs test or the George test shows that the merge is safe. It mixes these merges with the simplify steps of Chaitin's allocator: removing a vertex lowers the degrees of its neighbors, and a copy that failed the test before may pass it now.
In plain words
Many values in a program are only copies of other values. If a value and its copy share one register, the copy instruction is not needed. So the allocator tries to give them one register by joining them into one value. Joining is risky: the joined value clashes with everything that either part clashed with, so it can force a value into memory. The allocator joins two values only when a simple count shows that the joined value can still get a register. It takes out easy values first, and each removal can make another join safe. When nothing is easy and no join is safe, it gives up on a copy. Only when no copy is left to try does it pick a value that may go to memory.
The problem
The input is a program in the toy IR with const, copy and op instructions, and a number of registers. The output is a program with the same outcome that uses only the registers and memory slots mem.x (register allocation problem). A second aim is to delete as many copies x = y between two names as possible (register coalescing problem).
During one round, each vertex of the graph is a set of names, at first one name. Two vertices are adjacent if a name of one interferes with a name of the other. To merge two vertices and that are not adjacent is to replace them by their union, adjacent to every neighbor of or . The cost of a vertex is the sum of the costs of its names, without the infinite costs of spill temporaries, and it is infinite only if all its names are temporaries. A copy is live while it is not coalesced and not given up. A vertex is move-related if it has a live copy.
Two tests decide if a merge of and is safe:
- Briggs test. In the graph after the merge, fewer than neighbors of the merged vertex have degree or more.
- George test. Every neighbor of is a neighbor of or has degree less than , or the same holds with and swapped.
The parameter TEST is the Briggs test, the George test, or both (a merge is safe if one of them passes).
The algorithm
IRC-ALLOCATE(P, k, TEST)- 1
P <- P with a new entry block that loads each live parameter p from mem.p - 2
T <- the empty set // spill temporaries - 3
loop - 4
G <- the interference graph of P; W <- the copies x = y of P between two names // build - 5
cost[x] <- the number of definitions and uses of x in P, or infinity if x is in T - 6
stack <- empty - 7
while G has a vertex do - 8
if some vertex v has degree < k and is not move-related, or v is a spill candidate then // simplify - 9
push v on stack; remove v from G - 10
else if W is not empty then // coalesce - 11
take a copy x = y out of W; u <- the vertex of x; v <- the vertex of y - 12
if u = v then the copy is coalesced - 13
else if u and v are adjacent then the copy is given up // constrained - 14
else if TEST(G, u, v, k) then merge v into u; the copy is coalesced - 15
else the copy waits, and goes back to W when the degree of u, v or one of their neighbors drops to k - 1 - 16
else if some vertex v of degree < k is move-related then // freeze - 17
give up every live copy of v - 18
else // potential spill - 19
v <- a vertex with the least cost[v] / degree(v); give up every live copy of v; make v a spill candidate - 20
spill <- the empty set - 21
for each v on stack, from the top down do // select - 22
if some color in 0 .. k-1 is not used by a colored vertex adjacent to v then - 23
color[v] <- the least such color - 24
else spill <- spill + {v} - 25
if spill is empty then - 26
return P with each name x renamed to r[color[the vertex of x]] and each copy r = r deleted - 27
P <- P with each name of each vertex in spill kept in mem.x, by loads before uses and stores after definitions - 28
T <- T + the new temporaries
Line L8 simplifies only vertices that are not move-related, because removing a vertex ends all chances to coalesce it. Line L10 tries copies only when no such vertex is left. Line L16 freezes a low-degree vertex when all waiting copies have failed: its copies become ordinary instructions and the vertex can be simplified. Line L19 is reached only when every vertex left has degree or more. The spill candidate is then simplified at line L8, and line L24 spills it only if select finds no free color, as in optimistic coloring.
Line L15 is the "iterated" part. A copy that fails the test is not given up. The tests count neighbors of high degree, and simplify and other merges lower degrees. So when a degree drops to , the copies at that vertex and at its neighbors go back to . A merge of into also puts the waiting copies of back to .
Example
This loop adds the numbers , in the style of a program after out-of-SSA translation, with one copy per loop variable:
L0:
i = n
s = 0
jump L1
L1:
t = s + i
j = i - 1
s = t
i = j
br i L1 L2
L2:
ret s
After line L1 adds the block start with n = mem.n, the edges are -, -, - and -, a cycle of length 4, and is isolated. No copy makes an edge between its two names. The copies are i = n, i = j and s = t. Take and the Briggs test.
| step | line | action | why |
|---|---|---|---|
| 1 | L14, L15 | i = n waits |
merged with , vertex has the neighbors and , both of degree 2 |
| 2 | L14 | merge into | after the merge, and have degree 1, so no neighbor has a high degree; i = n goes back to |
| 3 | L14 | merge into | the only neighbor, , has degree 1 after the merge |
| 4 | L9 | push | degree 1 and no live copy |
| 5 | L14 | merge into | now has degree 0 |
| 6 | L9 | push | degree 0 |
Select gives color 0 and color 1. All three copies become r = r and are deleted:
start:
r0 = mem.n
jump L0
L0:
r1 = 0
jump L1
L1:
r1 = r1 + r0
r0 = r0 - 1
br r0 L1 L2
L2:
ret r1
Optimistic coloring without coalescing also colors this graph with , and it deletes s = t and i = j by chance, because a cycle of length 4 has only one 2-coloring up to a swap. But it gives color 0 and color 1, so i = n stays as r1 = r0. A script checked that both outputs return for from 1 to 7. With the George test instead, step 1 passes at once: has no neighbor, so the condition holds for every neighbor of .
Why the tests are needed. In this program, is a copy of on one path and is computed on the other:
L0:
y = p + 2
x = p + 1
br x L1 L2
L1:
a = x + 1
a = a + x
b = a
jump L3
L2:
b = y + 1
b = b + y
jump L3
L3:
ret b
The edges are -, -, - and -, so is a path and the graph is 2-colorable. Merging and makes the triangle . Both tests refuse the merge with : the merged vertex would have the two neighbors and of degree at least 2, and neither nor is a neighbor of the other end. So IRC-ALLOCATE keeps the copy and needs no spill. With aggressive coalescing, which merges every pair that does not interfere, the graph has a triangle, is spilled, and a second round is needed. The output then has one store and two loads of mem.y instead of one copy.
Correctness
The proof file shows:
- The tests are safe. If is -colorable and pass the Briggs test or the George test, the graph after the merge is -colorable. If has an empty -core, so does the merged graph. Aggressive merging has neither property: the path above becomes a triangle.
- No spill on easy graphs. If the interference graph has an empty -core, that is, if Chaitin's allocator colors it with no spill, then IRC-ALLOCATE never runs line L19 and spills nothing.
- Select is proper. A vertex pushed at line L9 that is not a spill candidate always gets a color, and adjacent vertices never get the same color. This holds even though merges change the graph after a vertex is pushed.
- The output is correct. Each name gets the color of its vertex. The names of one vertex never interfere, so this is a -coloring of the interference graph, and the renaming and spill lemmas of Chaitin's allocator apply.
- It stops. The inner loop stops by a counting argument, and each round that spills removes at least one name of the program after line L1 for good, so there are at most rounds.
Proof: The Briggs and George tests are safe, and iterated register coalescing gives a correct program and stopsfull
We prove the safety of the two coalescing tests on a fixed graph (Lemmas 1 and 2), then four facts about IRC-ALLOCATE: one round stops (Lemma 3), select is proper (Lemma 4), a graph with an empty -core is never spilled (Lemma 5), and the output is correct (Lemma 6). Lemma 7 shows that the outer loop stops.
Graphs and merges
is a finite simple graph and . is the set of neighbors of , and . For , is the induced subgraph and . For two vertices that are not adjacent, the merge replaces and by one new vertex with ; all other edges stay.
The -core of is the largest induced subgraph whose vertices all have degree at least in it. It exists because the union of two such vertex sets is again such a set, and it is empty exactly when every nonempty induced subgraph has a vertex of degree less than . Chaitin's allocator colors with no spill exactly when the -core is empty (Lemma 3 of the proof file of Chaitin's allocator).
We use the simplify rule (Lemma 1 there): if , then is -colorable if and only if is. Applied to a set of vertices removed one at a time, it needs each vertex to have degree less than only at its turn. Removing vertices never raises a degree, so it is enough that each vertex of has degree less than in . Then is -colorable if and only if is.
Also, an induced subgraph of a graph with an empty -core has an empty -core, because a -core of the subgraph would be an induced subgraph of the larger graph with all degrees at least .
Lemma 1 (Briggs test). Let be non-adjacent vertices of , let be the merge, and suppose that fewer than neighbors of have degree at least in . Then:
- if is -colorable, so is ;
- if has an empty -core, so has .
Proof. (1) Let be the set of neighbors of with degree less than in , and the set of the other neighbors, so . By the simplify rule, is -colorable if and only if is. In , the neighbors of are those in , fewer than , so by the simplify rule again, is -colorable if and only if is. That graph is , an induced subgraph of , and it is -colorable because is.
(2) Suppose has a nonempty -core, with vertex set . If , then , which has all degrees at least , so the -core of is not empty. If , then has at least neighbors in . Each of them has degree at least in , so also in . These are neighbors of with degree at least in , against the test.
Lemma 2 (George test). Let be non-adjacent vertices of such that every neighbor of is a neighbor of or has degree less than in . Let be the merge. Then (1) and (2) of Lemma 1 hold.
Proof. Let . Each has . In , the vertex loses its neighbor and gains , and it was not adjacent to , so .
(1) By the simplify rule, is -colorable if and only if is. In , the neighbors of are , because and . So is with renamed to . It is an induced subgraph of , so it is -colorable.
(2) Suppose has a nonempty -core with vertex set . If , then is a nonempty induced subgraph of with all degrees at least . If , each neighbor of in has , so , and so . Let . Map to and every other vertex to itself. Each edge of that does not touch is an edge of , and each edge of gives the edge of , because . So every vertex of has degree at least its degree in , which is at least . So the -core of is not empty.
Aggressive merges are not safe. Take the path and . It is 2-colorable and has an empty 2-core. Merging and gives the triangle , which is not 2-colorable and is its own 2-core. Both tests refuse this merge: the merged vertex has the two neighbors and of degree 2, and , , both of degree 2.
One round
In a round, the vertices of are sets of names, at first single names. A vertex is adjacent to when a name of interferes with a name of . Line L14 merges and only if they are not adjacent (line L13), so by induction no two names of one vertex interfere. Let be the graph after passes of the loop at line L7. Every vertex leaves either at line L9, as a whole, or at line L14, as part of a larger vertex. A vertex pushed at line L9 never changes after that. So the vertices on the stack at the end are disjoint, and every name is in exactly one of them. Call this set of vertices the final vertices, and let be the graph on them with the same adjacency rule. Line L22 uses adjacency in .
Lemma 3 (one round stops). The loop at line L7 stops after a finite number of passes.
Proof. When the conditions of lines L8 and L16 fail, every vertex of has degree at least : a vertex of degree less than is either not move-related or move-related. So line L19 always finds a vertex with a positive degree. Also, when line L19 runs there is no spill candidate in , because line L8 would apply to it first.
Let be the number of vertices of , the number of live copies, the number of vertices that are not spill candidates, and the size of . Each pass lowers the tuple in the lexicographic order. Line L9 and line L14 lower . Lines L12 and L13 do not change and lower . Line L17 lowers , because is move-related. Line L19 keeps , does not raise , and lowers . Line L15 keeps the first three and lowers : a copy goes back to only when a degree drops or after a merge, and both happen only at lines L9 and L14. So the loop stops.
Lemma 4 (select). Every vertex pushed at line L9 that is not a spill candidate gets a color at line L23. At the end of select, the colors form a -coloring of the colored final vertices in .
Proof. Let be pushed at pass , not as a spill candidate, so line L8 gave . Line L21 visits the stack from the top down, so when it reaches , the colored vertices were all pushed after . Let be such a vertex that is adjacent to in , by names and that interfere. At pass , the name is in some vertex of : it was not pushed yet, since is pushed later and . So is a neighbor of in . Distinct vertices come from distinct vertices , because the final vertices are disjoint. So fewer than colored vertices are adjacent to , they use fewer than colors, and line L22 finds a free color.
Line L23 uses only colors in . For an edge of between two colored vertices, the one colored second avoided the color of the other at line L22, and colors never change.
Lemma 5 (no spill on easy graphs). Let TEST be the Briggs test, the George test, or both. If the interference graph built at line L4 has an empty -core, the round never runs line L19 and ends with an empty set spill.
Proof. We show by induction on that has an empty -core. It holds for . Line L9 removes a vertex, which gives an induced subgraph. Line L14 merges two non-adjacent vertices that pass TEST in , so Lemma 1 or Lemma 2 applies. The other lines do not change the graph.
Suppose line L19 runs at pass . As in the proof of Lemma 3, every vertex of has degree at least , and is not empty. So is its own nonempty -core, a contradiction. So there is no spill candidate, and by Lemma 4 every vertex gets a color.
With aggressive coalescing, Lemma 5 fails: the second program of the example has an empty 2-core, and aggressive coalescing spills .
The output is correct
The program model, the liveness rule and the renaming and spill lemmas are those of the proof file of Chaitin's allocator (its Lemmas 4 and 5). The renaming lemma needs only a -coloring of the interference graph of the program. The spill lemma holds for any set of spilled names.
Lemma 6 (correct output). If IRC-ALLOCATE returns, its result uses only the registers and the memory slots, and it has the same outcome as on every input.
Proof. Line L26 runs only when spill is empty, so every final vertex has a color by Lemma 4. Let be the color of the final vertex of the name . For an interference edge , the names and are in different final vertices, because no two names of one vertex interfere, and these vertices are adjacent in . By Lemma 4 they have different colors. So is a -coloring of the interference graph, and line L26 keeps the outcome by the renaming lemma. A copy whose two names are in one vertex becomes r = r and is deleted. Line L27 keeps the outcome by the spill lemma, and line L1 keeps it because it only moves the parameters through their slots.
Termination
Call the non-slot names of the program after line L1 the original names, and the names made by line L27 the temporaries. A vertex is original if it holds an original name. Its cost is finite: it is the sum of the finite costs of its names. A vertex that holds only temporaries has an infinite cost.
The parameter loads that line L1 puts in the entry block are the only loads that write original names. A load temporary is a temporary whose write is a load and whose only read is the first instruction after the write that is not a load. A store temporary is a temporary whose only read is a store just after its write. We prove four statements together, by induction on the rounds.
- (T) Shape. Each temporary is written once and is a load temporary or a store temporary, and no load temporary is in the entry block.
- (M) Moves. A temporary is move-related only if it is a load temporary read by a copy, or a store temporary written by a copy. Such a temporary has no temporary neighbor in the interference graph.
- (V) Few edges. In , a vertex that holds only temporaries has at most one neighbor that holds only temporaries.
- (O) Original spills. Each time line L19 runs, it chooses an original vertex.
(T) implies (M). A load or a store copies between a name and a slot, so it is not a copy in . So a move-related temporary is read by a copy (then it is not a store temporary, which is read by a store) or written by a copy (then it is not a load temporary, which is written by a load). Now take an interference edge between two temporaries. It is made at the write of one of them, , with the other, , live just after. If is a store temporary, it is live only between its write and its store, so the write of is the write of and , which is not an edge. So is a load temporary, live from its load to its reader . Every instruction in that stretch before is a load, and none of them is in the entry block. So is written by a load that is followed only by loads up to . If were a store temporary, its store would come right after its write and before , and a store is not a load. So is a load temporary with the reader too. Then reads two different names and , so is an op, not a copy, and neither nor is move-related.
(M) and (T) imply (V). Merges at line L14 follow copies, so a vertex of two or more names that holds only temporaries holds only move-related temporaries, and by (M) none of them has a temporary neighbor. So that vertex has no neighbor that holds only temporaries. A vertex of one temporary has at most as many such neighbors as has temporary neighbors. By the proof of (M), these are load temporaries with the same reader as , and that reader reads at most two names, so there is at most one.
(V) implies (O). When line L19 runs, every vertex of has degree at least (proof of Lemma 3). If no vertex of were original, each would have degree at most 1 by (V). So some vertex is original. Its cost is finite and its degree is positive, so its ratio is finite, while every vertex of only temporaries has ratio infinity. So line L19 chooses an original vertex.
(O) implies (T) in the next round. By Lemma 4 and (O), each vertex in spill is original. Line L27 spills all names of these vertices. Such a name is original, or it is a temporary in an original vertex, which is move-related because merges follow copies. The new temporaries have the two shapes: the loads before a reader are placed just before , and the temporary of a definition is followed by its store. No new load is in the entry block: the instructions there read only slots and store temporaries of parameters, and a store temporary written by a load is not move-related, so it is never spilled. For an old temporary that is not spilled:
- if it is a store temporary, line L27 puts nothing between its write and its store, because its write defines no spilled name and its store reads no spilled name;
- if it is a load temporary with reader , line L27 adds loads just before , which keeps the shape. It adds a store between the load of and only after a load there that writes a spilled temporary . By (T), is a load temporary with reader , and it is move-related, so by (M) is a copy. But reads both and , and a copy reads one name. So this does not happen.
Lemma 7 (termination). Let be the number of original names. IRC-ALLOCATE with returns after at most rounds.
Proof. Each round stops by Lemma 3. A round that does not return has a nonempty set spill, and each of its vertices is original by Lemma 4 and (O). Line L27 replaces every occurrence of the spilled names by new temporaries, and later rounds make only temporaries, so a spilled original name never appears again. So each round that does not return removes at least one of the original names for good, and at most rounds do not return.
Together, Lemmas 3, 6 and 7 show that IRC-ALLOCATE stops with a correct program that uses registers. Lemmas 1, 2 and 5 show that conservative coalescing never makes a -colorable graph uncolorable, and never causes a spill on a graph that Chaitin's allocator colors.
Complexity
One round has at most pushes and merges. A copy is taken from once at the start and then only after a degree drops to . The degree of a vertex goes up only when another vertex is merged into it, so there are such drops in a round, and each one puts back at most copies. So there are tests in a round. Each test, merge or push costs with adjacency sets, and finding the spill candidates costs in all. With build in after a liveness analysis of cost , and at most rounds, the time is . This is a simple bound, not a tight one. The space is , if the copy list of a merged vertex replaces the lists of its parts.
Properties
- Safe coalescing. With the Briggs or George test, a merge never turns a graph with an empty -core into one with a nonempty -core. So coalescing never causes a spill on a graph that Chaitin's allocator colors.
- Not every safe merge is found. The tests are sufficient conditions. A merge that keeps the graph -colorable can fail both tests, and the order in which copies are tried changes the result.
- Conservative coalescing is hard to do best. Bouchez, Darte and Rastello (2007) proved that finding the most copies that conservative coalescing can remove is NP-complete. So IRC-ALLOCATE is a heuristic for the coalescing part as well.
- Freezing loses copies. A frozen copy stays in the program, even if a later merge would have been safe.
- Deterministic. The result depends on the order of the names and the copies.
Variants and improvements
- Precolored vertices. Real machines have registers with fixed roles, such as argument and return registers. George and Appel treat them as vertices that are already colored and never simplified or spilled, and use the George test when one end is precolored, because a precolored vertex can have a very large set of neighbors.
- Coalescing at the select phase. Biased coloring prefers, in select, the color of a copy partner. It deletes some copies without any merge.
- Optimistic coalescing. Park and Moon (2004) merge aggressively first and undo merges in select when a merged vertex finds no color.
- SSA-based allocation. SSA-based register allocation colors the chordal interference graph of an SSA program first and removes copies afterward.
- Spill code. Spill code placement, live range splitting and rematerialization improve the code for the actual spills.
When to use it
Use it in an optimizing compiler for a machine with a moderate number of registers when the program has many copies: after SSA destruction, after inlining, or with calling conventions that move arguments into fixed registers. It is the allocator of the textbook of Appel and the base of many graph-coloring allocators. When compile time matters more than code quality, use linear scan. When copies are rare, plain optimistic coloring is simpler.
Pitfalls
- A copy does not interfere. At a copy
x = y, the source does not interfere with , even if is still live. If the build phase adds this edge, no copy can be coalesced. - Aggressive is not safe. Merging every pair of non-interfering copy ends can turn a 2-colorable graph into a triangle, as in the example.
- Use the right degrees. The Briggs test counts degrees in the graph after the merge: a common neighbor of and loses one edge.
- Do not simplify a move-related vertex. Removing it early ends all chances to coalesce its copies. Freeze it first.
- Costs of merged vertices. A merged vertex that holds an original name must keep a finite cost. If it inherits the infinite cost of a spill temporary, the spill choice can get stuck.
- Color the names, not only the vertices. After select, each name takes the color of the vertex it was merged into.
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/iterated-register-coalescing/. The authors are listed in prov/ZBH45M.jsonl.
"""Iterated register coalescing (George and Appel).
irc_color(adj, moves, k, cost, test) works on a graph: adj maps each node to
the set of its neighbors and moves is a list of pairs (x, y), one for each
copy. It returns (color, spilled, coalesced). color maps each node that got
a color to a color in 0 .. k-1, spilled is the set of nodes left without a
color, and coalesced is the list of the indices of the moves whose two ends
got one node. test is the coalescing rule: "briggs", "george", "either"
(the move passes one of the two) or "aggressive" (any move whose ends do
not interfere). There are no precolored nodes.
briggs_ok, george_ok and merge apply the two tests and the merge to a
fixed graph. allocate(prog, k, test) is the full allocator for toy IR
programs with const, copy and op instructions; it returns
(out, rounds, spilled) as the allocators of the Chaitin and Briggs pages do.
"""
import math
import toyir
MEM = "mem."
def is_mem(name):
return isinstance(name, str) and name.startswith(MEM)
# ------------------------------------------------------- tests on one graph
def merge(adj, a, b):
"""The graph with b merged into a. a and b must not be adjacent."""
if b in adj[a]:
raise ValueError("cannot merge two adjacent nodes")
out = {v: set(ws) for v, ws in adj.items() if v != b}
for w in adj[b]:
out[w].discard(b)
out[w].add(a)
out[a].add(w)
return out
def briggs_ok(adj, a, b, k):
"""Briggs: the merged node has fewer than k neighbors of degree >= k,
with the degrees taken in the merged graph."""
m = merge(adj, a, b)
return sum(1 for w in m[a] if len(m[w]) >= k) < k
def george_ok(adj, a, b, k):
"""George, for merging a into b: each neighbor of a is a neighbor of b
or has degree < k."""
return all(w in adj[b] or len(adj[w]) < k for w in adj[a])
# -------------------------------------------------------------- the worklists
def _merged_cost(a, b):
# A spill temporary has an infinite cost; a node that holds any other
# name keeps the finite part, so it stays a possible spill choice.
if a == math.inf:
return b
if b == math.inf:
return a
return a + b
def irc_color(adj, moves, k, cost=None, test="briggs"):
if k < 1:
raise ValueError("k must be at least 1")
if test not in ("briggs", "george", "either", "aggressive"):
raise ValueError("unknown test %r" % test)
order = list(adj)
index = {v: i for i, v in enumerate(order)}
cost = dict(cost) if cost is not None else {v: 1 for v in order}
graph = {v: set(adj[v]) for v in order}
degree = {v: len(adj[v]) for v in order}
move_list = {v: set() for v in order}
for i, (x, y) in enumerate(moves):
if x != y:
move_list[x].add(i)
move_list[y].add(i)
worklist_moves = {i: None for i, (x, y) in enumerate(moves) if x != y}
active = set()
alias = {}
gone = set() # nodes on the stack or coalesced
stack = [] # @line L6
chosen = set()
simplify_wl, freeze_wl, spill_wl = {}, {}, {}
coalesced_moves = []
def get_alias(n):
while n in alias:
n = alias[n]
return n
def adjacent(n):
return sorted((w for w in graph[n] if w not in gone), key=index.__getitem__)
def node_moves(n):
return [i for i in sorted(move_list[n]) if i in active or i in worklist_moves]
def place(n):
"""Put n in the one worklist that its degree and its moves call for."""
if n in gone or n in chosen:
return
for wl in (simplify_wl, freeze_wl, spill_wl):
wl.pop(n, None)
if degree[n] >= k:
spill_wl[n] = None
elif node_moves(n):
freeze_wl[n] = None
else:
simplify_wl[n] = None
def enable_moves(nodes):
for n in nodes:
for i in node_moves(n):
if i in active:
active.discard(i)
worklist_moves[i] = None
def decrement_degree(m):
degree[m] -= 1
if degree[m] == k - 1:
enable_moves([m] + adjacent(m))
place(m)
def add_edge(u, v):
if v not in graph[u]:
graph[u].add(v)
graph[v].add(u)
degree[u] += 1
degree[v] += 1
def ok(u, v):
if test == "aggressive":
return True
nu, nv = set(adjacent(u)), set(adjacent(v))
if test in ("briggs", "either"):
high = sum(1 for t in nu | nv if degree[t] - (t in nu and t in nv) >= k)
if high < k:
return True
if test in ("george", "either"):
if all(t in nv or degree[t] < k for t in nu):
return True
if all(t in nu or degree[t] < k for t in nv):
return True
return False
def combine(u, v):
for wl in (simplify_wl, freeze_wl, spill_wl):
wl.pop(v, None)
gone.add(v)
alias[v] = u
move_list[u] |= move_list[v]
cost[u] = _merged_cost(cost[u], cost[v])
enable_moves([v])
for t in adjacent(v):
add_edge(t, u)
decrement_degree(t)
place(u)
def freeze_moves(u):
for i in node_moves(u):
x, y = get_alias(moves[i][0]), get_alias(moves[i][1])
v = x if y == get_alias(u) else y
active.discard(i)
worklist_moves.pop(i, None)
place(v)
for v in order:
place(v)
while simplify_wl or worklist_moves or freeze_wl or spill_wl: # @line L7
if simplify_wl: # @line L8
n = next(iter(simplify_wl))
del simplify_wl[n]
stack.append(n) # @line L9
gone.add(n)
for m in adjacent(n):
decrement_degree(m)
elif worklist_moves: # @line L10
i = next(iter(worklist_moves))
del worklist_moves[i]
u, v = get_alias(moves[i][0]), get_alias(moves[i][1]) # @line L11
if u == v: # @line L12
coalesced_moves.append(i)
place(u)
elif v in graph[u]: # @line L13
place(u)
place(v)
elif ok(u, v): # @line L14
coalesced_moves.append(i)
combine(u, v)
else:
active.add(i) # @line L15
elif freeze_wl: # @line L16
u = next(iter(freeze_wl))
del freeze_wl[u]
simplify_wl[u] = None
freeze_moves(u) # @line L17
place(u)
else: # @line L18
m = min(spill_wl, key=lambda u: (cost[u] / degree[u], index[u])) # @line L19
del spill_wl[m]
chosen.add(m)
simplify_wl[m] = None
freeze_moves(m)
color = {}
actual = set() # @line L20
while stack: # @line L21
n = stack.pop()
used = {color[get_alias(w)] for w in graph[n] if get_alias(w) in color}
c = 0
while c in used:
c += 1
if c < k: # @line L22
color[n] = c # @line L23
else:
assert n in chosen # a node that simplify removed always finds a color
actual.add(n) # @line L24
for n in order:
if n in alias and get_alias(n) in color:
color[n] = color[get_alias(n)]
spilled = {n for n in order if get_alias(n) in actual}
return color, spilled, sorted(coalesced_moves)
# ----------------------------------------------------------- program level
def _check(prog):
for b in prog.blocks.values():
for ins in b.instrs:
if ins[0] not in ("const", "copy", "op"):
raise ValueError("only const, copy and op instructions: %r" % (ins,))
def liveness(prog):
"""live_in and live_out of each block, by the backward fixed point."""
use, kill = {}, {}
for label, b in prog.blocks.items():
u, d = set(), set()
for ins in b.instrs:
u.update(a for a in toyir.uses(ins) if a not in d)
d.add(ins[1])
u.update(a for a in toyir.term_uses(b.term) if a not in d)
use[label], kill[label] = u, d
live_in = {label: set() for label in prog.blocks}
live_out = {label: set() for label in prog.blocks}
changed = True
while changed:
changed = False
for label in reversed(list(prog.blocks)):
out = set()
for s in toyir.succs(prog, label):
out |= live_in[s]
new_in = use[label] | (out - kill[label])
if out != live_out[label] or new_in != live_in[label]:
live_out[label], live_in[label] = out, new_in
changed = True
return live_in, live_out
def interference(prog):
"""The interference graph of the names that are not memory slots, and
the list of copies (x, y) for x = y between two such names. A copy does
not make its two names interfere."""
_check(prog)
_, live_out = liveness(prog)
adj = {}
moves = []
for b in prog.blocks.values():
for ins in b.instrs:
for a in [ins[1]] + toyir.uses(ins):
if not is_mem(a):
adj.setdefault(a, set())
for a in toyir.term_uses(b.term):
if not is_mem(a):
adj.setdefault(a, set())
for label, b in prog.blocks.items():
live = set(live_out[label]) | set(toyir.term_uses(b.term))
for ins in reversed(b.instrs):
x = ins[1]
src = ins[2] if ins[0] == "copy" else None
if not is_mem(x):
for y in live:
if y != x and y != src and not is_mem(y):
adj[x].add(y)
adj[y].add(x)
if src is not None and src != x and not is_mem(src):
moves.append((x, src))
live.discard(x)
live.update(toyir.uses(ins))
return adj, moves
def spill_costs(prog, infinite=()):
cost = {}
for b in prog.blocks.values():
for ins in b.instrs:
for a in [ins[1]] + toyir.uses(ins):
cost[a] = cost.get(a, 0) + 1
for a in toyir.term_uses(b.term):
cost[a] = cost.get(a, 0) + 1
for a in infinite:
cost[a] = math.inf
return cost
def _names(prog):
out = set(prog.params)
for b in prog.blocks.values():
for ins in b.instrs:
out.add(ins[1])
out.update(toyir.uses(ins))
out.update(toyir.term_uses(b.term))
return out
def _sub(a, m):
return m.get(a, a) if isinstance(a, str) else a
def spill_everywhere(prog, spilled):
"""Keep each name x of spilled in the memory slot mem.x: load a new
temporary before each use, store a new temporary after each definition.
Returns (program, temporaries)."""
taken = _names(prog)
temps = set()
count = [0]
def temp(x):
while True:
count[0] += 1
t = "%s.%d" % (x, count[0])
if t not in taken:
taken.add(t)
temps.add(t)
return t
blocks = {}
for label, b in prog.blocks.items():
out = []
for ins in b.instrs:
loads = {}
for a in toyir.uses(ins):
if a in spilled and a not in loads:
loads[a] = temp(a)
out.append(("copy", loads[a], MEM + a))
if ins[0] == "copy":
ins = ("copy", ins[1], _sub(ins[2], loads))
elif ins[0] == "op":
ins = ("op", ins[1], ins[2], _sub(ins[3], loads), _sub(ins[4], loads))
x = ins[1]
if x in spilled:
t = temp(x)
out.append((ins[0], t) + ins[2:])
out.append(("copy", MEM + x, t))
else:
out.append(ins)
term = b.term
if term[0] in ("br", "ret") and term[1] in spilled:
t = temp(term[1])
out.append(("copy", t, MEM + term[1]))
term = (term[0], t) + term[2:]
blocks[label] = toyir.Block(out, term)
return toyir.Program(list(prog.params), blocks), temps
def prepare(prog):
"""A copy of prog whose arguments arrive in memory slots: a new entry
block loads each parameter that is live on entry."""
_check(prog)
if any(is_mem(a) for a in _names(prog)):
raise ValueError("names that start with %r are reserved" % MEM)
live_in, _ = liveness(prog)
label = "start"
while label in prog.blocks:
label += "_"
pro = [("copy", p, MEM + p) for p in prog.params if p in live_in[prog.entry]]
blocks = {label: toyir.Block(pro, ("jump", prog.entry))}
for lab, b in prog.blocks.items():
blocks[lab] = toyir.Block(list(b.instrs), b.term)
return toyir.Program([MEM + p for p in prog.params], blocks)
def assign(prog, color):
"""Rename each name to its register; drop copies that become r = r,
which removes every coalesced copy."""
def reg(a):
if not isinstance(a, str) or is_mem(a):
return a
return "r%d" % color[a]
blocks = {}
for label, b in prog.blocks.items():
out = []
for ins in b.instrs:
if ins[0] == "const":
out.append(("const", reg(ins[1]), ins[2]))
elif ins[0] == "copy":
x, a = reg(ins[1]), reg(ins[2])
if x != a:
out.append(("copy", x, a))
else:
out.append(("op", reg(ins[1]), ins[2], reg(ins[3]), reg(ins[4])))
term = b.term
if term[0] in ("br", "ret"):
term = (term[0], reg(term[1])) + term[2:]
blocks[label] = toyir.Block(out, term)
return toyir.Program(list(prog.params), blocks)
def allocate(prog, k, test="briggs"):
"""Build, run the worklists, spill and repeat. Each spilled node holds
a name that is not a spill temporary, so the rounds end."""
if k < 2:
raise ValueError("k must be at least 2: one instruction can read two spilled names")
work = prepare(prog) # @line L1
infinite = set() # @line L2
spilled_all = []
rounds = 0
while True: # @line L3
rounds += 1
adj, moves = interference(work) # @line L4
cost = spill_costs(work, infinite) # @line L5
color, spilled, _ = irc_color(adj, moves, k, cost, test)
if not spilled: # @line L25
return assign(work, color), rounds, spilled_all # @line L26
work, temps = spill_everywhere(work, spilled) # @line L27
infinite |= temps # @line L28
spilled_all.extend(sorted(spilled))
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_iterated_register_coalescing.py 219 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterated-register-coalescing/. The authors are listed in prov/ZBH45M.jsonl.
import itertools
import random
import toyir
from iterated_register_coalescing import (
allocate,
briggs_ok,
george_ok,
interference,
irc_color,
is_mem,
merge,
prepare,
)
def graph(n, edges):
adj = {v: set() for v in range(n)}
for a, b in edges:
adj[a].add(b)
adj[b].add(a)
return adj
def k_colorable(adj, k):
"""Exhaustive search: True when some map to 0 .. k-1 has no equal edge."""
nodes = sorted(adj, key=lambda v: -len(adj[v]))
color = {}
def go(i):
if i == len(nodes):
return True
v = nodes[i]
used = {color[w] for w in adj[v] if w in color}
for c in range(k):
if c not in used:
color[v] = c
if go(i + 1):
return True
del color[v]
return False
return go(0)
def k_core(adj, k):
left = set(adj)
changed = True
while changed:
changed = False
for v in sorted(left):
if len(adj[v] & left) < k:
left.discard(v)
changed = True
return left
def check_merges(adj, k):
"""Returns how many merges of a k-colorable graph lose k-colorability."""
colorable = k_colorable(adj, k)
greedy = not k_core(adj, k)
broken = 0
for a, b in itertools.combinations(sorted(adj), 2):
if b in adj[a]:
continue
m = merge(adj, a, b)
m_colorable = k_colorable(m, k) if colorable else False
broken += colorable and not m_colorable
if briggs_ok(adj, a, b, k) or george_ok(adj, a, b, k) or george_ok(adj, b, a, k):
# A conservative merge keeps k-colorability and an empty k-core.
assert m_colorable or not colorable
assert not k_core(m, k) or not greedy
return broken
def test_every_graph_up_to_5_nodes():
broken = 0
for n in range(2, 6):
pairs = list(itertools.combinations(range(n), 2))
for mask in range(1 << len(pairs)):
adj = graph(n, [p for i, p in enumerate(pairs) if mask >> i & 1])
for k in (1, 2, 3):
broken += check_merges(adj, k)
assert broken > 0
def test_random_graphs_up_to_10_nodes():
rng = random.Random(1996)
for _ in range(120):
n = rng.randint(6, 10)
p = rng.choice((0.2, 0.35, 0.5))
adj = graph(n, [e for e in itertools.combinations(range(n), 2) if rng.random() < p])
for k in (2, 3):
check_merges(adj, k)
def test_aggressive_merge_breaks_a_path():
# The path a - x - y - b is 2-colorable; merging a and b makes a triangle.
p4 = graph(4, [(0, 1), (1, 2), (2, 3)])
assert k_colorable(p4, 2)
assert not k_colorable(merge(p4, 0, 3), 2)
assert not briggs_ok(p4, 0, 3, 2)
assert not george_ok(p4, 0, 3, 2) and not george_ok(p4, 3, 0, 2)
_, spilled, coalesced = irc_color(p4, [(0, 3)], 2, test="aggressive")
assert spilled and coalesced == [0]
color, spilled, coalesced = irc_color(p4, [(0, 3)], 2, test="briggs")
assert not spilled and coalesced == []
def check_irc(adj, moves, k, test):
color, spilled, coalesced = irc_color(adj, moves, k, test=test)
assert set(color) | spilled == set(adj) and not set(color) & spilled
assert all(0 <= c < k for c in color.values())
assert all(color[a] != color[b] for a in color for b in adj[a] if b in color)
for i in coalesced:
x, y = moves[i]
assert x not in adj[y]
assert (x in spilled) == (y in spilled)
assert x in spilled or color[x] == color[y]
if test != "aggressive" and not k_core(adj, k):
# No spill where Chaitin's allocator colors the graph.
assert not spilled
return spilled
def test_irc_on_random_graphs():
rng = random.Random(300)
aggressive_loss = 0
for _ in range(300):
n = rng.randint(2, 10)
p = rng.choice((0.2, 0.35, 0.5))
adj = graph(n, [e for e in itertools.combinations(range(n), 2) if rng.random() < p])
moves = [tuple(rng.sample(range(n), 2)) for _ in range(rng.randint(0, n))]
for k in (2, 3, 4):
for test in ("briggs", "george", "either"):
check_irc(adj, moves, k, test)
if check_irc(adj, moves, k, "aggressive") and not k_core(adj, k):
aggressive_loss += 1
assert aggressive_loss > 0
PAGE = """
# params: p, q
L0:
a = p + q
b = a
c = b * q
d = c
e = d + b
ret e
"""
def test_page_example():
prog = toyir.parse(PAGE)
adj, moves = interference(prepare(prog))
assert moves == [("d", "c"), ("b", "a")]
out, rounds, spilled = allocate(prog, 2)
assert rounds == 1 and spilled == []
copies = [ins for b in out.blocks.values() for ins in b.instrs if ins[0] == "copy" and not is_mem(ins[2])]
assert copies == []
for p, q in itertools.product(range(-2, 3), repeat=2):
assert toyir.run(out, [p, q]) == toyir.run(prog, [p, q])
PATH = """
# params: p
L0:
y = p + 2
x = p + 1
br x L1 L2
L1:
a = x + 1
a = a + x
b = a
jump L3
L2:
b = y + 1
b = b + y
jump L3
L3:
ret b
"""
def test_aggressive_coalescing_spills_a_program():
prog = toyir.parse(PATH)
adj, moves = interference(prepare(prog))
assert {v: adj[v] for v in "abxy"} == {"a": {"x"}, "x": {"a", "y"}, "y": {"x", "b", "p"}, "b": {"y"}}
assert moves == [("b", "a")]
assert allocate(prog, 2, "briggs")[1:] == (1, [])
assert allocate(prog, 2, "george")[1:] == (1, [])
assert allocate(prog, 2, "aggressive")[1:] == (2, ["y"])
def registers(prog):
names = set()
for b in prog.blocks.values():
for ins in b.instrs:
names.add(ins[1])
names.update(toyir.uses(ins))
names.update(toyir.term_uses(b.term))
return {a for a in names if not is_mem(a)}
def test_random_programs_keep_their_outcome():
rng = random.Random(18)
for trial in range(120):
prog = toyir.random_program(rng, rng.randint(2, 7), rng.randint(1, 6), trial % 2 == 0)
for k in (2, 3, 4):
for test in ("briggs", "either", "aggressive"):
out, rounds, spilled = allocate(prog, k, test)
assert registers(out) <= {"r%d" % i for i in range(k)}
for _ in range(3):
args = [rng.randint(-4, 6), rng.randint(-4, 6)]
assert toyir.run(out, args, fuel=100000) == toyir.run(prog, args, fuel=100000)
History
Chaitin's allocator (1982) coalesced aggressively: before coloring, it merged the two names of every copy that did not interfere, and repeated the build. Briggs, Cooper and Torczon (1994) noticed that this can make the graph harder to color, and proposed conservative coalescing with the Briggs test, run before simplify. George and Appel (1996) interleaved conservative coalescing with simplify and added the George test, freezing and the reuse of failed copies. Appel's textbooks present the full algorithm with its worklists. Bouchez, Darte and Rastello (2007) studied the complexity of the coalescing problems behind it.
References
- Lal George and Andrew W. Appel, Iterated register coalescing, ACM Transactions on Programming Languages and Systems 18(3), 1996, 300-324, the worklists for simplify, coalesce, freeze and potential spill, the George test, and the safety of the Briggs and George tests
- Preston Briggs, Keith D. Cooper and Linda Torczon, Improvements to graph coloring register allocation, ACM Transactions on Programming Languages and Systems 16(3), 1994, 428-455, conservative coalescing with the Briggs test and optimistic select
- Gregory J. Chaitin, Register allocation and spilling via graph coloring, Proceedings of the SIGPLAN '82 Symposium on Compiler Construction, SIGPLAN Notices 17(6), 1982, 98-105, aggressive coalescing (subsumption) of copies before coloring
- Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 11 (Register Allocation), the full iterated coalescing allocator with worklists, precolored nodes and pseudocode
- Florent Bouchez, Alain Darte and Fabrice Rastello, On the complexity of register coalescing, International Symposium on Code Generation and Optimization (CGO), 2007, 102-114, the complexity of aggressive, conservative, incremental conservative and optimistic coalescing
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ZBH45M Edit this page History Report an error Markdown