# Lab1: RV32I Simulator ###### tags: `Computer Architecture` ## Two Sum [(leetcode)](https://leetcode.com/problems/two-sum/) **Description**: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: ``` Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. ``` ### C code ```cpp int* twoSum(int* nums, int numsSize, int target, int* returnSize){ for (int i=0; i < numsSize; i++) { for (int j=i+1; j < numsSize; j++) { if ((nums[i]+nums[j]) == target) { *returnSize = 2; int *arr = malloc(sizeof(int) * 2); arr[0] = i; arr[1] = j; return arr; } } } return 0; } ``` ## RISC-V assembly code (R32I ISA) This code has 5 components 1. main * set the initial value 2. fori * if i < numSize, then go forj 3. forj * if j < numSize, then go if 5. if * if (nums[i]+nums[j]) == target , then go print 7. print * print the index of answer ```cpp .data len: .word 4 target: .word 26 arr: .word 2, 7, 11, 15 .text # t3 = i, t4 = j main: la t1, arr addi t1, t1, -4 la t2, arr // t1 = arr[0] addi t2, t2, 0 la t0, target lw s1, 0(t0) // s1 = target la t0, len lw s0, 0(t0) // s0 = len li t3, 0 // i = 0 j fori fori: slt t0, t3, s0 beq t0, x0, exit addi t1, t1, 4 la t2, arr addi t3, t3, 1 # i++ mv t4, t3 j forj forj: slt t0, t4, s0 beq t0, x0, fori addi t2, t2, 4 addi t4, t4, 1 # j++ j if if: lw s2, 0(t1) lw s3, 0(t2) add t5, s2, s3 beq t5, s1, print j forj print: mv a0, t3 li a7, 1 ecall mv a0, t4 li a7, 1 ecall j exit exit: ``` ## Ripes simulator ### Instruction fetch The Program Counter, is a register that holds the address of instruction. it will output the instruction that read out of instruction memory. `0x10000317` from IFID to Decode `0x00830313` from Instruction memory to IFID ![](https://i.imgur.com/qy4oOes.png) ### Instruction decode It will know the input instruction, and decide what it should output ### Execute The computation stage. this stage consists of an ALU The ALU is responsible for performing boolean operations(and, or, not, nand, nor, xor, xnor) and integer addition and subtraction. Then stroed output in EX/MEM ### Memory access if data memory needs to be accessed, it will done in this stage. ### Write back The output will write the result in the register file `0x10000004` will write in t0 at next cycle ![](https://i.imgur.com/N8zkNgv.png)