In: Computer Science
Please convert the following C program into the RISC-V assembly code
1)
#include <stdio.h>
int main()
{
int i = 2, j = 2 + i, k;
k = i * j;
printf("%d\n", k + j);
return 0;
}
2)
#include <stdio.h>
int main()
{
int i = 2, j = 2 + i, k = j / 2;
if (k == 1)
{
printf("%d\n", j)
k = k * 2;
if ( k == j)
{
printf("%d\n|, j);
}
else
printf("%d\n", k);
return 0;
}
This conversion can be done in several ways and the best mode of converting the C code into RISC-V assembly code is using a gcc compiler and follow this command.Let suppose the name of the c program file is program.c,in ur gcc compiler type
gcc -S program.c
This will generate you program.s file that is your assembly code for the C code.Anyways C language does the same process in the background.Here is the assembly code for C programs.
1)
.LC0:
.string "%d\n"
main:
addi sp,sp,-32
sd ra,24(sp)
sd s0,16(sp)
addi s0,sp,32
li a5,2
sw a5,-20(s0)
lw a5,-20(s0)
addiw a5,a5,2
sw a5,-24(s0)
lw a4,-20(s0)
lw a5,-24(s0)
mulw a5,a4,a5
sw a5,-28(s0)
lw a4,-28(s0)
lw a5,-24(s0)
addw a5,a4,a5
sext.w a5,a5
mv a1,a5
lui a5,%hi(.LC0)
addi a0,a5,%lo(.LC0)
call printf
li a5,0
mv a0,a5
ld ra,24(sp)
ld s0,16(sp)
addi sp,sp,32
jr ra
2)
.LC0:
.string "%d\n"
.LC1:
.string "%d\n|"
main:
addi sp,sp,-32
sd ra,24(sp)
sd s0,16(sp)
addi s0,sp,32
li a5,2
sw a5,-20(s0)
lw a5,-20(s0)
addiw a5,a5,2
sw a5,-24(s0)
lw a5,-24(s0)
srliw a4,a5,31
addw a5,a4,a5
sraiw a5,a5,1
sw a5,-28(s0)
lw a5,-28(s0)
sext.w a4,a5
li a5,1
bne a4,a5,.L2
lw a5,-24(s0)
mv a1,a5
lui a5,%hi(.LC0)
addi a0,a5,%lo(.LC0)
call printf
lw a5,-28(s0)
slliw a5,a5,1
sw a5,-28(s0)
lw a4,-28(s0)
lw a5,-24(s0)
sext.w a4,a4
sext.w a5,a5
bne a4,a5,.L3
lw a5,-24(s0)
mv a1,a5
lui a5,%hi(.LC1)
addi a0,a5,%lo(.LC1)
call printf
j .L4
.L3:
lw a5,-28(s0)
mv a1,a5
lui a5,%hi(.LC0)
addi a0,a5,%lo(.LC0)
call printf
.L4:
li a5,0
j .L5
.L2:
li a5,0
.L5:
mv a0,a5
ld ra,24(sp)
ld s0,16(sp)
addi sp,sp,32
jr ra
For any queries please comment.