cs 300 – lecture 10 intro to computer architecture / assembly language strings and characters and...
TRANSCRIPT
CS 300 – Lecture 10
Intro to Computer Architecture
/ Assembly Language
Strings and Characters and More
Function Calling
Basic ideas:
* Parameters passed into function
* Return address
* Return values
* Registers saved / destroyed during the call
* Saving other data during the call
The GORY DetailsSo what does a function look like?Initially:* Frame allocation* Save values to the frame (including return address). Usually need to move args there. Save $s0 - $s7 if used later.Finally:* Put return values in proper registers.* Resture $s0 - $s7* Deallocate the frame* Branch to the return address ("jr")Calling other functions:* Push needed information that is not in the stack frame or a saved register* Perform "jal"* Pop the stack
Aside: MIPS Register Convention
Name Register Number
Usage Preserve on call?
$zero 0 constant 0 (hardware) n.a.
$at 1 reserved for assembler n.a.
$v0 - $v1 2-3 returned values no
$a0 - $a3 4-7 arguments yes
$t0 - $t7 8-15 temporaries no
$s0 - $s7 16-23 saved values yes
$t8 - $t9 24-25 temporaries no
$gp 28 global pointer yes
$sp 29 stack pointer yes
$fp 30 frame pointer yes
$ra 31 return addr (hardware) yes
Example
Factorial: f(x) = if x <= 0 then 1 else x*f(x-1)fact: addi $sp, $sp, -8 # Make frame sw $ra, 4($sp) # save ra, a1 sw $a0, 0($sp) slti $t0, $a0, 1 # a0 < 1? beq $t0, $zero, L1 addi $v0, $zero, 1 # return 1 addi $sp, $sp, 8 jr $ra
Factorial
L1: addi $a0, $a0, -1
jal fact
lw $a0, 0($sp)
lw $ra, 4($sp)
addi $sp, $sp, 8
mul $v0, $a0, $v0
jr $ra
And Now for the Pentium …
_fact:pushl %ebpmovl %esp, %ebpsubl $8, %espcmpl $0, 8(%ebp)jne L2movl $1, -4(%ebp)jmp L1
%ebp = $fp esp = $sp
From "gcc –S"
See 2.16 for more
And Now for the Pentium …
L2: movl 8(%ebp), %eaxdecl %eaxmovl %eax, (%esp)call _factimull 8(%ebp), %eaxmovl %eax, -4(%ebp)
L1: movl -4(%ebp), %eaxleaveret
More About $fp
Why have both $sp and $fp?* Stack use varies within a function (why?). Using $fp, we always know where locals are* $fp allows for the creation of chained environments. This is needed in Java for nested objects.* $fp can accept incoming parameters from the stack top
Note that you often don't need $fp at all.