Skip to content

Lesson 2 of 9 · 26m

Pipelines, Hazards, and Branch Prediction

Understand how superscalar pipelines overlap work, what stalls them, and why unpredictable control flow can cost more than arithmetic.

The CPU pipeline is best pictured as an assembly line with a small theater troupe attached. It guesses what comes next, performs work speculatively, and throws away the props when the guess is wrong. Most of the time this is miraculous. When your hot loop is dominated by unpredictable branches, it becomes very expensive theater.

What the pipeline is doing

Classic teaching pipelines have fetch, decode, execute, memory, and writeback stages. Real cores are wider, deeper, out-of-order, and register-renamed, but the performance problem is the same: keep useful work flowing without waiting for unresolved inputs or directions.

fetch -> decode -> rename -> issue/execute -> complete/retire
                          +-> reorder buffer tracks speculation

A superscalar core may execute several operations per cycle. It cannot do so when the next operation depends on an unavailable result or when the direction of execution is uncertain.

Branches are predictions until proven otherwise

A conditional branch depends on a comparison. The predictor learns patterns: always taken, never taken, alternating, loop counts, and correlated history. Highly predictable branches are nearly free. Random branches are expensive because a miss causes the pipeline to discard speculative work and refill.

for (size_t i = 0; i < n; i++) {
    if (values[i] < threshold)   // random input data -> hard prediction
        count++;
}

This pattern is famous because sorted input becomes dramatically faster than shuffled input even though the instruction stream is identical. The data changed the predictor's success rate.

Branchless does not mean universally faster

Replacing control flow with arithmetic or conditional moves can help when the branch is unpredictable and both paths are cheap:

count += (values[i] < threshold);  // often compiles to a compare + add

But branchless code always performs the work. If the skipped path is expensive or usually unnecessary, a predictable branch may be faster. Measure with realistic data distributions, not uniform random input unless production really looks that way.

Hazards have names for a reason

  • Data hazard: an instruction needs a value that is not ready.
  • Control hazard: the core does not yet know which instructions are next.
  • Structural hazard: two operations want the same execution resource.

Out-of-order execution hides many hazards, but it cannot invent independent work where the algorithm contains none.

Exceptions, syscalls, and serialization are pipeline cliffs

System calls, page faults, atomic operations, locks, and serializing instructions can drain or restrict speculative execution. A loop doing arithmetic is not comparable to a loop doing I/O, even if both have the same iteration count. This is why microbenchmarks must preserve the surrounding operation mix.

Design for predictable control flow

Group work by outcome, pre-filter data, sort when reuse justifies it, or move rare cases outside the hot path. Interpreters and virtual machines often use jump tables, threaded dispatch, or superinstructions partly because indirect branches are hard to predict when opcode sequences vary.

Field notes

  • Sorting input can make a benchmark faster without making production faster; know which distribution matters.
  • cmov avoids branch misses but evaluates unconditionally and can extend dependency chains.
  • Deep pipelines amplify the cost of a prediction miss; exact cycle counts are less important than the shape.
  • Profile branches with hardware counters such as perf stat -e branch-misses before rewriting control flow.

Was this lesson helpful?

Sign in to rate