Exercise 4
Objective
Section titled “Objective”Consolidate conditional and unconditional branching in RISC-V assembly by implementing an if-else statement using bne and j. The following C expression is translated into assembly using bne and j:
if (i == j) f = g + h;else f = g - h;Instructions
Section titled “Instructions”- Open the RISC-V simulator.
- Transcribe the code below into the editor:
# Exercise 04# C expression:# if (i == j)# f = g + h;# else# f = g - h;
.textmain: addi s1, zero, 10 # g = 10 addi s2, zero, 20 # h = 20 addi s3, zero, 1 # i = 1 addi s4, zero, 2 # j = 2
bne s3, s4, Else # if (i != j) goto Else add s0, s1, s2 # f = g + h j Exit # goto Exit
Else: sub s0, s1, s2 # f = g - h
Exit: nopStep-by-step Execution - Scenario 1 (i ≠ j)
Section titled “Step-by-step Execution - Scenario 1 (i ≠ j)”With the initial values i = 1 and j = 2, the branch is taken and execution jumps to Else, computing f = g - h.
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.
Step-by-step Execution - Scenario 2 (i = j)
Section titled “Step-by-step Execution - Scenario 2 (i = j)”Now change the addi instruction that sets s4 to assign j = 1 (same as i):
addi s4, zero, 1 # j = 1Click Reset to reload the program, then run it step by step again. With i = j = 1, the branch is not taken and execution falls through to add, then jumps to Exit via j, skipping Else.
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.
Compare both tables and analyze the difference in the instruction flow (observe the PC sequence) and the final value of s0.