90 likes | 183 Views
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.
E N D
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 Details So 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
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 # return1 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 … %ebp = $fp esp = $sp _fact: pushl %ebp movl %esp, %ebp subl $8, %esp cmpl $0, 8(%ebp) jne L2 movl $1, -4(%ebp) jmp L1 See 2.16 for more From "gcc –S"
And Now for the Pentium … L2: movl 8(%ebp), %eax decl %eax movl %eax, (%esp) call _fact imull 8(%ebp), %eax movl %eax, -4(%ebp) L1: movl -4(%ebp), %eax leave ret
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.