Algorithm Search⌘K

Algorithmresearch

Copy-and-patch compilation

Also called stencil-based code generation.

Generates code very fast by copying precompiled binary stencils for each operation and patching holes with operands and addresses.

Time
O(n) worst
Space
O(n) extra
Where
n = the size of the IR program, counting instructions, terminators and phi operands

Copy-and-patch compilation turns a program in an intermediate representation into machine code by copying ready-made pieces of machine code. Before any program is compiled, a library of stencils is built: for each kind of operation, and for each variant of its operands, a short sequence of machine code with holes, places whose value is not yet known, such as the address of a variable, a constant, or the address of the next piece of code. The compiler then picks one stencil for each instruction of the program, copies its bytes into a buffer, and writes the right values into its holes. There is no instruction selection, no register allocation by search and no encoding of instructions at compile time: all of that was done once, when the stencils were made. Xu and Kjolstad introduced the method in 2021. They make the stencils by compiling C++ templates with an ordinary optimizing compiler, and the holes are references to external symbols, which the object file lists as relocations.

In plain words

A normal compiler builds each machine instruction one by one, which takes time. A copy-and-patch compiler works like filling in forms. For each kind of step, such as "add two variables" or "jump if a value is zero", it has a ready piece of machine code with a few blank fields. To compile a program, it takes the piece for each step, puts the pieces one after another in memory, and fills in the blanks: which variable to read, which number to use, and where to jump.

This is very fast, because copying and filling in blanks is cheap, and the pieces were made in advance by a good compiler. The code is not as good as the code of an optimizing compiler, because each piece is made without knowing its neighbours, but it is much better than interpreting the program.

The problem

Input: a program in three-address code, made of basic blocks that form a control flow graph. Each block has a list of instructions x = k, x = a, x = a op b and phi instructions at its top, and ends with a terminator jump L, br a L1 L2 or ret a. An operand aa is a variable or an integer constant.

Output: machine code for a target machine that, run on any arguments, has the same outcome as the IR program: the same returned value, a trap in the same cases (division by zero, a shift out of range), and, in the implementation of this page, running out of fuel at the same point.

The goal is to produce this code in time linear in the size of the program, with a small constant, so that a just-in-time compiler can use it as its first tier.

The algorithm

The target of this page is a small word machine with two registers r0 and r1 and an array of slots, one per variable. Its instructions are LDS r s (load slot ss), LDI r k (load a constant), STS s r (store), ALU i (r0 = r0 opi_i r1, or trap), JMP a, BR r a b (go to aa if r≠0r \ne 0, else to bb), RET r, and TICK, which uses one unit of fuel so that runs can be compared with the interpreter step by step. A real system copies x86 or ARM bytes instead, and has no TICK.

The stencil library. A stencil is a pair: a sequence of machine words with a 0 at each hole, and a list of holes, each an offset and a name. The library has one stencil per key:

  • const: TICK, LDI r0 aa, STS xx r0.
  • copy, for aa a variable or a constant: TICK, load aa into r0, STS xx r0.
  • op, for each operator and each of the four cases variable or constant for aa and for bb: TICK, load aa into r0, load bb into r1, ALU op, STS xx r0.
  • br: TICK, load aa into r0, BR r0 tt ff. ret: TICK, load aa into r0, RET r0.
  • jump: TICK, JMP tt. jump-next: TICK alone, for a jump to the code placed right after it.
  • For phis: phi: TICK, load aa into r0, STS xx r0, where xx is a temporary; move: LDS r0 aa, STS xx r0; goto: JMP tt.

"Load aa" means LDS for a variable and LDI for a constant, so the variant is chosen by the kind of the operand. With 14 operators the library has 69 stencils. The largest has 12 words.

COPY-AND-PATCH(P)
L1  give each variable of P a slot, and give k temporaries their own slots,
    where k is the largest number of phis in one block
L2  pc ← 0; pieces ← empty list; stubs ← empty list
L3  for each block B of P, in order:
L4      addr[B] ← pc
L5      for each instruction ι of B that is not a phi:
L6          pick the stencil S for the kind of ι and the kinds of its operands
L7          append (pc, S, the hole values of ι) to pieces; pc ← pc + |S|
L8      for the terminator of B, do the same, where the target of an edge B → C is
        the stub of the edge if C has phis, else C itself; a jump to the block placed
        right after B uses jump-next; record each new stub B → C in stubs
L9  for each stub B → C, with phis x_1 = φ(..., B: a_1, ...), ..., x_m = φ(..., B: a_m, ...):
L10     addr[B → C] ← pc
L11     append phi stencils that read a_1 .. a_m into temporaries t_1 .. t_m,
        then move stencils x_i ← t_i for i = 1 .. m, then goto C
L12 code ← a buffer of pc words
L13 for each piece (p, S, values) in pieces:
L14     copy the words of S to code[p .. p + |S| - 1]
L15     for each hole (o, h) of S: code[p + o] ← the value of h, where a variable
        becomes its slot, a constant stays itself and a block or stub becomes addr[.]
L16 return code

Lines L2 to L11 are the first pass: they choose and place the stencils. The size of every stencil is known in advance, so every address is known at the end of this pass, including the addresses of blocks placed later, which forward branches need. Lines L12 to L15 are the second pass: copy and patch. The phi stubs read all operands before they write any phi variable, which gives the parallel meaning of phis, as in out-of-SSA translation, where the same problem is known as the lost copy and swap problems.

Example

Take the program that sums 0+1+⋯+(n−1)0 + 1 + \dots + (n-1):

# params: n
B0:  s = 0;  i = 0;  jump B1
B1:  c = i < n;  br c B2 B3
B2:  s = s + i;  i = i + 1;  jump B1
B3:  ret s

L1 gives the slots n = 0, s = 1, i = 2, c = 3. There are no phis, so no stubs and no temporaries. The first pass places 9 stencils:

address stencil size hole values
0 const 7 a = 0, x = 1
7 const 7 a = 0, x = 2
14 jump-next 1 none
15 op<, variable and variable 12 a = 2, b = 0, x = 3
27 br, variable 8 a = 3, t = 35, f = 62
35 op+, variable and variable 12 a = 1, b = 2, x = 1
47 op+, variable and constant 12 a = 2, b = 1, x = 2
59 jump 3 t = 15
62 ret, variable 6 a = 1

The code has 68 words. jump B1 in B0 becomes a lone TICK, because B1 starts right after it. The branch at 27 needs the address 62 of B3, which is placed after it; the first pass knows it because it knows the size of each stencil.

The stencil op+, variable and constant, is the word sequence 1, 2, 0, 0, 3, 1, 0, 5, 0, 4, 0, 0 with holes a at offset 3, b at offset 6 and x at offset 10. Words 1, 2, 3, 5 and 4 are the opcodes TICK, LDS, LDI, ALU and STS, and the 0 after ALU selects the operator +. For i = i + 1 at address 47, the second pass copies the 12 words and writes 2 (the slot of i) at 50, 1 (the constant) at 53 and 2 at 57. The result is

47  TICK
48  LDS 0 2
51  LDI 1 1
54  ALU 0
56  STS 2 0

Run with n=4n = 4, the code returns 6, as the interpreter does. It runs 26 TICKs: 3 in B0, 5 in each of the four rounds through B1 and B2, 2 in the last visit to B1 and 1 in B3. The interpreter uses 26 units of fuel on the same run, so both report "out of fuel" with 25 units and both return 6 with 26. With n=100n = 100 both return 4950.

