Algorithm Search⌘K

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.

Time
Θ(n r) worst
Space
Θ(n r) extra
Where
n = the number of nodes of the tree; r = the number of registers
Properties
deterministicofflinerecursive
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 rr registers. It solves the instruction selection problem for trees and includes the register limit. For each node and for each number jj 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 TT with nn nodes and a machine. The nodes on this page are CONST kk, VAR xx (a variable in memory), MEM aa (load the word at address aa), ADD and MUL. The machine has registers R0,…,Rr−1R_0, \ldots, R_{r-1} with r≥2r \ge 2. 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 t←Rit \leftarrow R_i costs s=3s = 3. The output is a program that leaves the value of TT in R0R_0, never needs more than rr 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

C[v][j]C[v][j] is the least cost to compute TvT_v into a register when jj registers are free, and C[v][0]C[v][0] is the least cost to have it in memory. All entries start at ∞\infty.

  1. LABEL(v)
  2. 1for each child u of v do LABEL(u)
  3. 2for each pattern p that matches at v do ▷ LD matches here only at a variable
  4. 3base ← cost(p) + sum of C[m][0] over the memory operands m of p that are not variables
  5. 4for each order h_1, ..., h_q of the register operands of p do
  6. 5for j ← max(1, q) to r do total ← base + sum over t of C[h_t][j - t + 1]
  7. 6if total < C[v][j] then C[v][j] ← total; remember (p, the order)
  8. 7if v is a variable then C[v][0] ← 0
  9. 8else C[v][0] ← C[v][r] + s ▷ compute with all registers, then store
  10. 9for j ← 1 to r do C[v][j] ← min(C[v][j], C[v][0] + cost(LD)) ▷ store, then load back
  11. GENERATE(root)
  12. 10for each subtree that the chosen plan keeps in memory, deepest first:
  13. emit its code with all r registers free, then a store to a new temporary
  14. 11emit the code of the root with all r registers free

The code of a node vv with free registers Ri,…,Ri+j−1R_i, \ldots, R_{i+j-1} runs the operand hth_t in Ri+t−1,…,Ri+j−1R_{i+t-1}, \ldots, R_{i+j-1}, so the earlier operands wait in Ri,…,Ri+t−2R_i, \ldots, R_{i+t-2}. Then the instruction of vv writes RiR_i. 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 T=(a∗b)+(c∗MEM(a+8))T = (a * b) + (c * \mathrm{MEM}(a + 8)) and r=2r = 2. The vectors (C[v][0],C[v][1],C[v][2])(C[v][0], C[v][1], C[v][2]) are:

node C[v][0]C[v][0] C[v][1]C[v][1] C[v][2]C[v][2] choice for j=2j = 2
each variable 0 3 3 LD
8 4 1 1 LI
a+8a + 8 7 4 4 ADDI
MEM(a+8)(a + 8) 9 6 6 LDO, which covers the ADD too
a∗ba * b 12 15 9 MUL
c∗MEM(a+8)c * \mathrm{MEM}(a+8) 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 1+9+18=281 + 9 + 18 = 28 or 1+12+15=281 + 12 + 15 = 28: one product has to run with one free register, and C[⋅][1]C[\cdot][1] includes a store and a load. MADD needs three registers. ADDM costs 3+9+15=273 + 9 + 15 = 27: the right product is computed first and stored, and the left product then has both registers. The code is:

step instruction cost
1 R0←cR_0 \leftarrow c 3
2 R1←aR_1 \leftarrow a 3
3 R1←MEM(R1+8)R_1 \leftarrow \mathrm{MEM}(R_1 + 8) 3
4 R0←R0∗R1R_0 \leftarrow R_0 * R_1 3
5 t0←R0t_0 \leftarrow R_0 3
6 R0←aR_0 \leftarrow a 3
7 R1←bR_1 \leftarrow b 3
8 R0←R0∗R1R_0 \leftarrow R_0 * R_1 3
9 R0←R0+t0R_0 \leftarrow R_0 + t_0 3

The total is 27. With r=3r = 3 the cost falls to 20: load aa into R0R_0, compute the right product in R1R_1 with two free registers (12), load bb into R2R_2, 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 r=3r = 3 is 22.

