Skip to content

Exercise 8

Consolidate RISC-V assembly learning and understand how the stack is used to preserve registers across procedure calls. The same C expression as Exercise 7 is used, but now leaf_example saves and restores registers t0, t1, and s0 on the stack:

int f = (g + h) - (i + j);
  1. Open the RISC-V simulator.
  2. Transcribe the code below into the editor:
# Exercise 08
# int f = (g + h) - (i + j);
.text
j main
leaf_example:
addi sp, sp, -12 # adjust stack for 3 registers
sw t1, 8(sp) # save t1
sw t0, 4(sp) # save t0
sw s0, 0(sp) # save s0
add t0, a1, a2 # t0 = g + h
add t1, a3, a4 # t1 = i + j
sub s0, t0, t1 # f = t0 - t1
add a0, s0, zero # return value in a0
lw s0, 0(sp) # restore s0
lw t0, 4(sp) # restore t0
lw t1, 8(sp) # restore t1
addi sp, sp, 12 # free stack space
jr ra # return from function
main:
addi t1, zero, 1
addi t0, zero, 2
addi s0, zero, 3
addi a1, zero, 4 # g = 4
addi a2, zero, 7 # h = 7
addi a3, zero, 2 # i = 2
addi a4, zero, 1 # j = 1
jal leaf_example # call leaf_example
nop # result in a0

Run the program step by step using the Run One Step button. For each instruction, fill in the table below whenever a register or memory position 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 x10x11x12x13x14x1x2x5x6x8 0x7FFFEFF0 ... 0x7FFFEFF4 ... 0x7FFFEFF8 ...
(a0 (f))(a1 (g))(a2 (h))(a3 (i))(a4 (j))(ra)(sp)(t0)(t1)(s0) s0 t0 t1
0x000000000x000000000x000000000x000000000x000000000x000000000x7FFFEFFC0x000000000x000000000x00000000 0x00000000 0x00000000 0x00000000
0x00400000 jal x0 56 j main

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