Algorithmcore
Linear scan register allocation
Also called Poletto-Sarkar linear scan.
Sorts live intervals by start and assigns registers in one pass, spilling the interval that ends last when registers run out.
- Solves
- Register allocation
- Time
- O(l + s n + n log n) worst
- Space
- O(s n) extra
- Where
- k = the number of registers; l = the time of one liveness analysis; n = the number of names; s = the number of instructions and terminators
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Massimiliano Poletto, Vivek Sarkar, 1999
Linear scan register allocation gives registers to the names of a program without building an interference graph. It puts the instructions in one linear order, replaces each name by one interval from its first to its last live position, and visits the intervals by start. A free register goes to each new interval. When none is free, it spills the interval that ends last, which may be the new one. It runs in near-linear time, so JIT compilers use it, but it is a heuristic for the register allocation problem: an interval can contain points where its name is dead, and then it spills where a graph coloring allocator would not.
In plain words
Lay the whole function out as one long line of instructions. For each value, draw a bar from the first place it is needed to the last. Now walk along the line from left to right. When a bar starts, give it a free register. When a bar ends, its register becomes free again. If a bar starts and every register is busy, look at all the bars that cover this place, the new one included. Throw out the one that goes on the longest, and keep its value in memory. That choice frees a register for the longest time, and for bars on a line it is the best choice. The bars are rough, though: a bar can cover a branch where its value is never used, so the method can waste registers there.
The problem
The input is a program in the toy IR with const, copy and op instructions and no phi, and a number of registers. The output is a program that uses only the registers , two scratch registers and kept apart for spill code, and memory slots mem.x, and that has the same outcome as on every input.
Number the instructions and terminators of in the order of the blocks as items . Item reads at position and writes at position , so a value read for the last time by an item can give its register to the value that the same item writes. The interval of a name is the range from the first to the last position where is written or live before an item. The overlap of a set of intervals is the largest number of them that contain one position.
The algorithm
LINEAR-SCAN-ALLOCATE(P, k)- 1
number the items of P in block order; item n reads at 2n and writes at 2n+1 - 2
compute the names live just before each item - 3
I[x] <- [smallest, largest] of the write positions of x and the positions 2n with x live before item n - 4
active <- empty // sorted by end - 5
free <- {0, ..., k-1} - 6
for each interval i in order of increasing start do - 7
EXPIRE-OLD(i) - 8
if |active| = k then SPILL-AT(i) - 9
else reg[i] <- the lowest register in free; remove it from free; add i to active EXPIRE-OLD(i)- 10
for each j in active, in order of increasing end do - 11
if end[j] >= start[i] then return - 12
remove j from active; add reg[j] to free SPILL-AT(i)- 13
s <- the interval in active with the largest end - 14
if end[s] > end[i] then reg[i] <- reg[s]; spill s; remove s from active; add i to active - 15
else spill i - 16
return P with each kept name x renamed to r[reg[x]], each spilled name x kept in mem.x (loaded into s0 or s1 before a use, computed into s0 and stored after a definition),and each copy whose two sides get the same location deleted
Ties at line L6 go by end, then by name. Line L13 takes the largest end, then the largest start, then the last name, and line L14 keeps only if comes strictly later in that order. The implementation first adds a block that loads each parameter from its slot, as the Chaitin allocator does, so that a parameter has a definition.
Lines L6 to L15 are the interval partitioning greedy with a cap of colors. The spill rule of line L13 is the furthest end rule, the same rule as Belady's cache replacement, applied to intervals.
Example
Take this program with the parameter p and :
entry:
a = p + 1
br p B1 B2
B1:
b = p * 2
c = b + p
ret c
B2:
d = a - p
ret d
The items are numbered 0 to 6 in block order: a = p + 1 is 0, the branch is 1, b, c and ret c are 2 to 4, and d and ret d are 5 and 6. The names live before each item are , , , , , and . So the intervals are:
| name | written at | live at | interval |
|---|---|---|---|
| none | 0, 2, 4, 6, 10 | ||
| 1 | 2, 10 | ||
| 5 | 6 | ||
| 7 | 8 | ||
| 11 | 12 |
The value is dead in B1, but B1 lies between the definition of and its use in B2, so the interval of covers B1. Position 5 lies in the intervals of , and , so the overlap is 3. The scan goes:
| interval | expired | action | active after |
|---|---|---|---|
| none | |||
| none | |||
| none | full; (end 10, start 1), : spill , | ||
| , |
The implementation adds the block start with p = mem.p, which moves the other positions by 4, and gives:
start:
r0 = mem.p
jump entry
entry:
s0 = r0 + 1
mem.a = s0
br r0 B1 B2
B1:
r1 = r0 * 2
r1 = r1 + r0
ret r1
B2:
s0 = mem.a
r0 = s0 - r0
ret r0
The interference graph has only the edges - and -. Two colors suffice (, and ), so a graph coloring allocator needs no spill here. Linear scan spilled only because its interval covers B1. With the blocks in the order entry, B2, B1, the interval of ends before starts, the overlap is 2, and linear scan spills nothing. The block order matters.
Correctness
The full proof is in the proof file. Its parts are:
- Intervals contain interference. If two names are live before the same item, or one is written while the other is live after the write, their intervals share a position. So the overlap graph of the intervals contains the interference graph.
- Registers. An invariant on active shows that two kept intervals that overlap get different registers, and that at most kept intervals contain any position.
- No spill and few registers. The scan spills nothing if and only if the overlap is at most . Then it uses exactly as many registers as the overlap, since the lowest free register is always below the number of intervals that contain the current start.
- Fewest spills. For each prefix of the intervals, the kept set has at least as many intervals that end before any time as any other set with overlap at most . With this says the scan keeps the most intervals. The proof uses only that line L13 drops an interval with the largest end.
- Same outcome. At each point of a run, each live name that has a value is held by its register or its slot. A write goes to a register that no other live name holds, because of the first two parts.
So linear scan is optimal for its intervals, both in registers and in spills, and correct for the program. It is still a heuristic, because the intervals are larger than the live ranges: the example spills a program that two registers can hold.
Proof: Linear scan gives a correct program, and it is optimal for its intervalsfull
We prove five facts about LINEAR-SCAN-ALLOCATE. Lemma 1 links intervals to liveness. Lemmas 2 to 4 are about the scan on intervals: no two overlapping kept intervals share a register, no spill happens when the overlap is at most , and the number of spills is the smallest possible for the given intervals. Lemma 5 shows that the rewritten program has the same outcome as the input.
Setup
The program has const, copy and op instructions only, and it has been prepared: a new entry block copies each live parameter from its slot mem.p. Line L1 numbers the instructions and terminators of in block order as items . Item reads at position and writes at position . Each instruction is followed in its block by another item, at least by the terminator, so the only successor of an instruction is item . The successors of a terminator are the first items of its successor blocks.
Write for the set of non-slot names live just before item , as line L2 computes it. The backward fixed point of live variable analysis gives exactly the names for which some path of items from reaches a read of with no write of before that read. For an instruction that writes and reads ,
and for a terminator, is the name it reads (if any) together with the union of over its successor items .
Line L3 gives each non-slot name the interval , the smallest closed range of integers that contains every write position of and every position with . Two intervals overlap when they share a position. The overlap of a set of intervals is the largest number of them that contain one position.
Intervals contain interference
Lemma 1. If , then . If item writes and is live just after , then .
Proof. The first claim is the definition of . For the second, item is an instruction, so the point just after it is the point just before item , and . Since , the equation above gives . So and are both in , and is a range, so . The write of puts in .
So the overlap graph of the intervals contains the interference graph. The converse fails: an interval may contain positions where its name is dead, as in the example on the page. That is the only reason why linear scan is a heuristic for the program and not for its intervals.
The scan on intervals
Let be the order of line L6: by start, then by end, then by name. Write for the first intervals of , for the set of intervals of that hold a register after step , and for the start of the interval of the next step. For a set of intervals and an integer , let be the members of that end before .
Invariant (A). Just after line L7 in the step of , the list active is the set of members of that end at or after , the registers of its members are pairwise different, and free holds the other registers of .
Proof. By induction on . At both sides are empty and free is full. Suppose (A) holds at the step of . Lines L10 to L12 have just removed the members that end before , and returned their registers. Every member of that ends at or after ended at or after each earlier start too, so no earlier step removed it, and it is in active. Line L9 takes a register from free, which no active member holds. Line L14 moves the register of the removed interval to , and leaves active. Line L15 changes nothing. In each case the registers stay pairwise different, and active becomes the set of members of that end at or after . The next start is at least , so after line L7 of the next step, active is the set of members of that end at or after .
Every member of active starts at or before and ends at or after . So in the step of , active is a set of intervals that all contain the position .
Lemma 2 (registers). Two kept intervals that overlap get different registers. Each has overlap at most .
Proof. Let and be kept at the end with before in . If they overlap, then . A kept interval never loses its register, so is in for every step after its own, and in the step of , it ends at or after . By (A), is in active there. Interval gets its register at line L9 from free, or at line L14 from the removed interval . In both cases (A) says the register differs from that of , and keeps its register to the end.
For the overlap, take a position and let be the last interval of that contains and is in . Every member of that contains starts at or before and ends at or after , so it contains and was in active or was at the end of the step of . That set has at most members, since line L9 only adds an interval when fewer than are active, and line L14 swaps one for one.
Lemma 3 (no spill and the number of registers). Let be the overlap of all intervals. The scan spills nothing if and only if , and then it uses exactly registers.
Proof. A spill happens at line L8 only when , and then active is intervals that contain , so . Conversely, if nothing is spilled, every interval is kept, and Lemma 2 gives .
Now let nothing be spilled. When interval arrives with active intervals, those intervals and contain , so . The active intervals hold registers, so the lowest free register is at most . So only the registers are used. Some position lies in intervals, and by Lemma 2 they hold different registers.
Lemma 4 (fewest spills). Let be any set with overlap at most . Then for every integer , including , . In particular , so for the scan spills as few intervals as possible.
Proof. By induction on . For both sides are . Assume the claim for and take with overlap at most . Let be active after line L7 in the step of , so . Write when the statement is true and otherwise.
Case 1: . Then and . Line L9 adds , line L15 adds nothing, and line L14 replaces by with , so . In all three cases .
Case 2: and . Line L9 runs, so . With ,
Case 3: and . Lines L13 to L15 drop the interval of with the largest end: at line L14, or at line L15. So , and we must show
If , this is the claim for applied to . Let . Every member of and end before , and every member of outside ends before . So , and we must show . Every member of starts at or before , so those that end at or after contain . Together with , which contains , there are at most of them, so . By the claim for with , , because exactly the members of end at or after . Adding the two bounds gives .
The proof uses only that the dropped interval has the largest end in , so the way ties are broken does not matter. The kept set is a largest subfamily with overlap at most , which is the unit weight case of the maximum -colorable interval subgraph.
The rewritten program has the same outcome
Lemma 5. Assume that no run of reads a name before it writes it. Let be the result of line L16: each kept name becomes the register , each spilled name becomes the slot mem.x, an operand in a slot is first loaded into the scratch register or , a result that goes to a slot is computed into and then stored, and a copy whose two sides become the same location is deleted. Then for every input, and have the same outcome.
Proof. Run and on the same input, with stores and . Let be the location of in . We show that the runs visit the same blocks and that this holds just before each item of and the code of for it:
(R) Each name that has been written has , and each slot
mem.pof a parameter that the first block has not yet read holds the argument.
At the start, (R) holds, because both programs get the same arguments in the same slots and no non-slot name has been written.
Take an instruction that writes . Its operands are in and have been written, so by (R) their locations hold the right values, and loading them into or changes no location of a name. So computes the same value as , or traps in the same way. Then writes to , directly or through . A deleted copy y = a has , which already holds . So the claim holds for after the step.
Let be a name in that has been written. It is in , so its location was right before the step. The step writes only and the scratch registers. No name lives in a scratch register. If is spilled, its slot mem.x differs from . If and are both kept, Lemma 1 says that and overlap, and Lemma 2 gives them different registers. So still holds . The parameter slots are read only in the first block, which has no predecessor and runs once, and the slot of a parameter is written only when is spilled and itself is defined. So (R) holds before item .
A terminator reads a name in , so both programs take the same branch or return the same value. Each name live at the start of the next block is in , and the terminator writes nothing, so (R) holds there. By induction over the run, both programs end in the same way: with the same value, with the same trap, or not at all.
Summary
The scan is optimal for the interval graph that it builds: it uses the fewest registers when no spill is needed (Lemma 3) and spills the fewest intervals otherwise (Lemma 4). The result is always correct (Lemma 5). The interval graph contains the interference graph (Lemma 1), and it may be larger, so the scan may spill a program that a graph coloring allocator colors with registers.
Complexity
With names, items, registers and the time of live variable analysis:
- Intervals. One backward walk per block gives the live set before each item, in time and space. Each interval then needs only its smallest and largest position.
- Scan. Sorting by start takes . With active in a balanced search tree keyed by end, each step costs , so the scan costs besides the sort. The implementation keeps active as a sorted list, per step, which is the same for a fixed machine.
- Rewrite. One pass over the items, .
The total is . In a real compiler, liveness is computed once on sets of bits and the intervals come from one backward pass over the blocks, so the time is close to linear in the size of the program. That is the whole reason for the method: no graph with up to edges is built.
Properties
- Optimal on intervals. If the overlap is at most , it uses exactly the overlap number of registers. Otherwise it spills the fewest intervals that bring the overlap down to , which is the unit weight case of the maximum -colorable interval subgraph.
- Not optimal on programs. An interval is a convex hull of a live range in the linear order. The overlap graph can have more edges than the interference graph, as in the example.
- Depends on the block order. A different block order gives different intervals. Orders that keep a loop body together, such as reverse postorder, give shorter intervals.
- Whole intervals. A name is either in one register for its whole interval or in memory everywhere. It never moves between two registers.
- Not optimal in spill cost. It counts spilled intervals, not loads and stores. A spilled name that is used often in a loop costs more than its count of one.
Variants and improvements
- Second-chance binpacking (Traub, Holloway and Smith, 1998) keeps the lifetime holes of each name, lets a value move between a register and memory, and adds resolution moves on the edges of the control flow graph.
- Interval splitting (Wimmer and Mössenböck, 2005) keeps intervals with holes and splits an interval at a good position instead of spilling it whole. A split part can get a different register. This is the allocator of the Java HotSpot client compiler.
- Linear scan on SSA form (Wimmer and Franz, 2010) builds the intervals on SSA form, which makes them simpler, and resolves the phis after allocation.
- Spill weights. Many versions spill the interval with the lowest use count weighted by loop depth instead of the furthest end. That loses the optimality on intervals but often gives faster code.
- SSA-based allocation keeps the speed of a linear walk but colors the true interference graph of an SSA program, which is chordal, with the fewest registers.
When to use it
Use it when compile time matters more than the last few percent of code quality: in a JIT compiler (just-in-time compilation), in a baseline tier, or for very large generated functions. It is also simple to write and to debug. For an ahead-of-time compiler that can afford a graph, graph coloring or SSA-based allocation gives fewer spills. Inside one basic block, local register allocation with the furthest next use rule spills fewer loads and stores, because it splits values at each use.
Pitfalls
- Read before write. Give the reads of an item a position before its write. Otherwise
x = y + 1with dead after it needs two registers, and the overlap is one too high. - Dead definitions. A name that is written and never read still has an interval of one position. Without it, the write may land in the register of a live name.
- Live across a back edge. A name live at a loop header must be live to the end of the loop body in the linear order. Liveness from the fixed point gives this; a single pass that looks only at definitions and uses does not.
- Scratch registers. The spill code needs registers that no interval can hold. Here and are kept apart for loads, which is enough for an instruction with two operands.
- Ties at line L14. Spilling the active interval when it ends at the same position as the new one moves a register for nothing. Keep the active one on a tie.
- Parameters. A parameter live on entry needs a write position. The block that loads parameters from their slots gives it one.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-scan-register-allocation/. The authors are listed in prov/5E24WB.jsonl.
"""Linear scan register allocation (Poletto and Sarkar, 1999).
linear_scan(iv, k) works on intervals: iv maps each name to (start, end),
with start <= end, both ends included. It returns (reg, spilled): reg maps
each kept name to a register number in 0 .. k-1, and spilled is the set of
names that get no register.
allocate(prog, k) works on a toy IR program with const, copy and op
instructions only (no phi). It numbers the instructions in block order,
builds one interval per name, runs linear_scan and rewrites the program.
It returns (out, reg, spilled). The names in out are the registers
r0 .. r(k-1), the two scratch registers s0 and s1 that hold spilled values
for one instruction, and memory slots whose names start with "mem.". The
parameters of out are the memory slots of the parameters of prog.
"""
import toyir
MEM = "mem."
SCRATCH = ("s0", "s1")
def is_mem(name):
return isinstance(name, str) and name.startswith(MEM)
# ---------------------------------------------------------- interval level
def linear_scan(iv, k):
if k < 0:
raise ValueError("k must be at least 0")
reg = {}
spilled = set()
active = [] # @line L4 (kept sorted by end)
free = list(range(k)) # @line L5
order = sorted(iv, key=lambda x: (iv[x][0], iv[x][1], x))
def end_key(x):
return (iv[x][1], iv[x][0], x)
def expire_old(start):
for j in list(active): # @line L10
if iv[j][1] >= start: # @line L11
return
active.remove(j) # @line L12
free.append(reg[j])
free.sort()
for i in order: # @line L6
start, end = iv[i]
expire_old(start) # @line L7
if len(active) == k: # @line L8
# SPILL-AT: of the k + 1 intervals that contain start, drop the
# one that ends last.
if k > 0:
s = active[-1] # @line L13
if k > 0 and end_key(s) > end_key(i): # @line L14
reg[i] = reg.pop(s)
spilled.add(s)
active.pop()
active.append(i)
active.sort(key=end_key)
else:
spilled.add(i) # @line L15
else:
reg[i] = free.pop(0) # @line L9
active.append(i)
active.sort(key=end_key)
return reg, spilled
def max_overlap(iv):
"""The largest number of intervals that contain one point."""
events = []
for s, e in iv.values():
events.append((s, 0))
events.append((e, 1))
best = cur = 0
for _, kind in sorted(events):
if kind == 0:
cur += 1
best = max(best, cur)
else:
cur -= 1
return best
# ----------------------------------------------------------- program level
def _check(prog):
for b in prog.blocks.values():
for ins in b.instrs:
if ins[0] not in ("const", "copy", "op"):
raise ValueError("only const, copy and op instructions: %r" % (ins,))
def liveness(prog):
"""live_in and live_out of each block, by the backward fixed point."""
use, kill = {}, {}
for label, b in prog.blocks.items():
u, d = set(), set()
for ins in b.instrs:
u.update(a for a in toyir.uses(ins) if a not in d)
d.add(ins[1])
u.update(a for a in toyir.term_uses(b.term) if a not in d)
use[label], kill[label] = u, d
live_in = {label: set() for label in prog.blocks}
live_out = {label: set() for label in prog.blocks}
changed = True
while changed:
changed = False
for label in reversed(list(prog.blocks)):
out = set()
for s in toyir.succs(prog, label):
out |= live_in[s]
new_in = use[label] | (out - kill[label])
if out != live_out[label] or new_in != live_in[label]:
live_out[label], live_in[label] = out, new_in
changed = True
return live_in, live_out
def linear_order(prog):
"""The instructions and terminators in block order, as a list of
(label, item, is_term). Item n reads at 2n and writes at 2n + 1."""
out = []
for label, b in prog.blocks.items():
for ins in b.instrs:
out.append((label, ins, False))
out.append((label, b.term, True))
return out
def live_before(prog):
"""For each item n of linear_order, the names live just before it."""
_, live_out = liveness(prog)
order = linear_order(prog)
result = [None] * len(order)
n = len(order) - 1
for label in reversed(list(prog.blocks)):
b = prog.blocks[label]
live = set(live_out[label]) | set(toyir.term_uses(b.term))
result[n] = set(live)
n -= 1
for ins in reversed(b.instrs):
live.discard(ins[1])
live.update(toyir.uses(ins))
result[n] = set(live)
n -= 1
return result
def intervals(prog):
"""One interval per name that is not a memory slot: from the first to
the last position where the name is defined (2n + 1) or live before an
item (2n)."""
order = linear_order(prog) # @line L1
live = live_before(prog) # @line L2
pos = {}
for n, (_, item, is_term) in enumerate(order): # @line L3
for x in live[n]:
if not is_mem(x):
pos.setdefault(x, []).append(2 * n)
if not is_term and not is_mem(item[1]):
pos.setdefault(item[1], []).append(2 * n + 1)
return {x: (min(p), max(p)) for x, p in pos.items()}
def _names(prog):
out = set(prog.params)
for b in prog.blocks.values():
for ins in b.instrs:
out.add(ins[1])
out.update(toyir.uses(ins))
out.update(toyir.term_uses(b.term))
return out
def prepare(prog):
"""A copy of prog whose arguments arrive in memory slots. A new entry
block loads each parameter that is live on entry, then jumps to the old
entry."""
_check(prog)
if any(is_mem(a) for a in _names(prog)):
raise ValueError("names that start with %r are reserved" % MEM)
live_in, _ = liveness(prog)
label = "start"
while label in prog.blocks:
label += "_"
pro = [("copy", p, MEM + p) for p in prog.params if p in live_in[prog.entry]]
blocks = {label: toyir.Block(pro, ("jump", prog.entry))}
for lab, b in prog.blocks.items():
blocks[lab] = toyir.Block(list(b.instrs), b.term)
return toyir.Program([MEM + p for p in prog.params], blocks)
def rewrite(prog, reg, spilled):
"""Replace each name by its location. A spilled name x lives in mem.x:
each use loads it into a scratch register first, and each definition
computes into s0 and then stores s0 into mem.x."""
def loc(a):
if not isinstance(a, str) or is_mem(a):
return a
if a in spilled:
return MEM + a
return "r%d" % reg[a]
blocks = {}
for label, b in prog.blocks.items():
out = []
for ins in b.instrs:
x = loc(ins[1])
if ins[0] == "const":
out.append(("const", x, ins[2]))
continue
srcs = [ins[2]] if ins[0] == "copy" else [ins[3], ins[4]]
locs = [loc(a) for a in srcs]
if ins[0] == "copy":
a = locs[0]
if a == x:
continue
if is_mem(a) and is_mem(x):
out += [("copy", "s0", a), ("copy", x, "s0")]
else:
out.append(("copy", x, a))
continue
loaded = {}
for a in locs:
if is_mem(a) and a not in loaded:
loaded[a] = SCRATCH[len(loaded)]
out.append(("copy", loaded[a], a))
a, c = (loaded.get(v, v) for v in locs)
if is_mem(x):
out += [("op", "s0", ins[2], a, c), ("copy", x, "s0")]
else:
out.append(("op", x, ins[2], a, c))
term = b.term
if term[0] in ("br", "ret") and is_mem(loc(term[1])):
out.append(("copy", "s0", loc(term[1])))
term = (term[0], "s0") + term[2:]
elif term[0] in ("br", "ret"):
term = (term[0], loc(term[1])) + term[2:]
blocks[label] = toyir.Block(out, term)
return toyir.Program(list(prog.params), blocks)
def allocate(prog, k):
work = prepare(prog)
iv = intervals(work)
reg, spilled = linear_scan(iv, k)
return rewrite(work, reg, spilled), reg, spilled # @line L16
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_linear_scan_register_allocation.py 203 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-scan-register-allocation/. The authors are listed in prov/5E24WB.jsonl.
import itertools
import random
import toyir
from linear_scan_register_allocation import (
allocate,
intervals,
is_mem,
linear_order,
linear_scan,
max_overlap,
prepare,
)
DIAMOND = """# params: p
entry:
a = p + 1
br p B1 B2
B1:
b = p * 2
c = b + p
ret c
B2:
d = a - p
ret d
"""
def brute_live(prog):
"""Liveness by search on the graph of single items: x is live before
item n when some path from n reaches a use of x and no item before that
use on the path defines x. This does not use the block fixed point."""
order = linear_order(prog)
first = {}
for n, (label, _, _) in enumerate(order):
first.setdefault(label, n)
nxt = []
for n, (label, item, is_term) in enumerate(order):
nxt.append([first[s] for s in toyir.succs(prog, label)] if is_term else [n + 1])
prv = [[] for _ in order]
for n, ss in enumerate(nxt):
for s in ss:
prv[s].append(n)
names = set()
used = [set() for _ in order]
defined = [None] * len(order)
for n, (_, item, is_term) in enumerate(order):
used[n] = set(toyir.term_uses(item) if is_term else toyir.uses(item))
if not is_term:
defined[n] = item[1]
names |= used[n]
live = [set() for _ in order]
for x in names:
work = [n for n in range(len(order)) if x in used[n]]
seen = set(work)
while work:
v = work.pop()
for p in prv[v]:
if p not in seen and defined[p] != x:
seen.add(p)
work.append(p)
for n in seen:
live[n].add(x)
return order, nxt, live
def check_registers(prog, k):
"""No two values that are live at the same time share a register, by the
independent liveness above. Returns the number of spilled names."""
work = prepare(prog)
out, reg, spilled = allocate(prog, k)
assert set(reg) | spilled == set(intervals(work))
assert not (set(reg) & spilled)
assert all(0 <= r < k for r in reg.values())
order, nxt, live = brute_live(work)
for n in range(len(order)):
held = [reg[x] for x in live[n] if x in reg]
assert len(held) == len(set(held)), (n, live[n])
_, item, is_term = order[n]
y = None if is_term else item[1]
if y in reg:
after = set().union(*(live[s] for s in nxt[n]))
for x in after:
if x != y and x in reg:
assert reg[x] != reg[y], (n, x, y)
allowed = {"r%d" % i for i in range(k)} | {"s0", "s1"}
for b in out.blocks.values():
for ins in b.instrs:
for a in [ins[1]] + toyir.uses(ins):
assert a in allowed or is_mem(a), a
return len(spilled)
def test_random_programs_keep_their_outputs():
rng = random.Random(5)
spills = 0
for trial in range(250):
prog = toyir.random_program(rng, rng.randint(2, 7), rng.randint(1, 7), acyclic=trial % 2 == 0)
for k in (1, 2, 3, 5):
spills += check_registers(prog, k)
out, _, _ = allocate(prog, k)
for _ in range(4):
args = [rng.randint(-6, 6), rng.randint(-6, 6)]
assert toyir.run(out, args, fuel=100000) == toyir.run(prog, args, fuel=100000)
assert spills > 0
def test_registers_used_is_max_overlap():
rng = random.Random(11)
seen_no_spill = seen_spill = 0
for trial in range(200):
prog = toyir.random_program(rng, rng.randint(2, 7), rng.randint(1, 6), acyclic=trial % 3 != 0)
iv = intervals(prepare(prog))
m = max_overlap(iv)
for k in range(1, 7):
reg, spilled = linear_scan(iv, k)
if m <= k:
assert not spilled
assert len(set(reg.values())) == m
seen_no_spill += 1
else:
assert spilled
seen_spill += 1
assert seen_no_spill and seen_spill
def overlap_of(iv, keep):
return max_overlap({x: iv[x] for x in keep}) if keep else 0
def test_spill_count_is_minimum_on_intervals():
rng = random.Random(3)
for trial in range(400):
n = rng.randint(1, 8)
iv = {}
for i in range(n):
s = rng.randint(0, 12)
iv["v%d" % i] = (s, s + rng.randint(0, 8))
for k in range(0, 4):
reg, spilled = linear_scan(iv, k)
keep = set(reg)
assert overlap_of(iv, keep) <= k
for a, b in itertools.combinations(sorted(keep), 2):
if iv[a][0] <= iv[b][1] and iv[b][0] <= iv[a][1]:
assert reg[a] != reg[b]
best = min(
n - len(sub)
for r in range(n + 1)
for sub in itertools.combinations(sorted(iv), r)
if overlap_of(iv, sub) <= k
)
assert len(spilled) == best, (iv, k, spilled, best)
def two_colorable(prog):
"""The interference graph of prog by the independent liveness, and an
exhaustive check that two colors suffice."""
order, nxt, live = brute_live(prog)
names = sorted(set().union(*live) | {item[1] for _, item, t in order if not t})
adj = {x: set() for x in names}
for n, (_, item, is_term) in enumerate(order):
if is_term:
continue
y = item[1]
for x in set().union(*(live[s] for s in nxt[n])):
if x != y:
adj[x].add(y)
adj[y].add(x)
for colors in itertools.product(range(2), repeat=len(names)):
c = dict(zip(names, colors))
if all(c[a] != c[b] for a in adj for b in adj[a]):
return adj, True
return adj, False
def test_diamond_spills_although_two_colors_suffice():
prog = toyir.parse(DIAMOND)
iv = intervals(prog)
assert iv == {"p": (0, 10), "a": (1, 10), "b": (5, 6), "c": (7, 8), "d": (11, 12)}
assert max_overlap(iv) == 3
reg, spilled = linear_scan(iv, 2)
assert spilled == {"a"}
adj, ok = two_colorable(prog)
assert ok
assert adj["a"] == {"p"} and adj["b"] == {"p"}
out, _, spilled = allocate(prog, 2)
assert spilled == {"a"}
for p in range(-5, 6):
assert toyir.run(out, [p]) == toyir.run(prog, [p])
def test_block_order_changes_the_result():
# The same program with B2 placed before B1: now a ends before b starts.
text = DIAMOND.replace("B1:\n b = p * 2\n c = b + p\n ret c\n", "")
text += "B1:\n b = p * 2\n c = b + p\n ret c\n"
prog = toyir.parse(text)
iv = intervals(prog)
assert max_overlap(iv) == 2
reg, spilled = linear_scan(iv, 2)
assert not spilled
History
Poletto, Engler and Kaashoek (1997) used linear scan as the fast allocator of tcc, a dynamic code generator for the Tick C language. Poletto and Sarkar (1999) described the algorithm in full, gave the furthest end spill rule, and showed that it ran much faster than graph coloring and gave code that was almost as fast. Traub, Holloway and Smith (1998) had in the meantime added lifetime holes and moves between a register and memory in their second-chance binpacking allocator. Wimmer and Mössenböck (2005) brought interval splitting into the Java HotSpot client compiler, and Wimmer and Franz (2010) moved linear scan onto SSA form.
References
- Massimiliano Poletto and Vivek Sarkar, Linear scan register allocation, ACM Transactions on Programming Languages and Systems 21(5), 1999, 895-913, the live intervals in a linear order, the scan with the routines EXPIRE-OLD-INTERVALS and SPILL-AT-INTERVAL, the rule that spills the interval that ends furthest away, and the comparison with graph coloring on compile time and code quality
- Massimiliano Poletto, Dawson R. Engler and M. Frans Kaashoek, tcc, a system for fast, flexible, and high-level dynamic code generation, PLDI 1997, 109-121, the fast register allocator of the tcc dynamic compiler, the first use of linear scan
- Omri Traub, Glenn Holloway and Michael D. Smith, Quality and speed in linear-scan register allocation, PLDI 1998, 142-151, second-chance binpacking, lifetime holes, the split of a lifetime at a spill, and the resolution moves on the edges of the control flow graph
- Christian Wimmer and Hanspeter Mössenböck, Optimized interval splitting in a linear scan register allocator, VEE 2005, 132-141, lifetime intervals with holes, use positions, the split of an interval at an optimal position, fixed intervals for machine registers, and the use in the Java HotSpot client compiler
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5E24WB Edit this page History Report an error Markdown