Algorithm Search⌘K

Algorithmcore

Sethi-Ullman algorithm

Also called Ershov numbers, Sethi-Ullman numbering.

Labels each node of an expression tree with the fewest registers that evaluate it, then emits code that evaluates the child with the larger label first and stores only when registers run out.

Time
Θ(n) worst
Space
Θ(n) extra
Where
k = the number of registers; n = the number of nodes of the tree
Properties
deterministicofflinerecursive
Origin
Ravi Sethi, Jeffrey D. Ullman, 1970

The Sethi-Ullman algorithm generates code for an expression tree on a machine with kk registers. It gives each node a label: the fewest registers that evaluate the subtree of the node without a store to memory. Then it walks the tree and evaluates the child with the larger label first. For a tree, the label of the root is exactly the minimum register count, and the code is as short as possible. The method needs a tree: for code with shared subexpressions the problem is NP-complete (see the DAG theorem). It also has a fixed instruction set with unit costs. Aho-Johnson code generation handles any set of instructions with costs.

In plain words

To compute a sum of two parts, you must keep the result of the first part in a register while you work on the second part. So the second part has one register less.

The algorithm first finds out how many registers each part needs. A single variable on the left needs one register. A variable on the right can stay in memory, because the machine can read it directly. When the two parts need different counts, the node needs the larger count: do the hungry part first, and the other part fits in what is left. When the two parts need the same count, the node needs one more register.

Then the algorithm writes the code in that order. When there are not enough registers, it computes the right part first, saves it in memory, and reads it back as the right operand at the end.

The problem

The input is a binary expression tree TT with nn nodes and a number k≥1k \ge 1. Each leaf is a variable in memory. Each inner node vv has an operator, a left child a(v)a(v) and a right child b(v)b(v). No algebraic law is used: the operators need not be commutative or associative, and two nodes are different even when their subtrees are equal.

The machine has registers R0,…,Rk−1R_0, \ldots, R_{k-1} and four instructions, as in the model of Sethi and Ullman:

  • load: Ri←xR_i \leftarrow x, where xx is a variable or a temporary in memory,
  • store: t←Rit \leftarrow R_i,
  • operation with a register: Ri←RjopRlR_i \leftarrow R_j \mathbin{op} R_l,
  • operation with memory: Ri←RjopxR_i \leftarrow R_j \mathbin{op} x.

The left operand of an operation is always a register. The output is a program that leaves the value of the tree in R0R_0. The goal is the fewest registers when no store is allowed, and the fewest instructions when the registers are fixed. This is register allocation and evaluation order together, for one tree.

The algorithm

LABEL computes the labels bottom-up. GEN emits the code. In GEN, r=k−ir = k - i is the number of free registers Ri,…,Rk−1R_i, \ldots, R_{k-1}, and ℓ(v)\ell(v) is the label of vv.

  1. LABEL(v, left) ▷ left is true for the root and for each left child
  2. 1if v is a leaf and left then return 1
  3. 2if v is a leaf then return 0 ▷ a right leaf is a memory operand
  4. 3la ← LABEL(a(v), true), lb ← LABEL(b(v), false)
  5. 4if la = lb then return la + 1
  6. 5return max(la, lb)
  7. GEN(v, i) ▷ leave v in R_i, use only R_i .. R_(k-1)
  8. 6if v is a leaf then emit R_i ← v; return
  9. 7if b(v) is a leaf then GEN(a(v), i); emit R_i ← R_i op b(v); return
  10. 8if ℓ(a(v)) ≥ r and ℓ(b(v)) ≥ r then ▷ both children are too big: spill
  11. 9GEN(b(v), i); t ← a new temporary; emit t ← R_i
  12. 10GEN(a(v), i); emit R_i ← R_i op t
  13. 11else if ℓ(a(v)) ≥ ℓ(b(v)) then GEN(a(v), i); GEN(b(v), i + 1); emit R_i ← R_i op R_(i+1)
  14. 12else GEN(b(v), i); GEN(a(v), i + 1); emit R_i ← R_(i+1) op R_i