Correctness

Theorem. For every program PP of the supported form, in which every phi has an operand for each predecessor of its block and the entry block has no phi, and for all arguments and every amount of fuel, the code from COPY-AND-PATCH(PP) has the same outcome as the interpreter of the toy IR: the same returned value, or a trap, or out of fuel, or the same read of an undefined name.

The proof is in proofs/correctness.md. It has three steps. First, the two passes make a code buffer in which each placed stencil appears unchanged except at its holes, and each hole holds the slot, constant or address of the first pass (Lemma 1). Second, each stencil, started in a state that agrees with the interpreter on the variables and the fuel, does what the instruction does and ends at the start of the next stencil of the block, or, for a terminator or a stub, at the address of the next block or stub (Lemma 2). Third, an induction on the steps of the interpreter keeps the two states in agreement until the end of the run.

The implementation tests the theorem on random programs from the toy IR generator, with and without loops and with added phis, on several argument pairs and on every amount of fuel up to the amount the run needs.

Proof: Copy-and-patch code has the same outcome as the interpreterfull

We use COPY-AND-PATCH with lines L1 to L16, the stencil library and the word machine from the page. PP is a program of the supported form: its instructions are const, copy, op and phi, the phis of a block come before its other instructions, the entry block has no phi, every phi of a block CC has an operand for each predecessor of CC, the parameters are distinct, and the arguments are integers.

The interpreter. The interpreter of the toy IR keeps an environment EE, a partial map from names to integers, a fuel counter ff, the current block and the previous block. A tick stops the run with "out of fuel" if f=0f = 0, and otherwise sets f←f−1f \leftarrow f - 1. When it enters a block CC from a block BB, it does, for each phi xi=φ(…,B:ai,… )x_i = \varphi(\dots, B: a_i, \dots) in order, a tick and then reads aia_i; after all reads it sets xi←vix_i \leftarrow v_i for i=1,…,mi = 1, \dots, m in order. Then, for each other instruction in order, it does a tick and then the instruction, and for the terminator it does a tick and then jumps, branches on v≠0v \ne 0, or returns. Reading a name that is not in EE raises "undefined name". An operator traps on division or remainder by 0 and on a shift by an amount outside 0 to 63.

Agreement. A slot array σ\sigma agrees with EE when, for every name xx of PP, σ[slot(x)]=E(x)\sigma[\mathrm{slot}(x)] = E(x) if xx is in EE, and σ[slot(x)]\sigma[\mathrm{slot}(x)] is unset otherwise. Line L1 gives every name that PP defines or reads its own slot, and the temporaries get further slots. A temporary is not a name of PP, so writing a temporary does not change agreement.

Pieces. The first pass makes a list of pieces (p1,S1),(p2,S2),…(p_1, S_1), (p_2, S_2), \dots with p1=0p_1 = 0 and pi+1=pi+∣Si∣p_{i+1} = p_i + |S_i|, by line L7. For a block BB, its pieces are those of its non-phi instructions in order, then that of its terminator, and they are consecutive; addr[B]\mathrm{addr}[B] is the address of the first of them. All block pieces come before all stub pieces, and the blocks are placed in program order.

Lemma 1 (copy and patch)

After line L15, for every piece (p,S)(p, S) and every offset o<∣S∣o < |S|, code[p+o]=S.code[o]\mathrm{code}[p + o] = S.\mathrm{code}[o] if oo is not a hole of SS, and code[p+o]\mathrm{code}[p + o] is the value of the hole if (o,h)(o, h) is a hole: the slot of the variable, the constant, or addr\mathrm{addr} of the block or stub.

Proof. The intervals [pi,pi+∣Si∣)[p_i, p_i + |S_i|) are disjoint, because pi+1=pi+∣Si∣p_{i+1} = p_i + |S_i|, and their union is the whole buffer. Line L14 writes only the interval of its own piece, and line L15 overwrites only hole offsets of that interval. So after its own piece is processed, a word is never written again. Each addr\mathrm{addr} value is defined when line L15 needs it: every block gets an address at L4, and every stub that a terminator targets is put in the list at L8 and gets an address at L10, all before the second pass starts. □\square

Lemma 2 (one stencil)

Let the machine be at pc=p\mathrm{pc} = p, the address of a piece, with a slot array that agrees with EE and fuel ff, and let the interpreter be at the instruction or terminator of that piece with the same EE and ff, or about to enter CC from BB when the piece is the first of the stub B→CB \to C.

  1. For a piece of a const, copy or op instruction ι\iota of block BB: if the interpreter stops on ι\iota, the machine stops with the same outcome. Otherwise the machine reaches the address of the next piece of BB with a slot array that agrees with the new environment and the same fuel as the interpreter.
  2. For a piece of a terminator of BB: if it returns vv, the machine returns vv. If it goes to block CC, the machine reaches addr[B→C]\mathrm{addr}[B \to C] if CC has phis and addr[C]\mathrm{addr}[C] otherwise, with agreement and equal fuel. If the interpreter stops, the machine stops with the same outcome.
  3. For the stub B→CB \to C: if the interpreter stops while it runs the phis of CC, the machine stops with the same outcome. Otherwise the machine reaches addr[C]\mathrm{addr}[C] with a slot array that agrees with the environment after the phis, and with the same fuel.

Proof. By Lemma 1 the words at pp are those of the stencil with the patched values, so we can read the stencil from the library.

Case 1. Every such stencil starts with TICK, which stops with "out of fuel" exactly when f=0f = 0 and otherwise decrements ff, as the interpreter's tick does. Next, the stencil loads the operands in the order of the instruction, aa then bb: for a variable, LDS of its slot, which by agreement gives E(a)E(a), or raises "undefined name" exactly when aa is not in EE; for a constant, LDI of the constant, which is the value the interpreter uses. The variant was chosen at line L6 by the kind of each operand, so the right one of LDS or LDI is there. ALU computes the operator of the stencil on the two values with the same rules as the interpreter: the same results for the ten simple operators, division that truncates toward zero, a remainder with the sign of the dividend, a trap on a zero divisor and on a shift outside 0 to 63. So it traps exactly when the interpreter traps, and otherwise computes the same value vv. STS writes vv into the slot of xx, while the interpreter sets E(x)←vE(x) \leftarrow v, so agreement holds for the new environment. The stencil has no jump, so the machine continues at p+∣S∣p + |S|, which is the address of the next piece, and by the layout that is the next instruction or the terminator of BB.

Case 2. The stencil starts with TICK, as above. For ret, it loads aa as in Case 1 and returns it. For br a L1 L2, it loads aa and executes BR r0 t f, where tt and ff were patched with the targets chosen at L8 for the edges to L1L1 and L2L2; it goes to tt when the value is not 0, as the interpreter goes to L1L1. For jump L with the jump stencil, it goes to the patched target. For jump L with jump-next, line L8 chose this stencil only when the target is the block LL itself, so LL has no phis, and LL is placed right after BB. Then p+1p + 1 is the first address after the piece, which is addr[L]\mathrm{addr}[L], and the machine continues there. A terminator does not write any slot, so agreement holds.

