call
pseudolyszt.net covers call and other RISC-V instructions in more detail.
Description
call runs a function and handles the return. It jumps to the function and stores the return address in ra, which lets the function come back. It is a pseudo-instruction that usually expands to the instruction below.
jal ra, label
When a function sits too far away for a single jump to reach, the assembler substitutes a longer sequence that covers the distance. Writing call with the function name states the intent and leaves the choice of form to the assembler. The jal entry describes the jump and the saving of the return address. The line below calls the square function.
call square
Calling a function also requires an agreement on how information passes between caller and callee. That agreement is the calling convention. The caller puts the function's inputs in the argument registers, named a0, a1 and so on, and reads the result from a0 once the function returns. Both sides follow the same rule, so code written separately still works together.
Every call overwrites ra. A function that makes calls of its own saves the ra it received before making them, then restores that value before its own return. Without this, the inner call's return address replaces the outer one and the function cannot get back. A function that calls nothing else has no need to save ra.
The RISC-V manual states that the standard software calling convention uses x1 as the return address register. A jal reaches targets within plus or minus 1 MiB, where a MiB is 1,048,576 bytes. A target farther out requires an auipc followed by jalr, which reaches anywhere in a 32-bit pc-relative address range.
The example calls square with 6 in a0 and finds 36 in a0 afterward. The argument goes in and the result comes out through the convention.
Expands to
jal ra, label
The assembler replaces this pseudo-instruction with the real instruction or instructions listed above.
Example
call square # jumps to square; ra holds the return address
References
- [1]RISC-V International. The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture. Version 20260120. Section 2.5.1, Unconditional Jumps, page 30.
- [2]RISC-V International. The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture. Version 20260120. Section 2.4.1, Integer Register-Immediate Instructions, pages 28 to 29.
