COAL FALL 15 Lecture 11 and 12 Procedure Call
COAL FALL 15 Lecture 11 and 12 Procedure Call
Procedures
12/10/15
Supporting Procedures
Procedure Steps
1)
2)
3)
4)
5)
6)
2
$ra
12/10/15
addi
sw
sw
sw
12/10/15
lw
lw
lw
addi
$s0, 8($sp)
$t0, 4($sp)
$t1, 0($sp)
$sp $sp +12
Procedure
int leaf_example (int g, int h, int i, int j)
{
int f;
f = (g + h) (i + j);
return f;
}
f, g, h, i, j = $s0, $a0, $a1, $a2, $a3
12/10/15
Procedure
Leaf_example:
addi $sp, $sp, -12
sw $t1, 8($sp)
Adjusting Stack
sw $t0, 4($sp)
sw $s0, 0($sp)
12/10/15
Temporary contents
Not saved
Not restored
10
12/10/15
Example
int main()
{
x=addthem(a,b);
}
int addthem(int a, int b)
{
return a+b;
}
#assume value a is already in $t0, b in $t1
11
12/10/15
Example
.text
main: #assume value a is already in $t0, b in $t1
add $a0,$0,$t0 # it's the same function as move the value
add $a1,$0,$t1
jal addthem # call procedure
add $t3,$0,$v0 # move the return value from $v0 to where
#we want
syscall
addthem:
addi $sp,$sp,-4 # Moving Stack pointer
sw $t0, 0($sp) # Store previous value
add $t0,$a0,$a1 # Procedure Body
add $v0,$0,$t0 # Result
lw $t0, 0($sp) # Load previous value
addi $sp,$sp,4 # Moving Stack pointer
jr $ra # return (Copy $ra to PC)
12
12/10/15
Push on to stack
13
12/10/15
Recursive Procedure
14
12/10/15
Recursive Procedure
fact:
sub $sp, $sp, 8
sw $ra, 4($sp)
sw $a0, 0($sp)
slt $t0, $a0, 1
beq $t0, $zero, L1
add $v0, $zero, 1
add $sp, $sp, 8
jr $ra
L1:
15
02/03/05
Addressing Modes
12/10/15
rs
rt
Immediate
2. Register addressing
op
rs
rt
rd
...
funct
Registers
Register
3. Base addressing
op
rs
rt
Memory
Address
Register
Byte
Halfword
Word
4. PC-relative addressing
op
rs
rt
Memory
Address
PC
Word
5. Pseudodirect addressing
op
Address
PC
17
Memory
Word
12/10/15