3 Assignment Statements
In 8.1 we ignored the issue of symbol-table entry and lookup
(just assumed .place attribute worked properly)
Compiler Construction Now we show how symbol tables are actually used.
Replace .code attribute and gen function with emit function,
which emits (generates) three-address code directly
Chapter 8: Intermediate Code From previous section, we assume expressions are evaluated
Generation in context of declarations:
8.3-8.4: Assignment Statements and P
MD
M
∈
Boolean Expressions D
D ; D | id : T | proc id ; D ; S
N
id := E { p := lookup (id.name); // get address: t1, etc. newtmp generates a new temporary variable (t1, t2, t3, ...)
if p nil then emit (p ':=' E.place)
- E1 { E.place := newtmp;
code:
emit(E.place ':= 'uminus' E1.place) }
evaluate E1 into t1
E
( E1 ) { E.place := E1.place; } E
E1 + E2 ⇒ evaluate E2 into t2
E
id { p := lookup (id.name); t1 := t1 + t2
if p nil then E.place := p
else error }
Reusing Temporary Names 8.4 Boolean Expressions
Solution: keep a count of temporaries, which gets incremented Recall our grammar from PS7:
when a temp is created, and decremented when a temp is used
as an operand (acts like a stack) expr
true | false
t1 := c * d 2
t0 := t0 + t1 1
t1 := e * f 2 Need a way of translating booleans and control-flow (if-then-
t0 := t0 - t1 1 else) into three-address code
x := t0 0
⇓
• true represented as 1
• false represented as 0
• and, or work like arithmetic expressions t1 := not c
– Flow-of-control t2 := b and t1
• Represent value of boolean by position in program t3 := a or t1
• E.g., if first part of or evaluates to true, jump over evaluation of
second part
Numerical Representation Numerical Representation
E
E1 or E2 { E.place := newtmp;
emit(E.place ':= ' E1.place 'or' E2.place) }
if a < b then 1 else 0 E
⇓ E
( E1 ) { E.place := E1.place; }
103: t :=1
E
E.code S.begin:
E.code E.code
E.true: S1.code E.true: S1.code E.true: S1.code
E.false: ... goto S.next goto S.begin
if-then
E.false: S2.code E.false: ...
S.next: ... while-do
if-then-else
E1 or E2 { E1.true := E.true;
• Now we can see how to implement the flow-of-control version
E1.false := newlabel
of boolean expression translation.
E2.true := E.true;
• E.g., a < b or c < d and e < f E2.false := E.false;
⇓
E.code := E1.code || gen (E1.false ':' ) || E2.code }
E
( E1 ) {E1.true := E.true;
E1.false := E.false
E.code := E1.code;}
E
E