Presentation is loading. Please wait.

Presentation is loading. Please wait.

Function Calls in Assembly MIPS R3000 Language (extensive use of stack) Updated 7/11/2013.

Similar presentations


Presentation on theme: "Function Calls in Assembly MIPS R3000 Language (extensive use of stack) Updated 7/11/2013."— Presentation transcript:

1 Function Calls in Assembly MIPS R3000 Language (extensive use of stack)
Updated 7/11/2013

2 Function Call Stack High-level languages hide the behind-the-scenes details of stack allocations for function calls int ans = max(5, 17); // Function call. int max(int x, int y) { if(x >= y) return x; else return y; } max x = 5, y = 17 MAIN ans =

3 Dynamic Memory Allocation
Space for objects created using “new” are allocated from a pool of memory called the heap. String messg = new String(“Java”); int[] A = new int[4]; messg “Java” A { 0, 0, 0, 0 }

4 MIPS Memory Allocation
Text segment: holds the program instructions Data segment: holds static and dynamically allocated program data Stack segment: data, parameters, and local variables allocated for function calls

5 MIPS Memory Map calls: findMax(x, y); Stack Segment Dynamic Data
Static Data malloc(sizeof(MyStruct)); A: .word 1, 2, 3, 4, 5 Text Segment MIPS program code Reserved

6 MIPS Memory Map Stack grows downwards Stack Segment Dynamic Data
Static Data Dynamic data grows upwards Text Segment Reserved

7 Using the Stack In general the assembly programmer should use space on the stack to store information relevant to a function or procedure call. Parameters Local variables declared inside the function Save copy of registers whose contents are changed as result of being used as local variables Save $ra on stack for recursive functions

8 The MIPS Stack Stack pointer register $sp holds the address of the topmost data element on the stack. On MIPS the stack grows downwards in memory Address of next byte pushed on top has an address 1 less than current $sp. Address of next word pushed on top has an address 4 less than current $sp.

9 Push a Byte On “Top” of Stack
# Assume $t0 contains value of 8-bit variable C. # Push low-order byte in $t0 onto top of stack. addiu $sp, $sp, -1 sb $t0, ($sp) 0x7FFF A 0x7FFF A $sp 0x7FFE B 0x7FFE B $sp 0x7FFD 0x7FFD C 0x7FFC 0x7FFC ... ... BEFORE: $sp points to B AFTER: $sp points to the topmost value C the topmost value

10 Pop Byte From “Top” of Stack
# Pop byte from top of stack into $t0. lb $t0, ($sp) addiu $sp, $sp, 1 0x7FFF A 0x7FFF A $sp 0x7FFE B 0x7FFE B $sp 0x7FFD C 0x7FFD 0x7FFC 0x7FFC ... ... BEFORE: $sp points to C AFTER: $sp points to the topmost value B the topmost value

11 Push a Word On “Top” of Stack
# Assume $t0 contains value of variable C. # Push word in $t0 onto top of stack. addiu $sp, $sp, -4 sw $t0, ($sp) 0x7FFF A 0x7FFF A $sp 0x7FFB B 0x7FFB B $sp 0x7FF7 0x7FF7 C 0x7FF3 0x7FF3 ... ... BEFORE: $sp points to B AFTER: $sp points to the topmost value C the topmost value

12 Pop Word From “Top” of Stack
# Pop word from top of stack into $t0. lw $t0, ($sp) addiu $sp, $sp, 4 0x7FFF A 0x7FFF A $sp 0x7FFB B 0x7FFB B $sp 0x7FF7 C 0x7FF7 0x7FF3 0x7FF3 ... ... BEFORE: $sp points to C AFTER: $sp points to the topmost value B the topmost value

13 Evaluation of Arithmetic Expressions
Given the infix expression: * 5 Convert to postfix: * + Use a stack algorithm to evaluate the postfix expression. What was that algorithm?

14 Evaluate Postfix with a Stack
Given postfix: * + Loop through tokens from left to right. If token is an operand push it on stack. If token is an operator then Pop its operands from stack Evaluate that operator Push result on stack

15 Write Code to Evaluate this Postfix
See StackPostFix.asm source code file

