The Branch Instruction (without the times-4 trick; we'll do it later)

Here's a picture of a branch instruction. We'll use it to present some terminology.

There are two different aspects of this that we need to study:

  1. What does the CPU do to execute a branch instruction?
  2. What does the assembler do to assemble a branch instruction?

Let's tackle the first one first (with no tricks yet). Here's some code (with addresses):

  0x124:   add  $5  $10  $15
  0x128:   add  $6  $11  $16
  0x12C:   beq  $7  $12  0x138  <-- HERE'S THE BRANCH
  0x130:   add  $5  $10  $15    <-- PC is here by the time the CPU is ready to execute the branch
  0x134:   add  $6  $11  $16
  0x138:   add  $7  $12  $17    <-- this is the branch target
  0x13C:   add  $5  $10  $15
  0x140:   add  $6  $11  $16
      

Now let's tackle the second one (still with no tricks); how did the assembler come up with 0x8 for the offset?

And now for something slightly different: branching backwards

  0x124:   add  $5  $10  $15
  0x128:   add  $6  $11  $16
  0x12C:   add  $7  $12  $17    <-- this is the branch target
  0x130:   add  $5  $10  $15
  0x134:   beq  $6  $11  0x12C  <-- HERE'S THE BRANCH
  0x138:   add  $7  $12  $17    <-- PC is here by the time the CPU is ready to execute the branch
  0x13C:   add  $5  $10  $15
  0x140:   add  $6  $11  $16