Sub topic 9
Translating Control Flow and Boolean Expressions
Assume you know C-style statements, three-address code (TAC), labels, and basic control-flow graphs. This chapter shows how a compiler translates decisions and loops into jumps, then explains how backpatching fills in unknown jump targets.
Translating control flow
A TAC instruction usually has at most one operation and a small number of operands. Control flow is represented with labels and jumps.
For an if-else statement:
if (x < y)
z = x;
else
z = y;one possible translation is:
if x < y goto L_then
goto L_else
L_then:
z = x
goto L_end
L_else:
z = y
L_end:The conditional jump selects the true branch. The unconditional jump prevents the true branch from falling through into the false branch.
A while loop places its test before the body:
while (x < 10)
x = x + 1;L_test:
if x < 10 goto L_body
goto L_exit
L_body:
x = x + 1
goto L_test
L_exit:Each label begins a possible basic block. The conditional and unconditional jumps create the edges of the control-flow graph.
Short-circuit Boolean expressions
Boolean operators often use short-circuit evaluation:
A && BevaluatesBonly ifAis true.A || BevaluatesBonly ifAis false.!Aexchanges the true and false destinations.
For example:
if (a < b && c != 0)
result = 1;can become:
if a < b goto L_check_c
goto L_false
L_check_c:
if c != 0 goto L_true
goto L_false
L_true:
result = 1
goto L_end
L_false:
L_end:This preserves the source program's behavior. In particular, c is not tested when a < b is false.
Backpatching
During syntax-directed translation, the compiler may generate a jump before it knows the label's final instruction number. Backpatching records that unfinished jump and fills in its target later.
A Boolean expression commonly carries two lists:
truelist: jumps that should go to the expression's true destination.falselist: jumps that should go to its false destination.
A statement such as if (E) S1 else S2 also needs a list of jumps that leave S1. Once the compiler reaches the correct locations, it backpatches each list with the corresponding label.
For E1 && E2, the compiler backpatches E1.truelist to the beginning of E2. The false list of the combined expression contains both false lists. For E1 || E2, it backpatches E1.falselist to E2, and combines both true lists.
| Construct | Patch first part to | Combined result | Column | Column |
|---|---|---|---|---|
| `E1 && E2` | Start of `E2` | true from `E2`, false from either expression | ||
| `E1 | E2` | Start of `E2` | true from either expression, false from `E2` |
Exercise
In if (p || q) x = 1;, which pending jumps are patched to the start of q?
Show answer
The jumps in p.falselist, because q is evaluated only when p is false.