Code Generation

Outline

Stack Machines

Example of a Stack Machine Program

Why Use a Stack Machine?

Why Use a Stack Machine?

Optimizing the Stack Machine

Stack Machine with Accumulator: Invariants

Stack Machine with Accumulator: Example

From Stack Machines to Three-address Code

Notes

Simulating a Stack Machine with Assembly

Sample Instructions

Example

A Small Language

A Small Language

Code Generation Strategy

Code Generation for Constants

Code Generation for Addition

\(cgen(e_1 + e_2) =\)
\(\qquad cgen(e_1)\) ; acc := the value \(e_1\)
\(\qquad\)sw acc 0(sp) ; push that value on the stack
\(\qquad\)li t1 -4
\(\qquad\)add sp sp t1
\(\qquad cgen(e_2)\) ; acc := the value of \(e_2\)
\(\qquad\)lw t1 4(sp) ; retreive the value of \(e_1\)
\(\qquad\)add acc t1 acc ; perform the addition
\(\qquad\)li t1 4 ; pop the stack
\(\qquad\)add sp sp t1

Code Generation Notes

Code Generation for Subtraction

Code Generation for Conditionals

Code Generation for If Then Else

\(cgen(if \; e_1 = e_2 \; then \; e_3 \; else \; e_4) =\)
\(\qquad cgen(e_1)\)
\(\qquad\)sw acc 0(sp)
\(\qquad\)li t1 -4
\(\qquad\)add sp sp t1
\(\qquad cgen(e_2)\)
\(\qquad\)lw t2 4(sp)
\(\qquad\)li t1 4
\(\qquad\)add sp sp t1
\(\qquad\)beq acc t2
false_branch:
\(\qquad cgen(e_4)\)
\(\qquad\)jump end_if
true_branch:
\(\qquad cgen(e_3)\)
end_if:

Code Generation for Functions

Layout of the Activation Record

Code Generation for a Function Call

Code Generation for a Function Call

\(cgen(f(e_1, \ldots, e_n)) =\)
\(\qquad\)sw fp 0(sp) ; the caller saves the value of the
\(\qquad\)li t1 -4 ; frame pointer
\(\qquad\)add sp sp t1
\(\qquad cgen(e_n)\) ; push the actual parameters in
\(\qquad\)sw acc 0(sp) ; reverse order
\(\qquad\)li t1 -4
\(\qquad\)add sp sp t1
\(\qquad\ldots\)
\(\qquad cgen(e_1)\)
\(\qquad\)sw acc 0(sp)
\(\qquad\)li t1 -4
\(\qquad\)add sp sp t1
\(\qquad\)jumpal f_entry ; jump and save return address in ra

Code Generation for a Function Definition

\(cgen(f(x_1, \ldots, x_n) \; begin \; e \; end) =\)
f_entry
\(\qquad\)move fp sp
\(\qquad\)sw acc 0(sp)
\(\qquad\)li t1 -4
\(\qquad\)add sp sp t1
\(\qquad cgen(e)\)
\(\qquad\)lw ra 4(sp)
\(\qquad\)li t1 frame_size \(\qquad\); frame size is \(4n + 8\)
\(\qquad\)add sp sp t1
\(\qquad\)lw fp 0(sp)
\(\qquad\)jumpr ra

Calling Sequence: Example for \(f(x,y)\)

Calling Sequence: Example for \(f(x,y)\)

Calling Sequence: Example for \(f(x,y)\)

Calling Sequence: Example for \(f(x,y)\)

Code Generation for Variables/Parameters

Code Generation for Variables/Parameters

Code Generation for Variables/Parameters

Activation Record and Code Generation Summary