Subroutine Calling
- Do we need anything special to implement subroutines?
- Can we do it with just a branch?, or two?
- BL Rtmp,address
- Save the current value of the pc in a register
- Jump to address
- The value of the pc will already have been incremented.
- BR Rtmp
- Branch to the address stored in register tmp.
- This will work as long as the procedure is a leaf node.
- How about storing the value of the branch register?
- This will work as long as the procedure is only called
once in the activation sequence.
- So how do we do it?
- A register called the frame pointer
- A register called the stack pointer
- These provide access to the runtime stack
- All local addresses are relative to the frame pointer
- The return address and parameters
are all stored on the stack.
- This is called an activation record.
- Local variables are stored on the stack as well.
- The stack pointer is incremented as more variables are
added.
- To call a subroutine, place the parameters on the stack
- Make place for the return value
- Make a place for the return address
- Store the current frame pointer.
- call the routine (BL, JAL, ...)
- This will change the frame pointer to be the current
stack pointer
- And the stack pointer stays the same.
Upon return, the old frame pointer is restored,
- The stack pointer is reset
- Take any parameters, return values you need off of the stack
- Different architectures support slightly different versions of this
- Some (like the sparc) use registers for part of the parameters
- Some do more work than others.
- A calling convention
- Specifies how all this is to be done
- Where to put things
- What the programmer must do
- (Save registers, push frame pointers, ...)