Branch Prediction: Static, One-Bit and Two-Bit

The core of the last pages always guesses that a branch is not taken. In a loop that guess is wrong almost every time. This page tries three better guesses on branches that the real core executed.

You Will Be Able To

  • Explain two static guesses: not taken, and backward taken.
  • Show why a 1-bit entry is wrong twice for each run of a loop.
  • Step a 2-bit entry through its four states, and count its right guesses.
Lesson
S2.11
Time
30 min
Runs on
Your browser
Check
6 questions

A branch that ends a loop of 100 rounds is taken 99 times. Nobody needs to compute that again in every round. It is enough to remember what the branch did before.

Before You Start

You need the control hazard, predict not taken and the penalty of 2 cycles from S2.10.

You need a simple state machine with a state diagram.

Five questions this page answers
Question
1What is a static guess, and what is a dynamic one?
2Why is "backward taken" a good guess?
3Where is a 1-bit entry wrong in a loop?
4What does the second bit change?
5Which branch does a 2-bit entry never get right?

The Idea: Remember What the Branch Did

To guess the direction of a branch before it is decided is branch prediction. A wrong guess is a misprediction. It costs the flush of S2.10.

The simplest guess never changes: not taken. A second fixed guess looks at the target. A branch that goes back to a lower address is a backward branch, and most of those end a loop. So guess taken for them.

A guess that depends only on the instruction is a static prediction. It is the same every time the branch is met.

A dynamic prediction uses what the program did so far. The smallest form keeps one bit for a branch: was it taken the last time? Guess the same again.

One bit changes its mind too fast. A loop branch is not taken once, at the end. The bit flips, and the next run of the loop starts with a wrong guess.

So use two bits, as a counter from 0 to 3. Taken counts up, not taken counts down. The guess is taken when the count is 2 or 3. One odd outcome moves the count, but not the guess.

New Words

New words on this page
WordMeaning
Branch predictionTo guess, before a branch is decided, whether it will be taken.
MispredictionA wrong guess. The instructions fetched after it are flushed.
Static predictionA guess that depends only on the instruction, and is the same every time.
Dynamic predictionA guess that depends on what the branch did earlier in this run.
Backward branchA branch whose target is a lower address than its own. A forward branch goes to a higher one.
1-bit entryOne stored bit for a branch: what it did the last time.
2-bit counterTwo stored bits for a branch: a count from 0 to 3 that stops at both ends.
AccuracyThe right guesses divided by all guesses, mostly given in percent.
Warm-upThe first times of a branch, while its entry has not learned yet.

One Picture: Four States, Two Guesses

One Loop Exit, Two Different GuessesFollow both entries when the loop exits and when the branch next runs.
  • Control / FSM
  • Memory
One Loop Exit, Two Different GuessesFollow both entries when the loop exits and when the branch next runs. component Loop exit After several takenbranches, the branchis not taken once. component 1-bit entry The exit replaces thesaved outcome with N. component 2-bit entry The exit lowers thecounter from 3 to 2. component Guess N Wrong when the nextloop takes thebranch. component Guess T Right when the nextloop takes thebranch. replacecount downlast outcomecount ≥ 2
  1. component Loop exitAfter several taken branches, the branch is not taken once.
    • replace → 1-bit entry
    • count down → 2-bit entry
  2. component 1-bit entryThe exit replaces the saved outcome with N.
    • last outcome → Guess N
  3. component 2-bit entryThe exit lowers the counter from 3 to 2.
    • count ≥ 2 → Guess T
  4. component Guess NWrong when the next loop takes the branch.
  5. component Guess TRight when the next loop takes the branch.
Read the diagram as text
  • Loop exit: After several taken branches, the branch is not taken once.
  • 1-bit entry: The exit replaces the saved outcome with N.
  • 2-bit entry: The exit lowers the counter from 3 to 2.
  • Guess N: Wrong when the next loop takes the branch.
  • Guess T: Right when the next loop takes the branch.
  • Loop exit → 1-bit entry: replace
  • Loop exit → 2-bit entry: count down
  • 1-bit entry → Guess N: last outcome
  • 2-bit entry → Guess T: count ≥ 2
