Download Calling Functions, Call Stack, Local Variables, Return Values | CMSC 212 and more Study Guides, Projects, Research Computer Science in PDF only on Docsity!
CMSC 212 – F05 (lect 20)^1
Announcements
l Program
CMSC 212 – F05 (lect 20)^2
Recall Computer from Project 1
l Consider slight extensions
l Remember
- R0 is always 0
- Branch Rn Rm label
- saves currentPC + 1 into Rn
CMSC 212 – F05 (lect 20)^3
Calling Functions
l When you call a function, eventually you return
- Need to know where to return to
l Consider Machine from project
- Branch instruction saved program counter to register
- Can use that saved address to get back
- Consider this code:
foo: Branch R3 R0 bar Branch R4 R0 other Halt bar: Load R10 # Branch R0 R3 0 other: Load R10 # Branch R3 R0 bar Output R Branch R0 R4 0
CMSC 212 – F05 (lect 20)^4
Calling Functions
l Previous Code
- Allows functions to call and return
- But, need to coordinate which registers are used
- caller and callee need to agree
- what about recursion?
l Improved Solution
- Keep a stack of return addresses for function
- Dedicate a register to managing the stack
- called stack pointer (R15)
- Pick a standard register to save return address in
- caller always uses this one (R14)
- callee knows where return address is and saves it
- push return address onto stack onto stack
CMSC 212 – F05 (lect 20)^7
Local Variables
l Where to store variables local to a function?
- Option 1:
- in specific memory locations (like global vars)
- what about recursion?
- Option 2:
- on the stack
- specific address of a variables depends on call stack
CMSC 212 – F05 (lect 20)^8
Local Variables
l How to find local variables on the stack?
- Use stack pointer to define relative position of items
- When a function is called
- save return address on stack
- move stack pointer by size of locals plus return address
Stack
var
var
var
old Stack Pointer
Stack Pointer
Return address of current function
CMSC 212 – F05 (lect 20)^9
Local Variable Example
int main(void){
foo();
void foo()
int a, b, c, d;
a = 30;
b = 25;
c = a + b;
printf("%d\n", c);
0: Load R15 # 1: Branch R14 R0 3 2: Halt 3: Store R14 R15 0 4: Load R2 # 5: Negate R 6: Add R15 R2 R 7: Load R5 # 8: Store R5 R15 1 9: Load R6 # 10: Store R6 R15 2 11: Add R5 R6 R 12: Store R7 R15 3 13: Output R 14: Load R2 # 15: Add R15 R2 R 16: Load R14 R15 0 17: Branch R0 R14 0
CMSC 212 – F05 (lect 20)^10
Passing Parameters
l Parameters are like local variables
- values are only defined for lifetime of function
- but, they have initial values
l Implementation
- Option 1:
- use stack just like local variables
- copy initial values into locations prior to branch
- Option 2:
- put some parameters into registers
- registers are faster than memory
- finite number of them means still need option #
- put first n parameters into registers, then on stack