Function can often be implemented by compilers “in-line”. An in-line function is
ID: 3675835 • Letter: F
Question
Function can often be implemented by compilers “in-line”. An in-line function is when the body of the function is copied into the program space, allowing the overhead of the function call to be eliminated. Implement an “in-line” version of the C code above in MIPS assembly. What is the reduction in the total number of MIPS assembly instructions needed to complete the function? Assume that the C variable n is initialized to 5. The function is shown below.Int fib(int n) { if(n==0) return 0; else if (n==1) return 1; else return fib(n-1) + fib(n-2); } Function can often be implemented by compilers “in-line”. An in-line function is when the body of the function is copied into the program space, allowing the overhead of the function call to be eliminated. Implement an “in-line” version of the C code above in MIPS assembly. What is the reduction in the total number of MIPS assembly instructions needed to complete the function? Assume that the C variable n is initialized to 5. The function is shown below.
Int fib(int n) { if(n==0) return 0; else if (n==1) return 1; else return fib(n-1) + fib(n-2); }
Int fib(int n) { if(n==0) return 0; else if (n==1) return 1; else return fib(n-1) + fib(n-2); } Int fib(int n) { if(n==0) return 0; else if (n==1) return 1; else return fib(n-1) + fib(n-2); }
Explanation / Answer
addi $sp, $sp, -4 :Allocating memory to the stack frame (4 byte ) -> the value of n is 5
sw $ra, 0($sp) :Saving the returning address to stack
addi $a0, $zero ,$zero :(Here addi means ""add immidiate) ->temporary regesiter(a0) is given value of 0 --> a0=0+0
beq $a0,$zero, exit :(Here beq means "branch on equal" )-> Now checking (if (n == 0) ???) if yes then return 0 and get exit
addi $a1, $zero, 1 :temporary regesiter(a1) is given value of 1 -> a0= 0+1
beq $a1,1, exit :(Here beq means "branch on equal" )-> Now checking ( else if (n == 1) ???) if yes then return 1 and get exit
lw $a2, 0($sp) :(Here lw stands for loading) loadind a2 with value of n(which is 5)
sub $a2, $a2, 1 :(Here sub is "substraction")-> We are doing a2=a2-1
lw $a3, 0($sp) :(Here lw stands for loading) loadind a3 with value of n(which is 5)
sub $a3, $a3, 2 :(Here sub is "substraction")-> We are doing a3=a3-2
add $a4, $a2, $a3 :(Here add is "Addition ")-> We are implementing the logic of equetion (fib(n-1) + fib( n-1)
sw 0($sp), $a4 : (Here sw stands for "storeing")We are here storing actual location
bne 0($sp), $zero, loop : new value of n
exit: jr $ra :return value of register address to caller and exit
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.