分支预测与推测执行
了解现代 CPU 如何预测分支并进行推测执行来隐藏延迟,理解预测错误的周期成本,以及副作用如何导致 Spectre 类攻击。
分支预测与推测执行 是 CoddyKit 上的免费 Assembly Language & x86 Low-Level Systems Programming 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Assembly Language & x86 Low-Level Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Assembly Language & x86 Low-Level Systems Programming 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Pipeline Problem
Modern CPUs are deeply pipelined, fetching and decoding many instructions ahead. But a conditional branch is a fork: the CPU does not yet know which path to fetch. Stalling would waste the whole pipeline.
Branch Prediction
To avoid stalls the CPU predicts which way a branch will go and keeps fetching. If correct, no time is lost. If wrong, the pipeline is flushed — a costly misprediction penalty of 15-20+ cycles.
How Predictors Learn
The Branch Target Buffer and history tables record past outcomes. A simple 2-bit saturating counter remembers whether a branch was recently taken, predicting that loops keep looping.
Speculative Execution
Beyond predicting, the CPU speculatively executes the predicted path before the condition resolves. If the guess holds, results are committed; if not, they are discarded as if they never ran — architecturally.
Writing Predictable Branches
You help the predictor by making branches consistent. A branch that is almost always taken predicts well; a random branch defeats prediction. Sorting data before a conditional loop can dramatically speed it up.
for (int i = 0; i < n; i++)
if (data[i] >= 128) // predictable only if data is sorted
sum += data[i];A Runnable Benchmark
This C program shows the dramatic effect of sorted vs unsorted data on a branch-heavy loop. Run it and compare timings.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 32768;
int *d = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) d[i] = rand() % 256;
long sum = 0;
for (int r = 0; r < 1000; r++)
for (int i = 0; i < n; i++)
if (d[i] >= 128) sum += d[i];
printf("sum=%ld\n", sum);
free(d);
return 0;
}Branchless Programming
You can sometimes eliminate a branch entirely with arithmetic or conditional-move instructions (cmov), so the CPU never needs to predict.
cmp eax, 128
cmovge ebx, ecx ; conditionally move, no branch to mispredictLikely/Unlikely Hints
Compilers expose hints like __builtin_expect (the source of likely()/unlikely() macros) so hot paths fall through and cold paths jump away, improving instruction-cache layout.
if (__builtin_expect(error, 0)) {
handle_error(); // marked cold/unlikely
}The Security Side Effect
Speculative results are discarded architecturally — but they leave traces in the cache. Speculatively loaded data warms cache lines, and that timing difference can be measured. This is the basis of side-channel leaks.
Spectre in a Nutshell
Spectre tricks the predictor into speculatively reading memory it should not, then leaks the value through a cache timing side channel. The reads never commit, so they bypass normal bounds checks during the speculation window.
Mitigations
Defenses include serializing instructions (lfence) to stop speculation past a bounds check, retpolines for indirect branches, and microcode updates. They trade some performance for safety.
cmp index, limit
jae out_of_range
lfence ; block speculation past the checkQuick Check
Test your understanding of speculation.
Recap
You learned how CPUs hide branch latency:
- Branch prediction guesses the path; mispredicts cost a pipeline flush
- Speculative execution runs the predicted path early
- Predictable branches, cmov, and likely/unlikely hints boost speed
- Speculation leaves cache side effects exploited by Spectre;
lfenceand retpolines mitigate it
常见问题解答
「分支预测与推测执行」课时是免费的吗?
是的 — 「分支预测与推测执行」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Assembly Language & x86 Low-Level Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 Assembly Language & x86 Low-Level Systems Programming 课程共包含 4 节课。
「分支预测与推测执行」这节课中我会学到什么?
了解现代 CPU 如何预测分支并进行推测执行来隐藏延迟,理解预测错误的周期成本,以及副作用如何导致 Spectre 类攻击。 你通过在浏览器中直接运行的动手代码来练习 Assembly Language & x86 Low-Level Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Assembly Language & x86 Low-Level Systems Programming 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Assembly Language & x86 Low-Level Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「分支预测与推测执行」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Assembly Language & x86 Low-Level Systems Programming 课中编写并运行代码吗?
能。每节 Assembly Language & x86 Low-Level Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 缓存一致性与性能
- 手动优化关键代码段
- 缓冲区溢出与 Shellcode
- 分支预测与推测执行