Lecture 15: Branch Prediction

Section 1: The Cost of Branches and Foundations of Branch Prediction

Out-of-order superscalar processors can issue and complete multiple instructions per cycle by keeping dozens of instructions in flight simultaneously. However, all of that parallel machinery stalls or wastes vast amounts of work if the processor does not know which instructions to fetch next. Whenever the fetch unit encounters a conditional branch, it faces a control-flow penalty: modern processors may have more than 10 pipeline stages between next-PC calculation (PC \to I-cache \to Fetch Buffer \to Decode \to Issue Buffer) and branch resolution at the end of Execute.

How much work is lost if the pipeline waits or fetches down the wrong instruction stream? Roughly: \text{Lost Work} \approx (\text{Loop Length} \times \text{Pipeline Width}) + \text{Buffer Occupancy} Let’s break this expression down term by term:

Worked Example: Measuring the Misprediction Penalty

Consider a 4-way superscalar processor with 8 pipeline stages from fetch to dispatch, an 80-entry Reorder Buffer (ROB), and 3 cycles from issue to branch resolution:

  1. Suppose a branch is at the head of the ROB and resolves late. Up to 8 \times 4 = 32 instructions can be sitting in the frontend stages between fetch and dispatch.
  2. Up to 80 - 1 = 79 younger instructions can already be sitting behind that branch in the ROB.
  3. On a single misprediction, the processor could throw away: 8 \times 4 + (80 - 1) = 32 + 79 = \mathbf{111\text{ instructions}}

Because flushing 111 instructions is catastrophic, notice how sensitive performance is to prediction accuracy. Suppose 1/6 of all executed instructions are branches:

Software and Hardware Approaches to Control Flow

Engineers tried several ways to shrink this penalty before settling on dynamic prediction:

Because modern branch predictors achieve >95\% accuracy, speculation dominates. Doing it safely requires two kinds of hardware support:

  1. Prediction structures: Branch History Tables (BHTs), Branch Target Buffers (BTBs), and specialized predictors.
  2. Mispredict recovery mechanisms: Keeping result computation separate from commit (via the ROB), killing instructions following a mispredicted branch, and restoring architectural/rename state to the point immediately after the branch.

Static Branch Prediction

Before building dynamic predictors, how well can we predict branches statically at compile time? Overall, a conditional branch is taken roughly 60–70% of the time, but direction depends strongly on target direction:

Some ISAs encode preferred directions directly in the opcode (e.g., Motorola MC88110 had bne0 preferred taken and beq0 preferred not-taken), while others allow the compiler to set a static prediction bit per branch instruction (e.g., HP PA-RISC, Intel IA-64), achieving ~80% accuracy. To push past 80% into the 95%+ range needed by deep superscalars, hardware must learn dynamically from runtime execution history.

[Editor Note: removed course title slide, previous-lecture recap slide, quiz logistics slide, and acknowledgements.]

✎ Check Your Understanding

  1. In a 4-way superscalar with 6 frontend stages from fetch to dispatch and a 64-entry ROB, what is the maximum number of instructions that might be discarded on a single branch misprediction? Answer: Up to 6 \times 4 + (64 - 1) = 24 + 63 = \mathbf{87\text{ instructions}}.

  2. Why does improving branch prediction accuracy from 90\% to 95\% double the average number of instructions executed between mispredictions? Answer: Because the misprediction rate drops from 1 - 0.90 = 10\% to 1 - 0.95 = 5\%, cutting the frequency of mispredictions in half.


Section 2: Dynamic Branch Direction Predictors

Dynamic branch prediction exploits two patterns observed in real programs:

  1. Temporal correlation: The way a specific branch resolved in the past is often a good predictor of how that same branch will resolve the next time it executes.
  2. Spatial (global) correlation: Several nearby branches may resolve in a highly correlated manner along a preferred execution path.

The Branch History Table (BHT) Framework

To exploit temporal correlation, hardware uses a Branch History Table (BHT): a 2^k-entry table of N-bit state machines indexed by the lower k bits of the Fetch PC (ignoring the bottom two 00 bits for 4-byte-aligned instructions). Look at how the fetch hardware operates in parallel:

