J-Type
Learning Outcomes
- Translate between J-Type assembly instructions and machine instructions.
- Identify use cases for different unconditional jump instructions and pseudoinstructions:
j,jr,jal,jalr,ret. - Use J-Type instructions for conditional branches.
🎥 Lecture Video
Jump Instructions
The remainder of this page covers in-scope content that was not covered in lecture.
Conditionally Branching Far Away
Conditional Branches are typically used for if-else statements, for/while loops. In general, because these control structure are usually pretty small (<50 lines of C code), we can use B-Type instructions. However, as we saw earlier, B-Type instructions have limited range: instructions from the current instruction (PC).
To jump even further, we can use J-Type unconditional jumps in combination with B-Type instructions.
Admittedly, J-Type instructions also have a limited range: instructions from the currrent insturction (PC).
If we wanted to jump to any address, RISC-V opts for jumping with absolute addressing and jalr. As discussed in a previous section, jalr is an I-Type instruction that sets PC to PC = R[rs1] + imm, where imm specifies a 12-bit immediate imm.
- To call functions with absolute addressing, instead of
jal ra Label1:
lui ra <hi20bits*>
jalr ra ra <lo12bits>
- To break out of loops using absolute addressing, instead of
j Label(e.g.,jal x0 Label):
auipc ra <hi20bits*>
jalr x0 ra <lo12bits>
See the discussion of U-Type instructions lui and auipc. Just like with resolving li pseudoinstructions, jalr sign-extends immediates. So if lo12bits has sign bit set, increment hi20bits by 1.
Footnotes
-
The
jalrinstruction will save the jump address to the PC and save the currentPC + 4to therain the same cycle (effectively, “simultaneously”) ↩