[ENGN3213 Home]
Basic subroutine operation is illustrated in
Figure 109.
Figure 109:
Subroutine operation.
|
This corresponds to the code fragment
...
BSR SUB1
...
...
...
SUB1 ...
...
...
RTS
...
-
The subroutine in this illustration is the piece of code
between the label SUB1 and the RTS instruction.
-
The subroutine is called using the BSR instruction
BSR SUB1.
-
When the BSR instruction is executed, the value (PC) (which points
to the next instruction in the main program, the return address)
is saved
on the stack, and then (PC) is assigned the value SUB1, the address
of the first instruction in the subroutine.
-
The instructions in the subroutine are executed in turn until the
RTS instruction is encountered.
-
When the RTS instruction is executed, the return address is popped
from the stack and (PC) loaded with this value.
(It is important that if the stack were used in the subroutine,
it be cleaned up to its initial state so that the return address
can be recovered correctly.)
-
Execution of the main program continues from the return address.
Use of the stack for storing the return address permits the
nesting of subroutine calls, and recursive
programming.
JSR can be used in place of BSR, though BSR always uses PC relative
addressing.
[ENGN3213 Home]
ANU Engineering - ENGN3213