Advanced Topics

The Basics

In high-level programming languages, one of the techniques for making programming easier and programs easier to understand and maintain is to use modularisation in the form of functions and procedures. In assembly language programming, such modularisation can be achieved using subroutines.In high-level programming languages, one of the techniques for making programming easier and programs easier to understand and maintain is to use modularisation in the form of functions and procedures. In assembly language programming, such modularisation can be achieved using subroutines.

There are two steps to executing a subroutine, firstly calling the subroutine and secondly returning from the subroutine.

Calling a subroutine involves saving the value of the Program Counter (so that the subroutine can return to the correct place) and then branching to the start of the subroutine.

Returning from a subroutine involves resetting the Program Counter to its saved value, thus automatically restoring the program execution to the instruction immediately following the original subroutine call.

  BL SUBROUT ; call subroutine SUBROUT
  ADD r2, r0, r1 ; execution resumes here after
      ; SUBROUT returns
  .    
SUBROUT .   ; start of subroutine
  .    
  MOV r15, r14 ; return from subroutine

BL is a Branch-and-Link instruction. It saves the value of the Program Counter (r15) into r14. In the example program, r15 is pointing at the ADD instruction. Having saved the Program Counter, it then loads r15 with the address of the subroutine, causing the program to branch.

In the example, the destination of the branch is the line beginning with the label SUBROUT.

Once the subroutine is complete, returning simply requires moving the value in r14 back into the Program Counter, so MOV r15, r14 accomplishes this and the program returns to the ADD instruction.

The BL instruction always uses r14 to store the return address. It is called the link register.