branch-prediction-and-speculation — скилл для Claude Code
Скилл branch-prediction-and-speculation для Claude Code объясняет предсказание ветвлений и спекулятивное выполнение процессоров, помогая оптимизировать горячие циклы и защищать код от утечек.
MIT 382 установок ★ 298 обновлён 2026-06-27
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a claude-codeЧто делает branch-prediction-and-speculation
Процессор угадывает, какой путь выполнит условный оператор, и начинает исполнять инструкции до того, как ветвление разрешится. Если угадка верна — штраф близок к нулю, если нет — процессор откатывает 10–20 и больше циклов. Скилл показывает, как профилировать мисприедикты через perf, когда включать __builtin_expect, и как переписать код в бесветвистый (через cmov или lookup-таблицы).
Спекулятивное выполнение — тот же механизм, что открыл Spectre и Meltdown: CPU может закэшировать данные из адреса, зависящего от секрета, даже если спекуляция потом откатится. Скилл объясняет, почему это опасно для криптографии и как ядро использует retpoline, IBRS и KPTI. На уровне приложения это означает: если ваши условия зависят от тайных данных, нужен constant-time код без ветвлений по секретам.
Скилл активируется на запросы о производительности циклов, безопасности относительно side-channel-атак и микроархитектурных деталях процессора. Помогает отладить, почему якобы оптимальный код медленнее, чем ожидается, или убедиться, что криптографический код не протекает через кэш и predictor.
Какие задачи решает
- оптимизировать горячий цикл с непредсказуемыми ветвлениями
- защитить криптографический код от Spectre-подобных утечек через кэш
- выбрать между
__builtin_expectи переписью в бесветвистый код - понять, почему ядерные миtigations (KPTI, retpoline) влияют на производительность
- профилировать и диагностировать misprediction penalty в реальном приложении
Примеры запросов агенту
- Оптимизируй этот цикл сравнения от branch mispredict, он упирается в производительность
- Переделай функцию сравнения паролей в constant-time против Spectre
- Объясни, что происходит с
perf stat -e branches,branch-missesи как это читать
Как установить branch-prediction-and-speculation
1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a claude-code2Вручную: положить файлы
~/.claude/skills/branch-prediction-and-speculation/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/branch-prediction-and-speculation/
1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a codex2Вручную: положить файлы
.agents/skills/branch-prediction-and-speculation/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a cursor2Вручную: положить файлы
.cursor/skills/branch-prediction-and-speculation/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install mohitmishra786/low-level-dev-skills skills/computer-architecture/branch-prediction-and-speculation2Вручную: положить файлы
.github/skills/branch-prediction-and-speculation/SKILL.md1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a gemini-cli2Командой платформы
gemini skills install https://github.com/mohitmishra786/low-level-dev-skills --path skills/computer-architecture/branch-prediction-and-speculationВручную: положить файлы
.devin/skills/branch-prediction-and-speculation/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о branch-prediction-and-speculation
Как установить branch-prediction-and-speculation в Claude Code?
Выполни npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a claude-code, затем найди конфигурацию в ~/.claude/skills/branch-prediction-and-speculation/SKILL.md.
Что делает этот скилл?
Объясняет, как CPUs предсказывают ветвления и выполняют код спекулятивно, почему это создаёт security-уязвимости (Spectre/Meltdown), и как писать быстрый и защищённый код — через профилирование, branchless refactors и constant-time patterns.
Когда скилл активируется?
На вопросы о производительности циклов, branch mispredict, спекулятивном выполнении, Spectre/Meltdown, kernel миtigations и constant-time криптографии.
Исходный текст
SKILL.md · MIT
---
name: branch-prediction-and-speculation
description: Branch prediction and speculation skill for CPU security and performance. Use when explaining branch predictors, mispredict penalties, speculative execution, Spectre/Meltdown mitigations, or branchless patterns. Activates on queries about branch prediction, speculative execution, Spectre, Meltdown, mispredict, or branchless code.
---
# Branch Prediction and Speculation
## Purpose
Explain how modern CPUs predict branches, execute speculatively, recover on mispredict, and why speculation created side channels (Spectre/Meltdown) — linking performance tuning with security-aware low-level coding.
## When to Use
- Hot loop branchy code underperforms expectations
- Evaluating `likely`/`unlikely` or branchless refactors
- Understanding kernel `retpoline`, IBRS, and similar mitigations
- Secure coding around secret-dependent branches
## Workflow
### 1. Branch predictor basics
```
Fetch sees conditional branch
├── Predict direction (taken / not-taken)
├── Speculatively execute predicted path
└── On resolve:
├── Correct → commit, ~0 penalty (deep pipelines still cost on mispredict)
└── Wrong → squash, refill from correct PC (10–20+ cycles typical)
```
Patterns: backward branches often predicted taken (loops); forward not-taken.
### 2. Performance patterns
```c
/* Predictable — tight loop backward branch */
for (int i = 0; i < n; i++)
sum += a[i];
/* Unpredictable — data-dependent */
if (data[i] > threshold) /* hard to predict */
rare_path();
```
Techniques: branchless `cmov`/select, lookup tables, sorting data to reduce branches, splitting hot/cold paths.
```c
/* Branchless min (integer) */
int m = a < b ? a : b; /* compiler may lower to cmov */
```
### 3. Compiler hints (use sparingly)
```c
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
if (unlikely(ptr == NULL))
return -EINVAL;
```
Measure with `perf` — hints are not magic on modern predictors.
### 4. Speculative execution and side channels
CPUs may execute instructions before branch outcome is known. If speculated path touches secret-dependent memory, cache state can leak (Spectre variant 1).
**Mitigations (high level):**
- Kernel: retpoline, IBRS/IBPB, STIBP (see kernel `cpu_show_mitigations`)
- Compiler: speculative load hardening (`-mspeculative-load-hardening` on Clang)
- Code: constant-time crypto — no secret-dependent branches or indices
Meltdown (Intel): user load from kernel mapping — fixed by KPTI (separate page tables).
### 5. Measurement
```bash
perf stat -e branches,branch-misses ./app
```
High `branch-misses` ratio → investigate hot branches.
### 6. Agent usage
```
/branch-prediction-and-speculation Make this comparison function constant-time against Spectre-style leakage
```
## Common Problems
| Symptom | Cause | Fix |
|---------|-------|-----|
| Loop slower than expected | Mispredicted exit | Peel iterations; branchless tail |
| `likely` no help | Predictor already good | Profile first |
| Secret leak in crypto | Branches on secret bytes | Constant-time algorithms |
| Mitigation regression | KPTI/retpoline overhead | Accept or isolate secrets |
| "Branchless" slower | CMOV still executes both | Benchmark on target CPU |
## Related Skills
- `skills/computer-architecture/cpu-pipelines-and-hazards` — control hazards
- `skills/security/kernel-security` — KPTI, CET, speculation mitigations
- `skills/low-level-programming/cpu-cache-opt` — cache timing channels
- `skills/profilers/hardware-counters` — branch-misses event
- `skills/runtimes/binary-hardening` — userspace hardening overlap
© mohitmishra786 · MIT · mohitmishra786/low-level-dev-skills