Speculative execution

On this page 7

Speculative execution is a processor technique in which the CPU executes instructions before it knows whether they are needed, based on predictions about branches, memory dependencies or data values, and later commits or discards the results once the prediction is confirmed. In hardware, and particularly in the design of modern processors, it is one of the main reasons a single core can complete several instructions per clock cycle.

Without speculation, a deep pipeline would stall every time it met a conditional branch or an unresolved memory address. With it, the processor keeps its execution units busy and hides much of the latency of branches and cache misses, at the cost of extra power, design complexity and, as the Spectre disclosures showed, a new class of security vulnerabilities.

How speculative execution works inside the pipeline

Speculative execution works by letting the front end of the processor fetch and issue instructions along a predicted path while older instructions are still unresolved. The branch predictor guesses the direction and target of each branch, and the core continues decoding and executing instructions from that guessed path without waiting.

Results of speculative instructions are held in internal structures, chiefly the reorder buffer and renamed physical registers, rather than written to the architectural state. When the branch resolves, the core either retires the speculative instructions in program order or, on a misprediction, flushes them and restarts from the correct path. Programs therefore see exactly the same results as on a strictly sequential machine.

The table below lists the main hardware structures that make this possible and the role each one plays.

StructureRoleTypical effect of size
Branch predictorGuesses branch direction and targetHigher accuracy, fewer flushes
Reorder bufferTracks in-flight instructions in program orderDeeper speculation window
Register renamingMaps architectural registers to physical onesMore independent work in flight
Load and store queuesTrack memory operations and their orderingMore overlapping memory accesses
Checkpoint logicSaves state for fast recovery after mispredictionsShorter recovery time
Key structures that support speculative execution

Forms of speculation in modern CPUs

Branch speculation is the most familiar form, but modern CPU cores speculate on several kinds of uncertainty at once. Each form removes a different kind of stall, and each must be undone correctly if its guess proves wrong.

TypeWhat is predictedStall it avoids
Control speculationBranch direction and target addressWaiting for a condition to resolve
Memory dependence speculationThat a load does not depend on an earlier storeWaiting for store addresses
Value predictionThe result of a load or operationWaiting for data from memory
Prefetch speculationWhich cache lines will be needed soonCache miss latency
Return address predictionWhere a function call will returnIndirect jump resolution
Main types of speculation

In a contemporary high-performance core, the speculation window can cover several hundred instructions. Reorder buffers in recent x86-64 and ARM64 designs hold roughly 200 to over 600 entries, which means a core may be far ahead of the last confirmed instruction at any given moment.

Speculative execution is closely tied to out-of-order execution and branch prediction, yet the three ideas are distinct. Out-of-order execution reorders instructions whose inputs are ready; branch prediction supplies the guesses; speculation is the policy of acting on those guesses before they are confirmed.

The comparison below separates speculative execution from neighboring processor concepts that are often confused with it.

ConceptCore ideaRelation to speculation
Branch predictionGuessing the outcome of branchesProvides the path that is speculated
Out-of-order executionRunning ready instructions earlyUsually combined with speculation
PipeliningOverlapping stages of many instructionsDeep pipelines make speculation necessary
Simultaneous multithreadingSharing a core between threadsFills slots that speculation leaves idle
PredicationExecuting both sides and selecting a resultAvoids speculation for short branches
Speculative execution and neighboring concepts

Performance benefits and costs

The main benefit of speculative execution is a large gain in instructions per clock. Typical integer code contains a branch roughly every five to seven instructions, so a core that waited at each branch would leave most of its execution units idle. Combined with predictors that reach accuracy above 95 percent on common workloads, speculation lets wide cores sustain high throughput.

The cost is wasted work on mispredictions. A flush discards all younger instructions and refills the pipeline, which costs roughly 15 to 20 cycles on current designs. Wasted work also consumes energy, so designers of low-power microcontrollers often limit or omit speculation, while desktop and server processors embrace it aggressively.

Security risks: Spectre and transient execution attacks

In 2018, researchers disclosed Spectre and Meltdown, showing that speculative instructions leave measurable traces in caches even after their results are discarded. An attacker can steer speculation to read secret data and then recover it through a cache timing side channel, which breaks the assumption that discarded work is invisible.

These transient execution attacks exist in many variants. The following table summarizes representative ones and the typical mitigations.

VariantMechanism abusedTypical mitigation
Spectre v1Bounds check bypass through branch mispredictionSpeculation barriers and index masking
Spectre v2Poisoned indirect branch targetsRetpoline, IBRS and branch target isolation
MeltdownReading kernel memory before permission checksKernel page table isolation, fixed silicon
Speculative store bypassLoads executed ahead of older storesSpeculative store bypass disable
Representative transient execution vulnerabilities

Mitigations combine microcode updates, compiler changes and operating system patches, and some carry a measurable performance penalty, especially for workloads with many system calls. Newer processors include hardware fixes, but the class of attack is considered a long-term design concern rather than a solved problem.

In simple terms

Speculative execution means a processor works ahead on a guess. When it reaches a fork in a program, it does not stop to wait for the answer; it picks the more likely direction and keeps going.

If the guess was right, the processor has saved time. If it was wrong, it throws away the extra work and takes the correct path. Think of a cook who starts chopping onions before the order is confirmed: usually the onions are needed, and dinner arrives sooner. The lesson from recent years is that even thrown-away work can leave clues behind, which is why security patches for processors exist.

A practical example

A database team runs a query engine on a server with modern multicore CPUs. Profiling shows that the hot loop which filters rows contains a data-dependent branch, and branch mispredictions account for a large share of stalled cycles because the filter accepts roughly half of the rows in random order.

The engineers rewrite the filter with branch-free code that computes both outcomes and selects one with a conditional move. Speculation no longer guesses wrong on that branch, and the loop runs about 1.5 to 2 times faster on the same hardware.

Later, the operations team applies operating system patches against Spectre variants. Benchmarks show that the query engine, which makes few system calls, loses less than 3 percent of throughput, while a file-heavy batch job on the same server slows more noticeably. The outcome is a measured, workload-aware decision to keep all mitigations enabled.