Jump to the labeled instruction, if the given condition is == true==
JAL vs JALR
- JAL: Stores the address of the next instruction (PC + 4) in
rd
and jumps to PC + imm * 2.- Procedure call (jal ra, func)
- JALR: Stores the address of the next instruction (PC + 4) in
rd
and jumps to R[rs1] + imm.- Procedure return (jalr x0, 0(ra))
Why does only JALR not use *2?
JALR is an instruction in the I format. Applying a
>> 1
shift toimm12
here would require additional hardware implementation, as I format instructions typically do not require this operation. Additionally, the jump distance can be longer compared to other branch instructions due to the use of a register in JALR.
Example
if (i == j)
f = g + h;
else
f = g - h;
// i in x22, j in x23
// f in x19, g in x20, h in x21
while(A[i] == k)
i += 1;
// i in x22, k in x24
// address of A[] in x25
long max (long x, long y) {
if (x > y)
return x;
else
return y;
}
// x is in a0
// y is in a1
long fact_do (long x) {
long result = 1;
do {
result *= x;
x = x - 1;
} while (x > 1);
return result;
}
// x is in a0
long fact_while (long x) {
long result = 1;
while (x > 1) {
result *= x;
x = x - 1;
}
return result;
}
// x is in a0