jpseudo

j

pseudo
RISC-V Assembly Reference

lyszt.net covers j and other RISC-V instructions in more detail.

Description

j performs the simplest jump: it always transfers control to a label, with no condition attached. A branch instruction transfers control only when a comparison succeeds. The syntax is j label.

This is an unconditional jump, also known as a goto. Loops and if/else blocks rely on it. A basic loop puts a conditional branch at the top to decide when to leave, runs the loop body, and ends with a j that returns to the top for the next pass. Without that jump, execution falls off the end and the loop never repeats. In an if and else, a j at the end of the if block skips over the else block, so only one of the two blocks runs.

j does not record a return address, which sets it apart from a function call. Use j to move around inside your code, whether for loops or to skip a block, and use call when execution must come back. The deciding factor is whether a return is needed.

The RISC-V manual encodes plain unconditional jumps as a jal with rd set to x0. It states that this jump should always be used for unconditional branches rather than a conditional branch whose condition is always true. Jumps are also pc-relative, cover a much wider range than branches, and leave the conditional branch prediction tables untouched.

j is a pseudo-instruction for the line below.

jal zero, label

This is a jump and link that writes the return address into the zero register, which discards it, leaving only the jump. The example jumps back to the top of a loop.

Expands to

jal zero, label

The assembler replaces this pseudo-instruction with the real instruction or instructions listed above.

Example

j loop   # go back to the top of the loop