The Four States of a 2-Bit Entry
The Four States of a 2-Bit Entry10101010C000: strongly not takenC101: weakly not takenC212: weakly takenC313: strongly taken
  1. 0: strongly not taken · C00
    • ↓1 → C1
    • ↓0 → C0
  2. 1: weakly not taken · C10
    • ↓1 → C2
    • ↓0 → C0
  3. 2: weakly taken · C21
    • ↓1 → C3
    • ↓0 → C1
  4. 3: strongly taken · C31
    • ↓1 → C3
    • ↓0 → C2
StateInputNextOutput in state
C01C10
C00C00
C11C20
C10C00
C21C31
C20C11
C31C31
C30C21

Current state: C2 · Output: 1

Sampled input, state and output waveformStepState0C11C22C33C34C35C26C37C38C39C310C2taken—1111011110guess01111111111
Scroll horizontally ↔
Sampled waveform: Moore output after each edge; Mealy output on the taken arc.
Step012345678910
Input—1111011110
StateC1C2C3C3C3C2C3C3C3C3C2
Output01111111111

  1. Step 1. The first time, the entry is in state 1 and guesses not taken. The branch is taken: wrong. The entry moves to state 2.
  2. Step 4. Three more taken branches. The entry reaches state 3 and stays there: it cannot count higher.
  3. Step 5. The loop ends: not taken. The guess was taken: wrong. The entry steps down to state 2. It still guesses taken.
  4. Step 6. The loop starts again, and the branch is taken. The guess is right this time. A 1-bit entry is wrong here.

The input is what the branch did. The output is the guess for the next time: 1 means taken. The stream is the inner loop branch of the lab.

The four states
CountNameGuessAfter a taken branchAfter a branch that is not taken
0strongly not takennot taken10: it stays
1weakly not takennot taken20
2weakly takentaken31
3strongly takentaken3: it stays2

From a strong state, the guess changes only after two wrong guesses in a row.

The Smallest Example, Worked by Hand

Take the branch at the end of a loop of five rounds. It is taken four times and then not taken. Then the loop runs again. Write T for taken and N for not taken.

Both predictors start from "not taken". The 2-bit counter starts at 1.

Ten times of the loop branch
TimeIt did1-bit says2-bit count2-bit says
1TN wrong1N wrong
2TT right2T right
3TT right3T right
4TT right3T right
5NT wrong3T wrong
6TN wrong2T right
7TT right3T right
8TT right3T right
9TT right3T right
10NT wrong3T wrong

The lab below prints the same ten rows.

Look at times 5 and 6. The 1-bit entry is wrong at 5, when the loop ends. It flips, and it is wrong again at 6, when the loop starts again.

The 2-bit counter is wrong at 5 as well. But it only steps from 3 to 2, and still says taken at 6. It is wrong once for each run of the loop, not twice.

The Rules

  1. Rule 1: Predict not taken needs nothing.

    It is right for every branch that falls through, and wrong for every taken one.

  2. Rule 2: Backward taken needs the target of the branch.

    It is right for a loop branch in every round but the last.

  3. Rule 3: A 1-bit entry guesses what the branch did last time.

    It is wrong twice for each run of a loop: at the end, and at the next start.

  4. Rule 4: A 2-bit counter counts up for taken and down for not taken, and stops at 0 and at 3.

    It guesses taken at 2 and 3.

  5. Rule 5: From a strong state, one wrong guess does not change the guess.

    So a loop branch costs one misprediction for each run of the loop.

  6. Rule 6: A dynamic predictor learns after the branch is decided.

    The guess is made at the fetch. The outcome arrives in EX, two cycles later in ap_rv32.

Sources for These Rules

