Introduction
Using the following links and other sources, I have put together
a preliminary RISC-V assembly language program template for myself.
As I learn more and get more experience I will update/modify it.
Assembly Language Program Templates
Template #1
(RARS)
print string using a loop
(one ASCII character at a time)
print string reversed using a loop
(one ASCII character at a time)
File macros.asm
.macro push(%reg)
addi sp,sp,-4
sw %reg,0(sp)
.end_macro
.macro pop(%reg)
lw %reg,0(sp)
addi sp,sp,4
.end_macro
Simple Function Call and Return
No stack frame; No data saved; Return address saved in ra.
jal ra, func # call func
...
func:
addi a0, a0, 1 # do something
jalr zero, 0(ra) # return (or ret)
Note: ret is a pseudo instruction. It is equivalent to
jalr x0, x1, 0. (x1 holds the return address.)
Function Call Stack Diagram
High Addresses (Caller's Frame)
+---------------------------------------+
| Incoming Arguments (if > 8 args) |
+---------------------------------------+ <-- Old sp (Value before function call)
| Return Address (ra / x1) | |
+---------------------------------------+ |
| Saved Frame Pointer (fp / s0) | |
+---------------------------------------+ <-- New fp (Base of current frame)
| Callee-saved Registers (s1-s11) | |
+---------------------------------------+ | Current Stack Frame
| Local Variables & Temporary Arrays | |
+---------------------------------------+ |
| Outgoing Arguments (for next call) | v
+---------------------------------------+ <-- Current sp (Top of the stack)
Low Addresses (Next Callee's Frame)