University Computer Science — Year 3 · Bachelor Year 3
8Program Analysis and Optimisation
The compiler of chapter 7 is correct and slow: every temporary lives in memory, every copy is executed, and a constant computed at compile time by a reader is computed at run time by the machine. This chapter makes it faster without making it wrong. Every optimisation rests on a fact about the program that holds on all its executions, such as “this temporary is never read again” or “this temporary always holds 42”, and such facts are computed by one method: a system of equations over the control-flow graph, solved as a fixed point. With them the chapter removes useless work from the three-address code, then gives the temporaries registers by colouring a graph, and counts on rv what each step saves.
8.1 Dataflow analysis as a fixed point
Take the question “which temporaries may still be read later?” at every point of a function. A temporary is needed before an instruction if the instruction reads it, or if it is needed after the instruction and the instruction does not overwrite it. After a block, it is needed if it is needed at the start of some successor. These are equations, one pair per block, and a loop makes them circular: what is needed at the end of the loop body depends on what is needed at its top, which depends on the body. The equations are solved by starting from “nothing is needed” and applying them until nothing changes. Why this ends, and why it ends at the right answer, is a theorem about ordered sets.
You already know
A partial order on a set is reflexive, antisymmetric and transitive. An upper bound of two elements is above both; their least upper bound, when it exists, is below every other upper bound.
Definition 8.1 (Dataflow lattice, height)
A dataflow lattice is a set of facts with a partial order , read “is at most as informative a claim as”, in which every two facts have a least upper bound , their join, and which has a least element . Its height is the largest number of strict steps in a chain .
For liveness, the facts are sets of temporaries, ordered by inclusion, the join is union and is the empty set; with temporaries the height is . For constants, the fact about one temporary is “not yet seen” (), “always the constant ”, or “not a constant” (), a lattice of height 2 however many constants there are (the figure below); for temporaries, take one such fact per temporary, height .
Definition 8.2 (Transfer function, monotone framework)
A transfer function gives the fact at one end of a block from the fact at the other: at the end from the start for a forward analysis, at the start from the end for a backward one. It is monotone if implies . A monotone framework is a dataflow lattice, a direction, a monotone transfer function per block, and a fact at the boundary (the entry, or the exits). Its equations are , over the blocks the facts flow from, and .
Put all the blocks’ facts in one vector , ordered componentwise. The equations say for one function , monotone because joins and the are. A solution is a fixed point of , and the useful one is the least.
Definition 8.3 (Least fixed point)
A fixed point of is an with . The least fixed point is a fixed point below every other.
Theorem 8.4 (Fixed points by iteration)
Let be monotone on a lattice of finite height with least element . The sequence is increasing, becomes constant after at most strict steps, and its final value is the least fixed point of .
Proof. since is least, and if then monotonicity gives : the sequence increases. A strictly increasing chain has at most steps, so after at most strict steps two consecutive terms are equal, , and the sequence stays there. For leastness, let be any fixed point. , and if then ; so . ∎
Iterating on the whole vector recomputes every block when one has changed. The worklist algorithm recomputes only the blocks whose inputs changed: it keeps a queue of blocks, starts with all of them, and when a block’s output changes, it queues the blocks its facts flow to (Listing 8.2). It computes the same least fixed point, since each recomputation is one component of applied to a vector below the fixed point, and the values only grow; exercise 8.7 bounds its work. Listing 8.1 is the interface an analysis implements.
/// A monotone framework: a lattice of facts and a transfer function per block.
pub trait Analysis {
type V: Clone + PartialEq;
fn dir(&self) -> Dir;
fn bottom(&self) -> Self::V; // the starting value of every block
fn boundary(&self) -> Self::V; // the fact at the entry (forward) or an exit (backward)
fn join(&self, a: &Self::V, b: &Self::V) -> Self::V;
fn transfer(&self, block: usize, x: &Self::V) -> Self::V;
}
pub fn solve<A: Analysis>(a: &A, g: &Cfg) -> Solution<A::V> {
let (n, p, dir) = (g.blocks.len(), preds(g), a.dir());
// inn: the side facts flow in from; out: the side the transfer produces
let (mut inn, mut out) = (vec![a.bottom(); n], vec![a.bottom(); n]);
let mut work: VecDeque<usize> = (0..n).collect();
let mut queued = vec![true; n];
let mut visits = 0;
while let Some(b) = work.pop_front() {
queued[b] = false;
visits += 1;
let (from, to) = match dir {
Dir::Forward => (&p[b], &g.succ[b]),
Dir::Backward => (&g.succ[b], &p[b]),
};
let at_boundary = if dir == Dir::Forward { b == 0 } else { g.succ[b].is_empty() };
let mut x = if at_boundary { a.boundary() } else { a.bottom() };
for &s in from {
x = a.join(&x, &out[s]);
}
let y = a.transfer(b, &x);
inn[b] = x;
if y != out[b] {
out[b] = y;
for &m in to {
if !queued[m] {
queued[m] = true;
work.push_back(m);
}
}
}
}
match dir {
Dir::Forward => Solution { before: inn, after: out, visits },
Dir::Backward => Solution { before: out, after: inn, visits },
}
}
8.1.1 Liveness and reaching definitions
Definition 8.5 (Live temporary)
A temporary is live at a point if some path from that point reads it before writing it. Liveness is the backward analysis whose facts are sets of temporaries, joined by union, with the empty set at the exits, and for each instruction .
The transfer function of a block applies this rule to its instructions from the last to the first (Listing 8.3). It is monotone, since a larger set after gives a larger set before. Output 8.1 runs it on the function sumsq of loop.moor, a sum of squares; the solution took 12 visits for 6 blocks, two passes over a loop.
/// live before i = uses(i) + (live after i - def(i))
pub fn step(i: &Tac, after: &Set) -> Set {
let mut s = after.clone();
if let Some(d) = def(i) {
s.remove(&d);
}
s.extend(uses(i));
s
}
pub struct Liveness<'a> {
pub code: &'a [Tac],
pub g: &'a Cfg,
}
impl Analysis for Liveness<'_> {
type V = Set;
fn dir(&self) -> Dir { Dir::Backward }
fn bottom(&self) -> Set { Set::new() }
fn boundary(&self) -> Set { Set::new() } // nothing is live after a return
fn join(&self, a: &Set, b: &Set) -> Set { a.union(b).copied().collect() }
fn transfer(&self, b: usize, out: &Set) -> Set {
let (s, e) = self.g.blocks[b];
self.code[s..e].iter().rev().fold(out.clone(), |live, i| step(i, &live))
}
}
$ rustc --edition 2021 -O -o live_demo live_demo.rs && ./live_demo loop.moor
B0 live in {n}
s = 0
i = 0
live out {n, s, i}
B1 live in {n, s, i}
L1:
if i < n goto L2
live out {n, s, i}
B2 live in {s}
goto L3
live out {s}
B3 live in {n, s, i}
L2:
t3 = i * i
sq = t3
t5 = s + sq
s = t5
t6 = i + 1
i = t6
goto L1
live out {n, s, i}
B4 live in {s}
L3:
return s
live out {}
B5 live in {}
return
live out {}
6 blocks, 12 visits
sumsq. n, s and i stay live around the loop; inside the body, t3, sq, t5 and t6 each live for one instruction.sumsq with the live sets of Output 8.1 in red, at the start of the function and after each block. The unreachable final return is not drawn.Definition 8.6 (Reaching definition)
A definition is an instruction that writes a temporary. It reaches a point if some path from it to that point writes the same temporary nowhere else. Reaching definitions are a forward analysis on sets of instructions, joined by union: an instruction that writes adds itself and removes the other definitions of .
reaching.rs implements it in twenty lines with the same trait. At the top of the loop of sumsq, the definitions that reach are and from the entry and the six of the loop body, which come round the back edge (test reaching_definitions_of_the_loop). Two definitions of i reach the test i < n: from the entry and from the body. The next section gives each of them its own name.
8.2 Static single assignment
Most temporaries of chapter 7 are written once, by construction. The exceptions are the variables, which every assignment writes again. An analysis about a variable must then ask which assignment it is talking about at each point, which is what reaching definitions answer, at the price of a set per point. A form in which every temporary has one definition makes the question vanish: the name tells the definition.
Definition 8.7 (Static single assignment, phi-function)
A function is in static single assignment form if every temporary has exactly one definition in its text. Where definitions of one variable from different paths meet, at the start of a block, a -function defines a new name whose value is if control came from and if it came from .
The question is where to put the -functions. Everywhere two paths join would do, and would put far too many. The right places are given by dominance.
Definition 8.8 (Dominator, dominance frontier)
A block dominates a block if every path from the entry to passes through ; every block dominates itself, and strictly dominates if moreover . The immediate dominator of entry is the strict dominator of that every other strict dominator of dominates. The dominance frontier is the set of blocks such that dominates a predecessor of but does not strictly dominate . For a set , is the limit of , , the iterated frontier.
The dominators of are its own set plus those common to all its predecessors: , with . This is again a fixed point, a forward analysis whose join is intersection, started from “all blocks” (Listing 8.4). The dominators of a block form a chain, each dominating the next, so they are a path in a tree, the dominator tree, in which each block’s parent is its immediate dominator. The frontiers are computed by walking up that tree from each predecessor of a join (Listing 8.5).
/// Dom(b): the blocks on every path from the entry to b. Iterate
/// Dom(b) = {b} + intersection of Dom(p) over the predecessors p, from "all".
pub fn dominators(g: &Cfg) -> Vec<BTreeSet<usize>> {
let (n, p, live) = (g.blocks.len(), preds(g), reachable(g));
let all: BTreeSet<usize> = (0..n).filter(|&b| live[b]).collect();
let mut dom: Vec<BTreeSet<usize>> = (0..n)
.map(|b| {
if b == 0 {
[0].into()
} else if live[b] {
all.clone()
} else {
[].into()
}
})
.collect();
let mut changed = true;
while changed {
changed = false;
for b in 1..n {
if !live[b] {
continue;
}
let mut d = all.clone();
for &q in p[b].iter().filter(|&&q| live[q]) {
d = d.intersection(&dom[q]).copied().collect();
}
d.insert(b);
if d != dom[b] {
dom[b] = d;
changed = true;
}
}
}
dom
}
/// DF(x): the blocks y such that x dominates a predecessor of y but not y strictly.
pub fn frontiers(g: &Cfg, idom: &[Option<usize>]) -> Vec<BTreeSet<usize>> {
let (p, live) = (preds(g), reachable(g));
let mut df = vec![BTreeSet::new(); g.blocks.len()];
for y in (0..g.blocks.len()).filter(|&y| live[y]) {
for &q in p[y].iter().filter(|&&q| live[q]) {
let mut runner = Some(q);
while let Some(r) = runner {
if Some(r) == idom[y] {
break;
}
df[r].insert(y);
runner = idom[r];
}
}
}
df
}
/// Where phi-functions go: the iterated frontier of the blocks that define v.
pub fn phi_blocks(defs: &BTreeSet<usize>, df: &[BTreeSet<usize>]) -> BTreeSet<usize> {
let (mut placed, mut work): (BTreeSet<usize>, Vec<usize>) =
(BTreeSet::new(), defs.iter().copied().collect());
while let Some(x) = work.pop() {
for &y in &df[x] {
if placed.insert(y) && !defs.contains(&y) {
work.push(y);
}
}
}
placed
}
Lemma 8.9 (Leaving dominance)
Let be a path. If does not strictly dominate , some with is in .
Proof. Let be the least index such that does not strictly dominate ; it exists since qualifies. Then dominates : either and , or strictly dominates by the choice of . So dominates a predecessor of and does not strictly dominate : . ∎
Theorem 8.10 (Placing phi-functions)
Let be the blocks that define a variable , the entry included if is a parameter, and place a -function for at the start of every block of . Then (a) at every use of , the last definition of (an original one or a ) is the same on every path from the entry, and its block dominates the use. (b) Every placed this way is at a block where two paths from different definitions of first meet: none is placed where only one definition can arrive. Some may still be placed where is dead, and those can be left out without losing (a); pruned SSA leaves them out (Exercise 8.9).
Proof. We prove (a); (b) is admitted. Let , the blocks where is defined once the -functions are placed. is closed under frontiers: , by the construction of the limit. Take a use of in block , after any definition of in (otherwise treat the start of the same way), and a path from the entry to . Let be the last block of on , included; it exists, since is defined before it is used. If and did not strictly dominate , Lemma 8.9 applied to the part of from to would give a later block of on , contradicting the choice of . So dominates .
Let be the last block of on another path . Both dominate , so one dominates the other; suppose strictly dominates . Since does not dominate , some path from the entry to avoids . Follow it, then the part of after its last visit to : that part contains no block of but , so it avoids too, and the whole is a path from the entry to that avoids , which contradicts dominating . So : every path reaches the use through the same last definition. ∎
Renaming then walks the dominator tree from the entry, with a stack of current names per variable: a definition pushes a fresh name, a use takes the name on top, and on the way out of a block the stacks are popped back. Before leaving a block, the walk fills in the arguments of the -functions of its successors with the names current at its end. Output 8.2 shows the result for sumsq: s and i are each assigned twice, so each gets a at the loop’s header, B1, which is the frontier of the body B3. The temporaries written once keep their names.
$ rustc --edition 2021 -O -o ssa_demo ssa_demo.rs && ./ssa_demo loop.moor
B0 dom {B0} idom - frontier {}
B1 dom {B0, B1} idom B0 frontier {B1}
B2 dom {B0, B1, B2} idom B1 frontier {}
B3 dom {B0, B1, B3} idom B1 frontier {B1}
B4 dom {B0, B1, B2, B4} idom B2 frontier {}
SSA form, 2 phi-functions:
B0
s.0 = 0
i.0 = 0
B1
L1:
s.1 = phi(B0: s.0, B3: s.2)
i.1 = phi(B0: i.0, B3: i.2)
if i.1 < n goto L2
B2
goto L3
B3
L2:
t3 = i.1 * i.1
sq = t3
t5 = s.1 + sq
s.2 = t5
t6 = i.1 + 1
i.2 = t6
goto L1
B4
L3:
return s.1
sumsq, then its SSA form. Names are numbered from 0 per variable.sumsq (solid), each block below its immediate dominator, and the two non-empty frontiers (dashed). s and i are defined in B0 and B3; the iterated frontier of these blocks is B1, the loop’s header.SSA is how optimising compilers hold a program between their passes: an analysis about a name is an analysis about one definition, and many of the analyses of the next section become a single pass. The program in this chapter stays in three-address code and uses the dataflow equations; the SSA form is computed and printed, and the exercises use it.
8.3 The classic optimisations
An optimisation is a transformation of the code that keeps its meaning, in the sense of chapter 7: on every input on which the original program terminates normally, the transformed one prints the same and exits with the same code. Each one below is justified by a fact computed by a dataflow analysis, and the fact is what the proof needs.
Definition 8.11 (Constant propagation)
Constant propagation is the forward analysis whose fact at each point maps each temporary to , a constant , or , joined pointwise in the lattice of the figure above; the parameters are at the entry. Its transformation replaces a use of a temporary by where the fact says , computes at compile time an operation whose operands are constants (constant folding), and replaces a branch whose outcome is then known by a jump or by nothing.
/// The value lattice of one temporary: Undef < Const(k) < Nac (not a constant).
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Cv {
Undef,
Const(i32),
Nac,
}
pub fn meet(a: Cv, b: Cv) -> Cv {
match (a, b) {
(Cv::Undef, x) | (x, Cv::Undef) => x,
(Cv::Const(x), Cv::Const(y)) if x == y => a,
_ => Cv::Nac,
}
}
meet by tradition. code/bachelor-3/08-program-optimisation/listings/opt.rs/// Uses replaced by known constants, constant operations folded, and branches
/// whose outcome is known replaced by a jump or removed.
pub fn const_prop(f: &mut FuncTac) -> usize {
let g = cfg::build(f);
let sol = solve(&ConstProp { f, g: &g }, &g);
let mut out: Vec<Tac> = vec![];
for (b, &(s, e)) in g.blocks.iter().enumerate() {
let mut env = sol.before[b].clone();
for i in &f.code[s..e] {
let mut known = |v: Val| match v {
Val::T(t) => match env.get(&t) {
Some(Cv::Const(c)) => Val::K(*c),
_ => v,
},
k => k,
};
let new = match map_uses(i, &mut known) {
Tac::Bin(d, op, Val::K(x), Val::K(y)) => {
Some(Tac::Copy(d, Val::K(fold(op, x, y))))
}
Tac::Neg(d, Val::K(x)) => Some(Tac::Copy(d, Val::K(x.wrapping_neg()))),
Tac::Not(d, Val::K(x)) => Some(Tac::Copy(d, Val::K(1 - x))),
Tac::Branch(op, Val::K(x), Val::K(y), l) => {
(fold(op, x, y) != 0).then_some(Tac::Jump(l))
}
other => Some(other),
};
env = cp_step(&env, i);
out.extend(new);
}
}
replace(f, out)
}
Theorem 8.12 (Constant propagation is sound)
If the least fixed point maps to the constant at a point, then on every execution that reaches that point, holds there.
Proof. Say a concrete state, a value for each temporary, agrees with a fact if each temporary mapped to a constant holds that constant. By induction on the number of instructions executed, the state at each point agrees with the fact the solution gives there. At the entry, the fact maps only parameters, to , and every state agrees. One instruction: if the state before agrees with the fact before, the state after agrees with the transfer of that fact, because the transfer computes the same operation on the same constants, and gives whenever an operand is not known; folding uses Moor’s 32-bit arithmetic, the interpreter’s. Along an edge, the fact at the target is the join of the facts of its predecessors, so it is above the fact of the edge taken, and a state that agrees with a fact agrees with every fact above it. A temporary mapped to at a reachable point has not been written on any path to it, and the front end does not let it be read. ∎
Replacing a use by its constant then changes no value, so no output. A branch on two constants always goes the same way, so replacing it by a jump or deleting it changes no path that runs.
Definition 8.13 (Copy propagation, value numbering, dead code)
Copy propagation replaces a use of by where the copy is available: on every path to the point, it was executed and neither nor was written since. Value numbering gives each computed value a number, such that two operations with the same operator on operands with the same numbers get the same number; a computation whose value already has a temporary is replaced by a copy of it. An instruction is dead code if it can never run, or if it has no effect but writing a temporary that is not live after it; dead-code elimination removes it.
Available copies are a forward analysis like the others, with one difference: a copy must hold on every path, so the join is intersection, and the least element is “every copy”. opt.rs numbers values within each block only, which is enough to find a * b computed twice in one expression. Listing 8.8 removes dead code, with the liveness of the previous section. Each is proved correct the way constant propagation was: the fact holds on every execution, and under the fact the transformation changes no value that is ever read.
/// Removes the blocks no path reaches, and every instruction without side
/// effect whose result is not live afterwards.
pub fn dead_code(f: &mut FuncTac) -> usize {
let g = cfg::build(f);
let live_blocks = reachable(&g);
let sol = solve(&Liveness { code: &f.code, g: &g }, &g);
let after = live_after(&f.code, &g, &sol.after);
let mut out = vec![];
for (b, &(s, e)) in g.blocks.iter().enumerate() {
if !live_blocks[b] {
continue; // unreachable: dropped whole
}
for k in s..e {
let i = &f.code[k];
let pure = matches!(i, Tac::Bin(..) | Tac::Neg(..) | Tac::Not(..) | Tac::Copy(..)
| Tac::LoadG(..) | Tac::LoadA(..));
let dead = pure && def(i).is_some_and(|d| !after[k].contains(&d));
let self_copy = matches!(i, Tac::Copy(d, Val::T(s)) if d == s);
let jump_to_next =
matches!(i, Tac::Jump(l) if f.code.get(k + 1) == Some(&Tac::Label(*l)));
if !(dead || self_copy || jump_to_next) {
out.push(i.clone());
}
}
}
replace(f, out)
}
The passes feed each other. Folding a * 7 with a known to be 6 gives 42; propagating it may decide a branch; the branch removed makes a block unreachable; the block removed makes some temporaries dead; their definitions removed make more temporaries dead. optimise therefore runs the four passes in turn until a round changes nothing, which happens since each pass only removes instructions or replaces operands by constants. Exercise 8.4 predicts the result on a program that folds entirely.
Remark 8.14
The fixed point that constant propagation computes is not the best possible fact. In if c > 0 { a = 2; b = 3; } else { a = 3; b = 2; } x = a + b;, is 5 on both paths, yet the join at the end of the if makes a and b both before the addition, and is found . Exercise 8.10 shows that this happens because the transfer functions of constant propagation do not distribute over joins.
One more transformation is told and left as exercise 8.12. In while i < 100 { s = s + a * b + i; i = i + 1; }, the product a * b is the same on every iteration, since nothing in the loop writes a or b. Loop-invariant code motion computes it once, before the loop. The dominators give the loops: an edge such that dominates is a back edge, and the blocks that can reach without passing through form, with , the loop it closes.
8.4 Register allocation by graph colouring
Definition 8.15 (Register allocation, interference graph)
Register allocation decides, for each temporary, whether it lives in a register, and which, or in memory. Two temporaries interfere if one is written at a point where the other is live and may hold a different value; the interference graph has the temporaries as vertices and an edge between each pair that interferes.
Two temporaries that do not interfere can share a register: wherever one of them holds a value that will be read, the other holds nothing that will. The exception in the definition of interference is for copies: after x = y, the two hold the same value, and sharing a register is harmless, even useful (it makes the copy disappear). Listing 8.9 builds the graph from the live sets after each instruction. The parameters arrive together, in a0, a1, …, so they interfere with each other and with whatever is live at the entry.
/// Two temporaries interfere if one is written while the other is live and
/// holds a different value; the source of a copy does not interfere with its target.
pub fn interference(f: &FuncTac, g: &Cfg) -> Graph {
let sol = solve(&Liveness { code: &f.code, g }, g);
let after = live_after(&f.code, g, &sol.after);
let mut gr = Graph::default();
for (k, i) in f.code.iter().enumerate() {
for t in uses(i) {
gr.node(t);
}
if let Some(d) = def(i) {
gr.node(d);
for &t in &after[k] {
if !matches!(i, Tac::Copy(_, Val::T(s)) if *s == t) {
gr.edge(d, t);
}
}
}
}
let entry: BTreeSet<u32> = sol.before.first().cloned().unwrap_or_default();
for (n, &p) in f.params.iter().enumerate() {
// the parameters arrive together
gr.node(p);
for &q in f.params[..n].iter().chain(&entry) {
gr.edge(p, q);
}
}
gr
}
You already know
The Year 1 volume coloured graphs: a colouring with colours gives each vertex one of colours so that the two ends of every edge differ. It encoded the question “does a -colouring exist?” as a satisfiability problem.
A -colouring of the interference graph is an allocation with registers. Deciding whether a graph has one is NP-complete for every fixed , as chapter 17 proves for ; the fewest colours that suffice, the graph’s chromatic number, is as hard to compute. A compiler therefore uses a heuristic, built on one simple fact.
Proposition 8.16 (Simplify)
If a vertex of has fewer than neighbours, then is -colourable if and only if is.
Proof. A colouring of restricts to one of . Conversely, colour ; the neighbours of use at most colours, so one of the is free for . ∎
Definition 8.17 (Spill)
A spilled temporary lives in a slot of the frame instead of a register, and is loaded before each use and stored after each definition. Its spill cost estimates the memory accesses this adds: here, each use or definition counts , with the depth of the loops around it.
The allocator (Listing 8.10) repeats the proposition: while some vertex has fewer than neighbours, it removes it and pushes it on a stack (simplify). When none has, it removes the vertex with the least spill cost per neighbour and marks it spilled (spill). Then it pops the stack and gives each vertex the lowest colour its already coloured neighbours do not use (select); by the proposition, one is always free. The registers are s0–s11, which a callee must preserve, so a value in one survives calls; each function saves the ones it uses.
pub fn colour(gr: &Graph, k: usize, cost: &BTreeMap<u32, f64>) -> Colouring {
let mut left: BTreeMap<u32, BTreeSet<u32>> = gr.adj.clone();
let (mut stack, mut spilled) = (vec![], BTreeSet::new());
while !left.is_empty() {
// simplify: a node of degree < k can always be coloured later
let pick = left.iter().find(|(_, ns)| ns.len() < k).map(|(&t, _)| t);
let t = pick.unwrap_or_else(|| {
// spill: the cheapest per neighbour removed
let weight = |t: &u32| cost.get(t).unwrap_or(&0.0) / left[t].len() as f64;
let t = *left
.keys()
.min_by(|a, b| weight(a).total_cmp(&weight(b)))
.unwrap();
spilled.insert(t);
t
});
for n in left.remove(&t).unwrap() {
left.get_mut(&n).unwrap().remove(&t);
}
if pick.is_some() {
stack.push(t);
}
}
let mut colour = BTreeMap::new();
while let Some(t) = stack.pop() {
// select: the lowest colour no neighbour has
let taken: BTreeSet<usize> = gr.adj[&t]
.iter()
.filter_map(|n| colour.get(n).copied())
.collect();
colour.insert(t, (0..).find(|c| !taken.contains(c)).unwrap());
}
Colouring { colour, spilled }
}
Output 8.3 optimises sumsq, builds its interference graph and colours it. n, s, i and t3 are all live after t3 = i * i, so they form a clique and need four registers; with three, one of them is spilled, and the cheapest per neighbour is n, read once per iteration and with five neighbours.
$ rustc --edition 2021 -O -o color_demo color_demo.rs && ./color_demo loop.moor
s = 0
i = 0
L1:
if i < n goto L2
goto L3
L2:
t3 = i * i
t5 = s + t3
s = t5
t6 = i + 1
i = t6
goto L1
L3:
return s
interference graph: 6 nodes, 10 edges
n cost 10 -- s i t3 t5 t6
s cost 22 -- n i t3 t6
i cost 51 -- n s t3 t5
t3 cost 20 -- n s i
t5 cost 20 -- n i
t6 cost 20 -- n s
k = 3: s:2 i:1 t3:0 t5:0 t6:0 spilled: n
k = 4: n:2 s:3 i:1 t3:0 t5:0 t6:0 spilled: none
sumsq optimised (the copy sq = t3 is gone), its interference graph with each temporary’s spill cost and neighbours, and colourings with three and four registers.sumsq, 6 vertices and 10 edges as in Output 8.3, coloured with four colours. n, s, i and t3 form a clique, so three colours are not enough. The three short-lived temporaries share colour 0.The selection of chapter 7 is adapted in one place: an operand in a register is used where it is, and only a spilled one is loaded into a scratch register (Listing 8.11). A result is computed straight into its register, and stored only if it is spilled.
/// The register holding v, loading it into `scratch` if needed.
fn get(&mut self, v: Val, scratch: &'static str) -> &'static str {
match v {
Val::K(0) => "zero",
Val::K(n) => {
self.i(format!("li {scratch}, {n}"));
scratch
}
Val::T(t) => match self.loc[&t] {
Loc::Reg(r) => r,
Loc::Slot(o) => {
self.i(format!("lw {scratch}, {o}(sp)"));
scratch
}
},
}
}
/// Where to compute t: its register, or t0 before a store.
fn target(&self, t: u32) -> &'static str {
match self.loc[&t] {
Loc::Reg(r) => r,
Loc::Slot(_) => "t0",
}
}
fn finish(&mut self, t: u32, reg: &str) {
if let Loc::Slot(o) = self.loc[&t] {
self.i(format!("sw {reg}, {o}(sp)"));
}
}
zero. code/bachelor-3/08-program-optimisation/listings/rvgen.rsDefinition 8.18 (Register coalescing)
Register coalescing merges the two vertices of a copy x = y that do not interfere into one, so that they get the same register and the copy becomes mv r, r, which is deleted.
Our allocator does not coalesce, and its output shows the cost: in the loop of sumsq, s = t5 and i = t6 become mv instructions executed on every iteration. Merging vertices raises degrees and can turn a colourable graph into one that is not, so coalescing is done only when it cannot cause a spill, for instance when the merged vertex has fewer than neighbours of degree or more.
8.5 Measured
moorc_opt compiles at three levels: -O0 is chapter 7’s compiler, -O1 runs the optimisations of this chapter and keeps every temporary on the stack, and -O2 adds the allocator. Output 8.4 runs three samples at each level on rv, which counts exactly; these are numbers of instructions, not times.
$ rustc --edition 2021 -O -o moorc_opt $CH/moorc_opt.rs
$ for p in fib sum_array primes; do for O in 0 1 2; do ./moorc_opt -O$O $p.moor > $p.$O.S; done; done
$ python measure.py fib:20 sum_array primes
program level instructions loads stores output
fib -O0 426887 131347 98511 6765
fib -O1 426885 131346 98510 6765
fib -O2 448781 87566 87566 6765
same output and exit code
sum_array -O0 457 167 96 285
sum_array -O1 457 167 96 285
sum_array -O2 259 17 17 285
same output and exit code
primes -O0 3041 1039 659 2 3 5 ...
primes -O1 3041 1039 659 2 3 5 ...
primes -O2 2113 256 256 2 3 5 ...
same output and exit code
Three things stand out. First, -O1 hardly helps these samples: their copies are loop variables, live around the loop, which no pass here can remove. On straight-line code it helps a lot: expr.moor goes from 45 instructions to 13, because everything in it is a constant. Second, the allocator removes most memory accesses everywhere: sum_array from 263 to 34 loads and stores. Third, on fib, -O2 executes more instructions than -O1, 448,781 against 426,885, though it makes a quarter fewer memory accesses. Every call now saves and restores the s registers it uses, three of them and ra, and half of all calls are leaves that return at once: the leaf call went from 11 instructions to 16. A compiler that tests before saving anything, as gcc did in chapter 7, avoids this cost; the technique, which places the saves only on the paths that need them, is called shrink-wrapping.
In practice — Count before you time
rv’s counts are exact and the same on every run, so a change of one instruction per iteration is visible, which no timing on a laptop would show. They are not times: on a real processor, a load costs more or less depending on where the data is, and the Year 2 volume’s caches decide that. Counting tells whether an optimisation does what it means to; only timing on the target tells whether it matters.
History — Dataflow and colouring
Gary Kildall published a unified approach to global program optimisation in 1973, the analyses of this chapter as one algorithm over a lattice. John Kam and Jeffrey Ullman characterised monotone dataflow frameworks in 1977. Gregory Chaitin described register allocation and spilling via graph colouring in 1982. Ron Cytron, Jeanne Ferrante, Barry Rosen, Mark Wegman and Kenneth Zadeck published in 1991 how to compute static single assignment form efficiently, with dominance frontiers.
8.6 Exercises
Exercise 8.1 ★
In sumsq (Output 8.1), which temporaries are live after s = 0, after sq = t3 and after t6 = i + 1? Which is live at the entry, and why only that one?
Solution
Solution of Exercise 8.1.
After s = 0: ; after sq = t3: ; after t6 = i + 1: , since i is overwritten by the next instruction before any read. At the entry only n is live: s and i are written by the first two instructions before anything reads them (exercise_1_live_variables_of_the_loop).
Exercise 8.2 ★
Give the dominators and the immediate dominator of each block of the function f of chapter 7’s exercise 7.9, a while loop with a return inside.
Solution
Solution of Exercise 8.2.
With the blocks of that exercise’s solution: B0 (the loop’s test, also the entry) ; B1 ; B2 ; B3 ; B4 ; B6 ; B7 ; B8 . B5 and B9 are unreachable and have none. The immediate dominators are B0 for B1 and B2, B2 for B3 and B4, B3 for B6, B6 for B7 and B1 for B8: the dominator tree is the chain B0, B2, B3, B6, B7, with B4 hanging from B2, and B1, with B8 below it, from B0 (exercise_2_dominators).
Exercise 8.3 ★
Place the -functions of fn f(n: int) -> int { var x = 0; var y = 1; if n > 0 { x = n; } else { y = n; } while x < 10 { x = x + y; } return x; }, and give their arguments.
Solution
Solution of Exercise 8.3.
x is defined in the entry B0, in the then part B2 and in the loop body B7; y in B0 and in the else part B3. The frontier of each branch of the if is the block where they join, B4; the frontier of the loop body B7 is the loop’s header B5; and the frontier of B4 is empty, since B4 dominates everything after it. So and : x gets -functions at B4 and B5, y only at B4, since the loop does not assign it:
(exercise_3_phi_placement).
Exercise 8.4 ★
Predict the three-address code of var a = 6; var b = a * 7; var c = b - 40; if c > 1 { print(b); } else { print(a); } return c * a; after optimise, and the number of rounds it takes.
Solution
Solution of Exercise 8.4.
Round 1 propagates , folds and , decides the branch (), removes the else block and the copies that became dead. Round 2 removes the jumps and labels’ instructions made pointless and the last dead temporaries, and round 3 changes nothing. What is left is L1:, call print(42), L3:, return 12: three rounds (exercise_4_folded_tac).
Exercise 8.5 ★★
exercises/ex5_wrong_way.rs is liveness with the direction set to forward and nothing else changed. On sumsq it says that nothing is live at the entry and that n, s and i are live after the final return. Explain both answers from the equations, and say what an allocator would do with them.
Solution
Solution of Exercise 8.5.
Forward, the fact at a block’s start is the join of the facts at the ends of its predecessors, and the entry gets the boundary, the empty set. The transfer, still the backward rule, then adds what the block reads to what flowed in. The result is “the temporaries read on some path from the entry to here”, a fact about the past: at the entry nothing has been read, so nothing is “live”, and after the final return everything read in the loop has been read, so n, s and i are (exercise_5_liveness_the_wrong_way). An allocator fed with these sets would see no interference at the entry and could give n’s register to s, overwriting the loop bound; the program would then loop a wrong number of times. Liveness depends on the future of a point, so its facts must flow from the successors.
Exercise 8.6 ★★
Write dead-store elimination for globals: a store g = v is removed if, later in the same block, g is stored again with no load of g and no call in between. Why must a call stop the search? Test it on g = 1; h = 2; g = 3; print(g); g = 4; h = g; g = 5; return g + h;.
Solution
Solution of Exercise 8.6.
exercises/ex6_dead_store.rs scans forward from each store within its block. A call stops the search because the callee may read the global, and then the first store’s value is needed; a load of the same global stops it for the same reason. On the test program it removes g = 1 only: h = 2 is followed by the call to print before h is stored again, and g = 3 and g = 4 are read before the next store. The program still prints 3 and exits with (exercise_6_dead_stores).
Exercise 8.7 ★★
Prove that the worklist algorithm visits blocks at most times, for blocks, edges and a lattice of height per block.
Solution
Solution of Exercise 8.7.
Every value computed is at least the previous value of the same block: by induction, the facts flowing in only grow, and the transfer is monotone. So the output of a block changes at most times. Each change puts at most blocks in the queue, its successors (or predecessors, backwards), and each visit is caused by the initial queue or by one such insertion. The visits number at most . For liveness on sumsq the bound is , with temporaries (n, s, i, t3, sq, t5, t6) and edges; the actual count is 12.
Exercise 8.8 ★★
Colour the interference graph of Output 8.3 with three registers, or prove that a spill is needed.
Solution
Solution of Exercise 8.8.
A spill is needed. n, s, i and t3 are pairwise adjacent: all four are live just after t3 = i * i, as the edges listed show. Four vertices pairwise adjacent need four colours. With three registers the allocator spills n, whose cost per neighbour is , the smallest, and colours the rest (exercise_8_three_registers_are_not_enough).
Exercise 8.9 ★★
A nest of while loops, each with its own counter i0, …, initialised just before it, increments one accumulator s in the innermost body. How many -functions does the placement of Theorem 8.10 put, as a function of ? How many are useful?
Solution
Solution of Exercise 8.9.
: 2, 5, 9, 14, 20 for (exercise_9_phis_of_nested_loops). s is assigned in the innermost body, whose iterated frontier contains every header: -functions. The counter of the loop at depth is assigned before its loop, in the body of the loop at depth , and at the end of its own body; the iterated frontier of these blocks is its own header and the headers of the loops around it: -functions, in all. Only are useful: s is live at every header, and each counter at its own header; at the headers of the outer loops the counter is dead, since it is reset before being read. Placing -functions only where the variable is live gives the pruned SSA form, with .
Exercise 8.10 ★★★
A framework is distributive if for every transfer function. Show that constant propagation is not, with the program of the remark in Section 8.3, and prove that for a distributive framework the least fixed point equals the join, over all paths to a point, of the facts computed along each path.
Solution
Solution of Exercise 8.10.
Let and be the facts at the end of the two branches, and the transfer of x = a + b. Then maps to , but maps to (exercise_10_not_distributive).
For the theorem, let be the join over all paths from the entry to of , being the composition of the transfers along ; the lattice has finite height, so this join is a finite one. First, the least fixed point in any monotone framework: by induction on the length of , , since each step applies a monotone transfer and satisfies the equations. Second, if every distributes over joins, MOP satisfies the equations: the join over the predecessors of is the join over of the join over the paths to of , which is the join over all paths to . So MOP is a fixed point, and the least fixed point is below it. The two are equal. For constant propagation the least fixed point can be strictly above MOP, as the example shows: the analysis loses facts that hold on every path, because it joins before applying the transfer.
Exercise 8.11 ★★★
A graph is chordal if every cycle of four or more vertices has a chord. Admit that the interference graph of a program in SSA form, with interference defined at definitions, is chordal. Prove that a chordal graph has a vertex whose neighbours form a clique, deduce that simplify never gets stuck when is at least the largest clique, and conclude that such a program needs exactly as many registers as the most temporaries live at one point.
Solution
Solution of Exercise 8.11.
A vertex is simplicial if its neighbours form a clique. Claim: a chordal graph that is not complete has two non-adjacent simplicial vertices, and a complete one has every vertex simplicial. By induction on the number of vertices: if is not complete, take non-adjacent and a minimal set separating them. is a clique: for , both have neighbours in the component of and in the component of of (otherwise would not be minimal), so there are shortest paths through and through ; together they form a cycle of length at least 4 whose only possible chord is , since and are not joined. By induction, has a simplicial vertex in (two non-adjacent ones if it is not complete, and they cannot both be in the clique ; if it is complete, any vertex of ), and its neighbours in are all in , so it is simplicial in ; the same in .
A simplicial vertex in a graph whose largest clique has vertices has at most neighbours. Removing a vertex leaves a chordal graph, an induced subgraph. So if , simplify always finds a vertex of degree less than , never spills, and colours the graph with colours, which a clique of vertices needs anyway. For an SSA program the vertices of a clique are temporaries live together at one point (the definition of the one defined last, which the others’ definitions dominate), so is the largest number of temporaries live at one point, and that many registers are necessary and sufficient.
Exercise 8.12 ★★★
Write loop-invariant code motion: move an operation whose operands no instruction of the loop writes, into a temporary written nowhere else, to just before the loop’s header. Why is moving it safe even if the loop body might not run, given Moor’s division? Test it on while i < 100 { s = s + a * b + i; i = i + 1; } and count the instructions saved.
Solution
Solution of Exercise 8.12.
exercises/ex12_licm.rs finds the loops by their back edges, as in the text, and moves one candidate at a time until none is left. Moving the operation before the loop executes it even when the loop body would not run; this is safe because the operation has no effect but its result, and in Moor no arithmetic traps: division by zero gives , as on the processor. In a language where division by zero stops the program, only an operation that dominates the loop’s exits, or whose divisor is known to be non-zero, could be moved. On the test, t6 = t0 * t2 moves before L1:; with and both versions print , and the moved one executes 396 fewer instructions, 4 per iteration (two loads, the multiplication, a store) minus the 4 executed once before the loop (exercise_12_loop_invariant_code_motion).
8.7 Weekend problem
Problem 8.1
Weekend problem — A hot loop in the town’s billing
The library of the series’ invented town fines late returns: 10 cents a day for the first week, 25 cents a day after it, at most 500. billing.moor reads the days late of each returned loan, then fines and totals them in one loop. The data are the loans table of the town (data/town/loans.csv). Output 8.5 gives the interference graph of the program after -O1 and two colourings; Output 8.6 compiles it at each level, with fewer and fewer registers, and counts.
i = 0;
while i < n {
var days = late[i];
var fine = 0;
if days > 0 {
if days <= 7 { fine = day_rate * days; }
else { fine = 7 * day_rate + week_rate * (days - 7); }
if fine > cap { fine = cap; }
count = count + 1;
}
total = total + fine;
if fine > worst { worst = fine; }
i = i + 1;
}
billing.moor. The rates and the cap are variables set before it. code/bachelor-3/08-program-optimisation/listings/billing.moor$ rustc --edition 2021 -O -o color_demo $CH/color_demo.rs
$ ./color_demo billing.moor 7 6 | sed -n '/^interference/,$p'
interference graph: 16 nodes, 58 edges
t0 cost 21 -- i t3 t4 total count worst t11 fine t14 t16 t17 t18 t19 t20 t21
i cost 82 -- t0 t3 total count worst t11 fine t14 t16 t17 t18 t19 t20
t3 cost 20 -- t0 i
t4 cost 20 -- t0
total cost 22 -- t0 i count worst t11 fine t14 t16 t17 t18 t19 t21
count cost 22 -- t0 i total worst t11 fine t14 t16 t17 t18 t20 t21
worst cost 22 -- t0 i total count t11 fine t14 t16 t17 t18 t19 t20 t21
t11 cost 50 -- t0 i total count worst fine
fine cost 80 -- t0 i total count worst t11 t19 t20
t14 cost 20 -- t0 i total count worst
t16 cost 20 -- t0 i total count worst
t17 cost 20 -- t0 i total count worst
t18 cost 20 -- t0 i total count worst
t19 cost 20 -- t0 i total worst fine
t20 cost 20 -- t0 i count worst fine
t21 cost 20 -- t0 total count worst
k = 7: t0:5 i:6 t3:0 t4:0 total:4 count:3 worst:2 t11:0 fine:1 t14:0 t16:0 t17:0 t18:0 t19:0 t20:0 t21:0 spilled: none
k = 6: i:5 t3:0 t4:0 total:4 count:3 worst:2 t11:1 fine:0 t14:0 t16:0 t17:0 t18:0 t19:1 t20:1 t21:0 spilled: t0
billing.moor after -O1, and colourings with seven and six registers. t0 is n: copy propagation replaced n by the temporary returned by read.$ rustc --edition 2021 -O -o moorc_opt $CH/moorc_opt.rs
$ ./moorc_opt -O0 billing.moor > O0.S
$ ./moorc_opt -O1 billing.moor > O1.S
$ for k in 12 6 5 4 3 2 1; do ./moorc_opt -O2 -k $k billing.moor > k$k.S; done
$ python billing_counts.py loans.csv O0.S O1.S k12.S k6.S k5.S k4.S k3.S k2.S k1.S
378 returned loans, 87 late, at most 30 days
whole run hot loop
program instructions loads stores instr. ld+st output
O0.S 22528 8180 4743 15296 9125 87 24305 500
O1.S 21496 7473 4294 14272 7974 87 24305 500
k12.S 11815 385 385 7233 378 87 24305 500
k6.S 12484 1142 385 7525 757 87 24305 500
k5.S 12861 1520 763 7903 1513 87 24305 500
k4.S 13238 1898 768 8281 1896 87 24305 500
k3.S 13411 1985 855 8455 2070 87 24305 500
k2.S 15182 3001 1697 10228 3930 87 24305 500
k1.S 17452 5270 2454 11363 5443 87 24305 500
-O0, -O1, and -O2 with 12 down to 1 registers, run on the 378 returned loans: counts for the whole run, then for the hot loop alone. All print 87 late loans, 24,305 cents in fines, and a largest fine of 500.Part I — Liveness.
- Which of
n,i,days,fine,total,count,worst,day_rate,week_rateandcapare live at the top of the loop in the source, before any optimisation? - After
-O1,day_rate,week_rateandcaphave disappeared from the graph. Which pass removed them, and what did it put in their place? - Why is
finelive across the testfine > cap, anddaysnot after the computation offine? - Which temporaries are live at the point where most are, and how many are they?
- Why does
t3, the value returned byreadin the first loop, interfere with only two temporaries? - What does the cost 82 of
icount?
Part II — Colouring.
- Find a clique of seven vertices in the graph. What does it prove about the registers needed?
- Check that the colouring with seven registers is proper on the edges of
fine. - Why can the ten temporaries
t3,t4,t11,t14, …,t21all share colour 0? - With 12 registers available, how many does the allocator use, and which
sregisters must the function save? - Explain why
totalandcountcannot share a register, and whyt14andt16can. - Simulate simplify by hand with for the first three vertices it removes.
Part III — Fewer registers.
- With six registers, which temporary is spilled, and why that one by the cost per neighbour?
- Count, from the program, the extra loads that spilling
t0adds per iteration of each loop, and check against the table. - With five registers, which temporaries would you expect to be spilled next? Check the table’s loads and stores.
- Why do the counts with 12 and with 8 registers coincide, while 6 differ? (8 is not in the table; argue from the graph.)
- With one register, half the temporaries are spilled. Why is the count still well below
-O1’s? - Plot or tabulate the instructions against . Where is the largest step?
Part IV — The counts.
- In the hot loop, what fraction of
-O0’s loads and stores does-O1remove, and what fraction of its instructions? - In the hot loop, what fraction of
-O1’s loads and stores does the allocator remove with 12 registers, and what fraction of its instructions? Compare with the whole run. - Where do the 385 loads that remain in the whole run with 12 registers come from? And the 385 stores?
- How many instructions does one iteration of the hot loop execute at
-O1, and at-O2, on average? - What would coalescing save on this loop? Count the
mvinstructions in it. - Sum up: the percentage of loads and stores, and of all instructions, that graph-colouring allocation removes on the billing loop, and what limits it.
Solution
Solution of Problem 8.1.
1. n, i, total, count, worst, day_rate, week_rate and cap: each is read in the loop before being written, or after it. days and fine are written at the top of the body before any read.
2. Constant propagation: the three are 10, 25 and 500 on every path, so their uses became constants (7 * day_rate folded to 70), and dead-code elimination removed their now unread copies.
3. fine is read after the test: added to total and compared with worst. days (t11) is read only to compute fine; after the last such read no path reads it again.
4. Seven, for instance just after fine = 0: t0, i, total, count, worst, t11 and fine.
5. It is defined by read and read at once by the store into late[i]; between the two, only t0 and i are live.
6. Each use or definition of i weighted by : in each loop, the test, the index, the increment and the copy back, four times 10; two loops, 80; plus the two i = 0 outside any loop, 1 each: 82.
7. The seven of question 4: each pair is an edge in Output 8.5. Seven registers are needed to avoid spilling.
8. fine has colour 1; its neighbours t0, i, total, count, worst, t11, t19 and t20 have colours 5, 6, 4, 3, 2, 0, 0 and 0: none has 1.
9. No two of them interfere: each lives from its definition to its few uses, and none of the others is defined in between (the graph has no edge among them). Their neighbours are among the six long-lived temporaries t0, i, total, count, worst and fine, which select colours 5, 6, 4, 3, 2 and 1, so colour 0 is free for all ten.
10. Seven: s1 to s7, all saved in the prologue and restored in the epilogue. ra is not saved, since the function calls nothing: the built-ins are system calls.
11. total and count are both live throughout the loop: an edge. t14 and t16 are in different branches of the if; neither is live where the other is defined.
12. In the order of the temporaries’ numbers, the first vertex of degree less than 7 is t3 (degree 2), then t4 (degree 1), then t11, whose degree is 6.
13. t0. When simplify gets stuck, the remaining vertices all have six neighbours or more; t0 costs 21 for fifteen neighbours, the least cost per neighbour, since it is read only in the two loop tests: , against for total and 82/13 for i.
14. One load per evaluation of each loop’s test, 379 each: 758 more, minus the restore of the seventh s register, no longer used: . In the hot loop, loads and stores. The spill’s store replaces that register’s save: the stores stay at 385.
15. total is spilled next (color_demo with confirms it): one load and one store per iteration, 378 each, which is the step from 1142 to 1520 loads and 385 to 763 stores; its store at total = 0 and its load for print replace the save and the restore of the register no longer used. With four registers worst follows, and with three count follows: 87 more loads and 87 more stores, one of each per late loan, for count = count + 1 (1898 to 1985 loads, 768 to 855 stores).
16. The largest clique has seven vertices and simplify finds a colouring with seven colours; with it never gets stuck and select uses the lowest colours, so the allocation, and the code, are the same. With six, a spill is unavoidable.
17. The one register still holds fine and the short-lived temporaries that do not interfere with it, so part of the arithmetic of the loop stays in a register. A spilled temporary costs a load per use and a store per definition, as at -O1, but the operands in the register cost nothing, and the code generator of -O2 also uses zero for the constant 0, immediate forms, and computes a result straight into its location.
18. Instructions: 11,815 for 7 to 12 registers, then 12,484, 12,861, 13,238, 13,411, 15,182 and 17,452 for 6 down to 1. The largest step is from 2 registers to 1 (2,270), which spills the loop counter i, then from 3 to 2 (1,771), which spills days (t11) and two short-lived temporaries.
19. In the hot loop, loads and stores go from 9,125 to 7,974, 12.6 % fewer, and instructions from 15,296 to 14,272, 6.7 % fewer: the constants and some copies are gone, but every temporary still goes through memory.
20. From 7,974 loads and stores to 378, 95.3 % fewer; from 14,272 instructions to 7,233, 49.3 % fewer. Over the whole run, 11,767 to 770 (93.5 %) and 21,496 to 11,815 (45.0 %): the first loop’s read calls and stores are work the allocator cannot remove.
21. 378 loads of late[i] in the hot loop and 7 restores; 378 stores into late[i] in the first loop and 7 saves.
22. at -O1 and at -O2, the loop’s test counting 379 times in both.
23. The hot loop executes 935 mv instructions: the copies back into i and total on every iteration (378 each), into count and fine for late loans, and worst = fine five times. All but the last connect temporaries that do not interfere, so coalescing would remove about 930 of 7,233 instructions, 13 %. worst = fine must stay: both are live afterwards.
24. On the billing loop, graph-colouring allocation removes 95.3 % of the loads and stores and 49.3 % of all instructions executed (93.5 % and 45.0 % over the whole run). What is left is the essential memory traffic, one load of late[i] per loan, the arithmetic, the branches, and the copies that coalescing would remove. Seven registers suffice because at most seven temporaries are live at once; below that, each spilled temporary costs about one access per use in the loop.
Terms defined in this chapter
- Constant propagation
- Copy propagation, value numbering, dead code
- Dataflow lattice, height
- Dominator, dominance frontier
- Least fixed point
- Live temporary
- Reaching definition
- Register allocation, interference graph
- Register coalescing
- Spill
- Static single assignment, phi-function
- Transfer function, monotone framework