The first child keeps its result in RiR_i while the second child runs in Ri+1,…,Rk−1R_{i+1}, \ldots, R_{k-1}. Line L12 evaluates the right child first, but the operation still puts the left child on the left, so a non-commutative operator gives the right value. Line L8 is the only place with a store. There, the right child goes to a temporary tt, and line L10 reads tt directly as the right operand, so the algorithm never loads a temporary.

Example

Take (a−b)∗(c+(d−e))(a - b) * (c + (d - e)) with a=7a = 7, b=2b = 2, c=3c = 3, d=10d = 10 and e=4e = 4. Its value is 5⋅9=455 \cdot 9 = 45. The labels are:

node position label label without memory operands
aa, cc, dd left leaf 1 1
bb, ee right leaf 0 1
a−ba - b left child 1 2
d−ed - e right child 1 2
c+(d−e)c + (d - e) right child 2 (equal labels 1 and 1) 2
root ∗* root 2 (labels 1 and 2) 3

With k=2k = 2, the right child has the larger label, so line L12 runs it first:

step instruction value
1 R0←cR_0 \leftarrow c 3
2 R1←dR_1 \leftarrow d 10
3 R1←R1−eR_1 \leftarrow R_1 - e 6
4 R0←R0+R1R_0 \leftarrow R_0 + R_1 9
5 R1←aR_1 \leftarrow a 7
6 R1←R1−bR_1 \leftarrow R_1 - b 5
7 R0←R1∗R0R_0 \leftarrow R_1 * R_0 45

The code uses two registers and seven instructions, and no program for this tree does better. If you evaluate the left child first instead, a−ba - b holds R0R_0 while c+(d−e)c + (d - e) needs two more registers, so the peak is three.

With k=1k = 1, each inner node with an inner right child goes through line L8. The code is R0←dR_0 \leftarrow d, R0←R0−eR_0 \leftarrow R_0 - e, t0←R0t_0 \leftarrow R_0, R0←cR_0 \leftarrow c, R0←R0+t0R_0 \leftarrow R_0 + t_0, t1←R0t_1 \leftarrow R_0, R0←aR_0 \leftarrow a, R0←R0−bR_0 \leftarrow R_0 - b, R0←R0∗t1R_0 \leftarrow R_0 * t_1. That is nine instructions with two stores, which is the minimum for one register.

Correctness

A store-free program is a game on the tree: a register holds the value of one node, a node can enter a register when its operands are there, and any register can be overwritten. The lower bound looks at the last time that each subtree of a node vv was empty before vv is computed. When the two children have the same label LL, the child whose subtree became non-empty last needs LL registers at some moment, and at that moment the other subtree still holds a register. So every program needs at least ℓ(v)\ell(v) registers, even if it interleaves the two subtrees. The upper bound is an induction on GEN: GEN(v,i)(v, i) with ℓ(v)≤k−i\ell(v) \le k - i stays inside Ri,…,Ri+ℓ(v)−1R_i, \ldots, R_{i + \ell(v) - 1}. With fewer registers, GEN stays inside Ri,…,Rk−1R_i, \ldots, R_{k-1} and still computes the right value. The full proof is in the proof file.

Proof: Sethi-Ullman labels are the minimum register count, and GEN reaches itfull

We use the machine and the pseudocode of the page. A tree TT has leaves and inner nodes, and each inner node vv has a left child a(v)a(v) and a right child b(v)b(v). The label ℓ(v)\ell(v) is the value that LABEL returns for vv (lines L1 to L5). We write TvT_v for the subtree of vv.

The game of registers

A store-free program for TT is a sequence of instructions. Each instruction computes one node into a register RiR_i. A load computes a leaf. An operation computes an inner node vv, and it reads the value of a(v)a(v) from a register and the value of b(v)b(v) from a register, or from memory when b(v)b(v) is a leaf. The register keeps the value until another instruction writes to it. The program ends with the value of the root in a register.

Let StS_t be the set of nodes whose value is in some register after tt instructions. One register holds the value of one node, so ∣St∣|S_t| is at most the number of registers that the program uses. A step can add one node vv to SS when the operands of vv are in SS (a memory leaf needs nothing), and it can remove any node, because a register can be overwritten. So it is enough to bound max⁡t∣St∣\max_t |S_t| from below.

