ISA & Assembly

The code above is the start (prologue) of a function. What does it do?

addi sp, sp, -16
sw   ra, 12(sp)
sw   s0, 8(sp)
  1. AIt reserves stack space and saves the return address (ra) and the callee-saved s0
  2. BIt loads the function arguments ra and s0 from the stack
  3. CIt frees the stack in order to return from the function
Show answer and explanation

Answer: A. It reserves stack space and saves the return address (ra) and the callee-saved s0

Line 1 subtracts 16 from sp to allocate a stack frame, line 2 writes the return address ra into it, and line 3 writes the callee-saved s0. The function calls other functions, so it must protect ra, and it uses s0, so it must preserve s0's old value. The epilogue at the end reverses this with "lw s0, 8(sp)", "lw ra, 12(sp)", "addi sp, sp, 16" and "ret".

  • A. Correct. The epilogue undoes this in reverse.
  • B. sw is a store, and neither ra nor s0 is an argument.
  • C. sp is decreased, so this is allocation.
Practice this topic Back to topic

More ISA & Assembly questions

  1. What is an advantage of using a frame pointer (s0/fp in RISC-V) inside a function?
  2. In RISC-V, what happens if a recursive function (one that calls itself) forgets to save ra on the stack?
  3. On little-endian RISC-V, a register holding 0x12345678 is stored with sw to address 0x100. What value does lbu then read from address 0x101?
  4. In RISC-V, what can happen when the address of a 4-byte lw is not a multiple of 4 (misaligned)?
  5. The RISC-V instruction "slli t0, a0, 3" makes t0 how many times the value of a0 (ignoring overflow)?