Can sp / x2 be used as a temporary register?
It should not. sp is the stack pointer; corrupting it can break stack frames, saved registers, and return addresses.
sp is the stack pointer used by the RISC-V standard calling convention. Functions build stack frames around sp, save values that must be restored, and receive stack-passed arguments; the standard ABI requires sp to be 128-bit aligned on procedure entry and remain aligned during execution.
The psABI marks sp as preserved across calls, but it is special: a function may move sp during its prologue to build a stack frame, as long as it is exactly restored in the epilogue. This differs fundamentally from ordinary s* registers, which must be bitwise restored if borrowed; sp is allowed to change mid-function for stack frame construction.
The psABI names x2 as sp and marks it preserved across calls. A function may move sp while building its frame, but must restore it before returning.
sp / x2 is the stack pointer in the standard calling convention. The psABI marks it preserved across calls; a function may move sp to build a frame, but must restore it and maintain the standard ABI's 128-bit alignment rule.
The standard ABI requires the stack pointer to be aligned to a 128-bit boundary on procedure entry and remain aligned during execution.
A callee may move sp to build a frame, but must restore it before return.
Before calling another function, the current function must leave the stack in an ABI-compliant state.
addi sp, sp, -16
sd ra, 8(sp)
sd s0, 0(sp)
addi s0, sp, 16
...
ld s0, 0(sp)
ld ra, 8(sp)
addi sp, sp, 16
retsp is the x2 stack pointer; in the standard ABI the stack grows downward and sp is 128-bit aligned on procedure entry. s0/fp is x8; the psABI says a frame pointer is optional, but if one exists it must reside in x8/s0. Both are preserved ABI state, but sp tracks the stack position while s0/fp has a frame-pointer role only when that convention is used.
Using sp as an ordinary scratch register is extremely dangerous. If sp is corrupted, saved registers, the return address, local variables, incoming/outgoing arguments, and the entire call chain's stack frames will be damaged. The most common failure mode is ret jumping to a wrong address, or the caller's local variables being silently overwritten after a function returns. sp may only be moved according to ABI rules (down in prologue, back up in epilogue) and must never participate in general-purpose arithmetic.
It should not. sp is the stack pointer; corrupting it can break stack frames, saved registers, and return addresses.
The standard ABI requires sp to be aligned to a 128-bit boundary on procedure entry and remain aligned during execution.