16 Allocating Local Variables
Suppose a function declares and initializes the following local variables. public static void f() { int a = 0, b = 1; char c = ‘A’; // ASCII code is 65 }

17 Local Variable Memory Map
Suppose that we “carve” out stack space corresponding to pushing each local variable in order of its declaration. BOTTOM a (4 bytes) b (4 bytes) c (1 byte) TOP How many bytes to deduct from $sp to allocate the space? Where does $sp point to? What are the offsets from $sp for each local variable?

18 Local Variable Memory Map
Suppose that we “carve” out stack space corresponding to pushing each local variable in order of its declaration. BOTTOM +5 a (4 bytes) +1 b (4 bytes) +0 c (1 byte) TOP How many bytes to deduct from $sp to allocate the space? 9 Where does $sp point to? C What are the offsets from $sp for each local variable? $sp

19 Allocate & De-allocate in “Bulk”
# Decrement stack pointer to allocate space for # ALL three variables in one shot. # Two 32-bit words + One byte = 9 bytes addiu $sp, $sp, -9 sw $zero, 5($sp) # a = 0 li $t0, 1 # b = 1 sw $t0, 1($sp) li $t0, 65 # c = ‘A’ sbu $t0, 0($sp) … # Deallocate 9 bytes from stack when function exits addiu $sp, $sp, 9

20 Array Sum Allocate local variables on the stack in order of their declarations. All reads/writes to local variables must be done through the stack. { int[] A = { 1, 3, 5, 7 }; // Allocate on stack int sum = 0, i = 0; while(i < 4) sum = sum + A[i]; i++; }

21 Write Code to Perform ArraySum
See ArraySum1.asm source code file ..\MIPS code\ArraySumStack.asm

22 Function Calls Example P1
main: # Call the function named printIt jal printIt # MUST EXIT PROGRAM TO AVOID FUNCTION CODE li $v0, 10 syscall

23 Function Calls Example P2
printIt: # system call code for print_int li $v0, 1 # integer to print li $a0, 5 # print it syscall # Return to caller. # $ra holds the return address jr $ra

24 Calling a Function MIPS instruction “jump and link”
# Jump to first instruction at given label. # Automatically saves return address– # address of next instruction, in register $ra jal FunctionLabel << “Instruction for return address” >>

25 Passing Parameters In general the caller will push the parameters onto the stack. The callee (function) assumes that it receives the parameters filled into specific offsets from the $sp (top of stack pointer).

26 Passing Parameters Example P1
# Push a single 4-byte integer parameter value on the stack. addiu $sp, $sp, -4 li $t0, 7 sw $t0, ($sp) jal printIt li $t0, 3 # MUST EXIT PROGRAM li $v0, 10 syscall

27 Passing Parameters Example P2
# Assumes one 4-byte integer parameter is given # on the stack printIt: # system call code for print_int li $v0, 1 # Load integer to print into $a0 from top of stack. lw $a0, ($sp) # print it syscall # Release memory allocated for parameters. addiu $sp, $sp, 4 jr $ra

28 Exercise Write the equivalent MIPS code: main { printMax(5, 10); }
void printMax(int x, int y) { if(x >= y) System.out.println(x); else System.out.println(y);

29 Array Type Parameters How should we pass an array parameter to a function? What information should be pushed on the stack?

30 Array Type Parameters It’s more efficient to pass only the base address as a 32-bit value rather than copying all of the array data. Must also pass an integer giving the length of the array. By passing the base address, we can also make changes to the contents of the array.

31 Exercise Write the equivalent MIPS code: main {
int[] X = { 4, 8, 12 }; printSum(X, 3); } void printSum(int[] A, int length) int sum = 0, i = 0; while(i < length) sum = sum + A[i]; i++; System.out.println(sum);

32 Single Return Value In MIPS, a function that returns a single value “returns” the value by leaving it in the $v0 register. The last instruction of a function is its exit via the “jump register” instruction jr $ra

33 Write MIPS Code for… main() { $v0 = max(17, 5); System.out.println( $v0 ) } int max(int x, int y) int bigger = x; // Let $v0 hold bigger. if(x < y) bigger = y; return bigger;

34 Example: Caller Code Continued...
addiu $sp, $sp, -8 li $t0, 17 sw $t0, ($sp) li $t0, 5 sw $t0, 4($sp) jal max move $a0, $v0 # integer to print into $a0 li $v0, 1 # print integer system call code syscall # Do exit syscall for a clean end of program. li $v0, 10 # Prevents main from running syscall # into following max function Continued...

35 Example: Function Max # This code follows the previous slide of main. # Assume first parameter is at ($sp)+4 # Assume second parameters is at ($sp)+0 # Returns larger of two values in register $v0 max: # suppose first parameter is the larger. lw $v0, 4($sp) # load second parameter lw $v1, ($sp) bge $v0, $v1, MAX_END_IF move $v0, $v1 # second param is larger MAX_END_IF: # Pop off two 32-bit parameters addiu $sp, $sp, 8 # Return address automatically saved in $ra jr $ra

36 Example: Function Array Sum
Compute sum of given array of N integers. int arraySum(int[] A, int length) { int sum = 0; for(int i = 0; i < length; i++) sum = sum + A[i]; return sum; }

37 Example: Function Sum Compute sum of given array of integers.
int arraySum(int[] A, int length) Push base address of array onto stack Push length of array as a word onto stack Return sum in register $v0

38 Example: Caller Code .data # Data declaration section A: .word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 .text main: la $s0, A # Base address of A addiu $sp, $sp, -4 # allocate space for address sw $s0, ($sp) # push that element on the stack li $s1, 10 # Number of elements in A addiu $sp, $sp, -4 # allocate space on the stack sw $s1, ($sp) # push that on the stack jal ArraySum # Call function ArraySum li $v0, 1 # system call code for print_int syscall # print it li $v0, 10 syscall

39 Example: Function Array Sum
# Receives base address on stack ($sp)+4 # Receives length of array on stack ($sp) # Returns sum of array elements in $v0 # Uses registers $t0, $s0 and $s1 as local variables ArraySum: li $a0, 0 # Sum = 0 lw $s0, 4($sp) # Get base address lw $s1, 0($sp) # Get length LOOP: beqz $s1, END_LOOP lw $t0, ($s0) add $a0, $a0, $t0 addi $s0, $s0, 4 # Increment A address addi $s1, $s1, -1 # Decrement count b LOOP END_LOOP: # Pop parameters off stack addiu $sp, $sp, 8 jr $ra

40 Example: Local Variables
# Swaps values in $a0 and $a1. swap: # Use $t0 as the local variable temporary. # temp = $a0 move $t0, $a0 # $a0 = $a1 move $a0, $a1 # $a1 = temp move $a1, $t0 # return to caller. jr $ra

41 Local Variables  Side Effects!
# Code in “main” # Let $t0 hold current array base address. # Swap two array elements. lw $a0, 0($t0) lw $a1, 4($t0) jal swap # Swap two more array elements. lw $a0, 8($t0) lw $a1, 12($t0)

42 Local Variables for Functions
How can we use registers for local variables in functions but restore their contents to the values they had before the function call? Solution: Allocate space on the stack for local variables or to backup registers

43 Exercise Revisit your ArraySum function.
Does it produce unwanted side effects? If so what registers are affected? Update your code to save and restore local variable registers using the stack.

44 Side-effect Free Array Sum
.data # Data declaration section A: .word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 .text main: la $s0, A # Base address of A addiu $sp, $sp, -4 sw $s0, ($sp) li $s1, 10 # Number of elements in A jal ArraySum # Call function ArraySum # return value is in $v0

45 # Receives base address on stack ($sp)+4 # Receives length of array on stack ($sp) # Returns sum of array elements in $v0 # Uses registers $t0, $s0 and $s1 as local variables ArraySum: li $v0, 0 # Sum = 0 # Push contents of $t0, $s0, and $s1 lw $s0, 16($sp) # Get base address lw $s1, 12($sp) # Get length LOOP: bnez $s1, END_LOOP lw $t0, ($s0) add $v0, $v0, $t0 addi $s0, $s0, 4 # Increment A address addi $s1, $s1, -1 # Decrement count b LOOP # Restore saved contents of $t0, $s0, and $s1 # Pop parameters off stack addiu $sp, $sp, -20 jr $ra

46 Swap Function – Caller Code
data: A: .word 10 B: .word 20 .text main: # Main uses $a0, $a1, $t0, $t1 for some other purpose. li $a0, 1 li $a1, 2 li $t0, 3 li $t1, 4 # push address of two variables on stack la $s0, A addiu $sp, $sp, -4 sw $s0, ($sp) la $s0, B jal swap li $v0, 10 # exits program syscall

47 Side-Effect Free Swap Function
# Push original contents of $t0, $t1, $a0, $a1 addiu $sp, $sp, -4 sw $t0, ($sp) sw $t1, ($sp) sw $a0, ($sp) sw $a1, ($sp) # Get address of first argument into $a0 lw $a0, 20($sp) # Get address of second argument into $a1 lw $a1, 16($sp) lw $t0, ($a0) # $t0 = value of variable A lw $t1, ($a1) # $t1 = value of variable B sw $t0, ($a1) # A = B sw $t1, ($a0) # B = A # Restore preserved $a1, $a0, $t1, $t0 from the stack. lw $a1, ($sp) addiu $sp, $sp, 4 lw $a0, ($sp) lw $t1, ($sp) lw $t0, ($sp) # Pop off two 32-bit address arguments addiu $sp, $sp, 8 # return to caller. jr $ra

48 Re-Entrant Functions If a function calls itself then program control re-enters a function that is already active. Such code is known as re-entrant code. Example: recursive functions.

49 Re-Entrant Functions Re-entrant function must maintain separate copies of all values for each active call. Allocate stack space. Why? Later calls to the same function will overwrite information from previous calls.

50 Example Recursive Function
/** * Factorial(n) = n*(n-1)*(n-2)*...*1 */ int factorial(int n) { if(n <= 1) return 1; else return n * factorial(n-1); }

51 Recursive Stack Trace factorial(5) n = 5
Each procedure invocation pushes a new stack frame.

52 Recursive Stack Trace factorial(5) n = 5 n = 4 factorial(4)
Each procedure invocation pushes a new stack frame.

53 Recursive Stack Trace factorial(5) n = 5 n = 4 n = 3 factorial(3)
Each procedure invocation pushes a new stack frame.

54 Recursive Stack Trace factorial(5) n = 5 n = 4 n = 3 n = 2
Each procedure invocation pushes a new stack frame.

55 Recursive Stack Trace factorial(5) n = 5 n = 4 n = 3 n = 2 n = 1
Each procedure invocation pushes a new stack frame.

56 Recursive Stack Trace factorial(5) n = 5 n = 4 n = 3 n = 2 n = 1 1 1

57 Recursive Stack Trace factorial(5) n = 5 n = 4 n = 3 n = 2 2 * 1 n = 1
Each procedure return pops off its stack frame.

58 Recursive Stack Trace factorial(5) n = 5 n = 4 n = 3 3 * 2 n = 2 2 * 1
Each procedure return pops off its stack frame.

59 Recursive Stack Trace factorial(5) n = 5 n = 4 4 * 6 n = 3 3 * 2 n = 2
2 * 1 n = 1 1 6 2 1 Each procedure return pops off its stack frame.

60 Recursive Stack Trace n = 5 5 * 24 n = 4 4 * 6 n = 3 3 * 2 n = 2 2 * 1
factorial(5) = 120 n = 5 5 * 24 n = 4 4 * 6 n = 3 3 * 2 n = 2 2 * 1 n = 1 1 24 6 2 1 5! returns 120 Each procedure return pops off its stack frame.

61 Recursive Stack Trace n = 5 5 * 24 n = 4 4 * 6 n = 3 3 * 2 n = 2 2 * 1
factorial(5) = 120 n = 5 5 * 24 n = 4 4 * 6 n = 3 3 * 2 n = 2 2 * 1 n = 1 1 24 6 2 1 5! returns 120 Stack returns to its original state prior to call to factorial(5) since all procedure stack frames have been popped off.

62 What to Store on the Stack
Allocate a stack frame to store the following information used by a recursive function invocation: Parameter value(s) Local variables including saved copies of ALL registers read/written by the function Return address in $ra register

63 Recursive Factorial See factorial.asm See factorial-sef.asm

64 FYI Pass Parameters in Registers
For functions that take 4 or fewer 32-bit arguments you can pass the parameters in registers $a0, $a1, $a2, and $a3 The syscall mechanism works this way

65 Exercise Write calling code in main that assigns values of your choice to $a0-$a3 and calls function sum4. Write a function sum4 that receives 4 integer parameters in $a0-$a3 and returns their sum in $v0.

66 Solution: Caller Code Continued...
main: # Assign some values to argument registers li $a0, 5 li $a1, 17 li $a2, 7 li $a3, 40 # Jump to the function with label “sum4” jal sum4 # Do exit syscall for a clean end of program. li $v0, 10 # Prevents main from running syscall # into following sum4 function Continued...

67 Solution: Function Sum4
# This code follows the previous slide of main. # # Assume four integer arguments $a0-$a3. # Returns sum of integers in register $v0. sum4: add $v0, $a0, $a1 add $v0, $v0, $a2 add $v0, $v0, $a3 # Return address automatically saved in $ra jr $ra


Download ppt "Function Calls in Assembly MIPS R3000 Language (extensive use of stack) Updated 7/11/2013."

Similar presentations


Ads by Google