Skip to content
Branches & Jumps
step 1/5

Reading — step 1 of 5

Read

~2 min readInstruction Decoding

Branches & Jumps

Control flow instructions:

Branches (B-type, conditional, PC-relative):

  • BEQ rs1, rs2, offset: branch if equal.
  • BNE rs1, rs2, offset: branch if not equal.
  • BLT rs1, rs2, offset: branch if less (signed).
  • BGE rs1, rs2, offset: branch if greater-or-equal (signed).
  • BLTU / BGEU: unsigned variants.
python

If condition true: pc = pc + sign_extend(offset). Else: pc += 4 (next instruction).

Branch offsets are 13-bit signed (range ±4 KiB), multiples of 2.

JAL (J-type, jump and link):

  • jal rd, offset
  • rd = pc + 4 (return address).
  • pc += sign_extend(offset).

Used for function calls: jal ra, function.

JALR (I-type, jump and link register):

  • jalr rd, offset(rs1)
  • rd = pc + 4.
  • pc = (rs1 + sign_extend(offset)) & ~1.

Used for indirect calls and returns: jalr x0, 0(ra) (= ret).

Implementation:

python

After every instruction, advance pc. Branches may override.

Pseudoinstructions:

  • j labeljal x0, label (no return address saved).
  • jr rsjalr x0, 0(rs).
  • retjalr x0, 0(ra).
  • call labelauipc + jalr (for far calls).
  • bgt rs1, rs2, lblblt rs2, rs1, lbl (operands swapped).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…