Correctness

LABEL is a dynamic program over normal-form plans. A plan for vv with jj registers is a pattern at vv, an order of its register operands, plans with j,j−1,…j, j-1, \ldots registers for those operands, and plans in memory for its memory operands, or else a store and a load of vv. The parts of a plan are independent, so the cheapest plan is made of cheapest parts, and an induction on the tree shows that C[v][j]C[v][j] 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 C[root][r]C[\mathrm{root}][r] 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 r≥2r \ge 2 registers. Each instruction is a pattern pp with a cost c(p)>0c(p) > 0. A leaf of a pattern is a register operand, an immediate constant or a memory operand. A store costs s>0s > 0 and a load of a memory operand into a register costs cld>0c_{\mathrm{ld}} > 0. For a node vv we write TvT_v for its subtree. When pp matches at vv, the register leaves of pp sit on nodes h1,…,hqh_1, \ldots, h_q and the memory leaves on nodes m1,…,mem_1, \ldots, m_e. These nodes are the operand nodes of pp at vv, and their subtrees are disjoint.

Part 1: enough registers

A tiling of TvT_v is a pattern pp that matches at vv, a tiling of ThT_h for each register operand node hh of pp, and nothing for a constant or a variable. Its cost is the sum of the costs of its patterns. Let τ(v)\tau(v) be the least cost of a tiling of TvT_v in which every memory operand is a variable.

Lemma 1. τ(v)=min⁡p(c(p)+∑t=1qτ(ht))\tau(v) = \min_p \big( c(p) + \sum_{t=1}^{q} \tau(h_t) \big), where pp ranges over the patterns that match at vv and whose memory operands are variables.

Proof. A tiling of TvT_v is a choice of pp and independent tilings of the disjoint subtrees ThtT_{h_t}, and its cost is c(p)c(p) plus their costs. For a fixed pp the sum is least when each part is least. Take the minimum over pp. □\square

This is the case of Part 2 with r≥nr \ge n, on the machine of the page. With j≥∣Tv∣j \ge |T_v| free registers, the operand hth_t gets j−t+1≥∣Tht∣j - t + 1 \ge |T_{h_t}| registers, so no register limit binds. A plan that stores a subtree mm pays τ(m)+s\tau(m) + s for it, and then either a load of cost 3 or the memory form ADDM of cost 3. The plan that keeps mm in a register pays τ(m)\tau(m) and the register form ADD of cost 1, or nothing for the load. So a store never helps there, and C[root][r]=τ(root)C[\mathrm{root}][r] = \tau(\mathrm{root}).

Part 2: a limited number of registers

A program for TT computes nodes into registers by instructions, writes registers to temporaries by stores, and leaves the root in R0R_0. An instruction for vv 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 rr registers hold values that the program still needs.

Normal-form plans. For 0≤j≤r0 \le j \le r define the set P(v,j)\mathcal{P}(v, j) of plans, by induction on TvT_v:

  • j=0j = 0 (the value of vv ends in memory). If vv is a variable, the empty plan, of cost 0. Else a plan of P(v,r)\mathcal{P}(v, r) followed by a store, of cost cost+s\mathrm{cost} + s.
  • j≥1j \ge 1 (the value of vv ends in a register, and only jj registers are free). Either a reload: a plan of P(v,0)\mathcal{P}(v, 0) when vv is not a variable, followed by a load. Or a pattern pp that matches at vv with q≤jq \le j register operand nodes, an order h1,…,hqh_1, \ldots, h_q of them, a plan of P(mi,0)\mathcal{P}(m_i, 0) for each memory operand node, and a plan of P(ht,j−t+1)\mathcal{P}(h_t, j - t + 1) for each tt. A variable as a memory operand needs the empty plan. The cost is c(p)c(p) plus the costs of the parts.

Lemma 2. After LABEL(v)(v), C[v][j]C[v][j] is the least cost of a plan in P(v,j)\mathcal{P}(v, j), for each 0≤j≤r0 \le j \le r.