Lemma 1 (lower bound). Let vv be a node, and let s≤ts \le t be times such that Ss∩Tv=∅S_s \cap T_v = \varnothing and v∈Stv \in S_t. Then ∣Sτ∩Tv∣≥ℓ(v)|S_\tau \cap T_v| \ge \ell(v) for some τ\tau with s≤τ≤ts \le \tau \le t.

Proof. By induction on the height of vv. If vv is a leaf, then ∣St∩Tv∣=1≥ℓ(v)|S_t \cap T_v| = 1 \ge \ell(v), since ℓ(v)∈{0,1}\ell(v) \in \{0, 1\}.

Let vv be an inner node, with a=a(v)a = a(v), b=b(v)b = b(v), ℓa=ℓ(a)\ell_a = \ell(a) and ℓb=ℓ(b)\ell_b = \ell(b). Let t1t_1 be the first time in (s,t](s, t] with v∈St1v \in S_{t_1}. The step t1t_1 computes vv, so a∈St1−1a \in S_{t_1 - 1}, and b∈St1−1b \in S_{t_1 - 1} unless bb is a leaf that is read from memory. The subtree TaT_a is empty at time ss, so the induction hypothesis on [s,t1−1][s, t_1 - 1] gives a time with at least ℓa\ell_a nodes of Ta⊆TvT_a \subseteq T_v in SS. If b∈St1−1b \in S_{t_1-1}, the same holds for bb. If bb is read from memory, then bb is a right leaf and ℓb=0\ell_b = 0. So some time in [s,t][s, t] has at least max⁡(ℓa,ℓb)\max(\ell_a, \ell_b) nodes of TvT_v in SS. This proves the lemma when ℓa≠ℓb\ell_a \ne \ell_b, by line L5.

Now let ℓa=ℓb=L\ell_a = \ell_b = L. A left child has label at least 1 (line L1 and line L4 or L5), so L≥1L \ge 1. Then bb is not a right leaf of label 0, so b∈St1−1b \in S_{t_1 - 1}. Let sas_a be the last time in [s,t1−1][s, t_1 - 1] with Ta∩Ssa=∅T_a \cap S_{s_a} = \varnothing, and define sbs_b in the same way. Both exist, because ss is such a time. By the choice of sas_a, the subtree TaT_a is not empty at each time in (sa,t1−1](s_a, t_1 - 1], and the same holds for bb.

Assume sa≤sbs_a \le s_b. The induction hypothesis for bb on [sb,t1−1][s_b, t_1 - 1] gives a time τ\tau with ∣Sτ∩Tb∣≥L≥1|S_\tau \cap T_b| \ge L \ge 1. At time sbs_b the subtree TbT_b is empty, so τ>sb≥sa\tau > s_b \ge s_a. So TaT_a is not empty at time τ\tau, and TaT_a and TbT_b are disjoint. This gives ∣Sτ∩Tv∣≥L+1=ℓ(v)|S_\tau \cap T_v| \ge L + 1 = \ell(v), by line L4. If sb<sas_b < s_a, swap the roles of aa and bb. □\square

At time 0 no node is in a register, and at the end the root is in a register. So Lemma 1 with s=0s = 0 gives:

Theorem 1. Each store-free program for TT uses at least ℓ(root)\ell(\mathrm{root}) registers. This holds for every order of the instructions, including orders that interleave the two subtrees of a node, and for programs that compute a node more than once.

GEN reaches the bound

Lemma 2. Let k≥1k \ge 1 and 0≤i<k0 \le i < k, and let vv be a node that is the root or a left child, or an inner node. Then GEN(v,i)(v, i) emits code that leaves the value of vv in RiR_i, writes only Ri,…,Rk−1R_i, \ldots, R_{k-1} and fresh temporaries, and reads only registers that it wrote before. If ℓ(v)≤k−i\ell(v) \le k - i, the code has no store and writes only Ri,…,Ri+ℓ(v)−1R_i, \ldots, R_{i + \ell(v) - 1}.

