Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ch. 8 Functions.

Similar presentations


Presentation on theme: "Ch. 8 Functions."— Presentation transcript:

1 Ch. 8 Functions

2 Functions High-level languages have functions (methods)
For modularity – easier to change To eliminate duplication of code – code reuse allows different programmers to write different parts of the same program Assembly language programs have similar structure Comp Sci functions

3 High-level function example
void helloWorld(){ print("Hello, world"); } void main(){ helloWorld(); . . . Comp Sci functions

4 Mechanism for implementing functions
Steps in the invocation and execution of a function: save return address call the function execute the function return Comp Sci functions

5 Machine Language mechanism
What is the return address? Address of the instruction following call What is the function call? jump or branch to first instruction in the function What is a return? jump or branch to return address Comp Sci functions

6 Functions in assembly language
Labels to name functions Instructions to support function call & return System stack to track pending calls Programming conventions for parameter passing Comp Sci functions

7 MIPS function example __start: jal helloWorld ... .data
.text # Prints the string # "Hello, world" helloWorld: la $a0, hello li $v0, 4 syscall jr $ra __start: jal helloWorld ... .data hello: .asciiz "Hello, world" Comp Sci functions

8 Assembly language functions
Function name Label on first instruction Function call: Jump And Link instruction: jal label Jump to label Save return address in $ra Comp Sci functions

9 Assembly language functions
Return from function Jump Register instruction: jr Rsrc Jump to the address in the register jr $ra  jump to return address Comp Sci functions

10 Code Review See helloFunc.a in /shared/huen/251
Comp Sci functions

11 Complications: What if function calls another function?
Must keep track of multiple return addresses There is only one $ra i.e. $31 What if a function modifies some registers? Should it restore the original values before returning? Solution: have a way to save return addresses as they are generated This data is generated dynamically; while the program is running. These return addresses will need to be used (for returning) in the reverse order that they are saved. use system stack Comp Sci functions

12 Program memory model Memory contains three important segments
0x Reserved 0x Text segment 0x Data segment 0x7FFFEFFC Stack segment 0x 0xFFFFFFFF Operating system Memory contains three important segments Text segment: program instructions Data segment: global variables & constants Stack segment: arguments & local variables Comp Sci functions

13 System stack Stack: Last-in-first-out (LIFO) data structure
Push: place a new item on the top Pop: remove the top item Implementation Stack segment of memory holds stacked items Each item is one word $sp register points to top of stack Stack grows toward low addresses $sp Stacked items Comp Sci functions

14 Stack operations Push $t0 to top of stack: Pop top of stack to $t0:
subu $sp, $sp, 4 sw $t0, ($sp) Pop top of stack to $t0: lw $t0, ($sp) addu $sp, $sp, 4 Low word $sp High Comp Sci functions

15 Example: Problem - stack1.a
Count the number of negative integers on the stack by popping the stack until a non-negative integer is found, and print out the number of words popped. Comp Sci functions

16 Example: Solution stack1.a
Integers from an array are first pushed onto the stack Then the integers are popped and checked in turn until a non-negative integer is encountered Prints out the count The program portion to be written should be independent of the data and the rest of the program given Comp Sci functions

17 __start: # execution starts here
.text .globl __start __start: # execution starts here la $t0, test # This code sets up the stack lw $t1, num # Do not alter loop: lw $t2, ($t0) subu $sp, $sp, 4 # push stack w/ integers sw $t2, ($sp) # from test array add $t0, $t0, 4 add $t1, $t1, -1 bnez $t1, loop # Stack is set up now.... # At this point, the stack looks somewhat like # the following but in hexadecimal of course: # $sp ->| | # | | # | | # |0xfffabfff| # |0xffffffd5| # | | # | etc. | # Put your answer between dashed lines. Comp Sci functions

18 # loop to pop the stack and count
# Put your answer between dashed lines. # start cut li $t3, 0 # count = 0; next: lw $t2, ($sp) # pop the stack addu $sp, $sp, 4 bgez $t2, done # encounter non-negative addi $t3, $t3, 1 # count++ j next # At this point, the stack looks somewhat like # the following but in hexadecimal of course: # | | # | | # | | # |0xfffabfff| # |0xffffffd5| # $sp ->| | # | etc. | # done: Comp Sci functions

19 Example 2 stack2.a The stack is set up with integers and the top of stack contains the number of integers Required to find the sum of integers on the stack The top of stack number should not be included. Comp Sci functions

20 Use of system stack Stores temporary information
Key support for functions Pending function calls Saved register values Parameters Local variables Comp Sci functions

21 Functions that call functions
jal g #call g jr $ra #return g: jr $ra #return __start: jal f #call f Main calls f $ra = return addr. to main f calls g $ra = return addr. to f Problem: return addr. to main lost. Solution? Comp Sci functions

22 Functions that call functions
# push $ra subu $sp, $sp, 4 sw $ra, ($sp) . . . jal g #call g # pop $ra lw $ra, ($sp) addu $sp, $sp, 4 jr $ra # f return g: . . . jr $ra # g return _start: jal f #call f Comp Sci functions

23 Leaf vs. non-leaf functions
Does not call other functions No need to save & restore $ra Non-leaf function: Calls other functions Must save & restore $ra (use the stack) Comp Sci functions

24 MIPS function structure
Prologue: push items on stack Body: do required computation Epilogue: pop items off stack & return Comp Sci functions

25 What items must be stacked?
$ra (if function is non-leaf) Some registers… But not others… Comp Sci functions

26 MIPS register conventions
Callee-saved registers $s0 -- $s7, $ra, $sp, $fp All functions must guarantee: value upon return == value before call Caller-saved registers: $t0--$t9 Functions may freely modify these $t_ registers Caller must save these registers $t_ if values will be re-used after the call Comp Sci functions

27 Return value Some functions return a value MIPS register convention:
use $v0 Comp Sci functions

28 Functions with parameters
Parameters are special local variables Initial values come from arguments More MIPS register conventions Arguments: $a0 -- $a3 Comp Sci functions

29 Example: Vowel Count -1 Count the number of vowels in a string str
Main program Call vcount with the address of str Print the return value function vcount( address of String str) Checks one char at a time for vowel returns the number of vowels in str function vowelp( char c) Returns 1 if c is a vowel, 0 if not Comp Sci functions

30 Example: vowel count -2 Main program a0 points to str
Calls vcount passing a0 Print answer Terminate the program Comp Sci functions

31 Example: vowel count-3 Long time ago in a galaxy far away s1
Function Vcount Input: a0 holds address of str Internal: s0 holds number of vowels, i.e. count s1 points to a character in str Output: v0 holds result Pseudo code count = 0; set s1 to point to first character in str and call the character c while (c != 0) { count += vowelp( c ); // call another function vowelp move s1 to point to next character and call it c } Done: return count; Long time ago in a galaxy far away s1 Comp Sci functions

32 Example: vowel count-4 Function int vowelp(char c) result = 0;
if c == ‘a’ result = 1; if c == ‘e’ result = 1; if c == ‘i’ result = 1; if c == ‘o’ result = 1; if c == ‘u’ result = 1; return result; Comp Sci functions

33 Example: vowel count- 5 Integrate all together in vowel.a
Comp Sci functions

34 Local variables Global variables (static allocation)
Accessible throughout entire program execution Exist in data segment Local variables (dynamic allocation) Created upon function call Deleted upon function return Where? How to access them? Comp Sci functions

35 Local variables Implement locals on the stack
Reserve space in prologue Release it in epilogue Local Variables $sp Saved registers Comp Sci functions

36 Example: Translate to MIPS
int sum(){ int x; int y; x = read int; y = read int; return x + y; } Stack: sum: #prologue subu $sp, $sp, 8 jr $ra li $v0, 5 syscall sw $v0, 4($sp) sw $v0, 0($sp) lw $t0, 4($sp) lw $t1, 0($sp) add $t0, $t0, $t1 move $v0, $t0 #epilogue addu $sp, $sp, 8 y x Saved registers $sp Comp Sci functions

37 } Stack frame Data on the stack associated w/ function call
Saved registers Local variables Use register to point to fixed point in the stack frame $sp may change during function call Use $fp (frame pointer) to access locals $fp is callee-save (like $ra and s-registers) $sp } $fp Local Variables Stack frame Saved registers Comp Sci functions