Checked in the library. The first book is Patterson and Hennessy, Computer Organization and Design (ARM edition), section 4.8, part "Dynamic Branch Prediction". It has the 1-bit scheme, its two wrong guesses for each run of a loop, and the 2-bit scheme. The second is Harris and Harris (ARM edition), section 7.7.3. It has backward branches predicted taken, as a static prediction, and the four states with their names. The state after reset, weakly not taken, is a choice of this lab. So are the three programs. Every count on this page is recorded from the lab. The branches come from the real core ap_rv32, which has no predictor of this kind: docs/soc/ap_rv32-blueprint.md, section 8.4.

Now Run It

The lab at the end of this page is test code. It holds three traces: every branch and jump that the real core ap_rv32 executed for three programs.

The program "loops" has two loops, one inside the other, and a forward branch in the inner loop.

The program "loops", with the address of each instruction in hex. Its three branches are at 0c, 1c and 24.
00          addi x5, x0, 12
04          addi x7, x0, 0
08  outer:  addi x6, x0, 5
0c  inner:  bne x6, x5, add
10          addi x7, x7, 100
14  add:    add x7, x7, x6
18          addi x6, x6, -1
1c          bne x6, x0, inner
20          addi x5, x5, -1
24          bne x5, x0, outer
28          ebreak

The first part of the lab follows the inner loop branch, at address 1c.

Printed by the lab on Icarus: the first 12 times of the inner loop branch, then its totals. The counts equal those of a second model in JavaScript.
 n | did  | 1-bit says   | 2-bit state, says
 1 | T    | N wrong      | 1  N wrong
 2 | T    | T right      | 2  T right
 3 | T    | T right      | 3  T right
 4 | T    | T right      | 3  T right
 5 | N    | T wrong      | 3  T wrong
 6 | T    | N wrong      | 2  T right
 7 | T    | T right      | 3  T right
 8 | T    | T right      | 3  T right
 9 | T    | T right      | 3  T right
10 | N    | T wrong      | 3  T wrong
11 | T    | N wrong      | 2  T right
12 | T    | T right      | 3  T right
the branch at 1c: 60 times | 1-bit right=36 | 2-bit right=47

Rule 3 at work: read rows 5 and 6, and rows 10 and 11. The 1-bit entry is wrong in all four.

Rules 4 and 5 at work: in rows 5 and 10 the 2-bit state is 3 and the guess is wrong. In rows 6 and 11 the state is 2, and the guess is right.

The branch runs 60 times in 12 runs of the loop. The 1-bit entry is right 36 times: 60 minus 24. The 2-bit counter is right 47 times: 60 minus 12, minus the first.

The second part of the lab counts every branch of the three programs, for all four ways of guessing.

The right guesses of each way, out of all conditional branches of the trace.
trace   | branches | not taken | backward taken | 1-bit | 2-bit
loops   |      132 |        18 |             64 |    96 |   111
pattern |      160 |        51 |             89 |    78 |    77
calls   |       80 |        33 |             51 |    27 |    27

Rule 1 at work: "loops" has 132 branches, and 114 of them are taken. Not taken is right 18 times: 14 percent.

Rule 2 at work: backward taken is right 64 times. It gets the two loop branches. It loses the forward branch, which is taken 55 times in 60.

The 2-bit counters are right 111 times in 132: 84 percent. They learn the forward branch too, which no static guess can.

Now read the rows of "pattern" and "calls". The counters are right about half of the time or less. Their branches change direction in a regular way, and a counter cannot follow that.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Guess from what the branch didA fixed guess for each branchA forward branch that is mostly taken is learned. A table of entries must be stored and updated.
Two bits for each branchOne bitOne misprediction for each run of a loop, not two. Twice the bits.
A counter that stops at 0 and 3A counter that wraps from 3 to 0A long run of taken stays at 3. A wrapping counter would flip its guess for no reason.
Learn when the branch is decidedLearn when the guess is madeOnly real outcomes are learned. A branch met twice in two cycles is guessed with old knowledge.
Start at weakly not takenStart at strongly not takenOne taken branch is enough to turn the guess. A branch that is never taken needs no warm-up either way.

