Algorithmcore
Optimistic coloring
Also called Chaitin-Briggs allocator, Briggs allocator.
Pushes a spill candidate on the stack instead of spilling it at once and spills only if no color is free when it is popped.
- Solves
- Register allocation
- Time
- O(r (l + s n + n^2)) worst
- Space
- O(n + m + s) extra
- Where
- 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
- Preston Briggs, Keith D. Cooper, Ken Kennedy, Linda Torczon, 1989
Optimistic coloring is the change that Briggs, Cooper, Kennedy and Torczon (1989) made to Chaitin's allocator. Chaitin's allocator spills a name as soon as the simplify phase is stuck, that is, when every vertex left in the interference graph has neighbors or more. Optimistic coloring only marks that vertex as a spill candidate, pushes it on the stack like the others, and decides when it pops the vertex: if its neighbors happen to use fewer than colors, it gets a color and no spill code is needed. On the same graph with the same spill choices, it spills a subset of the names that Chaitin's allocator spills, and it colors graphs, such as a cycle of length 4 with two colors, that Chaitin's allocator cannot.
In plain words
Chaitin's method removes values with few clashes, one at a time, and gives them colors later in the reverse order. When every value left has many clashes, it gives up on one of them at once and sends it to memory. But many clashes do not mean many colors: four neighbors may all have the same color. So optimistic coloring does not give up yet. It removes the value anyway, as if it would get a color, and goes on. Later, when the colors are handed out and the turn of that value comes, it looks at its neighbors. If a color is still free, the value gets it and nothing goes to memory. Only if all colors are taken does the value 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 that uses only the registers and memory slots mem.x, and that has the same outcome as on every input (register allocation problem). The allocator works on the interference graph, with the spill cost of a name given by the number of its definitions and uses. A spill candidate is a vertex that the simplify phase removes while every vertex left has degree at least . An actual spill is a vertex that select cannot color.
The algorithm
BRIGGS-ALLOCATE(P, k)- 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 // 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 // simplify - 8
if some vertex v of G has degree < k then - 9
push v on stack; remove v from G - 10
else - 11
v <- a vertex of G with the least cost[v] / degree(v) // a spill candidate - 12
push v on stack; remove v from G - 13
spill <- the empty set - 14
for each v on stack, from the top down do // select - 15
if some color in 0 .. k-1 is not used by a colored neighbor of v then - 16
color[v] <- the least such color - 17
else spill <- spill + {v} // v stays without a color - 18
if spill is empty then - 19
return P with each name x renamed to r[color[x]] and each copy r = r deleted - 20
P <- P with each x in spill kept in mem.x: a load into a new temporary before each use of x and a store from a new temporary after each definition of x- 21
T <- T + the new temporaries
Lines L1 to L11 are those of Chaitin's allocator. The only changes are line L12, which pushes the candidate instead of spilling it, and lines L15 to L17, which spill a vertex only when it has no free color. As in Chaitin's allocator, line L8 takes the vertices of degree less than in the order in which they reach that degree, and line L11 breaks ties by the order of the names in the program.
A vertex pushed at line L9 always gets a color: when it was pushed, it had fewer than neighbors left, and only those can be colored before it. So line L17 is reached only for spill candidates. A neighbor that stays without a color does not block a color, which is why a vertex below an actual spill on the stack still finds one.
Example
This loop has one parameter n:
L0:
d = n
jump L1
L1:
a = d + 1
b = a + d
c = a + 1
d = b - c
d = d % c
br d L1 L2
L2:
ret d
After line L1 adds n = mem.n in a new block start, the interference edges are -, -, - and -, a cycle of length 4. The copy d = n makes no edge, and is isolated. The costs are , , , and . Take .
| step | line | removed | why |
|---|---|---|---|
| 1 | L9 | degree 0 | |
| 2 | L12 | all four left have degree 2; the ratios are , , and | |
| 3 | L9 | degree 1 after step 2 | |
| 4 | L9 | degree 1 after step 2 | |
| 5 | L9 | degree 0 |
Select pops . It gives , and ; both are neighbors of only among the colored vertices. The candidate has the colored neighbors and , both with color 1, so color 0 is free and gets it. Then . Nothing is spilled, and one round is enough. Chaitin's allocator spills at step 2 and needs a second round. The copy d = n becomes r0 = r0 and is deleted, by chance:
start:
r0 = mem.n
jump L0
L0:
jump L1
L1:
r1 = r0 + 1
r0 = r1 + r0
r1 = r1 + 1
r0 = r0 - r1
r0 = r0 % r1
br r0 L1 L2
L2:
ret r0
A script ran both programs for from to . They gave the same outcomes, including the trap for , where .
A graph that is 3-colorable but spilled. Take the triangular prism: the triangles and and the edges -, - and -. It has a 3-coloring. Every vertex has degree 3, so with and equal costs, line L11 picks vertex 0 at once. Then the rest simplify in the order . Select gives , , , and . Vertex 0 has the neighbors 3, 4 and 5, with colors 0, 1 and 2, so it is spilled. Optimistic coloring is still a heuristic.
Correctness
The proof file shows four facts:
- A vertex pushed at line L9 always gets a color, so only spill candidates can be spilled.
- The colors given at line L16 are a proper coloring of the colored vertices.
- On the same graph with the same costs and tie-breaking, the simplify phase of Chaitin's allocator and of this allocator remove the same vertices in the same order. So the actual spills of this allocator are a subset of the spills of Chaitin's allocator. In particular, every graph that Chaitin's allocator colors without a spill is colored by optimistic coloring, with the same colors.
- The renaming, the spill code and the termination proofs of Chaitin's allocator carry over: the result has the same outcome as the input, uses only registers, and comes after at most rounds.
The cycle of length 4 with shows that the subset can be strict.
Proof: Optimistic coloring gives a correct program, spills only where Chaitin's allocator spills, and stopsfull
We prove five facts about BRIGGS-ALLOCATE. Lemmas 1 and 2 are about select. Lemma 3 compares one round with one round of Chaitin's allocator on the same graph. Lemma 4 shows that the output keeps the outcome, and Lemma 5 shows that the loop stops.
Throughout, is a finite simple graph and . For , is the subgraph induced by . A -coloring of a set is a map with for every edge with . Let be the order in which lines L7 to L12 push the vertices, and let be the graph just before is removed. Call a low vertex if line L9 pushed it and a candidate if line L12 pushed it.
Select
Lemma 1 (low vertices get a color). Line L15 finds a free color for every low vertex. So the set spill contains only candidates.
Proof. Line L14 visits . When it reaches , the vertices that have a color are among , so each colored neighbor of is a neighbor of in . If is low, line L8 gives . So fewer than neighbors of have a color, they use fewer than of the colors, and line L15 finds a free one.
Lemma 2 (proper coloring). At the end of select, the map color is a -coloring of the set of colored vertices. If spill is empty, it is a -coloring of .
Proof. Line L16 gives only colors in . Let be an edge with both ends colored, and say line L14 colored first. When it reached , the color of was used by a colored neighbor of , so line L16 gave another color. Colors never change after line L16, so the edge has two different colors. If spill is empty, every vertex is colored.
Comparison with Chaitin's allocator
Lemma 3 (subset of Chaitin's spills). Run one round of Chaitin's allocator and one round of BRIGGS-ALLOCATE on the same graph with the same costs, the same and the same order of the names. Then:
- both simplify phases push the same vertices in the same order, and the candidates of BRIGGS-ALLOCATE are exactly the vertices that Chaitin's allocator puts in its set spill;
- the set spill of BRIGGS-ALLOCATE is a subset of the set spill of Chaitin's allocator;
- if Chaitin's allocator spills nothing, BRIGGS-ALLOCATE spills nothing and gives the same colors.
Proof. (1) Lines L7 to L11 are the same in both allocators. Each loop pass removes one vertex from the current graph, and it chooses from the current graph, the degrees in it, the costs and the order of the names. Chaitin's allocator adds to its set spill at line L12 and BRIGGS-ALLOCATE pushes it as a candidate, but in both the graph after the pass is the current graph minus . So, by induction on the passes, the two loops see the same graphs and choose the same vertices, and the vertices chosen at line L11 are the same.
(2) By Lemma 1, the set spill of BRIGGS-ALLOCATE contains only candidates, and by (1) those are the vertices that Chaitin's allocator spills.
(3) If Chaitin's allocator spills nothing, then by (1) there is no candidate, and by (2) spill is empty in BRIGGS-ALLOCATE. Both allocators then color the same stack, in the same order, with the least free color. So they give the same colors.
Part 3 is the claim that optimistic coloring colors every graph that Chaitin's allocator colors. The inclusion in part 2 can be strict. On the cycle with , Chaitin's allocator spills one vertex, while optimistic select finds that the two neighbors of the candidate have the same color and colors it.
A caution about later rounds. Lemma 3 compares rounds on the same graph. When both allocators spill, they spill different sets, so their next programs and graphs differ. The lemma does not say that over a full run, BRIGGS-ALLOCATE spills a subset of the names that Chaitin's allocator spills.
The output keeps the outcome
The program model, the liveness rule and the definition of the interference graph are those of the proof file of Chaitin's allocator. Its Lemma 4 (renaming) and Lemma 5 (spill everywhere) speak only about a program, a -coloring of its interference graph and a set of spilled names. They do not use the way the coloring or the set was found. We restate them.
- Renaming. If is a -coloring of the interference graph of , then renaming each non-slot name to and deleting each copy that becomes
r = rgives a program with the same outcome as on every input. The key step: if and get the same register and is live just after a definition of , then that definition is the copyx = y, because otherwise the definition rule gives the edge . - Spill everywhere. Replacing each read of a spilled name by a load from
mem.xinto a new name just before the reader, and each definition of by a definition of a new name followed by a store tomem.x, gives a program with the same outcome that reads no name before it writes it.
Lemma 4 (correct output). If BRIGGS-ALLOCATE returns, the result uses only the registers and the memory slots, and it has the same outcome as on every input.
Proof. Line L1 keeps the outcome, because it only moves the parameters through their slots. Line L20 keeps it by the spill lemma. The loop returns at line L19 only when spill is empty, and then color is a -coloring of the graph by Lemma 2. So line L19 keeps the outcome by the renaming lemma, and it uses only the registers .
Termination
The termination proof of Chaitin's allocator uses three statements, proved together by induction on the rounds: (T) each temporary is a load temporary, read by the first instruction after its load that is not a load, or a store temporary, read by the store just after it; (U) each temporary has at most one temporary neighbor; (O) each time line L11 runs, it chooses an original name, that is a name of the program after line L1.
The same induction works here, with one change. In Chaitin's allocator, line L17 spills exactly the vertices chosen at line L11. Here, line L20 spills the set spill, which by Lemma 1 contains only vertices chosen at line L11. So (O) again gives that line L20 spills only original names, and the step from (O) to (T) in the next round is unchanged. The steps from (T) to (U) and from (U) to (O) do not depend on select at all: they use only the shape of the temporaries, the fact that , and the infinite cost of the temporaries set at line L5.
Lemma 5 (termination). Let be the number of original names. BRIGGS-ALLOCATE with returns after at most rounds.
Proof. A round that does not return has a nonempty set spill, and by Lemma 1 and (O) its vertices are original names. Line L20 replaces every occurrence of these names by temporaries, and later rounds create 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 4 and 5 prove that BRIGGS-ALLOCATE stops and returns a program that uses only registers and has the same outcome as its input. Lemma 3 proves that, round by round, it never spills where Chaitin's allocator would not.
Complexity
The cost is that of Chaitin's allocator. Simplify and select take time, plus for each spill candidate when the candidates are found by a scan; build takes after a liveness analysis of cost . Each round spills at least one name of the original program, so there are at most rounds, and the total time is . The space is . The change costs nothing: the candidate is pushed instead of being put in a set.
Properties
- Never worse in one round. On a given graph, the actual spills are a subset of Chaitin's spills. When Chaitin's allocator colors the graph, optimistic coloring gives the same coloring.
- Strictly better on some graphs. The cycle of length 4 with and the loop above are colored without a spill.
- Not optimal. The prism with is spilled although it is 3-colorable, and the problem is NP-complete (register-allocation-np-completeness).
- Only one round is compared. After a spill, the two allocators rewrite the program in different ways, so the subset property says nothing about the later rounds.
- Deterministic. The result depends on the order of the names and on the tie-breaking rules.
Variants and improvements
- Iterated register coalescing of George and Appel keeps optimistic select and adds conservative coalescing of copies during simplify.
- Rematerialization. Briggs, Cooper and Torczon (1992, 1994) tag values that can be recomputed cheaply, such as constants, and replace their reloads by recomputation.
- Biased coloring. When select has a choice of colors, it can prefer the color of a copy partner, so that more copies become
r = rand disappear without any coalescing in the graph. - Other select orders. A general coloring heuristic such as DSatur or the greedy coloring in another order may color more graphs, but it loses the guarantee that every vertex pushed at line L9 gets a color.
- Better spill code. Spill code placement and live range splitting reduce the cost of the actual spills.
When to use it
Use it instead of Chaitin's allocator in every case: it costs the same and never spills more on the same graph. It is the base of the graph-coloring allocators in the textbooks of Appel and of Cooper and Torczon. If the program has many copies, as after SSA destruction, use iterated register coalescing, which adds coalescing. For fast compilation, linear scan is cheaper.
Pitfalls
- A spill candidate is not a spill. Do not insert spill code at line L12. Insert it only for the vertices that line L17 leaves without a color.
- Uncolored neighbors are free. When the colors of the neighbors are collected at line L15, a neighbor that was spilled earlier in the same select has no color and must be skipped.
- The candidate order matters. Line L11 still uses cost over degree. A candidate pushed early is popped late, when more neighbors have colors, so its chance of a free color is lower.
- Rebuild after spilling. As in Chaitin's allocator, the spill code changes liveness, so the graph is built again in the next round.
- Spill temporaries. Temporaries get an infinite cost; otherwise the loop may never end.
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/briggs-optimistic-coloring/. The authors are listed in prov/Y67E03.jsonl.
"""Optimistic coloring (Briggs, Cooper, Kennedy and Torczon).
briggs_color(adj, k, cost) works on a graph: adj maps each node to the set
of its neighbors. It returns (color, spilled). color maps each node that
got a color to a color in 0 .. k-1, and no edge between two colored nodes
has two equal colors. spilled is the set of nodes that found no free color.
Only a node that simplify pushed as a spill choice can end up in spilled.
allocate(prog, k) works on a toy IR program with const, copy and op
instructions only (no phi). It builds the interference graph, colors it
optimistically, spills the nodes left without a color everywhere and
repeats. It returns (out, rounds, spilled): out runs like prog, its
register names are r0 .. r(k-1), and its memory slots have names that start
with "mem.". The parameters of out are the memory slots of the parameters
of prog.
"""
from collections import deque
import math
import toyir
MEM = "mem."
def is_mem(name):
return isinstance(name, str) and name.startswith(MEM)
# ------------------------------------------------------------- graph level
def simplify(adj, k, cost):
"""The simplify phase, the same as in Chaitin's allocator. Returns the
stack as a list of (node, chosen) in the order of removal; chosen is
True for a spill choice, which stays in the graph's stack."""
order = list(adj)
index = {v: i for i, v in enumerate(order)}
deg = {v: len(adj[v]) for v in order}
removed = set()
low = deque(v for v in order if deg[v] < k)
queued = set(low)
stack = [] # @line L6
while len(stack) < len(order): # @line L7
if low: # @line L8
v, chosen = low.popleft(), False # @line L9
else: # @line L10
v = min((u for u in order if u not in removed), key=lambda u: (cost[u] / deg[u], index[u])) # @line L11
chosen = True
removed.add(v)
stack.append((v, chosen)) # @line L12 (L9 too: push v and remove it)
for w in sorted(adj[v], key=index.__getitem__):
if w not in removed:
deg[w] -= 1
if deg[w] < k and w not in queued:
queued.add(w)
low.append(w)
return stack
def briggs_color(adj, k, cost=None):
if k < 1:
raise ValueError("k must be at least 1")
if cost is None:
cost = {v: 1 for v in adj}
stack = simplify(adj, k, cost)
color = {}
spilled = set() # @line L13
for v, chosen in reversed(stack): # @line L14
used = {color[w] for w in adj[v] if w in color}
c = 0
while c in used:
c += 1
if c < k: # @line L15
color[v] = c # @line L16
else:
# Only a spill choice can get here: any other node had fewer
# than k neighbors left when simplify removed it.
assert chosen
spilled.add(v) # @line L17
return color, spilled
# ----------------------------------------------------------- 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. At
each definition of x, x interferes with each name live after it, except
the source of a copy x = y."""
_check(prog)
_, live_out = liveness(prog)
adj = {}
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)
live.discard(x)
live.update(toyir.uses(ins))
return adj
def spill_costs(prog, infinite=()):
"""The number of definitions and uses of each name; a spill temporary
gets an infinite cost, so it is never a spill choice."""
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."""
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):
"""Build, simplify, select and repeat until select colors every node.
Each round spills at least one name that is not a spill temporary."""
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 = interference(work) # @line L4
cost = spill_costs(work, infinite) # @line L5
color, spilled = briggs_color(adj, k, cost)
if not spilled: # @line L18
return assign(work, color), rounds, spilled_all # @line L19
work, temps = spill_everywhere(work, spilled) # @line L20
infinite |= temps # @line L21
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_briggs_optimistic_coloring.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/briggs-optimistic-coloring/. The authors are listed in prov/Y67E03.jsonl.
import itertools
import random
import toyir
from briggs_optimistic_coloring import allocate, briggs_color, interference, is_mem, prepare, simplify
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 chaitin_spills(adj, k, cost):
"""Chaitin's allocator spills every spill choice of the same simplify."""
return {v for v, chosen in simplify(adj, k, cost) if chosen}
def check(adj, k, cost=None):
"""Returns (Briggs colors all, Chaitin colors all)."""
cost = cost or {v: 1 for v in adj}
color, spilled = briggs_color(adj, k, cost)
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)
chaitin = chaitin_spills(adj, k, cost)
# Optimistic coloring spills only nodes that Chaitin spills.
assert spilled <= chaitin
# Chaitin colors the graph exactly when its k-core is empty.
assert bool(chaitin) == bool(k_core(adj, k))
if not spilled:
assert k_colorable(adj, k)
return not spilled, not chaitin
def test_every_graph_up_to_5_nodes():
gains = 0
for n in range(1, 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):
briggs, chaitin = check(adj, k)
assert briggs or not chaitin
gains += briggs and not chaitin
assert gains > 0
def test_random_graphs_up_to_10_nodes():
rng = random.Random(1989)
gains = 0
for _ in range(400):
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])
cost = {v: rng.randint(1, 9) for v in adj}
for k in (2, 3, 4):
briggs, chaitin = check(adj, k, cost)
gains += briggs and not chaitin
assert gains > 0
def test_cycle_of_four():
c4 = graph(4, [(0, 1), (1, 2), (2, 3), (3, 0)])
assert chaitin_spills(c4, 2, {v: 1 for v in c4})
color, spilled = briggs_color(c4, 2)
assert not spilled and sorted(color.values()) == [0, 0, 1, 1]
def test_prism_is_3_colorable_but_briggs_spills():
# Two triangles 0 3 4 and 1 2 5 joined by a perfect matching.
prism = graph(6, [(0, 3), (0, 4), (0, 5), (1, 2), (1, 4), (1, 5), (2, 3), (2, 5), (3, 4)])
assert k_colorable(prism, 3)
color, spilled = briggs_color(prism, 3)
assert spilled == {0}
LOOP = """
# params: n
L0:
d = n
jump L1
L1:
a = d + 1
b = a + d
c = a + 1
d = b - c
d = d % c
br d L1 L2
L2:
ret d
"""
def test_page_example():
prog = toyir.parse(LOOP)
adj = interference(prepare(prog))
assert {v: adj[v] for v in "abcd"} == {"a": {"b", "d"}, "b": {"a", "c"}, "c": {"b", "d"}, "d": {"a", "c"}}
assert chaitin_spills(adj, 2, {v: 1 for v in adj})
out, rounds, spilled = allocate(prog, 2)
assert rounds == 1 and spilled == []
for n in range(-4, 8):
assert toyir.run(out, [n]) == toyir.run(prog, [n])
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(94)
for trial in range(150):
prog = toyir.random_program(rng, rng.randint(2, 7), rng.randint(1, 6), trial % 2 == 0)
for k in (2, 3, 4, 5):
out, rounds, spilled = allocate(prog, k)
assert registers(out) <= {"r%d" % i for i in range(k)}
for _ in range(4):
args = [rng.randint(-4, 6), rng.randint(-4, 6)]
assert toyir.run(out, args, fuel=100000) == toyir.run(prog, args, fuel=100000)
History
Briggs, Cooper, Kennedy and Torczon presented the optimistic heuristic at PLDI 1989, as a change to Chaitin's allocator. Briggs, Cooper and Torczon described it in full in TOPLAS in 1994, together with rematerialization. George and Appel (1996) combined it with iterated coalescing, and the textbook allocators of Appel and of Cooper and Torczon follow this design.
References
- Preston Briggs, Keith D. Cooper, Ken Kennedy and Linda Torczon, Coloring heuristics for register allocation, Proceedings of the ACM SIGPLAN 1989 Conference on Programming Language Design and Implementation (PLDI), 1989, 275-284, the optimistic heuristic, which pushes the spill candidate on the stack and spills only when select finds no color, and the graphs that it colors where Chaitin's allocator spills
- 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, the optimistic allocator in full, its comparison with Chaitin's allocator, and rematerialization
- 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, the simplify rule and the spill choice by cost over degree that optimistic coloring keeps
- Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 11 (Register Allocation), coloring by simplification with potential spills and actual spills
- Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 13 (Register Allocation), the bottom-up coloring allocator and its optimistic spill decision
Where this leads
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 Y67E03 Edit this page History Report an error Markdown