Branch Instructions

In this section, we will briefly describe the necessary hardware and its interconnection in order to realise control flow instructions.

Which instructions?

In this section, we will implement conditional branch instructions, all of which are sharing the same B-type instruction format:

There are six different branch instructions:

  • beq (branch if equal)
  • bne (branch if not equal)
  • blt (branch if less than)
  • bge (branch if greater or equal)
  • bltu (branch if less than unsigned)
  • bgeu (branch if greater or equal unsigned)

All of the above instructions share the same opcode (1100011). The branching condition is indicated by the value of the funct3 field in the instruction word.

What do they do?

The branch instructions compare two registers, given by the register indices rs1 and rs2. If the values satisfy the respective branching condition (for example if both are equal in case of beq), the branch is taken, otherwise the program continues with the next instruction. If the branch is taken, then the instruction adds the offset (derived by sign extending the 12 bit immediate field in the instruction word) to the program counter.

What do we need?

We need a way to evaluate the branching conditions, which are evaluated on two registers. As before, we will again reuse the ALU. As a convention, we will only use the least significant bit of the ALU output. So if the condition is satisfied, we expect this bit to be 1, otherwise 0. Note that we can directly reuse two operations: The instructions slt (set less than) and sltu (set less than unsigned) perform the calculations needed for the blt and bltu instructions, respectively. However, we need to extend the ALU with additional operations for the remaining branch instructions. The decoder needs to take care of selecting the correct operation.

Secondly, we need to be able to manipulate the future program counter value. Up to now, we always added 4 to the PC in order to execute the next instruction. We need to add a possibility to choose between adding 4 and adding the constant offset from the instruction word. The latter one should be selected if we have encountered a branch instruction and if the branching condition is satisfied.

The data path

The figure below shows the new components and connections:

The most significant change has taken place on the left hand side, in the next instrucion logic: We have added a multiplexer selecting constant 4 or the immediate offset. Its select signal is the conjunction of a new control signal branch from the decoder and the lowest significant bit of the ALU result.