Case 3. Let the phis of CC be xi=φ(…,B:ai,… )x_i = \varphi(\dots, B: a_i, \dots) for i=1,…,mi = 1, \dots, m. By the assumption on PP, the operand aia_i exists. Line L11 placed mm phi stencils, then mm move stencils, then goto. The ii-th phi stencil does a tick, loads aia_i and stores it into temporary tit_i. These stores do not touch a slot of a name of PP, so during all mm reads the slot array still agrees with EE, and each load gives E(ai)E(a_i), or raises "undefined name" exactly when the interpreter does. The ticks come in the same order as the interpreter's ticks, each before its read, so the run stops for lack of fuel at the same phi. After the reads, ti=vit_i = v_i for every ii. The ii-th move stencil copies tit_i to the slot of xix_i, for i=1,…,mi = 1, \dots, m in order, which is the order in which the interpreter assigns; if a name appears twice, the last one wins in both. So the slot array agrees with the environment after the phis. The goto stencil jumps to addr[C]\mathrm{addr}[C]. The moves and the goto have no TICK, and the interpreter's assignments use no fuel, so the fuel is equal. □\square

Theorem

For every program PP of the supported form, every list of integer arguments and every fuel f0f_0, the code from COPY-AND-PATCH(PP) returns the same value as the interpreter, or traps when the interpreter traps, or runs out of fuel when the interpreter runs out of fuel, or reads an undefined name when the interpreter does.

Proof. We show that the following invariant holds each time the interpreter is about to run an instruction or terminator of a block, or about to enter a block from an edge: the machine is at the address of the matching piece (for entry from BB into a block CC with phis, the stub B→CB \to C; for entry into a block without phis, the address of the block), its slot array agrees with EE, and the two fuel counters are equal.

At the start, the interpreter is at the entry block, which has no phi, with EE mapping the parameters to the arguments and fuel f0f_0. The machine starts at address 0, which is addr\mathrm{addr} of the entry block because it is placed first. Its slot array holds the arguments in the slots of the parameters, which come first and are distinct, and all other slots are unset. So the invariant holds.

If the invariant holds, Lemma 2 applies to the current piece. Either both stop with the same outcome, or the interpreter moves to its next position and the machine to the matching address, and the invariant holds again. For a block CC without phis, the interpreter's entry into CC does no work, and Case 2 already brought the machine to addr[C]\mathrm{addr}[C], the first piece of CC.

Every instruction and every terminator uses one tick, so the interpreter takes at most f0+1f_0 + 1 instruction or terminator steps before it stops. Each such step is matched by one application of Lemma 2, plus one more for a stub. So the run ends, and by the invariant it ends with the same outcome on both sides. □\square

Remarks

  • The number of TICKs that the machine runs equals the fuel that the interpreter uses, on every run, by the cases of Lemma 2. This is why the outcomes agree for every fuel value, which the tests check one fuel value at a time.
  • The proof uses only two facts about each stencil: what it does to the slots and to the fuel, and where it leaves the program counter. A system with stencils made by a C++ compiler needs the same two facts about each stencil, plus the fact that the relocation records name every hole exactly.

Complexity

Let nn be the size of the program, counting instructions, terminators and phi operands, and let the variables and labels be numbered, as they are in a real IR.

  • Time. The first pass does constant work per instruction and terminator. There are at most two stubs per block, and the stub of an edge B→CB \to C has 2m+12m + 1 pieces, where mm is the number of phis of CC. Each of those phis has an operand for BB, so the stubs together have at most 2⋅(phi operands)+2⋅(blocks)2 \cdot (\text{phi operands}) + 2 \cdot (\text{blocks}) pieces. Every stencil has at most 12 words, so the second pass writes O(n)O(n) words. The total is O(n)O(n). The implementation maps names to slots with a dictionary, which gives the same bound in expectation.
  • Space. The code buffer and the list of pieces have O(n)O(n) words. The library has a fixed size that does not depend on the program.
  • The compiled code. Each IR instruction becomes one stencil of a fixed size, so the code runs a constant number of machine instructions per IR step, and an edge with mm phis costs O(m)O(m).

The constant is what matters in practice. Xu and Kjolstad report, as measurements, that their WebAssembly compiler compiles 4.9 to 6.5 times faster than Liftoff, the baseline WebAssembly compiler of Chrome, and that its code runs 39% to 63% faster than the code of Liftoff on the Coremark and PolyBenchC benchmarks. For TPC-H queries in a high-level language, their compiler compiles two orders of magnitude faster than LLVM at -O0 and three orders of magnitude faster than higher LLVM levels, and its code runs 14% faster than the code of LLVM at -O0. These numbers come from their setting and machines; the algorithm does not prove them.

Properties

  • Each stencil is copied unchanged except at its holes. The quality of the code inside a stencil is the quality of the compiler that made the stencil.
  • The compiled code does the same steps in the same order as the interpreter. The number of TICKs equals the fuel that the interpreter uses, on every run.
  • No optimization crosses a stencil boundary, except what the variants express, such as a constant operand in place of a load, or a jump that is left out when its target comes next.
  • The library grows with the variants. The number of op stencils is the number of operators times the square of the number of operand kinds, so a third kind for each of the two operands takes the 56 op stencils here to 126.

Variants and improvements

  • Operands in registers. Xu and Kjolstad make stencils that take some operands in machine registers and leave their result in a register, passed by a calling convention in which the stencil ends with a tail call to the next stencil. The tail call becomes a jump that is removed when the next stencil is placed right after it, as jump-next does here.
  • Larger stencils. A stencil can cover a common combination of operations, such as a compare and a branch, in the spirit of superoperators for interpreters. This removes the loads and stores between the operations.
  • Bytecode and AST tiers. The same method can compile bytecode or a syntax tree one node at a time, which makes it a cheap first tier in adaptive optimization. The experimental JIT compiler of CPython 3.13 uses copy-and-patch, with stencils made by compiling the code of the interpreter instructions with Clang.
  • Copying interpreter routines. Piumarta and Riccardi copy the compiled code of the routines of a threaded interpreter into one buffer, which removes the dispatch between them. Copy-and-patch adds holes, so the copied code can contain operands and addresses as constants.

When to use it

  • A baseline JIT tier, where compile time counts as much as code quality: WebAssembly, bytecode of dynamic languages, and database queries that are compiled and run once.
  • A system that wants machine code without writing an assembler or an instruction encoder for each target. The stencils come from an existing compiler for the target, so a new target needs only that compiler and its object format.
  • Not for code that runs for a long time and needs register allocation and optimization across operations. There a second, optimizing tier should take over.

Pitfalls

  • Patching the wrong field. A hole has a size and a kind. A 32-bit relative jump needs the difference between the target and the end of the instruction, not the absolute address, and a constant that does not fit the field needs another variant. Follow the relocation records of the object file exactly.
  • Forward references. A branch to a block that is placed later needs its address. Lay out all stencils first, or record the hole and patch it when the target is placed.
  • Phis as sequential copies. Writing each phi variable as soon as its operand is read gives a wrong result when one phi reads the variable of another, as in a swap. Read all operands into temporaries first.
  • Executable memory. The buffer must be made executable after patching, and on systems that forbid memory that is both writable and executable, the patching must happen before the memory is mapped as code.
  • Too many variants. Every new operand kind multiplies the number of stencils. Keep the variants to the cases that occur often.
  • Speed claims. The speedups above are measurements of one implementation on given benchmarks. They are not a property of the method.

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.

