05.08.2014 Views

Lecture Notes for Computer Architecture II - St. Cloud State University

Lecture Notes for Computer Architecture II - St. Cloud State University

Lecture Notes for Computer Architecture II - St. Cloud State University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example<br />

Write the MIPS code to compute the nth Fibonacci number F(n) where<br />

F(n) = 0, if n =0<br />

= 1, if n =1<br />

= F(n-1) + F (n-2), otherwise<br />

Base your algorithm on the straight<strong>for</strong>ward procedure below.<br />

int fib( int n) {<br />

if (n == 0) return 0;<br />

else if (n ==1) return 1;<br />

else return fib(n-1) + fib(n-2);<br />

}<br />

Solution<br />

n fib(n-1) fib(n-2)<br />

<br />

$a0 $t1 $t2<br />

<strong>St</strong>ack use<br />

Push return address, n, be<strong>for</strong>e calling fib(n-1)<br />

Pop n<br />

Push n, fib(n-1), be<strong>for</strong>e calling fib(n-2)<br />

Pop fib (n-1), n, return address<br />

If n==0 return 0<br />

Fib:<br />

bne $a0, $zero, fibne0<br />

Add $v0, $zero $zero<br />

Jr $31<br />

If n==1 return 1<br />

Fibne0: addi $v0, $zero 1<br />

Bne $a0, $v0, fibne1<br />

Jr $31<br />

Compute fib (n-1)<br />

Fibne1: addi $sp $sp –8<br />

Sw $ra 4($sp)<br />

Sw $a0 0($sp)<br />

Addi $a0 $a0 –1<br />

Jal fib<br />

add $t1, $v0 $zero<br />

Lw $a0 0$(sp)<br />

Addi $sp $sp 4<br />

Compute Fibn-2<br />

addi $sp $sp –8<br />

Sw $a0 4($sp)<br />

Sw $t1 0($sp)<br />

Page | 55<br />

Addi $a0 $a0 –2<br />

Jal fib<br />

Move $t2, $v0<br />

Lw $t1 0$(sp)<br />

Lw $a0 4$(sp)<br />

Lw $ra 8$(sp)<br />

Addi $sp $sp 12<br />

Return fib(n-1) + fib(n-2)<br />

Add $v0 $t1 $t2<br />

Jr $31

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!