Proof. By induction on the height of vv. Line L1 handles the children first, so the claim holds for each operand node. Lines L2 to L6 try each pattern that matches at vv, each order of its register operand nodes, and each jj with max⁡(1,q)≤j≤r\max(1, q) \le j \le r. For a fixed pattern and order, the cost of a plan is c(p)c(p) plus a sum of independent parts. By the induction hypothesis the least part costs are C[mi][0]C[m_i][0] and C[ht][j−t+1]C[h_t][j - t + 1]. 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, C[v][j]C[v][j] is the least cost of a plan of the pattern kind, for j≥1j \ge 1.

Let D[v][j]D[v][j] be this value. A reload plan for j≥1j \ge 1 costs at least D[v][r]+s+cld>D[v][r]D[v][r] + s + c_{\mathrm{ld}} > D[v][r], because its inner plan of P(v,r)\mathcal{P}(v, r) is a pattern plan or another reload, and a reload inside a reload only adds cost. So the least plan of P(v,r)\mathcal{P}(v, r) is a pattern plan, of cost D[v][r]D[v][r]. Lines L7 and L8 then set C[v][0]C[v][0] to the least cost in P(v,0)\mathcal{P}(v, 0): 0 for a variable, and D[v][r]+sD[v][r] + s else. Line L9 sets C[v][j]=min⁡(D[v][j],C[v][0]+cld)C[v][j] = \min(D[v][j], C[v][0] + c_{\mathrm{ld}}), which is the least cost over both kinds of plans of P(v,j)\mathcal{P}(v, j). For j=rj = r this is still D[v][r]D[v][r]. □\square

Lemma 3. GENERATE emits a program of cost C[root][r]C[\mathrm{root}][r]. It leaves the value of the tree in R0R_0, and at each moment at most rr 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 vv with jj free registers Ri,…,Ri+j−1R_i, \ldots, R_{i+j-1} runs the operand hth_t with the j−t+1j - t + 1 registers Ri+t−1,…,Ri+j−1R_{i+t-1}, \ldots, R_{i+j-1}. By induction it leaves hth_t in Ri+t−1R_{i+t-1} and does not write Ri,…,Ri+t−2R_i, \ldots, R_{i+t-2}, where the earlier operands wait. Then the instruction for vv reads its operands and writes RiR_i. So each part uses only its own registers, and the count of needed registers never exceeds rr. A reload loads the temporary of vv into RiR_i. 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 C[root][r]C[\mathrm{root}][r] by Lemma 2. □\square

Lemma 4. C[v][j]≥C[v][j+1]C[v][j] \ge C[v][j+1] for 1≤j<r1 \le j < r.

Proof. By induction on the height of vv. A pattern plan with jj registers is also allowed with j+1j + 1 registers, and the induction hypothesis gives C[ht][j−t+2]≤C[ht][j−t+1]C[h_t][j - t + 2] \le C[h_t][j - t + 1] for each operand. The reload term is the same for each jj. □\square

Theorem. For a tree TT and a machine of the class of Aho and Johnson, C[root][r]C[\mathrm{root}][r] is the least cost of a program for TT, 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 P(root,r)\mathcal{P}(\mathrm{root}, r). So the least cost of a program is the least cost of a plan, which is C[root][r]C[\mathrm{root}][r] by Lemma 2. Lemma 3 shows that GENERATE reaches it. ■\blacksquare

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 qq of register operands of a pattern and rr are constants. LABEL does O(patterns⋅q!⋅r⋅q)O(\text{patterns} \cdot q! \cdot r \cdot q) 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 qq register operands and each jj, and sums qq entries. That is O(P⋅q!⋅q⋅r)O(P \cdot q! \cdot q \cdot r) per node for PP patterns, and Θ(nr)\Theta(n r) for the whole tree when the machine is fixed, because LABEL fills n(r+1)n (r + 1) entries. For a fixed rr 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 Θ(nr)\Theta(n r) 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. C[v][j]≥C[v][j+1]C[v][j] \ge C[v][j+1], because each plan for jj registers is also a plan for j+1j + 1.
  • 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 rr 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 jj. Then C[v]C[v] 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 tt-th operand gets j−t+1j - t + 1 registers, not jj. Giving each operand all jj registers undercounts.
  • One order only. The example with r=3r = 3 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.

aho_johnson_code_generation.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example