1Learning Outcomes¶
TODO
TODO
🎥 Lecture Video
More coming soon!
2Conditionally 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 Label[1]: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.
The
jalrinstruction will save the jump address to the PC and save the currentPC + 4to therain the same cycle (effectively, “simultaneously”)