분기 예측과 추측 실행
최신 CPU가 지연 시간을 숨기기 위해 분기를 예측하고 추측 실행하는 방식, 예측 실패로 사이클이 소모되는 이유, 부작용이 Spectre 계열 공격으로 이어진 과정을 살펴봅니다.
분기 예측과 추측 실행은(는) CoddyKit의 무료 Assembly Language & x86 Low-Level Systems Programming 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 48
자주 묻는 질문
“분기 예측과 추측 실행” 강의는 무료인가요?
네 — “분기 예측과 추측 실행” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Assembly Language & x86 Low-Level Systems Programming 강의 전체를 잠금 해제할 수 있습니다. Assembly Language & x86 Low-Level Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“분기 예측과 추측 실행”에서 뭘 배우나요?
최신 CPU가 지연 시간을 숨기기 위해 분기를 예측하고 추측 실행하는 방식, 예측 실패로 사이클이 소모되는 이유, 부작용이 Spectre 계열 공격으로 이어진 과정을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Assembly Language & x86 Low-Level Systems Programming을(를) 배우며, 24/7 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 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 캐시 일관성과 성능
- 핵심 구간 수동 최적화
- 버퍼 오버플로와 셸코드
- 분기 예측과 추측 실행