Intermezzo
How to deal with
procedures / functions?
A (very) short introduction to the stack
and stack frames (activation records)
1
6 Steps in Execution of a Procedure
1. Main routine (caller) places parameters in a place
where the procedure (callee) can access them
! $a0 - $a3: four argument registers
2. Caller transfers control to the callee
3. Callee acquires the storage resources needed
4. Callee performs the desired task
5. Callee places the result value in a place where the
caller can access it
! $v0 - $v1: two value registers for result values
6. Callee returns control to the caller
! $ra: one return address register to return to the point of origin
2
Procedure Call Instructions
Procedure call: jump and link
jal ProcedureLabel
◦ Address of following instruction put in $ra
◦ Jumps to target address
Procedure return: jump register
jr $ra
◦ Copies $ra to program counter
◦ Can also be used for computed jumps
e.g., for case/switch statements
3
Non-Leaf Procedures
Procedures that call other procedures
For nested call, caller needs to save on
the stack (special section of memory):
◦ Its return address
◦ Any arguments and temporaries needed after
the call
Restore from the stack after the call
4
Memory Layout
Text: program code
Static data: global variables
◦ e.g., static variables in C,
constant arrays and
strings
◦ $gp initialized to address
allowing ±offsets into this
segment
Dynamic data: heap
◦ e.g., ‘malloc’ in C, ‘new’ in
Java
Stack: automatic storage
5
Local Data on the Stack
Local data allocated by callee
◦ e.g., C automatic variables
Procedure/Stack frame (activation record)
6
Recap: Register Usage
$zero: hardwired value 0 (reg 0)
$a0 – $a3: arguments (reg’s 4 – 7)
$v0, $v1: result values (reg’s 2 and 3)
$t0 – $t9: temporaries (reg’s 8 – 15, 24, 25)
◦ Can be overwritten by callee
$s0 – $s7: saved (reg’s 16 – 23)
◦ Must be saved/restored by callee
$gp: global pointer for static data (reg 28)
$sp: stack pointer (reg 29)
$fp: frame pointer (reg 30)
$ra: return address (reg 31)