Proof. By induction on the height of vv. Let r=k−i≥1r = k - i \ge 1. A leaf that reaches line L6 is the root or a left child, so ℓ(v)=1≤r\ell(v) = 1 \le r. The load writes only RiR_i.

Let vv be an inner node with children aa and bb and labels ℓa≥1\ell_a \ge 1 and ℓb\ell_b.

Line L7, bb is a leaf. Then ℓb=0\ell_b = 0 and ℓ(v)=ℓa\ell(v) = \ell_a by line L5. By induction, GEN(a,i)(a, i) leaves aa in RiR_i, and the operation reads bb from memory and writes RiR_i. The bounds of aa carry over to vv.

Lines L8 to L10, ℓa≥r\ell_a \ge r and ℓb≥r\ell_b \ge r. GEN(b,i)(b, i) leaves bb in RiR_i, and the store saves it in a fresh temporary tt. GEN(a,i)(a, i) then leaves aa in RiR_i and does not write tt. The operation reads aa from RiR_i and bb from tt. In this case ℓ(v)>r\ell(v) > r: if ℓa=ℓb\ell_a = \ell_b then ℓ(v)=ℓa+1>r\ell(v) = \ell_a + 1 > r, and else ℓ(v)=max⁡(ℓa,ℓb)>r\ell(v) = \max(\ell_a, \ell_b) > r. So the claim about ℓ(v)≤r\ell(v) \le r is empty here.

Line L11, ℓa≥ℓb\ell_a \ge \ell_b, not both at least rr. Then ℓb<r\ell_b < r: either ℓb<r\ell_b < r directly, or ℓa<r\ell_a < r and ℓb≤ℓa\ell_b \le \ell_a. Since bb is an inner node, ℓb≥1\ell_b \ge 1, so r≥2r \ge 2 and i+1<ki + 1 < k. GEN(a,i)(a, i) leaves aa in RiR_i. GEN(b,i+1)(b, i + 1) leaves bb in Ri+1R_{i+1}, and it does not write RiR_i. The operation reads both and writes RiR_i. If ℓ(v)≤r\ell(v) \le r: then ℓa≤ℓ(v)\ell_a \le \ell(v), so GEN(a,i)(a, i) has no store and stays in Ri,…,Ri+ℓa−1R_i, \ldots, R_{i + \ell_a - 1}. Also ℓb≤ℓ(v)−1\ell_b \le \ell(v) - 1: if ℓa>ℓb\ell_a > \ell_b this follows from ℓ(v)=ℓa\ell(v) = \ell_a, and if ℓa=ℓb\ell_a = \ell_b from ℓ(v)=ℓa+1\ell(v) = \ell_a + 1. So GEN(b,i+1)(b, i + 1) has no store and stays in Ri+1,…,Ri+ℓ(v)−1R_{i+1}, \ldots, R_{i + \ell(v) - 1}.

Line L12, ℓa<ℓb\ell_a < \ell_b. The same argument with aa and bb swapped. Here ℓa<ℓb\ell_a < \ell_b and not both at least rr give ℓa<r\ell_a < r, and ℓa≥1\ell_a \ge 1 gives r≥2r \ge 2. The operation writes Ri←Ri+1opRiR_i \leftarrow R_{i+1} \mathbin{op} R_i, so the left operand is still aa. If ℓ(v)≤r\ell(v) \le r, then ℓ(v)=ℓb\ell(v) = \ell_b, GEN(b,i)(b, i) stays in Ri,…,Ri+ℓb−1R_i, \ldots, R_{i+\ell_b-1}, and GEN(a,i+1)(a, i+1) stays in Ri+1,…,Ri+ℓaR_{i+1}, \ldots, R_{i + \ell_a} with ℓa≤ℓb−1\ell_a \le \ell_b - 1. □\square