The core ap_rv32 has none of this. It always fetches on in line, and S2.10 measured what that costs. A predictor is a block beside the fetch, and this page only counts what it would get right.

The Trap: A Branch That Alternates

The program "calls" has a function f that is called from two places in turn. The branch at 30, inside f, depends on the caller. So it is taken, not taken, taken, not taken.

The program "calls". The function g scrambles a number in x12, and its branch at 54 follows one bit of it.
00          addi x5, x0, 20
04          addi x10, x0, 0
08          addi x12, x0, 1445
0c  loop:   addi x11, x0, 1
10          jal x1, f
14          addi x11, x0, 2
18          jal x1, f
1c          jal x1, g
20          addi x5, x5, -1
24          bne x5, x0, loop
28          ebreak
2c  f:      andi x6, x11, 1
30          bne x6, x0, f_odd
34          addi x10, x10, 2
38  f_odd:  addi x10, x10, 1
3c          jalr x0, 0(x1)
40  g:      slli x13, x12, 3
44          xor x12, x12, x13
48          srli x13, x12, 5
4c          xor x12, x12, x13
50          andi x13, x12, 1
54          beq x13, x0, g_skip
58          addi x10, x10, 4
5c  g_skip: jalr x0, 0(x1)
The lab following the branch at address 30 of "calls": its first 8 times, then its totals.
 n | did  | 1-bit says   | 2-bit state, says
 1 | T    | N wrong      | 1  N wrong
 2 | N    | T wrong      | 2  T wrong
 3 | T    | N wrong      | 1  N wrong
 4 | N    | T wrong      | 2  T wrong
 5 | T    | N wrong      | 1  N wrong
 6 | N    | T wrong      | 2  T wrong
 7 | T    | N wrong      | 1  N wrong
 8 | N    | T wrong      | 2  T wrong
the branch at 30: 40 times | 1-bit right=0 | 2-bit right=0

The 1-bit entry says what the branch did last time. This branch never does that again. The entry is wrong every single time.

The 2-bit counter starts at 1. It steps to 2, back to 1, to 2 again. Each time it has just crossed to the wrong side. It is right 0 times in 40.

Not taken would have been right 20 times. So a predictor that learns can be worse than no predictor at all.

The pattern itself is as regular as a pattern can be. What is missing is memory of more than one outcome. S2.12 adds that.

At Scale

The program "loops" on ap_rv32283 instructions, 114 taken branches: 515 cycles, measured
The same branches with 2-bit counters111 of 132 guessed right; 21 mispredictions

This section looks ahead. A right guess of the direction is half of the work, and a real table is not endless.

  1. The target is needed too

    A guess of "taken" saves nothing unless the fetch also knows where to go. S2.27 adds a table of targets and counts the cycles.

  2. One entry for each branch is a dream

    This lab keeps an entry for every branch. A real table has a fixed number of entries, and branches share them. S2.27 shows what that does.

  3. Patterns need history

    A branch that alternates, or follows another branch, is easy with a few bits of history. S2.12 builds that.

  4. Good predictors

    Textbooks give more than 90 percent as the accuracy of a good predictor on typical programs. The three small programs here are not typical ones.

Try It

Run the lab. In the first table, find every row in which the two predictors disagree.

Change START to STRONG_NOT and run again. Which rows of the first table change, and which totals?

In the first replay line at the end of the bench, change the place from 1 to 0. That follows the forward branch of "loops". Which predictor is better for it?

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: n | did | 1-bit says | 2-bit state, says 1 | T | N wrong | 1 N wrong 2 | T | T right | 2 T right 3 | T | T right | 3 T right 4 | T | T right | 3 T right 5 | N | T wrong | 3 T wrong 6 | T | N wrong | 2 T right 7 | T | T right | 3 T right 8 | T | T right | 3 T right 9 | T | T right | 3 T right 10 | N | T wrong | 3 T wrong 11 | T | N wrong | 2 T right 12 | T | T right | 3 T right the branch at 1c: 60 times | 1-bit right=36 | 2-bit right=47 trace | branches | not taken | backward taken | 1-bit | 2-bit loops | 132 | 18 | 64 | 96 | 111 pattern | 160 | 51 | 89 | 78 | 77 calls | 80 | 33 | 51 | 27 | 27

