Sub topic 12
Backpatching
This chapter assumes you can read three-address code and know how a syntax-directed definition attaches attributes to grammar symbols. It also assumes you know the short-circuit translation of boolean expressions from the previous chapter, where B.true and B.false are labels passed down as inherited attributes.
The problem with forward jumps
When a compiler translates if (B) S, the jump out of B must name the instruction that follows S. That instruction has not been generated yet. There are two common fixes:
- Make two passes. The first pass emits jumps with symbolic labels. The second pass replaces each label with an instruction number.
- Make one pass. Leave each jump's target blank, remember which jumps are blank, and fill them in once the target number is known. This is backpatching.
Backpatching also works with bottom-up (LR) parsing. A bottom-up parser cannot pass inherited labels down into a subtree, so the translation is written with synthesized attributes only. Those attributes are lists of incomplete jumps.
Three list operations
An instruction number identifies a jump whose target field is still empty. The translation uses these functions, and nextinstr is the number of the next instruction to be emitted:
| Function | Meaning |
|---|---|
| `makelist(i)` | Create a new list containing only instruction `i` |
| `merge(p1, p2)` | Return the concatenation of lists `p1` and `p2` |
| `backpatch(p, t)` | Insert `t` as the target of every instruction on list `p` |
Marker nonterminals
A rule such as B → B1 && B2 has no point where the parser can record "the instruction number where B2 starts". The grammar adds a marker nonterminal M → ε with the action M.instr = nextinstr. Placing M just before B2 captures that number. A second marker N → ε emits an unconditional goto _ and sets N.nextlist = makelist(nextinstr). It is used to jump over an else part.
Each boolean expression B carries two attributes. B.truelist holds the jumps taken when B is true. B.falselist holds the jumps taken when B is false. Each statement S carries S.nextlist, the jumps that leave S for whatever instruction follows it.
Translation rules
B -> B1 || M B2 { backpatch(B1.falselist, M.instr);
B.truelist = merge(B1.truelist, B2.truelist);
B.falselist = B2.falselist; }
B -> B1 && M B2 { backpatch(B1.truelist, M.instr);
B.truelist = B2.truelist;
B.falselist = merge(B1.falselist, B2.falselist); }
B -> ! B1 { B.truelist = B1.falselist; B.falselist = B1.truelist; }
B -> ( B1 ) { B.truelist = B1.truelist; B.falselist = B1.falselist; }
B -> E1 rel E2 { B.truelist = makelist(nextinstr);
B.falselist = makelist(nextinstr + 1);
emit("if E1.addr rel.op E2.addr goto _");
emit("goto _"); }
B -> true { B.truelist = makelist(nextinstr); emit("goto _"); }
S -> if ( B ) M S1
{ backpatch(B.truelist, M.instr);
S.nextlist = merge(B.falselist, S1.nextlist); }
S -> if ( B ) M1 S1 N else M2 S2
{ backpatch(B.truelist, M1.instr);
backpatch(B.falselist, M2.instr);
S.nextlist = merge(merge(S1.nextlist, N.nextlist), S2.nextlist); }
S -> while M1 ( B ) M2 S1
{ backpatch(S1.nextlist, M1.instr);
backpatch(B.truelist, M2.instr);
S.nextlist = B.falselist;
emit("goto M1.instr"); }
S -> S1 ; M S2
{ backpatch(S1.nextlist, M.instr);
S.nextlist = S2.nextlist; }The rule for ! needs no code. It swaps the two lists.
Worked example
Translate if (a < b || c < d && e < f) x = 1; with the first instruction numbered 100. The operator && binds tighter than ||.
a < bemits 100 (if a < b goto _) and 101 (goto _). Its truelist is {100} and its falselist is {101}. The marker beforec < drecords 102.c < demits 102 and 103. The marker beforee < frecords 104.e < femits 104 and 105.- The
&&rule backpatches {102} with 104. The result has truelist {104} and falselist {103, 105}. - The
||rule backpatches {101} with 102. The result has truelist {100, 104} and falselist {103, 105}. - The
ifrule's marker records 106, andx = 1is emitted at 106. The rule backpatches {100, 104} with 106.S.nextlistis {103, 105}.
Instructions 103 and 105 stay open until the next statement begins.
A runnable sketch
This program carries out the same steps. Each list is a Python list of instruction numbers, and a jump's target is written over its trailing _.
BASE = 100
code = []
def nextinstr():
return BASE + len(code)
def emit(text):
code.append(text)
def makelist(i):
return [i]
def merge(p1, p2):
return p1 + p2
def backpatch(p, target):
for i in p:
code[i - BASE] = code[i - BASE][:-1] + str(target)
def rel(x, op, y):
t, f = makelist(nextinstr()), makelist(nextinstr() + 1)
emit(f"if {x} {op} {y} goto _")
emit("goto _")
return t, f
def b_and(b1, m, b2):
backpatch(b1[0], m)
return b2[0], merge(b1[1], b2[1])
def b_or(b1, m, b2):
backpatch(b1[1], m)
return merge(b1[0], b2[0]), b2[1]
b1 = rel("a", "<", "b")
m1 = nextinstr()
c = rel("c", "<", "d")
m2 = nextinstr()
e = rel("e", "<", "f")
B = b_or(b1, m1, b_and(c, m2, e))
m = nextinstr()
emit("x = 1")
backpatch(B[0], m)
nextlist = B[1]
backpatch(nextlist, nextinstr()) # the next statement starts at 107
for n, line in enumerate(code, BASE):
print(n, line)
# 100 if a < b goto 106
# 101 goto 102
# 102 if c < d goto 104
# 103 goto 107
# 104 if e < f goto 106
# 105 goto 107
# 106 x = 1Common errors
- Backpatching the wrong list. For
&&, the left operand's truelist is patched. For||, the left operand's falselist is patched. - Forgetting the unconditional
goto. Every relational expression emits two instructions. The second is the false jump. - Losing jumps in
S.nextlist. Inif-else, the nextlist combines three sources:S1.nextlist,N.nextlistandS2.nextlist. Dropping any one leaves a jump with no target. - Placing the marker in the wrong spot.
Mmust come before the operand whose first instruction it records, not after it. - Leaving jumps open. At the end of translation, every instruction must be on exactly one list or already patched. The outermost
S.nextlistis patched to the first instruction after the program.
Exercise
Apply the rules to while (a < b) x = 1;, numbering from 100. Give every instruction with its final target, and state the final S.nextlist.
Show answer
The first marker M1 records 100. The condition emits 100 if a < b goto _ and 101 goto _. The second marker M2 records 102. The body emits 102 x = 1. S1.nextlist is empty, so nothing is patched to M1. The rule backpatches B.truelist {100} with 102. It emits 103 goto 100. The final code is 100 if a < b goto 102, 101 goto _, 102 x = 1, 103 goto 100. S.nextlist is B.falselist, which is {101}. Instruction 101 is patched to 104 once the next statement starts.