In: Computer Science
Translate the following function f to MIPS assembly code.
int f(int a, int b, int c, int d)
{
return func(func(a,b), func(b+c,d));
}
Assume the followings.
• The prototype of function func is “int func(int a, int b);”.
• You do not need to implement function func. The first instruction in function func is labeled “FUNC”.
• In the implementation of function f, if you need to use registers $t0 through $t7, use the lower-numbered registers first.
• In the implementation of function f, if you need to use registers $s0 through $s7, use the lower-numbered registers first.
1). ANSWER :
GIVENTHA :
To translate the fuction f to MIPS assembly code
#int f(int a, int b, int c, int d)
#{
#return func(func(a,b), func(b+c,d));
#}
f:
sub $sp, $sp, 20 #allocate memory on stack to save ra, b, c, d and
s0. a is not needed to be saved
sw $ra, 0($sp) #save return address
sw $a1, 4($sp) # save b
sw $a2, 8($sp) #save c
sw $a3, 12($sp) #save d
sw $s0, 16($sp) #save s0, we will use to store intermediate
results
#already $a0 has a and $a1 has b, so simply call func(a,b)
jal func
move $s0, $v0 #now s0 = func(a, b)
#now set up arguments for func(b+c, d)
#calculate b + c by loading their saved values from stack
#store b + c into $a0
lw $t0, 4($sp)
lw $t1, 8($sp)
add $a0, $t0, $t1
#store value of d into $a1
lw $a1, 12($sp)
#call func(b+c, d)
jal func
move $a1, $v0 #store the return value into $a1 to make next func()
call
#now setup arguments for the final func( func(a,b), func(b+c,
d)) call
#set $a0 = func(a,b). func(a,b) is avaialbe in $s0
move $a0, $s0
#already $a1 is setup to the value of func(b+c, d)
jal func
#now result is in $v0
#now restore all registers and return
lw $ra, 0($sp) #restore return address
lw $a1, 4($sp) # restore b
lw $a2, 8($sp) # restore c
lw $a3, 12($sp) #restore d
lw $s0, 16($sp) #restore s0,
add $sp, $sp, 20 #deallocate memory on stack
jr $ra