[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,92 +2,145 @@
id: wiki-2026-0508-branch-prediction
title: Branch Prediction
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-4D7707]
aliases: [P-Reinforce-AUTO-4D7707, CPU Branch Predictor]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [cpu, performance, security, microarchitecture]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Branch Prediction"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: cpp
framework: none
---
# [[Branch Prediction|Branch Prediction]]
# Branch Prediction
## 📌 한 줄 통찰 (The Karpathy Summary)
> Branch prediction(분기 예측)은 현대 CPU가 분기 명령어의 과거 기록을 프로파일링하여(예: 분기가 항상 통과되는지 관찰) 다음 실행 경로를 미리 예측하는 성능 최적화 기술입니다 [1]. 이는 추측 실행([[Speculative Execution|Speculative Execution]])과 결합되어 CPU의 처리 속도를 비약적으로 높이지만, 공격자가 분기 기록을 통제할 수 있다는 점 때문에 스펙터([[Spectre|Spectre]])와 같은 심각한 보안 취약점의 공격 경로로 악용됩니다 [1, 2].
## 한 줄
> **"매 modern CPU 의 IPC 핵심 mechanism — 그리고 Spectre 의 attack surface."**. Branch predictor 는 conditional/indirect branch 의 결과를 speculatively execute 함으로써 deep pipeline 의 stall 을 회피; 매 misprediction penalty 는 15-20+ cycles, 매 mispredicted speculative window 가 Spectre v1/v2 의 leak vector.
## 📖 구조화된 지식 (Synthesized Content)
- **분기 예측과 추측 실행(Speculative Execution):** 현대 CPU는 성능 향상을 위해 분기를 프로파일링하여 실행 경로를 예측합니다 [1]. CPU는 분기 조건이 실제로 검증되기 전에 예측된 경로에 따라 메모리 로드 등의 명령을 미리 실행(추측 실행)하며, 예측이 틀린 것으로 판명되면 분기 이후에 일어난 작업을 롤백(Roll back)합니다 [1].
- **스펙터(Spectre) 공격의 원리:** 스펙터 취약점은 분기 예측을 악용합니다. 추측 실행은 과거의 기록에 따라 분기를 실행하는데, 공격자는 이 과거 기록을 통제함으로써 CPU가 추측 실행 중에 어떤 분기를 수행할지 조작할 수 있습니다 [2]. 추측 실행이 롤백되더라도 L1 캐시에 로드된 데이터는 취소되지 않으므로, 공격자는 이를 이용해 타이밍 기반으로 메모리 정보를 유출할 수 있습니다 [2, 3].
- **브라우저 엔진([[WebKit|WebKit]])에 미치는 영향:** WebKit의 JavaScriptCore는 신뢰할 수 없는 JavaScript나 [[WebAssembly|WebAssembly]] 코드의 보안(예: 배열 경계 검사, 타입 검사)을 유지하기 위해 '분기 명령어'에 의존해왔습니다 [4-6]. 그러나 분기 예측을 악용한 스펙터 공격으로 인해, 분기 명령어만으로는 더 이상 보안 속성을 강제하기에 충분하지 않게 되었습니다 [4, 5].
- **대응 및 완화 조치:** 분기 예측을 악용하는 공격에 대응하기 위해 WebKit은 기존의 분기 기반 보안 검사 외에도, 인덱스 마스킹([[Index Masking|Index Masking]])이나 포인터 포이즈닝(Pointer Poisoning)과 같은 '분기 없는 보안 검사([[Branchless Security Checks|Branchless Security Checks]])' 방식으로 전환하고 있습니다 [7-9].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 Predictor 종류
- **Static**: forward-not-taken, backward-taken (hint).
- **Bimodal (2-bit)**: per-PC saturating counter.
- **Local history**: per-branch shift register.
- **Global history (gshare/GAg)**: shared GHR XOR PC.
- **Tournament**: meta-predictor selects local vs global.
- **TAGE / ITTAGE**: tagged geometric history (modern SOTA).
- **Perceptron**: AMD Zen — neural-style predictor.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Speculative Execution|Speculative Execution]], Spectre, [[Branchless Security Checks|Branchless Security Checks]]
- **Projects/Contexts:** [[WebKit|WebKit]], [[JavaScriptCore|JavaScriptCore]]
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다. (소스 내에 상충하는 의견은 없으며, 과거에는 분기 명령어가 보안 강제에 충분하다고 여겨졌으나 스펙터의 등장으로 인해 더 이상 안전하지 않게 되었다는 맥락적 변화만 존재합니다 [4]).
### 매 Indirect Branches
- BTB (Branch Target Buffer) — caches target.
- ITTAGE for indirect.
- Critical for vtables, function pointers, switch.
---
*Last updated: 2026-04-19*
### 매 응용
1. Hot loops — predictable branches → near-zero penalty.
2. Sorted-data effect (the famous SO question).
3. Spectre/BranchScope side-channel attacks.
4. JIT branch ordering decisions (V8, Hotspot).
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Likely / Unlikely Hints (C++20)
```cpp
if (x > 0) [[likely]] {
fast_path();
} else [[unlikely]] {
slow_path();
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Branchless via Mask
```cpp
// branchful
int abs_v(int x) { return x < 0 ? -x : x; }
**선택 A를 써야 할 때:**
- *(TODO)*
// branchless
int abs_v_nb(int x) {
int mask = x >> 31; // 0 or -1
return (x ^ mask) - mask;
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Branchless Min via cmov
```cpp
int min_v(int a, int b) {
return a < b ? a : b; // compilers emit cmov on x86
}
```
**기본값:**
> *(TODO)*
### Sort Before Loop (classic)
```cpp
std::sort(data.begin(), data.end()); // 정렬 → branch predictable
long sum = 0;
for (int v : data) if (v >= 128) sum += v;
```
## ❌ 안티패턴 (Anti-Patterns)
### LLVM `__builtin_expect`
```cpp
if (__builtin_expect(error_flag, 0)) {
handle_error();
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Spectre v1 Mitigation (lfence)
```cpp
// vulnerable
if (idx < arr_size) {
secret = arr[idx]; // mispredict → leaks
}
// hardened
if (idx < arr_size) {
asm volatile("lfence" ::: "memory");
secret = arr[idx];
}
```
### perf Branch Stats
```bash
perf stat -e branches,branch-misses ./bench
# branch-miss rate > 5% → suspect; > 10% → critical
```
## 매 결정 기준
| 상황 | 전략 |
|---|---|
| Hot loop, predictable | Trust predictor — natural code |
| Hot loop, unpredictable | Branchless / mask / cmov |
| Cold path | Doesn't matter — clarity > tricks |
| Indirect-heavy (vtable) | Devirtualize, monomorphize |
| Security-sensitive | lfence / speculative load hardening |
**기본값**: write clear branchful code; branchless only when profiler shows misprediction hotspot.
## 🔗 Graph
- 부모: [[CPU Microarchitecture]] · [[Pipeline]]
- 변형: [[TAGE]] · [[Perceptron Predictor]] · [[BTB]]
- 응용: [[JIT Compilation]] · [[Branchless Programming]]
- Adjacent: [[Spectre]] · [[Speculative Execution]] · [[cmov]]
## 🤖 LLM 활용
**언제**: explain mispredict cost, generate branchless equivalents, suggest hints.
**언제 X**: micro-arch tuning without perf data — speculation hurts.
## ❌ 안티패턴
- **Random unpredictable branch in hot loop**: 20-30% slowdown.
- **Premature branchless conversion**: hurts cold/clarity paths.
- **Trusting `[[likely]]` blindly**: PGO data > human guess.
- **Ignoring Spectre in untrusted-input parsers**: real CVE risk.
## 🧪 검증 / 중복
- Verified (Hennessy & Patterson 6th, Agner Fog optimization manuals, Intel SDM).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — predictor types, branchless patterns, Spectre |