copy_and_patch_compilation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/copy-and-patch-compilation/. The authors are listed in prov/KRGC64.jsonl.
"""Copy-and-patch compilation of the toy IR.

The target is a small word machine. Its code is a list of integers, and it
has two registers r0 and r1 and an array of slots, one per variable.

    TICK            use one unit of fuel, or stop with ("fuel",)
    LDS r s         r = slot[s]
    LDI r k         r = k
    STS s r         slot[s] = r
    ALU i           r0 = r0 OPS[i] r1, or stop with ("trap",)
    JMP a           go to address a
    BR r a b        go to a if r != 0, else to b
    RET r           stop with ("ret", r)

A stencil is a piece of machine code made once, before any program is
compiled, with holes: words whose value is not known yet, listed by offset
and name like relocations in an object file. The compiler picks one stencil
for each IR instruction, by its kind, its operator and whether each operand
is a variable or a constant. It places the stencils one after the other,
copies their words into the code buffer, and writes the operands and the
addresses into the holes. TICK is there so that the compiled code uses fuel
exactly like toyir.run; a real system has no such instruction.
"""

from dataclasses import dataclass

import toyir

TICK, LDS, LDI, STS, ALU, JMP, BR, RET = range(1, 9)
NAMES = {TICK: "TICK", LDS: "LDS", LDI: "LDI", STS: "STS", ALU: "ALU", JMP: "JMP", BR: "BR", RET: "RET"}
SIZE = {TICK: 1, LDS: 3, LDI: 3, STS: 3, ALU: 2, JMP: 2, BR: 4, RET: 2}


@dataclass(frozen=True)
class Stencil:
    """Machine code with holes. code has a 0 at each hole; holes is a tuple
    of (offset, name) pairs."""

    name: str
    code: tuple
    holes: tuple

    def __len__(self):
        return len(self.code)


def assemble(name, items):
    """Make a stencil from machine instructions, where a str operand is a
    hole with that name."""
    code, holes = [], []
    for ins in items:
        if len(ins) != SIZE[ins[0]]:
            raise ValueError("bad instruction %r in stencil %s" % (ins, name))
        for w in ins:
            if isinstance(w, str):
                holes.append((len(code), w))
                code.append(0)
            else:
                code.append(w)
    return Stencil(name, tuple(code), tuple(holes))


def _load(r, kind, hole):
    # kind "v": the operand is a variable, so load its slot; "i": a constant.
    return (LDS, r, hole) if kind == "v" else (LDI, r, hole)


def build_stencils():
    """The stencil library. Keys are (instruction kind, ...variant)."""
    lib = {}
    lib[("const",)] = assemble("const", [(TICK,), (LDI, 0, "a"), (STS, "x", 0)])
    for ka in "vi":
        lib[("copy", ka)] = assemble("copy_" + ka, [(TICK,), _load(0, ka, "a"), (STS, "x", 0)])
        lib[("br", ka)] = assemble("br_" + ka, [(TICK,), _load(0, ka, "a"), (BR, 0, "t", "f")])
        lib[("ret", ka)] = assemble("ret_" + ka, [(TICK,), _load(0, ka, "a"), (RET, 0)])
        # The first half of an edge copy: read a phi operand into a temporary.
        lib[("phi", ka)] = assemble("phi_" + ka, [(TICK,), _load(0, ka, "a"), (STS, "x", 0)])
        for kb in "vi":
            for i, op in enumerate(toyir.OPS):
                lib[("op", op, ka, kb)] = assemble(
                    "op%s_%s%s" % (op, ka, kb),
                    [(TICK,), _load(0, ka, "a"), _load(1, kb, "b"), (ALU, i), (STS, "x", 0)],
                )
    lib[("jump",)] = assemble("jump", [(TICK,), (JMP, "t")])
    # A jump to the stencil placed right after it: the jump is left out.
    lib[("jump-next",)] = assemble("jump_next", [(TICK,)])
    # The second half of an edge copy: move a temporary into the phi variable.
    lib[("move",)] = assemble("move", [(LDS, 0, "a"), (STS, "x", 0)])
    lib[("goto",)] = assemble("goto", [(JMP, "t")])
    return lib


STENCILS = build_stencils()


@dataclass
class Compiled:
    code: list
    nslots: int
    nparams: int
    names: list  # slot number -> variable name
    placements: list  # (address, stencil, {hole name: value}) in address order

    def run(self, args, fuel=10000):
        return execute(self, args, fuel)


def _kind(a):
    return "i" if isinstance(a, int) else "v"


def _check(prog):
    pr = toyir.preds(prog)
    for label, b in prog.blocks.items():
        seen_other = False
        for ins in b.instrs:
            k = ins[0]
            if k not in ("const", "copy", "op", "phi"):
                raise ValueError("copy-and-patch: unsupported instruction %r" % (ins,))
            if k == "phi":
                if seen_other:
                    raise ValueError("phi after a non-phi instruction in %r" % label)
                if label == prog.entry:
                    raise ValueError("phi in the entry block")
                for p in pr[label]:
                    if p not in ins[2]:
                        raise ValueError("phi %s has no operand for %r" % (ins[1], p))
            else:
                seen_other = True
            if k == "op" and ins[2] not in toyir.OPS:
                raise ValueError("bad operator: %r" % (ins[2],))


def compile_program(prog, lib=STENCILS):
    """Compile prog in two passes. Pass 1 picks a stencil for each
    instruction and gives it an address. Pass 2 copies the stencils into
    the code buffer and patches the holes. Returns a Compiled."""
    _check(prog)
    labels = list(prog.blocks)

    # Slots: parameters first, then every other name in order of appearance.
    slot = {}
    for p in prog.params:
        if p in slot:
            raise ValueError("duplicate parameter %r" % p)
        slot[p] = len(slot)
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in [toyir.defs(ins)] + toyir.uses(ins):
                slot.setdefault(a, len(slot))
        for a in toyir.term_uses(b.term):
            slot.setdefault(a, len(slot))
    nphi = max((sum(1 for ins in b.instrs if ins[0] == "phi") for b in prog.blocks.values()), default=0)
    temps = []
    for i in range(nphi):
        t = "%%t%d" % i  # cannot clash: % is not allowed in a toy IR name
        temps.append(t)
        slot[t] = len(slot)

    def phis(label):
        return [ins for ins in prog.blocks[label].instrs if ins[0] == "phi"]

    def target(src, dst):
        # Where a branch from src to dst goes: the edge stub if dst has phis.
        return ("edge", src, dst) if phis(dst) else ("block", dst)

    def operand(a):
        return ("imm", a) if isinstance(a, int) else ("slot", a)

    # Pass 1: selection and layout. Each piece is (stencil, {hole: value}),
    # where a value is ("slot", name), ("imm", k) or ("addr", place).
    pieces = []
    addr = {}
    pc = 0

    def place(key, holes):
        nonlocal pc
        st = lib[key]
        pieces.append((pc, st, holes))
        pc += len(st)

    stubs = []
    for n, label in enumerate(labels):
        b = prog.blocks[label]
        addr[("block", label)] = pc
        for ins in b.instrs:
            k = ins[0]
            if k == "phi":
                continue
            if k == "const":
                place(("const",), {"x": ("slot", ins[1]), "a": ("imm", ins[2])})
            elif k == "copy":
                place(("copy", _kind(ins[2])), {"x": ("slot", ins[1]), "a": operand(ins[2])})
            else:
                key = ("op", ins[2], _kind(ins[3]), _kind(ins[4]))
                place(key, {"x": ("slot", ins[1]), "a": operand(ins[3]), "b": operand(ins[4])})
        t = b.term
        if t[0] == "jump":
            to = target(label, t[1])
            nxt = labels[n + 1] if n + 1 < len(labels) else None
            if to == ("block", nxt):
                place(("jump-next",), {})
            else:
                place(("jump",), {"t": ("addr", to)})
            if to[0] == "edge" and to not in stubs:
                stubs.append(to)
        elif t[0] == "br":
            t1, t2 = target(label, t[2]), target(label, t[3])
            place(("br", _kind(t[1])), {"a": operand(t[1]), "t": ("addr", t1), "f": ("addr", t2)})
            for to in (t1, t2):
                if to[0] == "edge" and to not in stubs:
                    stubs.append(to)
        elif t[0] == "ret":
            place(("ret", _kind(t[1])), {"a": operand(t[1])})
        else:
            raise ValueError("bad terminator: %r" % (t,))

    # Edge stubs: read all phi operands into temporaries, then move them.
    for e in stubs:
        _, src, dst = e
        addr[e] = pc
        ps = phis(dst)
        for i, ins in enumerate(ps):
            a = ins[2][src]
            place(("phi", _kind(a)), {"x": ("slot", temps[i]), "a": operand(a)})
        for i, ins in enumerate(ps):
            place(("move",), {"x": ("slot", ins[1]), "a": ("slot", temps[i])})
        place(("goto",), {"t": ("addr", ("block", dst))})

    # Pass 2: copy and patch.
    code = [0] * pc
    placements = []
    for at, st, holes in pieces:
        code[at:at + len(st)] = st.code
        values = {}
        for off, name in st.holes:
            kind, v = holes[name]
            if kind == "slot":
                w = slot[v]
            elif kind == "imm":
                w = v
            else:
                w = addr[v]
            code[at + off] = w
            values[name] = w
        placements.append((at, st, values))
    names = [None] * len(slot)
    for name, s in slot.items():
        names[s] = name
    return Compiled(code, len(slot), len(prog.params), names, placements)


