Procedures (Cont.)
Download
Report
Transcript Procedures (Cont.)
COMPUTER ARCHITECTURE &
OPERATIONS I
Instructor: Yaohang Li
Review
Last Class
Procedure Call
Leaf Procedure
This Class
Quiz
Non-leaf Procedure
Next Class
Characters
Starting a Program
Linking
Non-Leaf Procedures
Procedures that call other procedures
For nested call, caller needs to save on the
stack:
Its return address
Any arguments and temporaries needed after
the call
Restore from the stack after the call
Non-Leaf Procedure Example
C code:
int fact (int n)
{
if (n < 1) return 1;
else return n * fact(n - 1);
}
Argument n in $a0
Result in $v0
Non-Leaf Procedure Example
MIPS code:
fact:
addi
sw
sw
slti
beq
addi
addi
jr
L1: addi
jal
lw
lw
addi
mul
jr
$sp,
$ra,
$a0,
$t0,
$t0,
$v0,
$sp,
$ra
$a0,
fact
$a0,
$ra,
$sp,
$v0,
$ra
$sp, -8
4($sp)
0($sp)
$a0, 1
$zero, L1
$zero, 1
$sp, 8
$a0, -1
0($sp)
4($sp)
$sp, 8
$a0, $v0
#
#
#
#
adjust stack for 2 items
save return address
save argument
test for n < 1
#
#
#
#
#
#
#
#
#
#
if so, result is 1
pop 2 items from stack
and return
else decrement n = n - 1
recursive call
restore original n
and return address
pop 2 items from stack
multiply to get result
and return
What is preserved and what is not?
Data and registers preserved and not
preserved across a procedure call
Global Pointer
Two kinds of C/C++ variables
automatic
static
Local to a procedure
Discarded when the procedure exits
Global to a procedure
Still exist after procedure exits
Can be revisited
Global Pointer
$gp
Point to static area
Procedure Frame
Revisiting Stack
Stack not only stores the saved registers
but also local variables that do not fit in
registers
local arrays or structures
Procedure Frame (activation record)
Segment of the stack containing a procedure’s
saved registers and local variables
Frame pointer
Point to the location of the saved registers and
local variables for a given procedure
Local Data on the Stack
Local data allocated by callee
e.g., C automatic variables
Procedure frame (activation record)
Used by some compilers to manage stack storage
MIPS Memory Layout
32-bit address space
0x80000000 ~ 0xFFFFFFFF
0x00000000~0x003FFFFF
Reserved
0x00400000~0x0FFFFFFF
Not available for user program
For OS and ROM
Text: Machine language of the user program
0x10000000~0x7FFFFFFF
Data
Static
Static variables
Constants
Dynamic
Malloc() in C, New in java
Stack
Memory Layout
Register Summary
Register 1: $at
reserved for the assembler
Register 26-27: $k0-$k1
reserved for the OS
Summary
Procedure Call
Registers used
Stack
jal and jr
leaf and no-leaf procedure
Allocating space for new data on the heap
What I want you to do
Review Chapter 2
Work on your assignment 5