Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RISC-V difference between jal and jalr

I came across the instruction named jal and jalr while studying RISC-V assembly language.

I quite having hard times to understand the differences between jal and jalr.

jal x1, X 

It seems that above code is meaning that jump to X, and save the return address which is normally PC+4 to the x1.

But after that, jalr x0, 0(x1) comes.

0(x1) means that going back to the address which is the return address, but what is x0?

Essentially x0 is zero in RISC-V, so why do we need x0?

What is the actual difference between those two instructions, jal and jalr?

like image 390
jwkoo Avatar asked Oct 08 '19 04:10

jwkoo


People also ask

What is the JALR instruction used for?

The jump-and-link-register instruction ( JALR ) is the union of JAL and JR , meaning that it transfers control to the address in a specified register, and stores the return address in the register file. However, unlike JAL , JALR allows the programmer to specify the destination register of the return address.

What is JAL instruction in Riscv?

The JAL instruction encodes two operands: a register, and an immediate.

Is JAL a pseudo instruction?

These instructions can be simulated with a bgez or bltz respectively, followed by a jal , which means that both bgezal and bltzal should be classified as pseudo-instructions. However, both have opcodes assigned to them, hence they are classified as basic instructions.

What range of addresses can be reached using the JAL instruction in RISC V?

The immediate can reach +/- 1 MB from the JAL itself. The immediate is shifted by one bit, the true LSB is always zero, so is not encoded. Because RISC V supports instructions in multiples of 16-bits (two bytes), we cannot assume the next-to-LSB is also zero, as it would be with MIPS (which has 32-bit instructions).


1 Answers

As we can see in specification (page 15), the main difference between jal and jalr is the address value encoding.

jal use immediate (20bits) encoding for destination address and can jump +-1MiB range. And save the actual address + 4 in register rd. (x1 in your example).

jalr use indirect address (x1 in your example) plus a constant of 12bits (0 in your example). It save the actual address + 4 in register rd too. In your example your set x0 as return address register because you «don't care».

When you return from subroutine for example, the return address is not usefull then we set x0.

like image 133
FabienM Avatar answered Sep 19 '22 09:09

FabienM