RISC-V Calling Convention
In RISC-V, there are some rules which the programmer is advised to follow. The following are rules for callee-saved registers (registers saved by the function being called):
The register
x2is reserved as a “stack pointer” (sp), and points to the bottom of the stack. Data abovex2is (technically) immutable, andx2can be decremented during a function call to allocate more space on the stack if its value is returned back to its pre-function call value after the call.The registers
s0tos11are “saved” registers, meaning that just asx2, they need to be restored at the end of the function call. We can do so usingsw s0 0(sp)in the beginning of the function, andlw s0 0(sp)towards the end.The following are caller-saved registers (saved and restored by the function that is calling):
- The register
x1(akara) is reserved as the register to store return addresses in . There are two pseudoinstructions,jal labelandret(ja label), which assumex1as the return address.- The registers
a0toa7are registers used for function arguments, anda0anda1can alsobe used for return values.- If a function needs more than 8 arguments, the temporary registers
t0tot6can be used as addresses.The following are miscellaneous registers:
- The register
x0always stores 0/0x0.- The register
x3is the “global pointer”, used to store a reference on the heap.- The register
x4is the “thread pointer,” used to separate stacks for threads.
Examples
Callee-Saved Registers
Caller-Saved Registers