Modern processors execute hundreds of instructions simultaneously, yet every if-statement threatens to strand that parallelism: the pipeline cannot know which path to fetch until the branch resolves. Branch predictors guess outcomes with over 99% accuracy, speculatively executing the likely path. This article explains the fortune-telling hardware inside every CPU.
Why Pipelines Fear Branches
Deep pipelines overlap dozens of instructions across fetch, decode, execute, and retire stages, delivering throughput far beyond single-cycle rates. Conditional branches inject uncertainty: fetching must continue cycles before the condition evaluates, and guessing wrong means flushing speculative work, wasting energy and stalling throughput. Deeper pipelines amplify penalties, with mispredictions costing 15-25 cycles on aggressive cores.
Branches are frequent: roughly one instruction in six branches, so pipelines constantly bet their productivity on predictions. Without prediction, processors would stall at every branch, surrendering most superscalar gains. Speculative execution underpins the CPU performance story told in our processor comparison: guess early, verify later, recover rarely. Prediction accuracy directly converts to instructions per cycle.
From Static Hints to Two-Bit Counters
The simplest predictors guess statically: backward branches (loops) taken, forward branches not taken, encoding the observation that loops iterate. Compilers refine static hints with profile data, arranging hot paths fall-through. Static schemes cost nothing in hardware but cap out around 80% accuracy, leaving deep pipelines frequently flushed.
Two-bit saturating counters add learning: each branch owns a counter incrementing on taken outcomes and decrementing otherwise, predicting taken when the counter exceeds one. The two-bit hysteresis tolerates single anomalous outcomes, crucial for loops whose exits mispredict only once per iteration count. Bimodal tables of counters indexed by branch address lifted accuracy into the 90s with trivial hardware.
Two-Level and Gshare: Learning History Patterns
Branch outcomes correlate with history: a branch following a particular pattern of prior branches behaves predictably within that context. Two-level predictors record recent global outcomes in history registers, then index pattern tables by branch address combined with history. The same static branch predicts differently in different dynamic contexts, capturing correlations bimodal tables miss.
Gshare XORs branch addresses with global history to index shared counter tables, decorrelating collisions while halving storage versus per-branch history. Alloyed and perceptron-inspired variants refined indexing further. History lengths grew from bits to dozens as architects discovered longer correlations in real code. Context transformed prediction from per-branch statistics into program-behavior modeling.
TAGE and Tournament Predictors
Modern champions combine multiple predictors: TAGE maintains tagged tables indexed by geometrically increasing history lengths, preferring the longest matching history with useful predictions. Short histories answer quickly for simple branches; hundred-bit histories capture deep loop-nest correlations. Usefulness counters allocate entries to branches that benefit, evicting freeloaders.
Tournament and meta-predictors arbitrate among component predictors, selecting per-branch winners dynamically. Neural-inspired perceptron predictors weight long histories linearly, excelling on linearly separable branches. Championship branch prediction contests drove accuracy from 95% toward 99%+, with winning ideas shipping in commercial cores. Prediction is now a solved-ish problem whose remaining errors concentrate in genuinely data-dependent branches.
Predicting in Parallel: Fetch Bandwidth Challenges
Superscalar fetch demands multiple predictions per cycle: wide cores fetch 4-8 instructions simultaneously, potentially spanning several branches. Multi-ported predictor tables serve parallel lookups; overriding predictors refine coarse early guesses with accurate late ones. Taken branches redirect fetch mid-block, complicating alignment and merging logic.
Decoupled front ends run ahead: branch predictors drive fetch address generation independently, queuing predicted blocks into fetch buffers the decoder drains. Run-ahead depth absorbs predictor latency, letting slower accurate predictors guide fetch through buffering. Fetch-directed prefetching extends run-ahead into the cache hierarchy. Predicting one branch per cycle sufficed once; wide machines predict streams.
Wrong-path fetch wastes bandwidth and energy while polluting caches, so confidence estimators throttle speculation on shaky predictions. Gating fetch on confidence trades some performance for efficiency, a bargain gaining favor as power dominates. Speculation is an investment; confidence decides the stake.
Branch Targets: BTBs and Return Stacks
Predicting direction is half the battle; targets matter equally. Branch target buffers cache destination addresses per branch, letting fetch redirect the cycle after prediction. Indirect branches through registers and vtables need target prediction too: indexed BTBs guess destinations from history, while indirect-target arrays specialize on polymorphic call sites. Misses stall fetch until resolution.
Return addresses predict through dedicated return-address stacks: calls push, returns pop, matching program nesting with near-perfect accuracy. Deep call chains and exceptions stress stack depth; underflows fall back to BTB guesses. Fast caches backing these structures mirror techniques in our SRAM guide. Every cycle of target latency is a cycle fetch cannot use productively.
Misprediction Penalties and Spectre’s Shadow
Mispredictions waste more than cycles: flushed instructions consumed energy, polluted caches, and trained predictors on wrong paths. Recovery mechanisms checkpoint register maps at branches, restoring state on mispredict and selectively squashing dependent instructions while preserving independent work. Fast recovery shortens effective penalties below full pipeline depth.
Speculative execution’s dark side emerged with Spectre: mispredicted paths leave cache footprints encoding secrets, readable through timing side channels. Mitigations include speculation barriers, invisible speculation hiding wrong-path effects, and partitioned predictor structures preventing cross-domain training. Hardware security now constrains predictor design, as covered in our hardware security guide. Guessing fast must also mean leaking nothing.
Guessing Right Millions of Times Per Second
Branch predictors evolved from static hunches through two-bit counters and history-indexed tables to TAGE tournaments exceeding 99% accuracy: target buffers and return stacks supplying destinations, recovery mechanisms limiting mispredict damage, Spectre mitigations guarding speculation’s side effects. Pipelines stay full because predictors peer into code’s future. Modern CPUs are fundamentally prediction machines that also compute.

Leave a Reply