Check Yourself

Predict the outputThis lab follows the inner loop branch of "loops": taken four times, then not taken, for 12 runs of the loop. Every 2-bit entry starts at 0, strongly not taken. The 1-bit entries start at "not taken". What does the lab print?
// The inner loop branch, with every 2-bit entry starting at "strongly not taken". What does the last line say?
// Test code. It replays the branches that the real core ap_rv32 executed, and counts how often a way of
// guessing would have been right. The core ap_rv32 itself has no such logic: it always fetches on in line.
module tb;
  // ---- The recorded traces. Each is every branch and jump that the real core ap_rv32 executed for one
  // program, in order. One byte for each: bits 7:4 the place (a row of the table of places), bit 3 "it left
  // the line" (a taken branch, or any jump), bits 2:0 which target (used by a return only).
  // In each line of a trace, the first event is the byte at the right-hand end of the number.
  logic [1599:0] events;
  int          count;                 // how many events the trace has
  logic [31:0] place_pc [0:15];       // the address of the branch or jump
  logic [31:0] place_target [0:15];   // where it goes when it leaves the line (not used for a return)
  logic [1:0]  place_kind [0:15];     // 0: a conditional branch. 1: a jal. 2: a return (jalr)
  logic [31:0] return_target [0:7];   // the addresses that the returns of this trace go to
  task automatic load_loops;   // the program "loops": 283 instructions, 132 branches and jumps
    count = 132;
    place_pc[0] = 32'h0c;  place_target[0] = 32'h14;  place_kind[0] = 2'd0;   // branch
    place_pc[1] = 32'h1c;  place_target[1] = 32'h0c;  place_kind[1] = 2'd0;   // branch
    place_pc[2] = 32'h24;  place_target[2] = 32'h08;  place_kind[2] = 2'd0;   // branch
    events[0 +: 320] = 320'h08180818081808281008180818081808180828100818081808180818082810081808180818081808;   // events 0 to 39
    events[320 +: 320] = 320'h08180028100818081808180818082810081808180818081808281008180818081808180828100818;   // events 40 to 79
    events[640 +: 320] = 320'h10081800180818081808281008180818001808180828100818081808180018082810081808180818;   // events 80 to 119
    events[960 +: 96] = 96'h201000180818081808180828;   // events 120 to 131
  endtask

  // ---- Four ways to guess whether a branch is taken. Each keeps what it knows in one entry for each branch.
  localparam int NOT_TAKEN = 0, BACKWARD_TAKEN = 1, ONE_BIT = 2, TWO_BIT = 3;
  localparam logic [1:0] STRONG_NOT = 2'd0, WEAK_NOT = 2'd1, WEAK_TAKEN = 2'd2, STRONG_TAKEN = 2'd3;
  localparam logic [1:0] START = STRONG_NOT;   // the state of every 2-bit entry before the first branch
  logic       last [0:15];    // 1-bit: what this branch did the last time
  logic [1:0] state [0:15];   // 2-bit: one of the four states

  function automatic logic guess(input int way, input int p);
    case (way)
      NOT_TAKEN:      return 1'b0;
      BACKWARD_TAKEN: return place_target[p] < place_pc[p];   // a branch that goes back is likely the end of a loop
      ONE_BIT:        return last[p];
      default:        return state[p] == WEAK_TAKEN || state[p] == STRONG_TAKEN;
    endcase
  endfunction
  // After the branch is decided, each way learns what it did.
  task automatic learn(input int p, input logic taken);
    last[p] = taken;
    case (state[p])
      STRONG_NOT:   state[p] = taken ? WEAK_NOT     : STRONG_NOT;
      WEAK_NOT:     state[p] = taken ? WEAK_TAKEN   : STRONG_NOT;
      WEAK_TAKEN:   state[p] = taken ? STRONG_TAKEN : WEAK_NOT;
      default:      state[p] = taken ? STRONG_TAKEN : WEAK_TAKEN;
    endcase
  endtask

  // ---- Replay one trace. follow: a place whose first times are printed one by one, or -1.
  function automatic string mark(input logic guessed, input logic taken);
    return {guessed ? "T" : "N", guessed == taken ? " right" : " wrong"};
  endfunction
  task automatic replay(input string name, input int follow, input int times, input bit table_row);
    int right [0:3];
    int branches, seen, right_1, right_2, p;
    logic [7:0] e;
    logic taken;
    for (int way = 0; way < 4; way++) right[way] = 0;
    for (int n = 0; n < 16; n++) begin last[n] = 1'b0;  state[n] = START; end
    branches = 0;  seen = 0;  right_1 = 0;  right_2 = 0;
    for (int i = 0; i < count; i++) begin
      e = events[8 * i +: 8];
      p = e[7:4];
      taken = e[3];
      if (place_kind[p] == 2'd0) begin
        branches++;
        for (int way = 0; way < 4; way++) if (guess(way, p) == taken) right[way]++;
        if (p == follow) begin
          seen++;
          if (guess(ONE_BIT, p) == taken) right_1++;
          if (guess(TWO_BIT, p) == taken) right_2++;
          if (seen <= times) $display("%2d | %s    | %s      | %0d  %s", seen, taken ? "T" : "N", mark(guess(ONE_BIT, p), taken), state[p], mark(guess(TWO_BIT, p), taken));
        end
        learn(p, taken);
      end
    end
    if (follow >= 0) $display("the branch at %02h: %0d times | 1-bit right=%0d | 2-bit right=%0d", place_pc[follow][7:0], seen, right_1, right_2);
    if (table_row) $display("%-7s | %8d | %9d | %14d | %5d | %5d", name, branches, right[NOT_TAKEN], right[BACKWARD_TAKEN], right[ONE_BIT], right[TWO_BIT]);
  endtask

  initial begin
    load_loops;
    replay("loops", 1, 0, 1'b0);
    $finish;
  end
endmodule
ConceptWhich of these is a static prediction?
ConceptA 2-bit counter is at 3. The branch is not taken once, then taken again. How many of these two guesses are wrong?
ConceptA loop of 10 rounds runs 5 times. How many mispredictions does a warmed-up 1-bit entry make for its loop branch?
ConceptWhich guess does a 2-bit counter give at the count 2?
ConceptA branch is taken, not taken, taken, not taken, without end. A 2-bit counter starts at 1. How often is it right?

Common Mistakes

Wrong Expect a 1-bit entry to be wrong once for each run of a loop.

The exit flips the bit. The next entry into the loop is then guessed wrong as well.

Fix Count two mispredictions for each run of the loop.

Wrong Let the 2-bit counter wrap from 3 to 0.

A branch that is always taken would then be guessed not taken half of the time, at the counts 0 and 1.

Fix Stop at 3 and at 0.

Wrong Assume that a predictor that learns is always better than a fixed guess.

A branch that alternates makes a counter wrong every time.

Fix Measure the accuracy on the branches of real programs.

Remember

  • A static prediction is fixed for each branch. Backward taken gets loop branches right, and learns nothing else.
  • A 1-bit entry repeats the last outcome. It is wrong twice for each run of a loop.
  • A 2-bit counter stops at 0 and 3 and guesses taken at 2 and 3. A loop costs it one misprediction for each run.
  • On the recorded branches of "loops": not taken 18 of 132, backward taken 64, 1-bit 96, 2-bit 111. ap_rv32 itself has no such predictor.

Practice

Report a problem with this page