Theorem 2. For each k≥1k \ge 1, GEN(root,0)(\mathrm{root}, 0) leaves the value of the tree in R0R_0 and uses only R0,…,Rk−1R_0, \ldots, R_{k-1}. If k≥ℓ(root)k \ge \ell(\mathrm{root}), the code has no store and uses exactly the registers R0,…,Rℓ(root)−1R_0, \ldots, R_{\ell(\mathrm{root}) - 1}. With Theorem 1, ℓ(root)\ell(\mathrm{root}) is the minimum number of registers of a store-free program for TT.

Proof. Lemma 2 with v=rootv = \mathrm{root} and i=0i = 0 gives all claims except "exactly". Theorem 1 shows that the store-free code cannot use fewer than ℓ(root)\ell(\mathrm{root}) registers, and Lemma 2 shows that it uses no register outside the first ℓ(root)\ell(\mathrm{root}). ■\blacksquare

The order. The proof of Lemma 2 shows why the child with the larger label goes first. While the second child runs, the first child holds one register. If the first child has the smaller label ℓ1<ℓ2\ell_1 < \ell_2, the peak is at least ℓ2+1\ell_2 + 1 when the order is not interleaved, which is more than ℓ(v)=ℓ2\ell(v) = \ell_2.

Length. Each inner node gives one operation, each leaf that is the root or a left child gives one load, and each pass through line L8 gives one store. No instruction loads a temporary. Sethi and Ullman prove that their algorithm gives a program with the fewest instructions on their machine when no algebraic law is used. This file does not repeat that proof.

Complexity

LABEL visits each node once and does constant work there, so it takes Θ(n)\Theta(n) time. GEN also visits each node once. It emits one operation for each inner node, one load for each leaf that is the root or a left child, and at most one store for each inner node. So the code has Θ(n)\Theta(n) instructions, and GEN takes Θ(n)\Theta(n) time. A unit step is the work at one node. The extra space is Θ(n)\Theta(n) for the labels and the recursion stack, whose depth is the height of the tree.

Properties

  • Exact for trees. The label of the root is the minimum register count over all store-free programs, in every evaluation order. The proof file proves this.
  • Few registers suffice. A label ℓ\ell in the variant without memory operands needs at least 2ℓ−12^{\ell - 1} leaves, because a label goes up only when two children have the same label. Each label with memory operands is at most the label without them. So the label is at most 1+lg⁡(number of leaves)1 + \lg(\text{number of leaves}), and a complete tree of 32 leaves needs only 5 registers with memory operands.
  • A chain needs one register. A left-deep tree such as ((a+b)+c)+d((a + b) + c) + d has label 1.
  • Shortest code. On their machine and with no algebraic law, Sethi and Ullman prove that the program has the fewest instructions. The code also loads each variable once and never loads a temporary.

Variants and improvements

  • Ershov numbers. On a machine with no memory operand, each leaf needs a register, so each leaf gets the label 1. These labels are the Horton-Strahler numbers of the tree. A spill then needs a store and a later load. The example tree has label 3 in this variant.
  • Commutative and associative operators. Sethi and Ullman also reorder the operands of commutative operators, and regroup associative ones, to find an equal expression with the shortest code.
  • Unary operators. A unary node gets the label of its child.
  • Instruction costs. Aho-Johnson code generation replaces the fixed instructions by any set of tree patterns with costs and computes a cost for each number of free registers. The Sethi-Ullman algorithm is the special case with one pattern per operator.

When to use it

Use it to order the evaluation of expression trees in a simple compiler, or in the code generator of a tree-walking back end, when registers are few. Use the labels alone to decide which operand of a node to evaluate first. For straight-line code with named values, use local register allocation. For a machine with complex addressing modes and costs, use tree tiling by dynamic programming or a BURS generator.

Pitfalls

  • Left to right. A fixed left-to-right order can use more registers. The example needs three registers in that order and two in the labeled order.
  • Wrong operand order. In line L12 the right child is in RiR_i, but it is still the right operand. Writing Ri←RiopRi+1R_i \leftarrow R_i \mathbin{op} R_{i+1} there computes b−ab - a for a subtraction.
  • The wrong variant. Label 0 for a right leaf is right only when the machine can read that operand from memory. On a load-store machine it undercounts.
  • Shared subtrees. On a DAG, a node with two parents keeps its register until both parents are done. The labels then give no bound, and the exact problem is NP-complete.
  • Algebraic laws. The minimum is over programs that keep the tree as it is. With a commutative ++, the tree c+(d−e)c + (d - e) can become (d−e)+c(d - e) + c, which has label 1 instead of 2.
  • Calls inside the tree. A call clobbers registers that the calling convention does not save, so a tree with calls needs more care than the labels show.

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.