38 Re-work example w/ $fp # prologue subu $sp, $sp, 12 #create frame
sw $fp, 8($sp) #save old $fp addu $fp, $sp, 8 #set up $fp # epilogue lw $fp, 0($fp) # restore $fp addu $sp, $sp, 12 # remove frame jr $ra Exercise: re-work function body w/ $fp y x $sp old $fp $fp Comp Sci functions

39 Functions with parameters
Parameters are special local variables Initial values come from arguments More MIPS register conventions Arguments: $a0 -- $a3 Comp Sci functions

40 Example function w/ parameters
int power(int base, int exp){ int result = 1; int i; for(i = 0; i < exp; i++) result *= base; return result; } Sketch stack frame Write prologue & epilogue Write function body i result exp base old $fp $fp Comp Sci functions

41 Example function w/ parameters
#prologue subu $sp, $sp, 20 sw $fp, 16($sp) addu $fp, $sp, 16 sw $a0, -4($fp) # base sw $a1, -8($fp) # exp #epilogue lw $fp, 0($fp) addu $sp, $sp, 20 jr $ra $sp i result exp base old $fp $fp Prev frame Old $sp Comp Sci functions

42 Non-leaf function with parameters
int power(int base, int exp){ int result; if(exp == 0) result = 1; else result = base * power(base, exp – 1); return result; } Sketch stack frame Write prologue & epilogue Write function body result exp base old $fp $ra $fp Comp Sci functions

