# Lab1: RV32I Simulator ###### tags: `Computer Architecture 2022` ## Single number This problem is based on [LeetCode 137](https://leetcode.com/problems/single-number-ii/). Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. ## Assembly code ```cpp .data arr: .word 5, 1, 1, 1, 9, 5, 5, 9, 4, 9 len: .word 10 .text main: jal ra, singleNumber j print singleNumber: # t2: arr base t3: len t4: i t5: lower t6: higher li t5, 0 li t6, 0 li t4, 0 la t3, len lw t3, 0(t3) la t2, arr for: blt t4, t3, task jr ra task: lw s5, 0(t2) # s5 = nums[i] xor t5, t5, s5 # lower ^= nums[i]; xori t1, t6, -1 # t1 = ~higher and t5, t5, t1 # lower &= ~higher; xor t6, t6, s5 # higher ^= nums[i]; xori t1, t5, -1 # t1 = ~lower and t6, t6, t1 # higher &= ~lower; addi t2, t2, 4 addi t4, t4, 1 # i++ j for # --- print --- print: mv a0, t5 li a7, 1 ecall exit: ``` ## Pipeline feature in Ripes ### How to write-back ![](https://i.imgur.com/R8JLQSK.png) Write-back index should be pass into next stage ( yellow line ) because index will change in ID when last stage try to write-back. ### Branch instruction The pipeline in Ripes is reduced version, it lacks lot of components. e.g. the component compare `rs` and `rt` for branch instruction. `rs` and `rt` are compared in ID stage for performance reason. Structure described above likes: ![](https://i.imgur.com/nNvyk6w.png) Due to propagating comparison, new PC will be decided and new instruction will be fetched in next cycle. Real example show below: ![](https://i.imgur.com/8aoVH7a.png) ![](https://i.imgur.com/l7hW3a0.png) instruction `lw` will be fetched after comparison is true. ### Data hazard There are two famous data hazard. First is data dependency issue, which cause by RAW ( Read After Write ). Second is load and use. First issue can be solved perfectly by **forwarding** without any stall. On the other hand, load-use need to stall one cycle. The following is example of load-use: ![](https://i.imgur.com/NJHvDYf.png) ![](https://i.imgur.com/sfNhJxf.png) Load-use can be solved by one stall and forwarding from MEM/WB tp ID/EX. The following is example of RAW: ![](https://i.imgur.com/xzSQnme.png) ![](https://i.imgur.com/lycomzo.png) RAW can be solved by forwarding with no penalty(stall). We can observe that EX stage in second picture whose `rt` source come from MEM. That is exact **forwarding**. ## Reference [hrh47's computer organization note](https://hackmd.io/@8bFA57f7SRG-K7AAT8s62g/ryv1NT3S#%E7%AC%AC18%EF%BD%9E21%E8%AC%9B-Pipelining-75)