sethi_ullman_numbering.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sethi-ullman-numbering/. The authors are listed in prov/HKPTPW.jsonl.

"""Sethi-Ullman labels and code generation for expression trees.

An expression is a variable name (a str) or a tuple (op, left, right) with
op in "+", "-", "*". The same variable can occur at many leaves, but each
leaf is a separate node of the tree.

The machine has registers R0 .. R(k-1) and four instructions:
    ("load", i, x)          Ri <- x          x is a variable or a temporary
    ("op", o, i, j, l)      Ri <- Rj o Rl
    ("opm", o, i, j, x)     Ri <- Rj o x     the right operand is in memory
    ("store", t, i)         t <- Ri
The left operand of an operation is always a register.
"""

from typing import Union

Expr = Union[str, tuple]

OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b}


def is_leaf(e: Expr) -> bool:
    return isinstance(e, str)


def annotate(e: Expr, memory_operands: bool = True, is_left: bool = True) -> tuple:
    """Return a copy of e where each node carries its label.

    A leaf becomes ("leaf", x, label). An inner node becomes
    (op, left, right, label). With memory_operands=False each leaf gets 1,
    which gives the Ershov numbers of a machine with no memory operands.
    """
    if is_leaf(e):
        if is_left or not memory_operands:  # @line L1
            return ("leaf", e, 1)
        return ("leaf", e, 0)  # @line L2
    a = annotate(e[1], memory_operands, True)  # @line L3
    b = annotate(e[2], memory_operands, False)
    la, lb = a[-1], b[-1]
    if la == lb:  # @line L4
        return (e[0], a, b, la + 1)
    return (e[0], a, b, max(la, lb))  # @line L5


def label(e: Expr, memory_operands: bool = True) -> int:
    """The label of the root: the fewest registers that evaluate e without stores."""
    return annotate(e, memory_operands)[-1]


def generate(e: Expr, k: int) -> tuple[list[tuple], int]:
    """Return (code, number of stores) that leaves the value of e in R0.

    The code uses only R0 .. R(k-1). It stores to temporaries only when the
    label of e is larger than k.
    """
    if k < 1:
        raise ValueError("need at least one register")
    code: list[tuple] = []
    temps = [0]

    def gen(n: tuple, i: int) -> None:
        # Put the value of n in Ri. Use only Ri .. R(k-1).
        r = k - i
        if n[0] == "leaf":
            code.append(("load", i, n[1]))  # @line L6
            return
        op, a, b = n[0], n[1], n[2]
        if b[0] == "leaf":
            gen(a, i)  # @line L7
            code.append(("opm", op, i, i, b[1]))
        elif a[-1] >= r and b[-1] >= r:  # @line L8
            gen(b, i)  # @line L9
            t = "t%d" % temps[0]
            temps[0] += 1
            code.append(("store", t, i))
            gen(a, i)  # @line L10
            code.append(("opm", op, i, i, t))
        elif a[-1] >= b[-1]:
            gen(a, i)  # @line L11
            gen(b, i + 1)
            code.append(("op", op, i, i, i + 1))
        else:
            gen(b, i)  # @line L12
            gen(a, i + 1)
            code.append(("op", op, i, i + 1, i))

    gen(annotate(e, True), 0)
    return code, temps[0]


def evaluate(e: Expr, env: dict[str, int]) -> int:
    """Evaluate e directly."""
    if is_leaf(e):
        return env[e]
    return OPS[e[0]](evaluate(e[1], env), evaluate(e[2], env))


