28/06/2015CMPUT Functions (2) Function calling convention Various conventions available One is specified by CMPUT229 Recursive functions
28/06/2015CMPUT Recursive functions A function that calls itself Terminating condition Stack frame implementation
28/06/2015CMPUT Function calling convention In summary, caller: 1.saves temporary registers by pushing their values on stack 2.pushes arguments (both “value” and “variable” on stack 3.calls the function with jal instruction (function runs until it returns, then:) 4.clears function arguments by popping allocated space 5.restores saved temporary registers by popping their values off the stack 6.uses the return value found in both $v0 and popped “variable” arguments
28/06/2015CMPUT Function calling convention In summary, callee: 1.saves $ra by pushing its value on stack 2.saves $fp by pushing its value on stack 3.copies $sp to $fp 4.allocates local variables (body of function goes here, then:) 5.chooses return value by setting register $v0 6.deallocates local variables by popping allocated space 7.restores $fp by popping its saved value 8.restores $ra by popping its saved value 9.returns with jr $ra
28/06/2015CMPUT Recursion Function calling convention works exactly the same for recursive functions don’t need to do anything special Each invocation of the function has its own stack frame local variables and parameters with their current valueswith their current values return address where to return towhere to return to
28/06/2015CMPUT Example Fibonacci’s numbers fib(0) = 0 fib(1) = 1 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) for n > 1 fib(n) = fib(n-1) + fib(n-2) for n > 1
28/06/2015CMPUT Fibonacci Numbers
28/06/2015CMPUT Implementation of Recursive Functions Different conventions can be used for writing recursive functions MIPS $a0 for taking input parameters $v0 for returning results Callers save $t0, $t1, …, Callees save $s0, $s1, …,
28/06/2015CMPUT Implementation of Recursive Functions Other conventions Callees save all registers
28/06/2015CMPUT More restricted conventions All arguments are passed with the stack frame, including the value and variable parameters Useful and important
28/06/2015CMPUT More restricted conventions All arguments are passed with the stack frame, including the value and variable parameters Frame pointers Used by compilers but difficult to understand
28/06/2015CMPUT More restricted conventions All arguments are passed with the stack frame, including the value and variable parameters Frame pointers Used by compilers but difficult to understand
28/06/2015CMPUT Two different implementations of fibonacci numbers Simple one (fib.a) Using $a0 and $v0 to pass argumentsUsing $a0 and $v0 to pass arguments Callees save all the registersCallees save all the registers Stack frame (fib_stack.a) Using the stack frame for passing the arguments to and from the functionUsing the stack frame for passing the arguments to and from the function