Skip to content

Exercise 5

Consolidate RISC-V assembly learning and understand how conditional branch instructions are executed inside a loop. The following C expression is translated into assembly using bne and j:

while (save[i] == k)
i = i + 1;
  1. Open the RISC-V simulator.
  2. Transcribe the code below into the editor:
# Exercise 05
# C expression:
# while (save[i] == k) i = i + 1;
.data
Array_save: .word 3, 3, 1, 3, 3, 1, 4, 3, 1 # save[0] to save[8]
.text
main:
la s6, Array_save # base address of save[]
addi s5, zero, 3 # k = 3
addi s3, zero, 0 # i = 0
Loop:
add t1, s3, s3 # t1 = i * 2
add t1, t1, t1 # t1 = i * 4
add t1, t1, s6 # t1 = address of save[i]
lw t0, 0(t1) # t0 = save[i]
bne t0, s5, Exit # if (save[i] != k) goto Exit
addi s3, s3, 1 # i = i + 1
j Loop # repeat loop
Exit:
nop # end of loop

Run the program step by step using the Run One Step button. For each instruction, fill in the table below whenever a register is modified.

Fill in the table below

  • Fill in the PC with the instruction address and copy the Instruction column exactly as it appears in the simulator. Only fill in fields that are modified.
  • For pseudo-instructions, the simulator shows the real instruction in the Basic column and the original form in the Source column. Copy the Basic value into the Instruction column and the Source value into the Pseudo-instruction column. Leave the pseudo column blank for non-pseudo instructions.
  • If you need more rows, click Add row. Verification only runs when all rows are filled, if nothing appears after clicking Check, it means there are still empty rows.
Before After executing the instruction
PC Instruction Pseudo-instruction x5x6x19x21x22
(t0)(t1)(s3 (i))(s5 (k))(s6 (save))
0x000000000x000000000x000000000x000000000x00000000
0x00400000 auipc x22 64528 la s6 Array_save 0x10010000
0x00400004 addi x22 x22 0

Tip: in the print dialog, select A2 paper size for best results.