def run(code: list[tuple], env: dict[str, int], k: int) -> int:
    """Run the code on a machine with k registers and return R0."""
    reg: dict[int, int] = {}
    mem = dict(env)
    for ins in code:
        if ins[0] == "load":
            _, i, x = ins
            assert 0 <= i < k
            reg[i] = mem[x]
        elif ins[0] == "op":
            _, o, i, j, l = ins
            assert 0 <= i < k
            reg[i] = OPS[o](reg[j], reg[l])
        elif ins[0] == "opm":
            _, o, i, j, x = ins
            assert 0 <= i < k
            reg[i] = OPS[o](reg[j], mem[x])
        else:
            _, t, i = ins
            assert t not in env
            mem[t] = reg[i]
    return reg[0]
test_sethi_ullman_numbering.py 206 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sethi-ullman-numbering/. The authors are listed in prov/HKPTPW.jsonl.

import random
from collections import deque
from functools import lru_cache

from sethi_ullman_numbering import evaluate, generate, label, run


def random_tree(rng: random.Random, inner: int) -> object:
    """A random expression tree with the given number of inner nodes."""
    if inner == 0:
        return rng.choice("abcd")
    left = rng.randint(0, inner - 1)
    return (rng.choice("+-*"), random_tree(rng, left), random_tree(rng, inner - 1 - left))


def flatten(e: object) -> tuple[list, list]:
    """Number the nodes. Return (kids, is_left) lists; node 0 is the root."""
    kids: list = []
    is_left: list = []

    def walk(n: object, left: bool) -> int:
        i = len(kids)
        kids.append(None)
        is_left.append(left)
        if not isinstance(n, str):
            kids[i] = (walk(n[1], True), walk(n[2], False))
        return i

    walk(e, True)
    return kids, is_left


def min_registers(e: object, memory_operands: bool = True) -> int:
    """Brute force: the smallest peak of live register values over all
    store-free evaluation orders, interleaved or not."""
    kids, _ = flatten(e)
    n = len(kids)
    parent = [-1] * n
    for i, ks in enumerate(kids):
        if ks:
            parent[ks[0]] = parent[ks[1]] = i

    def live(done: int) -> int:
        return sum(1 for u in range(n) if done >> u & 1 and (parent[u] < 0 or not done >> parent[u] & 1))

    @lru_cache(maxsize=None)
    def best(done: int) -> int:
        if done >> 0 & 1:
            return 0
        res = 10**9
        for v in range(n):
            if done >> v & 1:
                continue
            if kids[v] is None:
                nxt = done | 1 << v  # load a leaf
            else:
                a, b = kids[v]
                if not done >> a & 1:
                    continue
                if done >> b & 1:
                    nxt = done | 1 << v
                elif kids[b] is None and memory_operands:
                    nxt = done | 1 << v | 1 << b  # b is a memory operand
                else:
                    continue
            res = min(res, max(live(nxt), best(nxt)))
        return res

    return best(0)


def min_instructions(e: object, k: int) -> int:
    """Brute force: the fewest instructions of any program for e with k registers.

    Status of a node: 0 not computed, 1 in a register, 2 in memory,
    3 in both, 4 used by its parent. Leaves start in memory. Loads, stores
    and operations cost 1. Forgetting the register copy of a value that is
    also in memory costs 0.
    """
    kids, _ = flatten(e)
    n = len(kids)
    start = tuple(2 if ks is None else 0 for ks in kids)
    dist = {start: 0}
    dq = deque([start])
    while dq:
        s = dq.popleft()
        d = dist[s]
        if s[0] in (1, 3):
            return d
        regs = sum(1 for x in s if x in (1, 3))
        moves = []
        for v in range(n):
            x = s[v]
            if x == 2 and regs < k:
                moves.append((v, 3, 1))  # load
            if x == 1:
                moves.append((v, 3, 1))  # store
            if x == 3:
                moves.append((v, 2, 0))  # forget the register copy
            if x == 0 and kids[v] is not None:
                a, b = kids[v]
                if s[a] in (1, 3) and s[b] in (1, 2, 3):
                    t = list(s)
                    t[a] = t[b] = 4
                    t[v] = 1
                    moves.append((tuple(t), None, 1))
        for v, x, c in moves:
            if x is None:
                t = v
            else:
                t = s[:v] + (x,) + s[v + 1:]
            if t not in dist or dist[t] > d + c:
                dist[t] = d + c
                if c == 0:
                    dq.appendleft(t)
                else:
                    dq.append(t)
    raise AssertionError("no program")


