In: Computer Science
3. Translate the following C code to MIPS assembly code (in two separate files). int main() { printf(“before subroutine!\n”); Subfunc(); printf(“after subroutine!\n!”); } void Subfunc() {printf(“I am subroutine!\n”);}
4. Translate the following C code to MIPS assembly (in two separate files). Run the program step by step and observe the order of instructions being executed and the value of $sp. int main() { int x=2; z=Subfunc(x); printf(“Value of z is: %d”, z); } int Subfunc(int x) { return x+1;}
Answer 3
Step 1
Step 1:-
Given:-
Program in c language:-
#include<stdio.h>
void subfunc(); //Function Declaration
int main()
{
printf ("before subroutine");
subfunc (); //Call the function
printf ("after subroutine");
return 0;
}
void subfunc() //Function definition
{
printf("I am subroutine");
}
Step 2
Step 2:-
Convert the C code into Mips assembly code:-
code:-
$LC0:
.ascii "before subroutine\000"
$LC1:
.ascii "after subroutine\000"
main:
addiu $sp,$sp,-32
sw $31,28($sp)
sw $fp,24($sp)
move $fp,$sp
lui $2,%hi($LC0)
addiu $4,$2,%lo($LC0)
jal printf
nop
jal subfunc
nop
lui $2,%hi($LC1)
addiu $4,$2,%lo($LC1)
jal printf
nop
move $2,$0
move $sp,$fp
lw $31,28($sp)
lw $fp,24($sp)
addiu $sp,$sp,32
j $31
nop
$LC2:
.ascii "I am subroutine\000"
subfunc:
addiu $sp,$sp,-32
sw $31,28($sp)
sw $fp,24($sp)
move $fp,$sp
lui $2,%hi($LC2)
addiu $4,$2,%lo($LC2)
jal printf
nop
nop
move $sp,$fp
lw $31,28($sp)
lw $fp,24($sp)
addiu $sp,$sp,32
j $31
nop
Answer 4.
Step 1:
Value of $sp before and after the program execution remains the same. Only during function call it will decrease that to store the saved registers like return value , stack pointer or if some values are changed. But, here in this program it won't matter much but mainly in recursive kind of functions stack usage is very much crucial.
Step 2
MIPS PROGRAM :-
.data
print_prompt: .asciiz "Value of z is: "
.text
.globl main
main:
#int x = 2
addi $a0, $zero, 2
#z = Subfunc(x)
jal Subfunc
move $t0, $v0
#printf("Value of z is: %d ")
addi $v0, $zero, 4
la $a0, print_prompt
syscall
addi $v0, $zero, 1
move $a0, $t0
syscall
#system exit
addi $v0, $zero , 10
syscall
Subfunc:
#creating stack
addiu $sp, $sp, -4
sw $fp, 4($sp)
#return x+1
addiu $v0, $a0, 1
#releasing stack
addiu $sp, $sp, 4
jr $ra
Kindly upvote please,
Thank you.