# Lab1: RV32I Simulator ###### tags: `CA2020` ## IsPrime C-Code ```= #include <stdio.h> int main () { int n; int prime = 1; int i; printf("Please enter a positive integer\n"); scanf("%d", &n); for(i = 2; i*i <= n; i++) { if(n % i == 0) { prime = 0; break; } } if(prime) printf("%d is a prime number\n", n); else printf("%d is not a prime number\n", n); return 0; } ``` ## IsPrime Assembly-Code 1. prologue 2. for & i++ : for (i = 2 ; i * i <= n ; i++) 3. if : if (n%i == 0)... 4. epilogue 5. print1 : n is prime . ```= .data argument: .word 19 str1: .string " is a prime number." str2: .string " is not a prime number." .text prologue: addi sp,sp,-12 #prologue sw s0,8(sp) #prologue addi s0,sp,12 #prologue lw a5,argument #n sw a5,-4(s0) #store n in -4(s0) li a5,1 #prime = 1 sw a5,-8(s0) #store prime in -8(s0) li a5,2 #i = 2 sw a5,0(s0) #store i in -0(s0) lw a4,-4(s0) #a4 = n j for if: lw a5,0(s0) #a5 = i rem a5,a4,a5 #n%i bne a5,zero,i++ #whether n is divided by i sw zero,-8(s0) #if n can be divided by i, prime = 0 j epilogue i++: lw a5,0(s0) #a5 = i addi a5,a5,1 sw a5,0(s0) for: lw a5,0(s0) #a5 = i mul a5,a5,a5 #a5 = i*i bge a4,a5,if #for loop condition epilogue: lw a0,argument #a5 = n (for print) lw a4,-8(s0) #a4 = prime lw s0,8(sp) #epilogue addi sp,sp,12 #epilogue bne a4,zero,print1 #if(prime) li a7, 1 #print "n" ecall la a0,str2 #print " is not a prime number." li a7, 4 ecall li a7, 10 #exit ecall print1: li a7, 1 ecall la a0,str1 li a7, 4 #print " is a prime number." ecall li a7, 10 ecall ``` * Result ![](https://i.imgur.com/KDrkj6n.png) ![](https://i.imgur.com/16PkO1z.png) ## Branch The pipeline decide whether to branch in the execution stage. If jump,then insert 2 nop to flush because you don't have to fetch the following 2 instructions without branch. ![](https://i.imgur.com/eWDx3xH.png) ![](https://i.imgur.com/74nXUcj.png) ## Load-use The rem instruction wants to use a5 at the execution stage,but the correct a5 hasn't write back.Thus,we need to insert nop.Because of forwarding,we only need to insert 1 nop. ``` lw a5,argument #n sw a5,-4(s0) #store n in -4(s0) ``` ![](https://i.imgur.com/cHXIn3m.png) ![](https://i.imgur.com/Lc9GCKf.png) ## Print 1. a7 = 1 , print int a0 2. a7 = 4 , print string a0 3. a7 = 10 , exit ## Memory and Register In prologue,stackpointer -12 and create a space for stack. This is because there are 3 local variables (n,i,prime). sp : 0x7ffffff0 -> 0x7fffffe4 ![](https://i.imgur.com/OSGdUNa.png) ![](https://i.imgur.com/Gepn0oc.png) ![](https://i.imgur.com/bEp2dSg.png)