43 Wait a minute! What if your function has more than 4 parameters?
Any registers needed by the caller must be restored to the values that they contain before the procedure was invoked. Spill the registers to memory. Comp Sci functions

44 Call by value vs. call by reference
C++ has reference parameters Java passes all objects by reference Assembly language implementation? Pass the address of the argument Comp Sci functions

45 Pass By Value // This program uses variables as function parameters.
#include <iostream> using namespace std; // Function prototypes. The function uses pass by value void doubleNum(int ); Comp Sci functions

46 Pass By Value int main() { int value;
// Get a number and store it in value. cout << "Enter a number: "; cin >> value; cout << "That value entered is " << value << endl; // Double the number stored in value. doubleNum(value); cout << "That value doubled is " << value << endl; return 0; } Comp Sci functions

47 Pass By Value //********************************************************** // Definition of doubleNum. // The parameter valueVar is a value variable. The value // in valueVar is doubled. void doubleNum (int valueVar) { valueVar *= 2; // display valueVar in doubleNum cout << "In doubleNum, valueVar is " << valueVar << endl; } Comp Sci functions

48 Pass By Reference // This program uses reference variables as function
// parameters. #include <iostream> using namespace std; // Function prototypes. Both functions use reference // variables // as parameters. void doubleNum( int & ); void getNum( int & ); Comp Sci functions

49 Pass By Reference int main() { int value;
// Get a number and store it in value. getNum(value); // Display the resulting number. cout << "That value entered is " << value << endl; // Double the number stored in value. doubleNum(value); cout << "That value doubled is " << value << endl; return 0; } Comp Sci functions

50 Pass By Reference // The parameter userNum is a reference variable. The user is // asked to enter a number, which is stored in userNum. void getNum(int &userNum) { cout << "Enter a number: "; cin >> userNum; } // The parameter refVar is a reference variable. The value // in refVar is doubled. void doubleNum (int &refVar) refVar *= 2; Comp Sci functions

51 Example // x is passed by ref. void increment(int &x){ x++; }
int foo = 5; increment(foo); // foo contains 6 increment: #prologue... lw $t0, -4($fp) lw $t1, ($t0) addi $t1, $t1, 1 sw $t1, ($t0) #epilogue... __start: la $a0, foo jal increment .data foo: word 5 Comp Sci functions

52 Example Value_ref.a Comp Sci functions

53 Arrays are passed by reference
void f(int[] a){...} int bar[1000]; f(bar); .text f: jr $ra __start: la $a0, bar jal f .data bar: space 4000 Comp Sci functions

54 Exercise: function to sum an array
int sum(int[] a, int size){ int result = 0; int i; for(i=0; i< size; i++) result += a[i]; return result } int bar[1000]; cout << sum(bar, 1000); .text sum: # fill in code jr $ra __start: la $a0, bar li $a1, 1000 jal sum .data bar: space 4000 Comp Sci functions


Download ppt "Ch. 8 Functions."

Similar presentations


Ads by Google