Sub topic 11
Translating control flow and boolean expressions
This chapter assumes you know three-address code from the previous chapters. You should be able to read instructions such as t1 = a + b, goto L and if a < b goto L. You should also know what a syntax-directed definition is, with inherited and synthesized attributes.
Two ways to compile a boolean
A boolean expression can be used in two ways, and the compiler translates each differently.
- As a value. In
x = a < b && c < d, the result is stored as 0 and 1. This is the numerical representation. - As a branch condition. In
if (a < b && c < d) ..., only the jump matters. This is the flow-of-control representation, also called jumping code.
Jumping code never builds a 0 or 1. The position in the program tells you the result. This also gives short-circuit evaluation for free. In B1 || B2, if B1 is true, the code jumps past B2 without running it.
Inherited labels
Each boolean expression B gets two inherited attributes, B.true and B.false. These are the labels where control goes when B is true or false. Each statement S gets an inherited S.next, the label of the code that follows it. A function newlabel() returns a fresh label each time.
| Production | Labels and code | Column | Column |
|---|---|---|---|
| `B → B1 \ | \ | B2` | `B1.true = B.true`, `B1.false = newlabel()`. `B2` gets `B.true` and `B.false`. Code: `B1.code`, label `B1.false`, `B2.code`. |
| `B → B1 && B2` | `B1.true = newlabel()`, `B1.false = B.false`. `B2` gets `B.true` and `B.false`. Code: `B1.code`, label `B1.true`, `B2.code`. | ||
| `B → ! B1` | `B1.true = B.false`, `B1.false = B.true`. Code: `B1.code`. | ||
| `B → E1 rel E2` | `if E1 rel E2 goto B.true`, then `goto B.false`. | ||
| `B → true` | `goto B.true` | ||
| `B → false` | `goto B.false` |
Statements use these rules.
| Statement | Labels and code |
|---|---|
| `if (B) S1` | `B.true = newlabel()`, `B.false = S.next`. Code: `B.code`, label `B.true`, `S1.code`. |
| `if (B) S1 else S2` | `B.true`, `B.false` are new. `S1.next = S2.next = S.next`. Code: `B.code`, label `B.true`, `S1.code`, `goto S.next`, label `B.false`, `S2.code`. |
| `while (B) S1` | `begin`, `B.true` are new. `B.false = S.next`, `S1.next = begin`. Code: label `begin`, `B.code`, label `B.true`, `S1.code`, `goto begin`. |
The goto S.next in the if-else rule is needed. Without it, the true branch would fall into the else code.
Eliminating the extra jumps
The relop rule emits two instructions, a conditional jump and an unconditional one. Most of the time one of the targets is the next instruction. The usual optimization uses a special label fall that means "continue with the next instruction".
- If both
B.trueandB.falseare real labels, emitif test goto B.trueandgoto B.false. - If only
B.trueis a real label, emitif test goto B.true. - If only
B.falseis a real label, emitifFalse test goto B.false.
For ||, if B.true is fall, then B1.true must be a new label. That label is placed after B2.code. The rule for && is symmetric.
Worked example
Translate if (a < b || c < d && e < f) x = 1; with fall-through. Here && binds tighter than ||. Let L1 be S.next. The code is:
if a < b goto L2
ifFalse c < d goto L1
ifFalse e < f goto L1
L2: x = 1
L1:If a < b holds, control jumps straight to x = 1. Otherwise both c < d and e < f must hold, and failing either skips the assignment.
A while loop works the same way. For while (i < 10) { s = s + i; i = i + 1; }, the code is:
L1: ifFalse i < 10 goto L3
s = s + i
i = i + 1
goto L1
L3:The same rules in code
This Python program implements the rules above. None stands for fall.
import itertools
_counter = itertools.count(1)
code = []
def newlabel():
return f"L{next(_counter)}"
def emit(line):
code.append(line)
def gen_bool(e, true, false):
kind = e[0]
if kind == "rel":
_, op, a, b = e
test = f"{a} {op} {b}"
if true and false:
emit(f" if {test} goto {true}")
emit(f" goto {false}")
elif true:
emit(f" if {test} goto {true}")
elif false:
emit(f" ifFalse {test} goto {false}")
elif kind == "or":
b1_true = true or newlabel()
gen_bool(e[1], b1_true, None)
gen_bool(e[2], true, false)
if true is None:
emit(f"{b1_true}:")
elif kind == "and":
b1_false = false or newlabel()
gen_bool(e[1], None, b1_false)
gen_bool(e[2], true, false)
if false is None:
emit(f"{b1_false}:")
elif kind == "not":
gen_bool(e[1], false, true)
def gen_if(cond, body):
after = newlabel()
gen_bool(cond, None, after)
emit(f" {body}")
emit(f"{after}:")
cond = ("or", ("rel", "<", "a", "b"),
("and", ("rel", "<", "c", "d"), ("rel", "<", "e", "f")))
gen_if(cond, "x = 1")
print("\n".join(code))Running it prints exactly the five-line listing shown in the worked example.
Boolean values and common errors
When a boolean is stored in a variable, the compiler can still use jumping code. For x = a < b && c < d, it first generates the jumps and then converts them to values:
ifFalse a < b goto L1
ifFalse c < d goto L1
x = 1
goto L2
L1: x = 0
L2:Common mistakes:
- Swapping the labels for
&&and||. For&&, a failed first operand jumps toB.false. For||, a successful first operand jumps toB.true. - Forgetting
goto S.nextafter the true branch of an if-else. - Jumping to the wrong label at the end of a loop. The body ends with
goto begin, and the exit label isS.next. - Counting labels as instructions. A label is not an instruction, but each
gotoandifis one.
Exercise
Translate while (a < b && c < d) a = a + 1; into three-address code using fall-through. How many instructions are there, not counting labels?
Show answer
The code is L1: ifFalse a < b goto L3, ifFalse c < d goto L3, a = a + 1, goto L1, and then label L3. This is 4 instructions. The first test fails to B.false = L3. The second test also fails to L3. If both pass, the code falls into the body and goto L1 repeats the loop.
Exercise
In if (x != 0 && y / x > 2) z = 1;, why must the translation test x != 0 first and jump out on failure?
Show answer
Because && is short-circuit. The rule B1.false = B.false makes a failed x != 0 skip the rest of the condition, so y / x never runs when x is 0. This prevents a division by zero.