Notice an important property: a BHT is a “lossy” hash table. It stores no tags—if two branches have the same lower k PC bits, they alias and overwrite each other’s state. When the branch eventually resolves in Execute, hardware updates that entry’s state based on the actual outcome.

1-Bit vs. 2-Bit Hysteresis Predictors

Suppose each BHT entry is just 1 bit (N = 1), simply remembering the last direction the branch took. What goes wrong on a standard loop (for (i=0; i<10; i++))? A 1-bit predictor suffers two mispredicts on every single execution of the loop:

  1. On the first iteration, it predicts the loop-closing backward branch not-taken (because the loop exited on the final iteration the last time the loop ran).
  2. On the last iteration, it predicts the backward branch taken (because the previous 9 iterations stayed inside the loop).

To fix this, we use 2 branch prediction bits per entry (N = 2) and change the prediction only after two consecutive mistakes! Look carefully at how the 4-state hysteresis state machine is structured—its state encodes (predict taken / not taken) × (last prediction right / wrong):

Notice why this beats a 1-bit predictor on loops: when the loop exits on the last iteration, state 11 drops only to 10—so on the next entry into the loop, it still predicts Taken, cutting loop mispredicts from 2 down to 1! A 4K-entry BHT with 2 bits/entry achieves ~80–90% correct predictions.

Exploiting Spatial Correlation: Two-Level and GShare Predictors

Can we do better than 90%? Consider this C code (Yeh and Patt, 1992):

if (x[i] < 7) then y += 1;
if (x[i] < 5) then c -= 4;

Look at the correlation between the two branches: if the first condition (x[i] < 7) is false, the second condition (x[i] < 5) is guaranteed to be false too! A per-branch BHT cannot see what happened at the previous branch.

To capture spatial correlation, we add a global History register (H)—a P-bit shift register that records the Taken / ¬Taken outcomes of the last P branches executed by the processor. This creates a Two-Level Branch Predictor (used in the Intel Pentium Pro with P=2, achieving ~95% accuracy):

Multiplying the number of BHT tables by 2^P grows hardware exponentially with history length P (for P=10, you would need 1024 separate BHT tables!). The GShare Two-Level Predictor avoids this blowup:

Tournament Branch Predictor (Alpha 21264)

Different branches prefer different predictors: loop branches love local per-branch history, while if/else chains love global path history. The Alpha 21264 Tournament Predictor runs both in parallel and learns which one to trust per branch (achieving 90–100% accuracy across applications):

  1. Local Path: PC indexes a Local history table (1,024 \times 10\text{b}) to retrieve that specific branch’s last 10 outcomes; that 10-bit pattern indexes a Local prediction table (1,024 \times 3\text{b}).
  2. Global Path: A Global History (12\text{b}) shift register indexes a Global Prediction table (4,096 \times 2\text{b}).
  3. Choice Selector: The same 12-bit Global History also indexes a Choice Prediction table (4,096 \times 2\text{b}) of 2-bit saturating counters that learns whether the local or global predictor has been more accurate recently, driving a mux to output the final Prediction. (Crucial detail: the Global History register is speculatively updated with each prediction at fetch time so back-to-back branches see the latest predicted path, and restored if a mispredict occurs!)

TAGE: Tagged Geometric History Length Prediction

Two-bit counters, GShare, and the tournament predictor are older designs. A stronger one is TAGE (Seznec and Michaud, 2006), which at equal storage outperformed every predictor entered in the first Championship Branch Prediction (December 2004).

TAGE combines two ideas:

  1. Geometric history lengths. A base predictor T_0 (a PC-indexed table of 2-bit counters) is backed by M tagged tables T_1 \dots T_M. Table T_i is indexed by a hash of the PC and the most recent L(i) global history bits, where the lengths grow geometrically: L(i) = \text{int}\left(\alpha^{i-1} \cdot L(1) + 0.5\right) With \alpha = 2 and L(1) = 2, an 8-component predictor uses history lengths \{0, 2, 4, 8, 16, 32, 64, 128\}. A few tables capture very long correlations while most of the storage goes to short histories.
  2. Partial tags. Each tagged entry holds a 3-bit signed prediction counter ctr, a partial tag, and a 2-bit useful counter u. Unlike a BHT, a tagged table only offers a prediction when its tag matches, so unrelated branches stop aliasing.