def used_registers(code: list) -> int:
    regs = set()
    for ins in code:
        if ins[0] == "load":
            regs.add(ins[1])
        elif ins[0] in ("op", "opm"):
            regs.update(r for r in ins[2:5] if isinstance(r, int))
        else:
            regs.add(ins[2])
    return len(regs)


def test_example() -> None:
    # (a - b) * (c + (d - e)), the tree of the page.
    e = ("*", ("-", "a", "b"), ("+", "c", ("-", "d", "e")))
    assert label(e) == 2
    assert label(e, memory_operands=False) == 3
    code, stores = generate(e, 2)
    assert stores == 0
    assert code == [
        ("load", 0, "c"),
        ("load", 1, "d"),
        ("opm", "-", 1, 1, "e"),
        ("op", "+", 0, 0, 1),
        ("load", 1, "a"),
        ("opm", "-", 1, 1, "b"),
        ("op", "*", 0, 1, 0),
    ]
    env = {"a": 7, "b": 2, "c": 3, "d": 10, "e": 4}
    assert run(code, env, 2) == evaluate(e, env) == 45
    code1, stores1 = generate(e, 1)
    assert stores1 == 2 and len(code1) == 9 == min_instructions(e, 1)
    assert run(code1, env, 1) == 45
    assert len(code) == 7 == min_instructions(e, 2)


def test_leaf_and_chain() -> None:
    assert label("x") == 1
    chain = "a"
    for v in "bcdefg":
        chain = ("+", chain, v)
    assert label(chain) == 1
    code, stores = generate(chain, 1)
    assert stores == 0 and len(code) == 7


def test_label_is_minimum_register_count() -> None:
    rng = random.Random(1970)
    for _ in range(300):
        e = random_tree(rng, rng.randint(0, 5))
        assert label(e) == min_registers(e)
        assert label(e, False) == min_registers(e, False)
        code, stores = generate(e, label(e))
        assert stores == 0
        assert used_registers(code) == label(e)


def test_complete_trees_need_more_registers() -> None:
    e = "a"
    for depth in range(1, 6):
        e = ("+", e, e)
        assert label(e) == depth
        assert label(e, False) == depth + 1


def test_code_computes_the_value() -> None:
    rng = random.Random(7)
    for _ in range(400):
        e = random_tree(rng, rng.randint(0, 12))
        env = {v: rng.randint(-9, 9) for v in "abcd"}
        for k in range(1, 5):
            code, stores = generate(e, k)
            assert run(code, env, k) == evaluate(e, env)
            assert (stores == 0) == (label(e) <= k)


def test_fewest_instructions() -> None:
    rng = random.Random(1976)
    for _ in range(150):
        e = random_tree(rng, rng.randint(1, 6))
        for k in (1, 2, 3):
            code, _ = generate(e, k)
            assert len(code) == min_instructions(e, k)

History

Sethi and Ullman published the labels, the algorithm and the proofs in the Journal of the ACM in 1970. They prove that the code is shortest when no algebraic law applies, and they extend the method to commutative and associative operators. The dragon book calls the labels Ershov numbers, after a 1958 paper by A. P. Ershov on the programming of arithmetic operations.

References

  1. Ravi Sethi and J. D. Ullman, The generation of optimal code for arithmetic expressions, Journal of the ACM 17(4), 1970, 715-728, the labels of the nodes, the algorithm for a machine with N registers, and the proof that its programs are shortest when no algebraic law applies; the extension to commutative and associative operators
  2. A. P. Ershov, On programming of arithmetic operations, Communications of the ACM 1(8), 1958, 3-6, the whole paper, an English translation of a 1958 note in Doklady AN SSSR
  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.10, Ershov numbers and the evaluation of expressions with too few registers
  4. Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 11 (Register Allocation), the part on register allocation for trees

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