Stacks and Subroutines
Stacks and Subroutines
Stacks and Subroutines
SUBROUTINES
• Large programs are hard to handle and so
broken into smaller programs called as
subroutines.
• A subroutine is a block of code that is called
from different places from within a main
program or other subroutines.
SUBROUTINES
When using subroutines, it is necessary to know the
following:
• When should we jump? (use CALL) - A
subroutine call can be implemented by pushing
the return address on the stack and then jumping
to the branch target address.
• Where do we return to? (use RETURN) - When
the subroutine is done, remember to pop out the
saved information so that it will be able to return
to the next instruction immediately after the
calling point.
SUBROUTINES(cont..)
• A Branch and Link (BL) instruction is used to call a
subroutine or a procedure in ARM.
For instance,
• BL foo /*BL- Branch and link instruction, foo is a
subroutine/procedure name*/
• The branch and link is much like a branch, except that before
branching it stores the current PC value in r14. Thus, to return
from a procedure, simply move the value of r14 (LR) to r15
(PC)
MOV r15,r14
SUBROUTINES(cont..)
• When subroutines are nested, the contents of the link
register must be saved on a stack by the subroutine.
Register R13, Stack Pointer is normally used as the
pointer for this stack.