Prediction: all tables are read in parallel, and the hitting table with the longest history (the provider) supplies the prediction. The prediction the next-longest hit would have given is the alternate prediction; with no tag hit at all, the base predictor decides.

Update:

The global history is hundreds of bits long and is updated speculatively at prediction time, so it must be restored on a misprediction; a circular buffer makes that a single head-pointer restore. The same paper applies the scheme to indirect branch targets as ITTAGE.

Why Not Just Execute Both Directions?

You might wonder: Instead of predicting, why not speculatively execute both the taken and not-taken paths at every branch?

✎ Check Your Understanding

  1. Suppose a 2-bit hysteresis BHT entry is in state 11 (Predict Taken, last right). The branch resolves as Not taken once, and then Taken on the next execution. What state does the entry visit after each outcome, and did it ever predict Not taken? Answer: After Not taken, it transitions from 11 to 10 (which still predicts Taken). After Taken, it returns to 11. It never predicted Not taken because changing prediction requires two consecutive mistakes.

  2. How does a GShare predictor capture 10 bits of global branch history without multiplying BHT storage by 2^{10} = 1024? Answer: It bitwise-XORs the 10-bit global branch history register with 10 bits of the branch’s PC to index a single 1024-entry predictor table.

  3. In a TAGE predictor, tables T_2 and T_4 hit and T_1, T_3 miss. Which table provides the prediction, and what happens on a misprediction? Answer: T_4 (the longest-history hit) provides it, with T_2 as the alternate prediction. On a misprediction TAGE tries to allocate a new entry in a table with a longer history than T_4, picking one whose candidate entry has u = 0, or decrements those u counters if none is free.


Section 3: Predicting Branch Targets and High-Bandwidth Fetch

Even a 100%-accurate BHT has two critical blind spots:

  1. A BHT only predicts branch direction (Taken / ¬Taken). It cannot redirect the fetch stream until the branch’s target address is computed!
  2. We cannot even use a BHT prediction until we know the fetched instruction is a branch—which only happens after decoding!

Look at what this costs in a deep frontend such as the UltraSPARC-III fetch pipeline (A: PC Gen/Mux \to P: Inst Fetch 1 \to F: Inst Fetch 2 \to B: Branch Addr Calc/Begin Decode \to I: Complete Decode \to J: Steer \to R: Reg File Read \to E: Integer Execute):

The Branch Target Buffer (BTB)

To redirect the PC in the very first cycle—before the branch is even fetched or decoded—we add a Branch Target Buffer (BTB). A 2^k-entry direct-mapped (or set-associative) BTB is accessed in parallel with the I-Cache using the current PC:

Combining BTB and BHT

Because every BTB entry must store a full PC tag and a full target PC, BTB entries are considerably more expensive than BHT entries (which are just 2 bits each!). So real processors combine them:

Indirect Branches (JR) and the Subroutine Return Stack (RAS)

How well does a BTB handle the three common uses of indirect Jump Register (JR) instructions?

  1. Switch statements (jump to matching case): BTB works well if the same case is taken repeatedly.
  2. Dynamic function calls (jump to runtime function pointer, e.g., C++ virtual function calls): BTB works well if objects usually have the same type.
  3. Subroutine returns (jump to return address): BTB works well only if the function always returns to the same caller—which fails whenever one helper function is called from many distinct call sites!

To fix subroutine returns, processors add a tiny hardware Subroutine Return Address Stack (RAS) (typically k = 8\text{--}16 entries). Look at nested calls fa() { fb(); }, fb() { fc(); }, fc() { fd(); }:

High-Bandwidth Fetch: Alpha 21264 I-Cache and Trace Caches

