Unit 7.1 -- Subroutine that figures C:=A+B
PROG
Adds A and B putting result in C
PED
first subroutine example -- no parameters, no IBM convention
CONCEPTS
BAL regA,lab1
lab1 EQU * BEGINNING OF SUBROUTINE
.
.
.
BR regA RETURN FROM SUBROUTINE
basic subroutine logic:
"regA" must be the same at "lab1" as it is at "BR..."
statement
SF
BAL regA,label
-puts into "regA", the address of the next instruction after
BAL
-then it branches to "label"
BR regA
-branches to memory location stored in "regA"
24.html
Unit 7.1 -- Subroutine that figures C:=A+B
In this unit, we learn to write a simple subroutine--one
that doesn't have any parameters. That is, we learn how to
call a subroutine, ensuring that we go back to the
instruction after the call when the subroutine finishes.
The BAL instruction is how we do a call.
It's format is
BAL regA,lab1
This does two things.
1 It puts the address of the next instruction following
it into "regA". (It will have a number 2001C in
"regA")
2 Then it branches (transfers control to) the instruction
at "lab1"
At the label, "lab1" we simply put the first instruction of
the subroutine.
When it is time to do a "return," we simply do a "BR regA."
"regA" is the register containing the address saved by the
"BAL"
BR "regA" will branch to the address given in regA.
Our example program calls a subroutine three times. For
lack of anything better to do, it will add the contents of A
and B and put the result in C. The main program simply
initializes A and B to various values and then calls the
subroutine.
The first call is at line 28. Note, here that we use
register five to contain address of the next
instruction--that on line 30. In this example, register 5
would contain 20016.
Then, we execute the instruction at the label "BLAH" which
is line 43, address 20040. Upon completing the three lines
of code at lines 40, 41, and 42, we execute the "BR 5" That
takes the 20016 in register five and goes to the instruction
at hex location (address) 20016 on line 30--the "L 1,F3"
A and B are changed to 3 and 4 and now we execute the second
call at line 34. Here register five is changed to the
address of the instruction on line 33, 2002A. The
subroutine does its thing at BLAH. Upon hitting the "BR 5,"
it goes to the instruction at 2002A. That is, it goes to
the L 1,F5 at line 363.
Here we initialize A and B to 5 and 6, respectively. The
"BAL 5,BLAH" initializes register five to 2003e--the "BR 14"
on line 41.
At "BLAH", the subroutine does its thing, computing C=A+B.
Then, the "BR 5" takes us to address 2003E, the address of
the "BR 14." Last, but not least, the "BR 14" takes us back
to the operating system.
Note that the operating system has called what we so
self-centeredly called the main program. In fact, our
program is nothing more than a subroutine for the great big
operating system.