risc-v

Definition

jal (RISC-V)

Jumps to the target address and stores the address of the next instruction in register rd.

jal rd, offset

Equivalent C code:

rd = next_pc;
goto target;

Examples

Example 1: Function Calling

We want to translate the following C code to RISC-V:

int main() {
	simple();
	a = b + c;
}
 
void simple() {
	return;
}

Solution: What jal does is to write the program counter to the return address register, i.e.:

Why PC + 4?

RISC-V instructions are 32 bits wide, so each instruction occupies 4 bytes. When jal executes, it must save the address of the instruction after the call so execution can resume there after the callee returns. The next instruction is therefore at PC + 4.

and jumps to a label, which sets the program counter to the label, i.e.:

Then, in the label, we can simply jump back using the jr instruction and ra register, which sets:

Thus:

main:
	jal simple      # call
	add s0, s1, s2
	
simple:
	jr ra           # return