# ------------------------------------------------------------------ the machine


class _Trap(Exception):
    pass


_SIMPLE = {
    "+": lambda a, b: a + b,
    "-": lambda a, b: a - b,
    "*": lambda a, b: a * b,
    "&": lambda a, b: a & b,
    "|": lambda a, b: a | b,
    "^": lambda a, b: a ^ b,
    "<": lambda a, b: int(a < b),
    "<=": lambda a, b: int(a <= b),
    "==": lambda a, b: int(a == b),
    "!=": lambda a, b: int(a != b),
}


def _alu(op, a, b):
    if op in _SIMPLE:
        return _SIMPLE[op](a, b)
    if op == "/" or op == "%":
        # Division truncates toward zero, and the remainder has the sign of a.
        if b == 0:
            raise _Trap()
        q = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            q = -q
        return q if op == "/" else a - b * q
    if b < 0 or b > 63:
        raise _Trap()
    return a << b if op == "<<" else a >> b


_UNSET = object()


def execute(c, args, fuel=10000):
    """Run compiled code. Returns ("ret", v), ("trap",) or ("fuel",)."""
    if len(args) != c.nparams:
        raise ValueError("expected %d arguments" % c.nparams)
    code = c.code
    slots = list(args) + [_UNSET] * (c.nslots - c.nparams)
    r = [0, 0]
    pc = 0
    while True:
        o = code[pc]
        if o == TICK:
            if fuel <= 0:
                return ("fuel",)
            fuel -= 1
            pc += 1
        elif o == LDS:
            v = slots[code[pc + 2]]
            if v is _UNSET:
                raise toyir.UndefinedName(c.names[code[pc + 2]])
            r[code[pc + 1]] = v
            pc += 3
        elif o == LDI:
            r[code[pc + 1]] = code[pc + 2]
            pc += 3
        elif o == STS:
            slots[code[pc + 1]] = r[code[pc + 2]]
            pc += 3
        elif o == ALU:
            try:
                r[0] = _alu(toyir.OPS[code[pc + 1]], r[0], r[1])
            except _Trap:
                return ("trap",)
            pc += 2
        elif o == JMP:
            pc = code[pc + 1]
        elif o == BR:
            pc = code[pc + 2] if r[code[pc + 1]] != 0 else code[pc + 3]
        elif o == RET:
            return ("ret", r[code[pc + 1]])
        else:
            raise ValueError("bad opcode %r at %d" % (o, pc))


def run(prog, args, fuel=10000):
    """Compile prog and run it, with the same result format as toyir.run."""
    return compile_program(prog).run(args, fuel)


def disassemble(c):
    """One line per machine instruction, with its address."""
    out = []
    code = c.code
    pc = 0
    while pc < len(code):
        o = code[pc]
        n = SIZE[o]
        out.append("%3d  %s %s" % (pc, NAMES[o], " ".join(str(w) for w in code[pc + 1:pc + n])))
        pc += n
    return [line.rstrip() for line in out]


EXAMPLE = """
# params: n
B0:
  s = 0
  i = 0
  jump B1
B1:
  c = i < n
  br c B2 B3
B2:
  s = s + i
  i = i + 1
  jump B1
B3:
  ret s
"""


def example():
    """The worked example of the page: the sum 0 + 1 + ... + (n - 1)."""
    prog = toyir.parse(EXAMPLE)
    return prog, compile_program(prog)


if __name__ == "__main__":
    prog, c = example()
    for at, st, values in c.placements:
        print(at, st.name, values)
    print("\n".join(disassemble(c)))
    print(len(c.code), c.names, c.run([4]), toyir.run(prog, [4]))
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.

A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:

    ("const", x, k)          x = k
    ("copy", x, a)           x = y
    ("op", x, op, a, b)      x = a op b
    ("phi", x, {pred: a})    x = phi [pred: a, ...]
    ("addr", p, x)           p = &x
    ("load", x, p)           x = *p
    ("store", p, a)          *p = a
    ("alloc", p)             p = alloc
    ("call", x, f, args)     x = call f(a, b)   (args is a list)

Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""

from dataclasses import dataclass, field
import re

OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")


@dataclass
class Block:
    instrs: list = field(default_factory=list)
    term: tuple = ("ret", 0)


@dataclass
class Program:
    params: list
    blocks: dict

    @property
    def entry(self):
        return next(iter(self.blocks))


class UndefinedName(Exception):
    """A name was read before any definition."""


# ---------------------------------------------------------------- text form

_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"


def _operand(tok):
    if re.fullmatch(_INT, tok):
        return int(tok)
    if re.fullmatch(_NAME, tok):
        return tok
    raise ValueError("bad operand: %r" % tok)


def _name(tok):
    if not re.fullmatch(_NAME, tok):
        raise ValueError("bad name: %r" % tok)
    return tok


def _parse_instr(line):
    toks = line.split()
    if toks[0] == "jump" and len(toks) == 2:
        return "term", ("jump", _name(toks[1]))
    if toks[0] == "br" and len(toks) == 4:
        return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
    if toks[0] == "ret" and len(toks) == 2:
        return "term", ("ret", _operand(toks[1]))
    lhs, eq, rhs = line.partition("=")
    if not eq:
        raise ValueError("bad line: %r" % line)
    lhs, rhs = lhs.strip(), rhs.strip()
    if lhs.startswith("*"):
        return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
    x = _name(lhs)
    if rhs.startswith("phi"):
        body = rhs[3:].strip()
        if not (body.startswith("[") and body.endswith("]")):
            raise ValueError("bad phi: %r" % line)
        args = {}
        inner = body[1:-1].strip()
        if inner:
            for part in inner.split(","):
                pred, colon, a = part.partition(":")
                if not colon:
                    raise ValueError("bad phi: %r" % line)
                args[_name(pred.strip())] = _operand(a.strip())
        return "instr", ("phi", x, args)
    if rhs.startswith("call "):
        m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
        if not m:
            raise ValueError("bad call: %r" % line)
        inner = m.group(2).strip()
        args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
        return "instr", ("call", x, m.group(1), args)
    if rhs == "alloc":
        return "instr", ("alloc", x)
    if rhs.startswith("&"):
        return "instr", ("addr", x, _name(rhs[1:].strip()))
    if rhs.startswith("*"):
        return "instr", ("load", x, _name(rhs[1:].strip()))
    parts = rhs.split()
    if len(parts) == 1:
        a = _operand(parts[0])
        if isinstance(a, int):
            return "instr", ("const", x, a)
        return "instr", ("copy", x, a)
    if len(parts) == 3 and parts[1] in OPS:
        return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
    raise ValueError("bad instruction: %r" % line)