In wide out-of-order machines, performance is often limited by instruction fetch bandwidth: speculative execution fetches 2–3\times more instructions than are committed, mispredict penalties are dominated by the time to refill the instruction window, and taken branches break sequential cache-line fetches.

How do architects fetch wide and fast around taken branches?

  1. Increasing Taken Branch Bandwidth (Alpha 21264 I-Cache): Fetching 4 instructions per cycle at ~1 GHz leaves no time for tag comparisons or branch prediction inside the single-cycle fetch loop. Alpha 21264 folds Line Predict and Way Predict bits directly into every cached instruction block! On the fast fetch path, each block directly supplies the predicted next cache line and way for the very next cycle—taking tag checks (Tag Way 0/1), instruction decode, and branch prediction completely out of the critical 1-cycle fetch loop! If the separate tag check or BTB later disagrees, it corrects the PC; a 2-bit hysteresis counter per block prevents overtraining the line predictor.
  2. The Taken Branch Limit and Trace Caches: Integer programs execute a taken branch roughly every 6–9 instructions. To sustain wide superscalar execution (say, 8+ instructions/cycle), the frontend must execute multiple taken branches per cycle, which requires predicting multiple branches per cycle and fetching multiple non-contiguous basic blocks per cycle. Using a multiported I-cache is too expensive, interleaving suffers bank conflicts, and merging blocks adds latency before decode.
    • Key Idea — Trace Cache (used in the Intel Pentium 4 to store decoded micro-operations): Dynamically pack multiple non-contiguous basic blocks along a hot taken-branch path (e.g., [Red block + BR] -> [Green block + BR] -> [Blue block + BR]) into one contiguous trace cache line!
    • The Trace Cache is indexed by both the starting PC address and the next n branch predictions, allowing a single fetch to deliver multiple basic blocks across multiple taken branches in one cycle.

✎ Check Your Understanding

  1. Why is a BTB unable to accurately predict JR instructions used for subroutine returns when a utility function like printf or malloc is called from dozens of places in a program, and what hardware structure solves this? Answer: A BTB only remembers the single most recent target for that JR instruction’s PC, so it mispredicts whenever the function returns to a different call site. A Subroutine Return Address Stack (RAS) pushes return addresses on calls and pops them in LIFO order on returns.

  2. How does a Trace Cache overcome the taken-branch fetch limit of one basic block per cycle? Answer: It stores dynamically linked sequences of non-contiguous basic blocks contiguously inside a single trace cache line (indexed by start address and the next n branch predictions), delivering multiple basic blocks in a single fetch.


Section 4: Branch Misprediction Recovery in Out-of-Order Superscalars

Both in-order and out-of-order superscalars can share the exact same frontend branch predictors (BTB, BHT, RAS, Trace Cache) and span 10–30 pipeline stages, but their misprediction recovery differs sharply:

Wait: we already have an in-order commit point at the ROB head for precise traps. Could we simply handle branch mispredictions at commit, just like precise traps? No! What is the problem with waiting until commit? If a branch depends on a slow load or divide, waiting for the branch to reach the head of the ROB before squashing wastes dozens of cycles fetching and executing useless wrong-path instructions while starving the correct path!

Instead, out-of-order machines resolve branches out-of-order as soon as the branch executes:

Remember from our earlier discussion of register renaming: killing instructions in the middle of the ROB also means restoring the Rename Table to the exact state it held right after the mispredicted branch! How fast can hardware restore the rename table?

✎ Check Your Understanding

  1. Why don’t out-of-order processors wait until a mispredicted branch reaches the commit stage at the head of the ROB to trigger recovery? Answer: Waiting until commit would waste many cycles fetching and executing wrong-path instructions and delay refilling the pipeline with the correct path; resolving branches out-of-order cuts the misprediction penalty dramatically.

  2. In the MIPS R10000, what happens to the 4 branch mask bits and 4 rename-table snapshots when a speculative branch resolves as correctly predicted? Answer: Its corresponding mask bit is cleared across all dependent instructions in the ROB/queues, and both that mask bit and its rename-table snapshot become free to be reused by a newly decoded branch.