2-8-11 - a0 = 3 ra= 4024 a0 = 2 ra = 4024 a0 = 1 ra = 1004...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Handling recursive procedure calls Example . Compute factorial (n) int fact (int n) { if (n < 1) return (1); else return (n * fact(n-1)) } ( Plan ) Put n in $a0. Result should be available in $v0. fact: subi $sp, $sp, 8 $sp sw $ra, 4($sp) sw $a0, 0($sp) $fp OLD NEW $sp (current top of the stack) a0 ra
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
calling program procedure fact 4000 996 4004 1000 1004 4024 $sp a0 v0 The growth of the stack as the recursion unfolds a0 = n (3) jal fact (4000) read fact(n) from v0 push ra push a0 if n<1 then {v0=1 Return to ra} a0=n-1 jal fact (4000) v0=old a0* fact(n-1) return to old ra
Background image of page 2
Background image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: a0 = 3 ra= 4024 a0 = 2 ra = 4024 a0 = 1 ra = 1004 n=3 result Now test if n < 1 (i.e. n = 0). In that case return 0 to $v0. slti $t0, $a0, 1 # if n ! 1 then goto L1 beq $t0, $zero, L1 addi $v0, $zero, 1 # return 1 to $v0 addi $sp, $sp, 8 # pop 2 items from stack jr $ra # return L1: addi $a0, $a0, -1 # decrement n jal fact # call fact with (n – 1) Now, we need to compute n * fact (n-1) lw $a0, 0($sp) # restore argument n lw $ra, 4($sp) # restore return address addi $sp, $sp, 8 # pop 2 items mult $v0, $a0, $v0 # return n * fact(n-1) jr $ra # return to caller...
View Full Document

{[ snackBarMessage ]}

Page1 / 3

2-8-11 - a0 = 3 ra= 4024 a0 = 2 ra = 4024 a0 = 1 ra = 1004...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online