Branch prediction

On this page 8

Branch prediction is the technique by which a processor guesses the outcome and target of a branch instruction before the branch is actually resolved, so that the pipeline can keep fetching and executing instructions without waiting. In modern processors, branch prediction is one of the most important contributors to instructions per clock, because a typical program contains a conditional or indirect jump roughly every five to seven instructions.

In computer hardware, the predictor is a dedicated block in the CPU front end. It works together with speculative execution: the core follows the predicted path, and if the guess proves wrong, it discards the speculative work and restarts from the correct address. The quality of the predictor therefore decides how much of a deep pipeline is doing useful work.

Why pipelined processors need to predict branches

A pipelined CPU needs branch prediction because it fetches new instructions many cycles before older instructions finish. A conditional branch such as if (x > 0) is only resolved in the execute stage, yet the fetch unit must decide where to read next in the very first cycle. Without a guess, the front end would sit idle for the full pipeline depth.

The cost of a wrong guess is called the misprediction penalty. It equals roughly the number of stages between fetch and branch resolution, plus the time needed to refill the pipeline. On wide out-of-order cores that can issue six to ten instructions per cycle, each mispredict throws away dozens to hundreds of instruction slots.

The following table shows typical penalty ranges by core class. Exact values vary by microarchitecture and by where in the pipeline the branch is detected.

Processor classPipeline depthTypical penaltyEffect of one mispredict
Simple microcontroller2 to 5 stages1 to 3 cyclesMinor delay
In-order application core8 to 13 stages7 to 12 cyclesNoticeable stall
Out-of-order desktop core14 to 20 stages15 to 20 cyclesLost work across a wide window
Deep high-frequency design20+ stages20 to 30 cyclesSevere throughput loss
Typical misprediction penalties by processor class

How a branch predictor makes its guess

A branch predictor answers three separate questions: whether an instruction is a branch, whether a conditional branch is taken or not taken, and where the branch goes. Different hardware structures handle each question, and all of them must respond within one or two clock cycles.

  • The branch target buffer (BTB) is a cache indexed by instruction address that stores the target of recently seen branches, so the front end knows the destination before decoding.
  • The direction predictor decides taken or not taken, usually with tables of saturating counters and branch history.
  • The return address stack predicts the targets of function returns by pushing the address after each call.
  • The indirect target predictor handles jumps through registers, such as virtual function calls and switch tables, by correlating targets with history.

The direction predictor relies on global history, a shift register that records the outcomes of the most recent branches. Combining this history with the branch address lets the predictor learn correlations between branches, for example that a second test always fails when the first one succeeded.

Static and dynamic prediction schemes

Branch prediction schemes range from fixed rules to adaptive structures that learn from billions of executed branches. The progression below reflects decades of research, and current high-performance cores combine several of these ideas in a hybrid design.

SchemeHow it decidesTypical accuracyWhere it appears
Static ruleBackward taken, forward not taken60 to 70%Fallback for unseen branches
One-bit counterRepeats the last outcomeAbout 80%Early pipelined designs
Two-bit saturating counterNeeds two misses to flip85 to 90%Classic textbook predictor
Two-level adaptive (gshare)History combined with address90 to 95%Mid-range cores
PerceptronWeighted sum of history bits95 to 97%Several AMD Zen generations
TAGE-styleMultiple tagged tables, varied history lengths97 to 99%Leading desktop and server cores
Main branch prediction schemes compared

The accuracy figures are workload dependent. Loop-heavy scientific code often exceeds 99 percent, while interpreters, compilers and database engines with data-dependent control flow can fall noticeably lower. Even a one percent difference in accuracy can shift performance by several percent on a wide core.

Branch prediction is often confused with neighboring mechanisms, yet each one solves a different problem. The table separates the concepts that sit closest to it in processor design.

TechniqueProblem it solvesRelationship to branch prediction
Speculative executionDoing work before it is certainConsumes the predicted path
Instruction prefetchingHiding instruction cache latencyGuided by predicted targets
PredicationRemoving short branches entirelyAvoids prediction by executing both paths
Simultaneous multithreadingFilling idle execution slotsMasks part of the misprediction cost
Value predictionGuessing data resultsResearch idea, rarely shipped
Branch prediction and neighboring concepts

Compilers can reduce the load on the predictor by emitting conditional move instructions for short, unpredictable choices. This form of predication trades a possible pipeline flush for a small, fixed extra cost, which is beneficial only when the branch is genuinely hard to predict.

Software patterns that help or hurt prediction

Software developers influence branch prediction through data layout and control flow. A loop over sorted data, where a condition stays true for long runs, is predicted almost perfectly, whereas the same loop over random data may mispredict on about half of the iterations.

Code patternPredictor behaviorRecommended response
Counted loopsPredicted almost perfectlyNo change needed
Random data comparisonsFrequent mispredictsSort data or use branchless code
Deep virtual call chainsIndirect target missesReduce polymorphism on hot paths
Interpreter dispatch loopsHistory pollutionUse threaded dispatch
Rare error checksEasily learned as not takenMark as unlikely for code layout
Code patterns and their effect on the predictor

Hardware performance counters expose branch-misses per thousand instructions, a metric often abbreviated as MPKI. Values below one are excellent, while values above ten usually indicate a hot spot worth optimizing.

Security implications and design limits

Branch predictors became a security concern in 2018, when the Spectre class of attacks showed that an attacker can train the predictor to steer another process into speculatively executing chosen code. The architectural state is rolled back, but traces remain in caches and can be measured through timing side channels.

Mitigations include flushing or partitioning predictor state on context switches, indirect branch restrictions such as IBRS and IBPB, and compiler techniques like retpolines. Each mitigation costs some performance, so vendors balance isolation against throughput. Larger predictors also consume die area and power, and they must still answer in a single cycle, which limits how much history any design can exploit.

The short version

A processor works like a fast assembly line, and it has to load new work long before it knows which way the program will go at each decision point. Branch prediction is an educated guess about that direction, based on what the program did the last few thousand times.

When the guess is right, the line keeps moving at full speed. When it is wrong, the processor throws away the unfinished work and starts again from the correct point. Better guessing means a faster computer, even at the same clock speed.

Where it makes a difference

A backend engineer profiles a log-filtering service that checks whether each record value exceeds a threshold. Performance counters show about 12 branch misses per thousand instructions on the hot loop, because the input values arrive in random order and the comparison is taken roughly half the time.

The engineer replaces the if statement with a branchless arithmetic expression that the compiler turns into a conditional move. The misprediction rate on the loop falls close to zero, and throughput rises by about 40 percent on the same server, with no change to the hardware or to the clock speed. The fix works because the predictor no longer has to guess an outcome that the data makes inherently unpredictable.