jalr
lyszt.net covers jalr and other RISC-V instructions in more detail.
Encoding format
Description
Jumps to an address held in a register and stores the return address. In jalr rd, rs1, imm, execution continues at the value in rs1 plus imm, with the lowest bit of the target cleared, and the address of the next instruction is written to rd. It covers returns through saved addresses and computed jumps.
Official definition
Unconditional Jumps
The indirect jump instruction JALR (jump and link register) uses the I-type encoding. The target address is obtained by adding the sign-extended 12-bit I-immediate to the register rs1, then setting the least-significant bit of the result to zero. The address of the instruction following the jump (pc+4) is written to register rd. Register x0 can be used as the destination if the result is not required.
Plain unconditional indirect jumps (assembler pseudoinstruction JR) are encoded as a JALR with rd=x0. Procedure returns in the standard calling convention (assembler pseudoinstruction RET) are encoded as a JALR with rd=x0, rs1=x1, and imm=0.
The JAL and JALR instructions will generate an instruction-address-misaligned exception if the target address is not aligned to a four-byte boundary.
Return-address prediction stacks are a common feature of high-performance instruction-fetch units, but require accurate detection of instructions used for procedure calls and returns to be effective. For RISC-V, hints as to the instructions' usage are encoded implicitly via the register numbers used. A JAL instruction should push the return address onto a return-address stack (RAS) only when rd is 'x1' or x5. JALR instructions should push/pop a RAS as shown in rashints.
Return-address stack prediction hints encoded in the register operands of a JALR instruction.
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.