def parse(text):
    """Parse the text form. A line "# params: a, b" gives the parameters;
    without it, the parameters are the names that are read and never
    defined, in the order of their first use."""
    params = None
    blocks = {}
    cur = None
    for raw in text.splitlines():
        line = raw.strip()
        if not line:
            continue
        if line.startswith("#"):
            m = re.fullmatch(r"#\s*params:(.*)", line)
            if m:
                inner = m.group(1).strip()
                params = [_name(p.strip()) for p in inner.split(",")] if inner else []
            continue
        if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
            label = line[:-1]
            if label in blocks:
                raise ValueError("duplicate label: %r" % label)
            cur = label
            blocks[label] = Block([], None)
            continue
        if cur is None:
            raise ValueError("instruction outside a block: %r" % line)
        if blocks[cur].term is not None:
            raise ValueError("instruction after the terminator in %r" % cur)
        kind, item = _parse_instr(line)
        if kind == "term":
            blocks[cur].term = item
        else:
            blocks[cur].instrs.append(item)
    for label, b in blocks.items():
        if b.term is None:
            raise ValueError("block %r has no terminator" % label)
    if not blocks:
        raise ValueError("empty program")
    prog = Program([], blocks)
    if params is None:
        params = _free_names(prog)
    prog.params = params
    return prog


def _free_names(prog):
    defined = set()
    for b in prog.blocks.values():
        for ins in b.instrs:
            d = defs(ins)
            if d is not None:
                defined.add(d)
    out = []
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in uses(ins):
                if a not in defined and a not in out:
                    out.append(a)
        for a in term_uses(b.term):
            if a not in defined and a not in out:
                out.append(a)
    return out


def _show_instr(ins):
    k = ins[0]
    if k == "const":
        return "%s = %d" % (ins[1], ins[2])
    if k == "copy":
        return "%s = %s" % (ins[1], ins[2])
    if k == "op":
        return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
    if k == "phi":
        return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
    if k == "addr":
        return "%s = &%s" % (ins[1], ins[2])
    if k == "load":
        return "%s = *%s" % (ins[1], ins[2])
    if k == "store":
        return "*%s = %s" % (ins[1], ins[2])
    if k == "alloc":
        return "%s = alloc" % ins[1]
    if k == "call":
        return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
    raise ValueError("bad instruction: %r" % (ins,))


def _show_term(t):
    if t[0] == "jump":
        return "jump %s" % t[1]
    if t[0] == "br":
        return "br %s %s %s" % (t[1], t[2], t[3])
    if t[0] == "ret":
        return "ret %s" % (t[1],)
    raise ValueError("bad terminator: %r" % (t,))


def show(prog):
    lines = ["# params: " + ", ".join(prog.params)]
    for label, b in prog.blocks.items():
        lines.append(label + ":")
        for ins in b.instrs:
            lines.append("  " + _show_instr(ins))
        lines.append("  " + _show_term(b.term))
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------- names and graph


def defs(ins):
    """The name an instruction defines, or None for a store."""
    return None if ins[0] == "store" else ins[1]


def uses(ins):
    """The names an instruction reads, in order (phi operands included)."""
    k = ins[0]
    if k == "const" or k == "alloc" or k == "addr":
        ops = []
    elif k == "copy":
        ops = [ins[2]]
    elif k == "op":
        ops = [ins[3], ins[4]]
    elif k == "phi":
        ops = list(ins[2].values())
    elif k == "load":
        ops = [ins[2]]
    elif k == "store":
        ops = [ins[1], ins[2]]
    elif k == "call":
        ops = list(ins[3])
    else:
        raise ValueError("bad instruction: %r" % (ins,))
    return [a for a in ops if isinstance(a, str)]


def term_uses(t):
    if t[0] == "br" or t[0] == "ret":
        return [t[1]] if isinstance(t[1], str) else []
    return []


def succs(prog, label):
    """Successor labels of a block, without repeats, in terminator order."""
    t = prog.blocks[label].term
    if t[0] == "jump":
        return [t[1]]
    if t[0] == "br":
        return [t[2]] if t[2] == t[3] else [t[2], t[3]]
    return []


def edges(prog):
    return [(a, b) for a in prog.blocks for b in succs(prog, a)]


def preds(prog):
    """Dict from label to the list of predecessor labels, in block order."""
    out = {label: [] for label in prog.blocks}
    for a, b in edges(prog):
        out[b].append(a)
    return out


def is_acyclic(prog):
    color = {label: 0 for label in prog.blocks}
    for root in prog.blocks:
        if color[root]:
            continue
        color[root] = 1
        stack = [(root, iter(succs(prog, root)))]
        while stack:
            v, it = stack[-1]
            w = next(it, None)
            if w is None:
                color[v] = 2
                stack.pop()
            elif color[w] == 1:
                return False
            elif color[w] == 0:
                color[w] = 1
                stack.append((w, iter(succs(prog, w))))
    return True


def paths(prog):
    """Every path from the entry to a ret block, as a list of labels.
    The CFG must be acyclic."""
    if not is_acyclic(prog):
        raise ValueError("paths needs an acyclic CFG")
    out = []

    def walk(path):
        last = path[-1]
        s = succs(prog, last)
        if not s:
            out.append(list(path))
        for w in s:
            path.append(w)
            walk(path)
            path.pop()

    walk([prog.entry])
    return out


# ------------------------------------------------------------------ running


class _Trap(Exception):
    pass


class _Fuel(Exception):
    pass


def _binop(op, a, b):
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError("arithmetic on a pointer")
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "/" or op == "%":
        if b == 0:
            raise _Trap()
        q = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            q = -q
        return q if op == "/" else a - b * q
    if op == "&":
        return a & b
    if op == "|":
        return a | b
    if op == "^":
        return a ^ b
    if op == "<<" or op == ">>":
        if b < 0 or b > 63:
            raise _Trap()
        return a << b if op == "<<" else a >> b
    if op == "<":
        return int(a < b)
    if op == "<=":
        return int(a <= b)
    if op == "==":
        return int(a == b)
    if op == "!=":
        return int(a != b)
    raise ValueError("bad operator: %r" % op)


class _Frame:
    """One activation: its program, its variables and its position."""

    def __init__(self, prog, args, fid):
        if len(args) != len(prog.params):
            raise ValueError("expected %d arguments" % len(prog.params))
        self.prog = prog
        self.env = dict(zip(prog.params, args))
        self.fid = fid
        self.label = prog.entry
        self.prev = None
        self.pc = 0  # 0 means: the phis of the block have not run yet
        self.dest = None  # the name that receives the value of a pending call

    def val(self, a):
        if isinstance(a, int):
            return a
        if a not in self.env:
            raise UndefinedName(a)
        return self.env[a]


