Advertisement
Singasking

Untitled

Feb 3rd, 2023
2,525
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fib:
  2.     addi $sp,$sp,-12 #create stack for 2 words
  3.     slti $t0,$a0,1 #n<1
  4.     beq $t0,1,ret #we return value
  5.     beq $a0,1,ret #we ret value as n==1
  6.    
  7.     #store the ra
  8.     sw $ra,8($sp)
  9.     sw $a0,0($sp) #first element will be the argument passed to fib, that is n
  10.     addi $a0,$a0,-1 #compute n-1 and call fib
  11.     jal fib
  12.    
  13.     #restore back value
  14.     lw $a0,0($sp)
  15.    #now store the result
  16.     sw $v0,4($sp)
  17.    
  18.     #now compute n-2 and call fib
  19.     addi $a0,$a0,-2
  20.     jal fib
  21.    
  22.     #now return fib(n-1)+fib(n-2)
  23.     lw $t0,4($sp) #restore fib(n-1) value
  24.     add $v0,$v0,$t0
  25.     lw $ra,8($sp)
  26.    #now just pop last 3 elements of stack
  27.     addi $sp, $sp, 12
  28.  
  29.    
  30.     jr $ra #jump to return addr
  31.    
  32.  
  33. ret:
  34.    
  35.     add $v0,$a0,$zero #just return n as it was <=1
  36.     jr $ra
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement