/branch-prediction-and-speculation
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
$ npx -y skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
- You can call itInvoke it directly when you want it.
- Slash command
/branch-prediction-and-speculation
Context preview
The summary Claude sees to decide when to auto-load this skill.
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
SKILL.md
branch-prediction-and-speculation.SKILL.mdname: 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
/* 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.
/* Branchless min (integer) */
int m = a < b ? a : b; /* compiler may lower to cmov */
3. Compiler hints (use sparingly)
#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
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
Read more
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
/* 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.
/* Branchless min (integer) */ int m = a < b ? a : b; /* compiler may lower to cmov */
3. Compiler hints (use sparingly)
#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
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
A curated suite of AI agent skills for systems and low-level programming — C/C++, Rust, Zig, GPU, bare-metal firmware, Linux kernel/driver development, computer architecture, compiler internals, HPC, and more.
Repo: mohitmishra786/low-level-dev-skills
Other skills on low-level-dev-skills.
- /custom-allocators
Custom allocator skill for memory allocation strategies. Use when implementing pool/slab/arena allocators, tuning jemalloc/mimalloc, writing Rust GlobalAlloc, or benchmarking allocator performance. Activates on queries about jemalloc, mimalloc, tcmalloc, arena allocator,
Open skill - /numa-programming
NUMA programming skill for multi-socket memory locality. Use when detecting NUMA topology, binding processes with numactl, using libnuma API, building NUMA-aware data structures, or measuring remote access penalties. Activates on queries about numactl, libnuma, NUMA topology,
Open skill - /af-xdp
AF_XDP skill for high-performance XDP sockets. Use when creating AF_XDP sockets, configuring UMEM and XSK rings, XDP_REDIRECT programs, copy vs zero-copy mode, or comparing with DPDK. Activates on queries about AF_XDP, xsk_umem, XDP_REDIRECT, libbpf xsk, or zero-copy XDP.
Open skill - /dpdk
DPDK skill for userspace packet I/O. Use when initializing EAL, configuring PMD drivers, using mbuf pools and rte_ring, setting up huge pages, RSS, or testpmd validation. Activates on queries about DPDK, EAL, rte_eth_rx_burst, hugepages, PMD, or testpmd.
Open skill - /io-uring
io_uring skill for Linux async I/O. Use when building high-performance servers with liburing, multi-shot operations, provided buffers, fixed files, zero-copy send, or tokio-uring. Activates on queries about io_uring, SQE/CQE, liburing, IORING_OP_PROVIDE_BUFFERS, or io_uring vs
Open skill - /adc-dac-baremetal
Bare-metal ADC and DAC skill. Use when configuring analog sampling, DMA-driven ADC, calibration, or DAC output on MCUs. Activates on queries about ADC bare-metal, sampling time, DMA ADC, or DAC channel setup.
Open skill