def _run(prog, args, fuel, funcs):
    """Run with an explicit stack of frames, so deep recursion in the toy
    program does not use Python recursion."""
    heap = {}
    envs = {}
    stack = []
    fr = _Frame(prog, args, 0)
    envs[0] = fr.env
    nframes = 1

    def tick():
        nonlocal fuel
        if fuel <= 0:
            raise _Fuel()
        fuel -= 1

    while True:
        block = fr.prog.blocks[fr.label]
        instrs = block.instrs
        if fr.pc == 0:
            # Phis at the top of the block read all operands first, then assign.
            incoming = []
            i = 0
            while i < len(instrs) and instrs[i][0] == "phi":
                tick()
                ins = instrs[i]
                if fr.prev not in ins[2]:
                    raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
                incoming.append((ins[1], fr.val(ins[2][fr.prev])))
                i += 1
            for x, v in incoming:
                fr.env[x] = v
            fr.pc = i if i > 0 else -1
        start = fr.pc if fr.pc > 0 else 0
        called = False
        env = fr.env
        for j in range(start, len(instrs)):
            ins = instrs[j]
            tick()
            k = ins[0]
            if k == "const":
                env[ins[1]] = ins[2]
            elif k == "copy":
                env[ins[1]] = fr.val(ins[2])
            elif k == "op":
                env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
            elif k == "addr":
                env[ins[1]] = ("var", fr.fid, ins[2])
            elif k == "alloc":
                cell = ("heap", len(heap))
                heap[cell] = None
                env[ins[1]] = cell
            elif k == "load":
                p = fr.val(ins[2])
                if p[0] == "var":
                    if p[2] not in envs[p[1]]:
                        raise UndefinedName(p[2])
                    env[ins[1]] = envs[p[1]][p[2]]
                else:
                    if heap[p] is None:
                        raise UndefinedName(repr(p))
                    env[ins[1]] = heap[p]
            elif k == "store":
                p = fr.val(ins[1])
                if p[0] == "var":
                    envs[p[1]][p[2]] = fr.val(ins[2])
                else:
                    heap[p] = fr.val(ins[2])
            elif k == "call":
                if funcs is None or ins[2] not in funcs:
                    raise ValueError("unknown function %r" % ins[2])
                vals = [fr.val(a) for a in ins[3]]
                fr.pc = j + 1
                fr.dest = ins[1]
                stack.append(fr)
                fr = _Frame(funcs[ins[2]], vals, nframes)
                envs[nframes] = fr.env
                nframes += 1
                called = True
                break
            elif k == "phi":
                raise ValueError("phi after a non-phi instruction")
            else:
                raise ValueError("bad instruction: %r" % (ins,))
        if called:
            continue
        tick()
        t = block.term
        if t[0] == "jump" or t[0] == "br":
            if t[0] == "jump":
                nxt = t[1]
            else:
                nxt = t[2] if fr.val(t[1]) != 0 else t[3]
            fr.prev, fr.label, fr.pc = fr.label, nxt, 0
            continue
        v = fr.val(t[1])
        if not stack:
            return ("ret", v), fuel
        fr = stack.pop()
        fr.env[fr.dest] = v


def run(prog, args, fuel=10000, funcs=None):
    """Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
    Each instruction, phi and terminator uses one unit of fuel. funcs is an
    optional dict from function name to Program, used by call; deep
    recursion in the toy program is fine, because the frames are kept on an
    explicit stack."""
    try:
        out, _ = _run(prog, list(args), fuel, funcs)
        return out
    except _Trap:
        return ("trap",)
    except _Fuel:
        return ("fuel",)


# ------------------------------------------------------------ random programs

_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")


