Skip to content
BIASED

Procedures, the stack and calling conventions

Block 1 of 5~2 min

`jal` and `jalr`

Loops and memory were enough for one routine that called nothing else. A procedure must find arguments, return to any caller, deliver a result, and leave the caller’s values intact.

Baseline. Sharing code with a fixed j back works for one caller only. Store the return address in a register — then a nested call overwrites it. Hence per-call storage and rules about who saves what.

jal rd, label: x[rd]←pc+4x[rd]\leftarrow pc+4, pc←pc\leftarrow label (±1 MiB, J format). jalr rd, rs1, imm: jump to x[rs1]+sext⁡(imm)x[rs1]+\operatorname{sext}(imm) (bit 0 cleared), link into rd (I format). Pseudos: jal label / call (auipc+jalr for far targets), ret = jalr zero, ra, 0, jr rs = jalr zero, rs, 0.

Example. jal at 0x00400004 → ra=0x00400008, pc=fact at 0x00400050. Recursive jal at 0x0040006c → every recursive return lands at 0x00400070.

Answers are saved on the server and tied to this browser until you sign in.