Lecture 6
Subroutines
G
Subroutines
G
The stack
G
Recursion
Subroutines
G
Used for
Frequently executed code segments
Library routines
Team-developed systems
in other words all the same reasons for using subroutines in
higher level languages where they may be called functions
procedures methods etc!
G
"equirements#
$ass parameters and return values via registers or
memory!
%all from any point & return control to the same point!
The %all ' "eturn mechanism
G
The figure illustrates the execution of a program
comprising code fragments ( ) * + and ,!
-ote that fragment ( is repeated several times and so is
well suited for pac.aging as a subroutine#
%alling and "eturning
G
/S" 0addr1
"2 3 $%
$% 3 0addr1
G
"4T
$% 3 "2
G
%omments#
The address to 5ump to is represented as a signed
offset from the $% so that the computation requires
adding the sign-extended offset to the $%!
$% value is after incrementing it! $oints to the next
instruction!
Similarly /S"" allows 5umping to a subroutine
addressed by a register!
%an you imagine when this may come in handy6
Subroutine call example
7 %alling program
!8"9: x;<<<
L= "> num>
L= "? num?
/S" multi
ST "; prod
@(LT
7
7 9nput data & result
num> !F9LL x<<<6
num? !F9LL x<<<;
prod !ALB) >
7 Subroutine multi
7 Cultiply ? positive numbers
7 $arameters#
7 9n# "> "?7 8ut# ";
7
multi (-= "; "; D<
(== "E "> D<
ArF Fero
loop (== "; "? ";
(== "> "> D ->
A"p loop
Fero "4T
!4-=
-otice any undesirable side-effects6
Saving & restoring registers
G
$rotect your valuesG
(ny subroutine call may change values currently stored in
a register!
Sometimes the calling program HIcallerJK .nows what
needs to be protected so it saves the endangered register
before calling the subroutine!
This is .nown as Icaller saveJ
Saving & restoring registers Hcont!K
8ther times it will be the called program HIcalleeJK that .nows
what registers it will be using to carry out its tas.!
9n the multi subroutine "E is used as temporary wor.ing space! 9t
needs to be restored before returning to the main program!
This is .nown as Icallee saveJ
)hat are the trade-offs between caller and callee saves6
9n this course we will use Icallee savesJ as default!
)here are registers saved6
Saving to another register6
8nly moves the problem from one register to another!
Saving to a fixed memory location6
)ill solve the problem!
(ny Limitations6
Saving & restoring registers# 4xample
7 Subroutine multi
7 Cultiply ? positive numbers
7 $arameters#
7 9n# "> "?7 8ut# ";
7
multi ST R4, R4Save
(-= "; "; D<
(== "E "> D<
ArF Fero
loop (== "; "? ";
(== "> "> D ->
A"p loop
Fero LD R4, R4Save
"4T
R4Save .fill #0
!4-=
Library "outines
G
Library
( set of routines for a specific domain application!
4xample# math graphics :U9 etc!
=efined outside a program!
G
Library routine invocation
Labels for the routines are defined as external! 9n L%-;#
!4xternal Label
4ach library contains its own symbol table!
( lin.er resolves the external addresses before
creating the executable image!
The Stac.
9mplementing a Stac. in (ssembly
G
)e use a register to indicate the top of the stac. HS$K!
8n the L%-; we use "6 by convention!
G
pushHxK#
memL"6M 3 x
"6 3 "6 - >
G
x 3 popHK#
"6 3 "6 N >
x 3 memL"6M
G
Ay convention the stac. grows from the highest address
to the lowest!
G
The stac. is useful for saving register values passing
arguments and maintaining local variables!
The stac. frame
G
$ushing and popping each variable separately can be
tedious when entering ' leaving a subroutine!
G
9dea# we can consolidate the instructions modifying the S$
H"6K!
This results in a single shift of the stac. for all
variables!
The result is an opening or closing of a stack frame!
G
8pen#
"6 3 "6 - 0stac. frame siFe1
G
%lose#
"6 3 "6 N 0stac. frame siFe1
The stac. frame - 4xample
multi ADD R6, R6, #-1 ; Open a stack frame
STR R4, R6, #0 ; Save R4
AND R3, R3, #0
ADD R4, R1, #0
BRz zer
lp ADD R3, R!, R3
ADD R1, R1, # "1
BRp lp
#er LDR R4, R6, #0 ; Restre R4
ADD R6, R6, #1 ; $lse t%e stack frame
R&'
Function
G
Smaller simpler subcomponent of program
G
$rovides abstraction
hide low-level details
give high-level structure to program
easier to understand overall program flow
enables separable independent development
G
% functions
Fero or more arguments passed in
single result returned HoptionalK
return value is always the same type
by convention only one function named main Hthis defines
the initial $%K
G
9n other languages called procedures subroutines
methods !!!
Functions# )hy we need
%onventions
G
Functions may be implemented by others#
Functions are implemented in both our code and
external libraries!
Functions can be implemented in different
programming languages!
G
%alling functions not compiled by our compiler
requires a convention that specifies responsibilities#
%allee save vs! %aller save!
@ow the stac. is managed!
@ow arguments are passed!
@ow return value is returned!
O
Function %all %onventions
G
)e will cover two different conventions#
1)Patt and Patel# The original L%-; function call
convention as described in the $att & $atel
boo. using "E Hfor globalsK "P and "6!
2)aifa# ( simpler convention using only "6!
G
9n this course you can choose whatever convention
you feel comfortable with as long as you .eep
consistent!
%onventions are all about consistent behavior!!!
9mplementing a Function %all#
8verview
G
Ca.ing a function call involves three basic steps
The parameters of the call are passed from the caller to
the callee
The callee does its tas.
( return value is returned to the caller
G
Functions in % are caller-independent
4very function must be callable from any other function
G
(ctivation record
information about each function including arguments and
local variables
also includes boo..eeping information
arguments and boo..eeping info pushed on run-time stac.
by caller
callee responsible for other uses of stac. Hsuch as local
variablesK
popped of the stac. by caller after getting return value
G
"P Hthe frame pointerK is the IbottomJ of the stac. as far
as the callee function definition is aware!
(ctivation "ecord
G
int funName(int a, int b)
{
int w, x, y;
.
.
.
return y;
}
-ame Type 8ffset Scope
a
b
w
x
y
int
int
int
int
int
E
P
<
->
-?
fun-ame
fun-ame
fun-ame
fun-ame
fun-ame
y
x
w
dynamic lin.
return address
return value
a
b
bookkeeping
locals
args
"P
"6
9mplementing a Function %all#
8verview
9mplementing a Function %all#
8verview
%alling function H%allerK
allocate memor! for
activation
record "#$s%)
co#! ar&$ments into stack
call f$nction
&et res$lt from stack
"#o#)
deallocate memor! for
activation record "#o#)
%alled function H%alleeK
allocate s#ace for ret$rn val$e
'(ookkee#in&) "#$s%)
store mandator! callee save
re&isters '(ookkee#in&)
"#$s%)
allocate local varia(les "#$s%)
e*ec$te code
#$t res$lt in ret$rn val$e
s#ace
deallocate local varia(les
"#o#)
load callee save re&isters
"#o#)
ret$rn
(ctivation "ecord Aoo..eeping
G
"eturn value
space for value returned by function
allocated even if function does not return a value
G
"eturn address
save pointer to next instruction in calling function
convenient location to store "2 to protect it from change in
case
another function H/S"K is called
G
=ynamic lin.
callerQs frame pointer Hbasically a caller save of its
own frame pointer "PK
used to IpopJ this activation record from stac.
G
9n the L%-; the format for an activation record
includes only Hand alwaysK these three words
pushed in that orderG
"un-Time Stac.
Caller
Memory
"6
Callee
Memory
"6
Caller
Memory
Caller
Before call During call After call
"P
"P
"6
"P
4xample Function %all
int %allee Hint q int rK
R
int . m7
!!!
return .7
S
int %aller Hint aK R
int w T ?P7
w T %allee Hw><K7
return w7
S
w
dyn lin.
ret addr
ret val
a
25
xFD00
"P
"6
The Function %all# $reparation to
/ump
G
int Callee (int q, int r)
G
int Caller (int a)
G
w = Callee(w, 10);
G
; pu! e"#n$ ar%
&ND '0, '0, (0
&DD '0, '0, ()0
&DD '*, '*, (+)
,-' '0, '*, (0
; pu! firt ar%ument
.D' '0, '5, (0
&DD '*, '*, (+)
,-' '0, '*, (0
G
/,' C&..00 ; /ump1
-ote# %aller needs to .now number and type of arguments
doesnUt .now about local variables!
q
r
w
dyn lin.
ret addr
ret val
a
25
)0
25
xFD00
"P
"6
New R6
Starting the %allee Function
G
; pu! pa"e f#r return 2alue
&DD '*, '*, (+)
; pu! return a$$re
&DD '*, '*, (+)
,-' '3, '*, (0
; pu! $yn lin4 ("aller5 '5)
&DD '*, '*, (+)
,-' '5, '*, (0
; et new frame p#inter
&DD '5, '*, (+)
; all#"ate pa"e f#r l#"al
&DD '*, '*, (+2
G
exe"ute b#$y #f fun"ti#n
m
.
=yn ln. H"PK
ret addr
ret value
q
r
w
dyn lin.
ret addr
ret val
a
xFCF6
x7)00
25
)0
25
xFD00
"P
"6
new "P
new "6
-ote# %allee ma.es room for boo..eeping variables
Hstandard formatK and its local variables Has necessaryK
4nding the %allee Function
G
return 4;
G
; "#py 4 int# return 2alue
.D' '0, '5, (0
,-' '0, '5, (7
; p#p l#"al 2ariable
&DD '*, '5, ()
; p#p $ynami" lin4 (int# '5)
.D' '5, '*, (0
&DD '*, '*, ()
; p#p return a$$r (int# '3)
.D' '3, '*, (0
&DD '*, '*, ()
; return "#ntr#l t# "aller
'0-
m
.
dyn lin.
ret addr
ret val
q
r
w
dyn lin.
ret addr
ret val
a
+87
2)3
xFCF6
x7)00
2)3
25
)0
25
xFD00
"6
"P
new "6
new "P
"esuming the %aller Function
G
w 9 Callee(w,)0);
G
; /,' Callee ; .&,- C:;;&ND
; l#a$ return 2alue (t#p #f ta"4)
.D' '0, '*, (0
; perf#rm ai%nment #f return 2alue
,-' '0, '5, (0
; p#p return 2alue an$ ar%ument
&DD '*, '*, (7
C#ntinue "aller "#$e
ret val
q
r
w
dyn lin.
ret addr
ret val
a
2)3
25
)0
2)3
xFD00
"6
"P
new "6
Summary of L%-; Function %all
9mplementation
>! %aller pushes arguments Hlast to firstK!
?! %aller invo.es subroutine H/S"K!
;! %allee allocates return value pushes "2 and "P!
E! %allee allocates space for local variables Hfirst to lastK!
P! %allee executes function code!
6! %allee stores result into return value slot!
2! %allee pops local vars pops "P pops "2!
V! %allee returns H/C$ "2K!
W! %aller loads return value and pops arguments!
><! %aller resumes computationO
The I@aifaJ %onvention
Use a simple frame H"6 only no
use of "P ' =ynamic Lin.K!
"eturn value# Use "<!
"eturn address H"2K saved li.e any
other register!
-o boo..eepingG
The I@aifaJ %onvention# Stac.
Frame
$allee Ar(uments
Save) Re(isters
* +cal ,ars
$aller Ar(uments
R-
'%e frame
The I@aifaJ %onvention# %aller
%ode
$allee Ar(uments
Save) Re(isters
* +cal ,ars
$aller Ar(uments
R-
Befre
.us% callee ar(uments
S'R /ar( 10, R-, #"1n"02
S'R /ar( !0, R-, #"1n"12
S'R /ar( n0, R-, #"1
ADD R-, R-, #"n
4ake t%e call
5SR /funcName0
.p ar(uments
ADD R-, R-, #n
Return value in R06
R-
Durin(
The I@aifaJ %onvention# %allee
%ode
$allee Ar(uments
Save) Re(isters
* +cal ,ars
$aller Ar(uments
R-
Befre
.us% stack frame
ADD R-, R-, #"/frame size0
Save re(isters
S'R R7, R-, #8
D smet%in( useful666
.lace return value in R0
Restre re(isters
+DR R7, R-, #8
.p stack frame
ADD R-, R-, #/frame size0
Return
R&'
R-
Durin(
I@aifaJ %onvention# 4xample
Function %all
int %allee Hint q int rK R
int . m7
!!!
return .7
S
int %aller Hint aK R
int w T ?P7
w T %allee Hw><K7
return w7
S
$aller
AND R0, R0, #0
ADD R0, R0, #10
S'R R0, R-, #"1
+DR R0, R-, #0
S'R R0, R-, #"!
ADD R-, R-, #"!
5SR $allee
ADD R-, R-, #!
S'R R0, R-, #0
9
10
9
R-
Befre
666
R-
Durin(
I@aifaJ %onvention# 4xample
Function %all
int %allee Hint q int rK R
int . m7
!!!
return .7
S
int %aller Hint aK R
int w T ?P7
w T %allee Hw><K7
return w7
S
: 1;102
r 1;92
m
R<
k
666
R-
Befre
$allee
ADD R-, R-, #"3
S'R R<, R-, #!
; D smet%in( useful666
+DR R0, R-, #1
+DR R<, R-, #!
ADD R-, R-, #3
R&'
R-
Durin(
)hat Frame SiFe do we -eed6
G
$aller part=
8ne word per argument!
G
%allee part#
)e need enough space for all the local variables we
need as well as for saving registers!
9f we call other functions ' subroutines we need to
save "2!
)e do not need to save "< as it is expected to
change by our function!
-ote that local variables are interchangeable with
registers!
Aut we need an extra place to ma.e the swap!
)hat Frame SiFe do we -eed X 4xample
G
9magine we have
three places in our
stac. and two local
variables# * and +!
G
>e 9is% t calculate=
? @ ?AB
G
>e nee) t allcate
t9 re(isters t
calculate t%e a))itin6
G
>e nee) t%e e7tra
space t ) t%e s9ap6
?
B
/Clank0
R-
R1= D
R!= D
)hat Frame SiFe do we -eed X 4xample
G
ST" "> "6 D?
G
+DR R1, R-, #0
G
S'R R!, R-, #0
G
+DR R!, R-, #1
G
ADD R1, R1, R!
G
'%e up)ate) value f
? is %el) in R1
?
B
/Clank0
R-
?
B
R1
R!
B
R1
R1= D
R!= D
R1= ?
R!= D
R1= ?
R!= B
)hat is "ecursion6
G
( recursive function is one that solves its tas. by calling
itself on portions of the tas.!
Similar to recurrence function in mathematics!
Li.e iteration -- can be used interchangeably7
sometimes recursion results in a simpler solution!
G
Standard example# Fibonacci numbers
The n-th Fibonacci number is the sum of the previous
two Fibonacci numbers!
FHnK T FHn X >K N FHn X ?K where FH>K T FH<K T >
int Fib#na""i(int n){
if ((n 99 0) << (n 99 )))
return );
ele
return Fib#na""i(n+)) = Fib#na""i(n+2);
}
(ctivation "ecords
G
)henever Fibonacci is invo.ed a new activation record is
pushed onto the stac.!
Fib())
"6
Fib(2)
Fib(7)
main
main calls
EiCnacci132
EiCnacci132 calls
EiCnacci1!2
EiCnacci1!2 calls
EiCnacci112
"6
Fib(7)
main
"6
Fib(2)
Fib(7)
main
(ctivation "ecords Hcont!K
EiCnacci112 returns,
EiCnacci1!2 calls
EiCnacci102
EiCnacci1!2 returns,
EiCnacci132 calls
EiCnacci112
EiCnacci132
returns
"6
main
"6
Fib())
Fib(7)
main
Fib(0)
"6
Fib(2)
Fib(7)
main
Tracing the Function %alls
G
9f we are debugging this program
we might want to trace all the calls of Fibonacci!
-ote# ( trace will also contain the arguments
passed into the function!
G
For FibonacciH;K a trace loo.s li.e#
G
Fib#na""i(7)
Fib#na""i(2)
Fib#na""i())
Fib#na""i(0)
Fib#na""i())
G
)hat would trace of FibonacciHEK loo. li.e6
9n Summary# The Stac.
G
Since our program usually starts at a low memory
address and grows upward we start the stac. at a high
memory address and wor. downward!
G
$urposes
Temporary storage of variables
Temporary storage of program addresses
%ommunication with subroutines
$ush variables on stac.
/ump to subroutine
%lean stac.
"eturn
%haracteristics of good
subroutines
G
+eneralit! X can be called with any arguments
$assing arguments on the stac. does this!
G
Trans#arenc! X you have to leave the registers li.e you found
them except "6!
"egisters must be callee saved!
G
Reada(ilit! X well documented!
G
Re,entrant X subroutine can call itself if necessary
Store all information relevant to specific execution to non-fixed
memory locations
The stac.G
This includes temporary callee storage of register valuesG
Bnow how toO
G
$ush parameters onto the stac.
G
(ccess parameters on the stac. using base N offset
addressing mode
G
=raw the stac. to .eep trac. of subroutine execution
$arameters
"eturn address
G
%lean the stac. after a subroutine call