def random_program(rng, nvars, nblocks, acyclic):
    """A random program with blocks B0 .. B(nblocks-1) and variables
    x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
    others, so no run reads an undefined name. A division by a variable can
    trap. Every block is reachable from
    B0 and B0 has no predecessor. With acyclic=False, each loop has its own
    counter c that is set to 0 in B0 and never reset, and the back edge is
    taken only while c < m and c < 4, where m is the first parameter. So the
    whole run takes each back edge at most 3 times."""
    nvars = max(nvars, 1)
    nblocks = max(nblocks, 1)
    xs = ["x%d" % i for i in range(nvars)]
    params = xs[:2]
    labels = ["B%d" % i for i in range(nblocks)]

    def operand():
        if rng.random() < 0.25:
            return rng.randint(-3, 9)
        return rng.choice(xs)

    def instr():
        x = rng.choice(xs)
        r = rng.random()
        if r < 0.15:
            return ("const", x, rng.randint(-5, 9))
        if r < 0.25:
            return ("copy", x, rng.choice(xs))
        if r < 0.3:
            # A division by a variable may trap.
            return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
        if r < 0.4:
            op = rng.choice(_CONST_RIGHT)
            k = rng.randint(1, 5)
            return ("op", x, op, rng.choice(xs), k)
        return ("op", x, rng.choice(_SAFE), operand(), operand())

    blocks = {}
    has_pred = [False] * nblocks
    has_pred[0] = True
    for i in range(nblocks):
        instrs = [instr() for _ in range(rng.randint(1, 3))]
        if i == 0:
            instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
        if i == nblocks - 1:
            term = ("ret", rng.choice(xs))
        elif has_pred[i + 1] and rng.random() < 0.2:
            term = ("ret", rng.choice(xs))
        else:
            first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
            if rng.random() < 0.5:
                term = ("jump", labels[first])
                has_pred[first] = True
            else:
                second = rng.randrange(i + 1, nblocks)
                if second == first:
                    term = ("jump", labels[first])
                else:
                    term = ("br", rng.choice(xs), labels[first], labels[second])
                    has_pred[second] = True
                has_pred[first] = True
        blocks[labels[i]] = Block(instrs, term)

    if not acyclic and nblocks > 1:
        nloops = rng.randint(1, max(1, nblocks // 3))
        for k in range(nloops):
            latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
            if not latches:
                break
            t = rng.choice(latches)
            h = labels[rng.randint(1, labels.index(t))]
            c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
            blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
            out = blocks[t].term[1]
            blocks[t].instrs += [
                ("op", c, "+", c, 1),
                ("op", w1, "<", c, m),
                ("op", w2, "<", c, 4),
                ("op", w, "&", w1, w2),
            ]
            blocks[t].term = ("br", w, h, out)
    return Program(list(params), blocks)
test_copy_and_patch_compilation.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/copy-and-patch-compilation/. The authors are listed in prov/KRGC64.jsonl.

import random

import pytest

import toyir
from copy_and_patch_compilation import (
    STENCILS,
    compile_program,
    disassemble,
    example,
    run,
)

ARGS = [(0, 0), (1, 2), (3, -1), (5, 7), (-4, 2), (9, 0), (2, 3)]


def add_phis(rng, prog):
    """Put phis for the variables x0, x1, ... at the top of some blocks. The
    entry of random_program defines every x, so every operand is defined."""
    xs = sorted({ins[1] for ins in prog.blocks[prog.entry].instrs if ins[1].startswith("x")} | set(prog.params))
    pr = toyir.preds(prog)
    for label, b in prog.blocks.items():
        if label == prog.entry or not pr[label] or rng.random() < 0.4:
            continue
        dests = rng.sample(xs, min(len(xs), rng.randint(1, 3)))
        new = []
        for x in dests:
            args = {p: (rng.randint(-3, 9) if rng.random() < 0.25 else rng.choice(xs)) for p in pr[label]}
            new.append(("phi", x, args))
        b.instrs[0:0] = new
    return prog


def check_layout(prog, c):
    """The stencils tile the code, each copied unchanged except at its holes,
    and each hole holds the value that was patched into it."""
    pc = 0
    for at, st, values in c.placements:
        assert at == pc
        holes = dict(st.holes)
        for i, w in enumerate(st.code):
            if i in holes:
                assert c.code[at + i] == values[holes[i]]
            else:
                assert c.code[at + i] == w
        assert set(values) == set(holes.values())
        pc += len(st)
    assert pc == len(c.code)


def same(prog, args, fuel=10000):
    expect = toyir.run(prog, args, fuel)
    got = run(prog, args, fuel)
    assert got == expect, (toyir.show(prog), args, fuel, got, expect)
    return expect


def test_example():
    prog, c = example()
    assert len(c.code) == 68
    assert c.names == ["n", "s", "i", "c"]
    assert [st.name for _, st, _ in c.placements] == [
        "const", "const", "jump_next", "op<_vv", "br_v", "op+_vv", "op+_vi", "jump", "ret_v",
    ]
    assert c.placements[4][2] == {"a": 3, "t": 35, "f": 62}
    assert c.placements[7][2] == {"t": 15}
    lines = disassemble(c)
    assert lines[7:9] == [" 15  TICK", " 16  LDS 0 2"]
    assert lines[14] == " 31  BR 0 35 62"
    assert c.run([4]) == ("ret", 6)
    assert c.run([100]) == ("ret", 4950)
    for n in range(-2, 12):
        same(prog, [n])
    check_layout(prog, c)


def test_library():
    # 1 const, 2 each of copy, br, ret and phi, 4 times 14 operators, and
    # jump, jump-next, move and goto.
    assert len(STENCILS) == 1 + 8 + 56 + 4
    st = STENCILS[("op", "+", "v", "i")]
    assert st.code == (1, 2, 0, 0, 3, 1, 0, 5, 0, 4, 0, 0)
    assert st.holes == ((3, "a"), (6, "b"), (10, "x"))


@pytest.mark.parametrize("acyclic", [True, False])
def test_random_programs(acyclic):
    rng = random.Random(1 if acyclic else 2)
    for _ in range(250):
        prog = toyir.random_program(rng, rng.randint(2, 6), rng.randint(1, 8), acyclic)
        c = compile_program(prog)
        check_layout(prog, c)
        for a in ARGS:
            assert c.run(list(a)) == toyir.run(prog, list(a))


def test_random_programs_with_phis():
    rng = random.Random(3)
    nphis = 0
    for _ in range(250):
        prog = toyir.random_program(rng, rng.randint(2, 6), rng.randint(2, 8), rng.random() < 0.5)
        add_phis(rng, prog)
        nphis += sum(ins[0] == "phi" for b in prog.blocks.values() for ins in b.instrs)
        c = compile_program(prog)
        check_layout(prog, c)
        for a in ARGS:
            same(prog, list(a))
    assert nphis > 300


def test_every_fuel_value():
    # The compiled code runs out of fuel at exactly the same point.
    rng = random.Random(4)
    for _ in range(40):
        prog = toyir.random_program(rng, 4, rng.randint(2, 7), False)
        add_phis(rng, prog)
        a = [rng.randint(0, 5), rng.randint(-3, 5)]
        need = 0
        while toyir.run(prog, a, need) == ("fuel",):
            need += 1
        for f in range(0, need + 2):
            same(prog, a, f)


def test_traps():
    prog = toyir.parse("# params: a, b\nB0:\n  q = a / b\n  r = a % b\n  s = q << r\n  ret s\n")
    for a, b in [(7, 2), (-7, 2), (7, -2), (-7, -2), (5, 0), (1, 70), (-1, 64)]:
        same(prog, [a, b])
    assert run(prog, [7, 0]) == ("trap",)
    assert run(prog, [7, 2]) == ("ret", 6)
    # -7 / 2 is -3 and -7 % 2 is -1, and a shift by -1 traps.
    assert run(prog, [-7, 2]) == ("trap",)


def test_parallel_phis():
    # The two phis swap a and b on each round, so they must read before they write.
    text = """
    # params: a, b, n
    B0:
      i = 0
      jump B1
    B1:
      x = phi [B0: a, B2: y]
      y = phi [B0: b, B2: x]
      c = i < n
      br c B2 B3
    B2:
      i = i + 1
      jump B1
    B3:
      r = x * 10
      r = r + y
      ret r
    """
    prog = toyir.parse(text)
    for n in range(5):
        same(prog, [1, 2, n])
    assert run(prog, [1, 2, 3]) == ("ret", 21)
    assert run(prog, [1, 2, 4]) == ("ret", 12)


def test_jump_to_next_block_is_left_out():
    prog = toyir.parse("# params: a\nB0:\n  x = a + 1\n  jump B1\nB1:\n  ret x\n")
    c = compile_program(prog)
    assert [st.name for _, st, _ in c.placements] == ["op+_vi", "jump_next", "ret_v"]
    assert run(prog, [4]) == ("ret", 5)
    prog = toyir.parse("# params: a\nB0:\n  x = a + 1\n  jump B2\nB1:\n  ret 0\nB2:\n  ret x\n")
    c = compile_program(prog)
    assert [st.name for _, st, _ in c.placements] == ["op+_vi", "jump", "ret_i", "ret_v"]
    assert run(prog, [4]) == ("ret", 5)


def test_rejects():
    with pytest.raises(ValueError):
        compile_program(toyir.parse("# params: p\nB0:\n  x = *p\n  ret x\n"))
    with pytest.raises(ValueError):
        compile_program(toyir.parse("# params: a\nB0:\n  x = phi [B0: a]\n  ret x\n"))
    with pytest.raises(ValueError):
        run(toyir.parse("# params: a\nB0:\n  ret a\n"), [1, 2])
    with pytest.raises(toyir.UndefinedName):
        run(toyir.parse("# params: a\nB0:\n  ret z\n"), [1])

History

Copying ready-made machine code is an old idea in interpreters and simple JIT compilers. Piumarta and Riccardi in 1998 copied the code of the routines of a direct threaded interpreter to remove its dispatch. Xu and Kjolstad in 2021 made the idea a general code generator: stencils with holes, made automatically by a C++ compiler from templates, chosen by operand variants, and patched with the help of the relocation records of the object file. They applied it to a WebAssembly compiler and to a compiler for a high-level language used for database queries. The method then went into practice as the experimental JIT compiler of CPython 3.13.

References

  1. Haoran Xu and Fredrik Kjolstad, Copy-and-patch compilation: a fast compilation algorithm for high-level languages and bytecode, Proceedings of the ACM on Programming Languages 5(OOPSLA), 2021, 1-30, the abstract (the measured compile times and run times quoted on this page); the construction of binary stencils from C++ templates whose holes are external symbols that the object file records as relocations; the stencil variants per operand location; the code generation by copying stencils and patching holes; the removal of the jump to a continuation that is placed right after
  2. Ian Piumarta and Fabio Riccardi, Optimizing direct threaded code by selective inlining, PLDI 1998, 291-300, the copying of the compiled code of interpreter routines into one buffer, so that a sequence of threaded instructions becomes straight machine code without dispatch

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)
WritingW0 stub
  • pseudocode in The algorithm