Algorithmcore
Aho-Johnson dynamic programming code generation
Also called optimal tree tiling.
Computes, bottom-up, the cheapest cost of each subtree for every number of free registers and for memory, then emits code that stores whole subtrees only where that is cheaper.
- Solves
- Instruction selection
- Time
- Θ(n r) worst
- Space
- Θ(n r) extra
- Where
- n = the number of nodes of the tree; r = the number of registers
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alfred V. Aho, Stephen C. Johnson, 1976
Aho-Johnson code generation picks the instructions for an expression tree, and the order of their operands, on a machine with registers. It solves the instruction selection problem for trees and includes the register limit. For each node and for each number of free registers, it computes the cost of the cheapest code that leaves the node in a register, and also the cost to leave it in memory. The answer at the root is the least cost of any program for the tree, on the class of machines of Aho and Johnson. The Sethi-Ullman algorithm is the special case with one unit-cost instruction per operator. BURS and maximal munch tile the same trees but ignore the register limit, and munch does not find the cheapest tiling.
In plain words
One machine instruction can do a small piece of a tree. Choosing the instructions is like covering the tree with tiles, where each tile has a price.
The algorithm works from the leaves up. At each node it writes down a short price list: the cheapest way to compute this subtree if one register is free, if two are free, and so on, and also the price to compute it and save it in memory. To fill the list at a node, it tries every tile that fits there and every order of the operands of the tile. The operand that is computed first can use all the free registers, and each later operand has one fewer, because the earlier results wait in registers.
When the list at the root is full, the algorithm goes down again and writes out the choices that gave the best price.
The problem
The input is an expression tree with nodes and a machine. The nodes on this page are CONST , VAR (a variable in memory), MEM (load the word at address ), ADD and MUL. The machine has registers with . Each instruction is a tree pattern with a cost. In a pattern, reg is an operand in a register, CONST is an immediate constant, and VAR is a memory operand: a variable, or a temporary that holds a stored subtree.
| name | pattern | cost |
|---|---|---|
| LI | CONST | 1 |
| LD | VAR | 3 |
| ADD | ADD(reg, reg) | 1 |
| ADDI | ADD(reg, CONST) | 1 |
| ADDM | ADD(reg, VAR) | 3 |
| MUL | MUL(reg, reg) | 3 |
| LDR | MEM(reg) | 3 |
| LDO | MEM(ADD(reg, CONST)) | 3 |
| LDX | MEM(ADD(reg, reg)) | 3 |
| MADD | ADD(MUL(reg, reg), reg) | 2 |
A store costs . The output is a program that leaves the value of in , never needs more than registers at one time, and has the least total cost. A program here may evaluate the operands in any order, interleave them, store any value and load it back.
The algorithm
is the least cost to compute into a register when registers are free, and is the least cost to have it in memory. All entries start at .
LABEL(v)- 1
for each child u of v do LABEL(u) - 2
for each pattern p that matches at v do ▷ LD matches here only at a variable - 3
base ← cost(p) + sum of C[m][0] over the memory operands m of p that are not variables - 4
for each order h_1, ..., h_q of the register operands of p do - 5
for j ← max(1, q) to r do total ← base + sum over t of C[h_t][j - t + 1] - 6
if total < C[v][j] then C[v][j] ← total; remember (p, the order) - 7
if v is a variable then C[v][0] ← 0 - 8
else C[v][0] ← C[v][r] + s ▷ compute with all registers, then store - 9
for j ← 1 to r do C[v][j] ← min(C[v][j], C[v][0] + cost(LD)) ▷ store, then load back GENERATE(root)- 10
for each subtree that the chosen plan keeps in memory, deepest first: emit its code with all r registers free, then a store to a new temporary- 11
emit the code of the root with all r registers free
The code of a node with free registers runs the operand in , so the earlier operands wait in . Then the instruction of writes . A subtree that the plan keeps in memory is computed before everything else, when all registers are free, and its temporary is then a memory operand or the source of a load.
Example
Take and . The vectors are:
| node | choice for | |||
|---|---|---|---|---|
| each variable | 0 | 3 | 3 | LD |
| 8 | 4 | 1 | 1 | LI |
| 7 | 4 | 4 | ADDI | |
| MEM | 9 | 6 | 6 | LDO, which covers the ADD too |
| 12 | 15 | 9 | MUL | |
| 15 | 18 | 12 | MUL | |
| root | 30 | 33 | 27 | ADDM with the right product in memory |
At the root, ADD with both products in registers costs or : one product has to run with one free register, and includes a store and a load. MADD needs three registers. ADDM costs : the right product is computed first and stored, and the left product then has both registers. The code is:
| step | instruction | cost |
|---|---|---|
| 1 | 3 | |
| 2 | 3 | |
| 3 | 3 | |
| 4 | 3 | |
| 5 | 3 | |
| 6 | 3 | |
| 7 | 3 | |
| 8 | 3 | |
| 9 | 3 |
The total is 27. With the cost falls to 20: load into , compute the right product in with two free registers (12), load into , and finish with one MADD. The best tiling with no register limit also costs 20. If the operands of a pattern may only go left to right, the best cost for is 22.
Correctness
LABEL is a dynamic program over normal-form plans. A plan for with registers is a pattern at , an order of its register operands, plans with registers for those operands, and plans in memory for its memory operands, or else a store and a load of . The parts of a plan are independent, so the cheapest plan is made of cheapest parts, and an induction on the tree shows that is the least cost of a plan. GENERATE turns the plan into code with the same cost, and the registers of the operands do not overlap. Aho and Johnson prove that each tree has a cheapest program in strong normal form, which is exactly such a plan. So is the least cost of any program. The proof file gives the details.
Proof: The Aho-Johnson cost vectors are the costs of the best normal-form programsfull
We use the machine and the pseudocode of the page. The machine has registers. Each instruction is a pattern with a cost . A leaf of a pattern is a register operand, an immediate constant or a memory operand. A store costs and a load of a memory operand into a register costs . For a node we write for its subtree. When matches at , the register leaves of sit on nodes and the memory leaves on nodes . These nodes are the operand nodes of at , and their subtrees are disjoint.
Part 1: enough registers
A tiling of is a pattern that matches at , a tiling of for each register operand node of , and nothing for a constant or a variable. Its cost is the sum of the costs of its patterns. Let be the least cost of a tiling of in which every memory operand is a variable.
Lemma 1. , where ranges over the patterns that match at and whose memory operands are variables.
Proof. A tiling of is a choice of and independent tilings of the disjoint subtrees , and its cost is plus their costs. For a fixed the sum is least when each part is least. Take the minimum over .
This is the case of Part 2 with , on the machine of the page. With free registers, the operand gets registers, so no register limit binds. A plan that stores a subtree pays for it, and then either a load of cost 3 or the memory form ADDM of cost 3. The plan that keeps in a register pays and the register form ADD of cost 1, or nothing for the load. So a store never helps there, and .
Part 2: a limited number of registers
A program for computes nodes into registers by instructions, writes registers to temporaries by stores, and leaves the root in . An instruction for reads the value of each register operand node from a register and the value of each memory operand node from a variable or a temporary. At each moment at most registers hold values that the program still needs.
Normal-form plans. For define the set of plans, by induction on :
- (the value of ends in memory). If is a variable, the empty plan, of cost 0. Else a plan of followed by a store, of cost .
- (the value of ends in a register, and only registers are free). Either a reload: a plan of when is not a variable, followed by a load. Or a pattern that matches at with register operand nodes, an order of them, a plan of for each memory operand node, and a plan of for each . A variable as a memory operand needs the empty plan. The cost is plus the costs of the parts.
Lemma 2. After LABEL, is the least cost of a plan in , for each .
Proof. By induction on the height of . Line L1 handles the children first, so the claim holds for each operand node. Lines L2 to L6 try each pattern that matches at , each order of its register operand nodes, and each with . For a fixed pattern and order, the cost of a plan is plus a sum of independent parts. By the induction hypothesis the least part costs are and . Line L3 adds the first ones, and line L5 adds the second ones. A memory operand that is a variable adds 0. So after line L6, is the least cost of a plan of the pattern kind, for .
Let be this value. A reload plan for costs at least , because its inner plan of is a pattern plan or another reload, and a reload inside a reload only adds cost. So the least plan of is a pattern plan, of cost . Lines L7 and L8 then set to the least cost in : 0 for a variable, and else. Line L9 sets , which is the least cost over both kinds of plans of . For this is still .
Lemma 3. GENERATE emits a program of cost . It leaves the value of the tree in , and at each moment at most registers hold needed values.
Proof. GENERATE follows the plan that LABEL remembered. Line L10 first runs each subtree that the plan puts in memory, with all registers free, and stores it. Such a subtree runs before the code that reads its temporary, and the subtrees that it puts in memory run before it. The temporaries are fresh, so later code does not overwrite them.
Then the code of a node with free registers runs the operand with the registers . By induction it leaves in and does not write , where the earlier operands wait. Then the instruction for reads its operands and writes . So each part uses only its own registers, and the count of needed registers never exceeds . A reload loads the temporary of into . Each instruction and each store of the code belongs to exactly one part of the plan, so the cost of the code is the cost of the plan, which is by Lemma 2.
Lemma 4. for .
Proof. By induction on the height of . A pattern plan with registers is also allowed with registers, and the induction hypothesis gives for each operand. The reload term is the same for each .
Theorem. For a tree and a machine of the class of Aho and Johnson, is the least cost of a program for , and GENERATE emits a program with this cost.
Proof. Aho and Johnson prove that each tree has a cheapest program in strong normal form: the program first computes and stores some subtrees, each with all registers free, and then computes the root, where each instruction evaluates its register operands one after the other, each one in full before the next one starts. A program in strong normal form is exactly a plan of . So the least cost of a program is the least cost of a plan, which is by Lemma 2. Lemma 3 shows that GENERATE reaches it.
The normal form theorem is the deep step, and this file does not repeat its proof. It needs the assumptions of their class of machines, in particular that the registers are interchangeable and that a memory operand can be any variable or temporary. A machine with special registers, such as a multiply that writes a fixed register pair, is outside the class.
Time. For a fixed machine, the number of patterns, their size, the number of register operands of a pattern and are constants. LABEL does work at each node, and GENERATE does constant work for each node and each emitted instruction. So both run in time linear in the number of nodes.
Complexity
For each node, LABEL tries each pattern, each order of its register operands and each , and sums entries. That is per node for patterns, and for the whole tree when the machine is fixed, because LABEL fills entries. For a fixed the time is linear in the size of the tree. Matching a pattern at a node takes time proportional to the size of the pattern, a constant for a fixed machine. GENERATE does constant work per emitted instruction. The tables take space.
Properties
- Exact for trees. On the machine class of Aho and Johnson, the cost at the root is the least cost over all programs, including programs that interleave operands or store and reload values.
- Fewer registers never help. , because each plan for registers is also a plan for .
- Stores of whole subtrees. The code stores only complete subtrees, each computed with all registers free, and each stored value is used once.
- Equal to the best tiling when registers are plenty. On the machine of the page, with at least the number of nodes, no plan stores a value, and the cost is the least tiling cost.
Variants and improvements
- No register limit. Drop the index . Then is one number, the least tiling cost, and the program is the tiling dynamic program of most modern code generators. A global register allocator handles the registers later.
- Precomputed states. BURS moves the dynamic program to the time when the code generator is built, so that labeling a tree is one table lookup per node. iburg runs the same dynamic program at compile time from a tree grammar.
- Fast matching. Twig, by Aho, Ganapathi and Tjiang, finds the patterns that match at each node with a top-down tree pattern matcher and then runs the dynamic program.
- Commutative operators. Add a second pattern with the operands swapped. Then ADDM also covers a variable on the left of an ADD. The order loop of line L4 only changes the order of evaluation, not the place of an operand.
- Several nonterminals. A real grammar has more classes of results than "register" and "memory", for example addressing modes and condition codes. Each class is one more entry of the cost vector.
When to use it
Use it when the input is a tree, the instructions overlap in complex ways, and the register limit matters for the code of one expression. In most compilers today, a tiling dynamic program without the register index chooses the instructions, and a separate register allocator assigns registers. The register-aware version suits small machines, accumulator machines and code generators for single expressions. For code with shared values the problem is NP-complete (see the DAG theorem), so split the DAG into trees first.
Pitfalls
- Ignoring the register limit. The tiling cost of the example is 20, but with two registers the best program costs 27.
- The wrong share of registers. The -th operand gets registers, not . Giving each operand all registers undercounts.
- One order only. The example with costs 22 if the operands go left to right, and 20 with the best order.
- Shared nodes. On a DAG, a shared subtree is counted once per parent and computed twice. The labels are no longer exact.
- Machines outside the class. An instruction that needs a fixed register or a pair of registers breaks the normal form theorem, and the result is no longer guaranteed to be the least cost.
- Ties. Many plans can have the same cost. Break ties by a fixed rule, so that the output is reproducible.
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/aho-johnson-code-generation/. The authors are listed in prov/10CJ5M.jsonl.
"""Aho-Johnson dynamic programming code generation for expression trees.
A tree is written with tuples: ("CONST", k), ("VAR", x), ("MEM", a),
("ADD", a, b) or ("MUL", a, b). VAR is a variable in memory. MEM(a) loads
the word at the address a. Each instruction of the machine is a tree
pattern with a cost. In a pattern, "reg" is an operand in a register,
("CONST",) is an immediate constant and ("VAR",) is an operand in memory:
a variable, or a temporary that holds a stored subtree. The machine has r
registers and a store instruction t <- Ri of cost STORE_COST.
"""
from itertools import permutations
RULES = [
("li", ("CONST",), 1),
("ld", ("VAR",), 3),
("add", ("ADD", "reg", "reg"), 1),
("addi", ("ADD", "reg", ("CONST",)), 1),
("addm", ("ADD", "reg", ("VAR",)), 3),
("mul", ("MUL", "reg", "reg"), 3),
("ldr", ("MEM", "reg"), 3),
("ldo", ("MEM", ("ADD", "reg", ("CONST",))), 3),
("ldx", ("MEM", ("ADD", "reg", "reg")), 3),
("madd", ("ADD", ("MUL", "reg", "reg"), "reg"), 2),
]
LD = 1
STORE_COST = 3
INF = float("inf")
class Node:
"""One node of the tree. Two nodes are never shared."""
__slots__ = ("op", "val", "kids")
def __init__(self, op: str, val: object, kids: list["Node"]) -> None:
self.op, self.val, self.kids = op, val, kids
def build(t: tuple) -> Node:
if t[0] in ("CONST", "VAR"):
return Node(t[0], t[1], [])
return Node(t[0], None, [build(c) for c in t[1:]])
def heap(a: int) -> int:
"""The word at address a."""
return (31 * a + 7) % 97
def match(pat: object, n: Node) -> list | None:
"""Match pat at n. Return the leaves of the pattern, left to right, as
(kind, node) pairs with kind "reg", "const" or "mem", or None."""
if pat == "reg":
return [("reg", n)]
if pat == ("CONST",):
return [("const", n)] if n.op == "CONST" else None
if pat == ("VAR",):
return [("mem", n)]
if n.op != pat[0]:
return None
out: list = []
for p, child in zip(pat[1:], n.kids):
m = match(p, child)
if m is None:
return None
out += m
return out
class Generator:
"""The dynamic program on one tree, and the code that it chooses."""
def __init__(self, tree: tuple, r: int) -> None:
if r < 2:
raise ValueError("this machine needs at least two registers")
self.r = r
self.root = build(tree)
self.cost: dict[Node, list[float]] = {}
self.choice: dict[Node, list] = {}
self.label(self.root)
def label(self, n: Node) -> None:
r = self.r
for child in n.kids: # @line L1
self.label(child)
c = [INF] * (r + 1)
ch: list = [None] * (r + 1)
for idx, (_, pat, cost) in enumerate(RULES): # @line L2
if pat == ("VAR",) and n.op != "VAR":
continue # a reload, handled at line L9
leaves = match(pat, n)
if leaves is None:
continue
regs = [i for i, (k, _) in enumerate(leaves) if k == "reg"]
base = cost # @line L3
for k, h in leaves:
if k == "mem" and h.op != "VAR":
base += self.cost[h][0]
for order in permutations(regs): # @line L4
for j in range(max(1, len(order)), r + 1):
total = base + sum(self.cost[leaves[i][1]][j - t] for t, i in enumerate(order)) # @line L5
if total < c[j]: # @line L6
c[j] = total
ch[j] = (idx, leaves, order)
if n.op == "VAR": # @line L7
c[0], ch[0] = 0, ("var",)
else:
c[0], ch[0] = c[r] + STORE_COST, ("store",) # @line L8
for j in range(1, r + 1): # @line L9
if c[0] + RULES[LD][2] < c[j]:
c[j], ch[j] = c[0] + RULES[LD][2], ("reload",)
self.cost[n] = c
self.choice[n] = ch
def generate(self) -> list[tuple]:
"""Return the code. An instruction is (rule, Ri, args) or ("store", t, Ri)."""
self.code: list[tuple] = []
self.temp: dict[Node, str] = {}
self.jobs(self.root, self.r) # @line L10
self.emit(self.root, ["R%d" % i for i in range(self.r)]) # @line L11
return self.code
def run_job(self, n: Node) -> None:
# Compute n with all registers free, then store it.
self.jobs(n, self.r)
self.emit(n, ["R%d" % i for i in range(self.r)])
t = "t%d" % len(self.temp)
self.temp[n] = t
self.code.append(("store", t, "R0"))
def jobs(self, n: Node, j: int) -> None:
# Emit first every subtree that the plan of (n, j) keeps in memory.
ch = self.choice[n][j]
if ch[0] == "reload":
self.run_job(n)
return
_, leaves, order = ch
for k, h in leaves:
if k == "mem" and h.op != "VAR":
self.run_job(h)
for t, i in enumerate(order):
self.jobs(leaves[i][1], j - t)
def emit(self, n: Node, regs: list[str]) -> None:
# Leave n in regs[0]. The stored subtrees are already in memory.
ch = self.choice[n][len(regs)]
if ch[0] == "reload":
self.code.append((LD, regs[0], [self.temp[n]]))
return
idx, leaves, order = ch
args: list = [None] * len(leaves)
for t, i in enumerate(order):
self.emit(leaves[i][1], regs[t:])
args[i] = regs[t]
for i, (k, h) in enumerate(leaves):
if k == "const":
args[i] = h.val
elif k == "mem":
args[i] = h.val if h.op == "VAR" else self.temp[h]
self.code.append((idx, regs[0], args))
def generate(tree: tuple, r: int) -> tuple[list[tuple], float]:
"""Return (code, cost) of an optimal program for the tree with r registers."""
g = Generator(tree, r)
return g.generate(), g.cost[g.root][r]
def code_cost(code: list[tuple]) -> int:
return sum(STORE_COST if ins[0] == "store" else RULES[ins[0]][2] for ins in code)
def evaluate(t: tuple, env: dict[str, int]) -> int:
"""The value of the tree, computed directly."""
op = t[0]
if op == "CONST":
return t[1]
if op == "VAR":
return env[t[1]]
if op == "MEM":
return heap(evaluate(t[1], env))
a, b = evaluate(t[1], env), evaluate(t[2], env)
return a + b if op == "ADD" else a * b
def run(code: list[tuple], env: dict[str, int], r: int) -> int:
"""Run the code on the machine with r registers and return R0."""
reg: dict[str, int] = {}
mem = dict(env)
for ins in code:
if ins[0] == "store":
mem[ins[1]] = reg[ins[2]]
continue
idx, dst, args = ins
assert int(dst[1:]) < r
it = iter(args)
def ev(p: object) -> int:
if p == "reg":
return reg[next(it)]
if p == ("CONST",):
return next(it)
if p == ("VAR",):
return mem[next(it)]
vals = [ev(q) for q in p[1:]]
if p[0] == "MEM":
return heap(vals[0])
return vals[0] + vals[1] if p[0] == "ADD" else vals[0] * vals[1]
reg[dst] = ev(RULES[idx][1])
return reg["R0"]
test_aho_johnson_code_generation.py 209 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aho-johnson-code-generation/. The authors are listed in prov/10CJ5M.jsonl.
import heapq
import random
from aho_johnson_code_generation import RULES, STORE_COST, code_cost, evaluate, generate, run
def random_tree(rng: random.Random, size: int) -> tuple:
"""A random tree with exactly size nodes."""
if size == 1:
if rng.random() < 0.5:
return ("CONST", rng.randint(0, 9))
return ("VAR", rng.choice("abc"))
if size == 2 or rng.random() < 0.25:
return ("MEM", random_tree(rng, size - 1))
left = rng.randint(1, size - 2)
return (rng.choice(["ADD", "ADD", "MUL"]), random_tree(rng, left), random_tree(rng, size - 1 - left))
def bushy_tree(rng: random.Random, size: int) -> tuple:
"""A random tree with size nodes and two children of near equal size.
Such trees need many registers."""
if size == 1:
return ("VAR", rng.choice("abc")) if rng.random() < 0.7 else ("CONST", rng.randint(0, 9))
if size == 2 or rng.random() < 0.15:
return ("MEM", bushy_tree(rng, size - 1))
left = (size - 1) // 2
if rng.random() < 0.5:
left = size - 1 - left
return (rng.choice(["ADD", "MUL"]), bushy_tree(rng, left), bushy_tree(rng, size - 1 - left))
def tilings(t: tuple) -> list[int]:
"""The cost of every tiling of t, with no limit on registers.
A memory operand of a pattern matches only a variable here."""
def leaves(p: object, n: tuple) -> list | None:
if p == "reg":
return [n]
if p == ("CONST",):
return [] if n[0] == "CONST" else None
if p == ("VAR",):
return [] if n[0] == "VAR" else None
if n[0] != p[0]:
return None
out: list = []
for q, c in zip(p[1:], n[1:]):
m = leaves(q, c)
if m is None:
return None
out += m
return out
def all_costs(n: tuple) -> list[int]:
res = []
for _, p, cost in RULES:
holes = leaves(p, n)
if holes is None:
continue
partial = [cost]
for h in holes:
partial = [x + y for x in partial for y in all_costs(h)]
res += partial
return res
return all_costs(t)
def min_program_cost(t: tuple, r: int) -> int:
"""Brute force: the cheapest program for t over all orders of instructions,
stores and reloads, with at most r values in registers at each step."""
nodes: list = []
kids: list = []
def walk(n: tuple) -> int:
i = len(nodes)
nodes.append(n)
kids.append([])
if n[0] not in ("CONST", "VAR"):
kids[i] = [walk(c) for c in n[1:]]
return i
walk(t)
m = len(nodes)
def leaves(p: object, i: int) -> list | None:
# (kind, node index) for the leaves of p, and ("inner", i) for covered nodes.
if p == "reg":
return [("reg", i)]
if p == ("CONST",):
return [("inner", i)] if nodes[i][0] == "CONST" else None
if p == ("VAR",):
return [("mem", i)]
if nodes[i][0] != p[0]:
return None
out: list = []
for q, c in zip(p[1:], kids[i]):
x = leaves(q, c)
if x is None:
return None
out += x
return out
# Status: 0 not computed, 1 in a register, 2 in memory, 3 used or covered.
start = tuple(2 if n[0] == "VAR" else 0 for n in nodes)
dist = {start: 0}
pq = [(0, start)]
while pq:
d, s = heapq.heappop(pq)
if d > dist[s]:
continue
if s[0] == 1:
return d
inreg = sum(1 for x in s if x == 1)
nxt = []
for i in range(m):
if s[i] == 1:
nxt.append((s[:i] + (2,) + s[i + 1:], STORE_COST))
if s[i] == 2 and inreg < r:
nxt.append((s[:i] + (1,) + s[i + 1:], RULES[1][2])) # load
if s[i] != 0:
continue
for _, p, cost in RULES:
if p == ("VAR",):
continue
lv = leaves(p, i)
if lv is None:
continue
ok = True
new = list(s)
for k, h in lv:
want = {"reg": (1,), "mem": (2,), "inner": (0,)}[k]
if s[h] not in want:
ok = False
break
new[h] = 3
if not ok:
continue
# the covered inner nodes of the pattern are also not computed
cov = [i]
stack = [(p, i)]
while stack:
q, j = stack.pop()
if isinstance(q, tuple) and len(q) > 1:
for qq, c in zip(q[1:], kids[j]):
if isinstance(qq, tuple) and len(qq) > 1:
cov.append(c)
stack.append((qq, c))
if any(s[c] != 0 for c in cov):
continue
for c in cov:
new[c] = 3
new[i] = 1
if sum(1 for x in new if x == 1) <= r:
nxt.append((tuple(new), cost))
for ns, c in nxt:
if ns not in dist or dist[ns] > d + c:
dist[ns] = d + c
heapq.heappush(pq, (d + c, ns))
raise AssertionError("no program")
def check_code(t: tuple, r: int, rng: random.Random) -> float:
code, cost = generate(t, r)
assert code_cost(code) == cost
for _ in range(3):
env = {v: rng.randint(-20, 20) for v in "abc"}
assert run(code, env, r) == evaluate(t, env)
return cost
def test_example() -> None:
t = ("MEM", ("ADD", ("MUL", ("VAR", "a"), ("VAR", "b")), ("VAR", "c")))
code, cost = generate(t, 3)
assert cost == 14 == min(tilings(t))
assert [RULES[ins[0]][0] for ins in code] == ["ld", "ld", "ld", "madd", "ldr"]
code, cost = generate(t, 2)
assert cost == 15 == min_program_cost(t, 2)
env = {"a": 4, "b": 5, "c": 6}
assert run(code, env, 2) == evaluate(t, env) == 37
def test_enough_registers_gives_the_cheapest_tiling() -> None:
rng = random.Random(1976)
for _ in range(300):
size = rng.randint(1, 8)
t = random_tree(rng, size)
assert check_code(t, 8, rng) == min(tilings(t))
def test_few_registers_against_all_programs() -> None:
rng = random.Random(488)
spills = 0
for _ in range(200):
t = random_tree(rng, rng.randint(1, 8)) if rng.random() < 0.3 else bushy_tree(rng, rng.randint(5, 10))
for r in (2, 3):
assert check_code(t, r, rng) == min_program_cost(t, r)
spills += any(ins[0] == "store" for ins in generate(t, r)[0])
assert spills >= 30
def test_cost_falls_with_registers() -> None:
rng = random.Random(5)
for _ in range(100):
t = random_tree(rng, rng.randint(1, 12))
costs = [generate(t, r)[1] for r in range(2, 6)]
assert all(x >= y for x, y in zip(costs, costs[1:]))
History
Aho and Johnson published the algorithm in the Journal of the ACM in 1976. They generalized the result of Sethi and Ullman (1970) from a fixed instruction set to any machine of their class, proved the strong normal form theorem, and showed that the algorithm runs in time linear in the size of the tree for a fixed machine. The tiling dynamic program became the base of the code generator generators twig, BURG and iburg.
References
- Alfred V. Aho and Stephen C. Johnson, Optimal code generation for expression trees, Journal of the ACM 23(3), 1976, 488-501, the class of machines with r interchangeable registers, the cost vectors computed bottom-up, the strong normal form theorem, and the bound linear in the size of the tree for a fixed machine
- Ravi Sethi and J. D. Ullman, The generation of optimal code for arithmetic expressions, Journal of the ACM 17(4), 1970, 715-728, the special case of a machine with one instruction per operator, which the cost vectors generalize
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Chapter 8 (Code Generation), Section 8.11, dynamic programming code generation, contiguous evaluation and the cost vectors
- Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 9 (Instruction Selection), the dynamic programming algorithm for an optimum tiling
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 10CJ5M Edit this page History Report an error Markdown