cpu-pipelines-and-hazards — скилл для Claude Code: конвейеры
Объясняет стадии конвейера CPU, конфликты данных и управления, проброс и простои. Пригодится, когда непонятно, почему горячий цикл тормозит.
npx skills add mohitmishra786/low-level-dev-skills --skill cpu-pipelines-and-hazards -a claude-codeЧто делает cpu-pipelines-and-hazards
Скилл разбирает классический пятистадийный конвейер IF → ID → EX → MEM → WB и то, что его ломает. Конфликты данных RAW лечатся пробросом из EX/MEM/WB, WAR и WAW всплывают при переименовании регистров в процессорах с неупорядоченным исполнением. Конфликты управления разбираются через предсказание переходов и сброс неверно выбранных инструкций, цена ошибки равна глубине конвейера.
Есть структурные конфликты: нехватка функциональных устройств даёт простои даже без зависимостей. В практической части — пример с накоплением в одном регистре против нескольких аккумуляторов для роста ILP, разбор perf stat -e instructions,cycles,stalls-frontend,stalls-backend и таблица типичных симптомов: высокий stalls-frontend от промахов I-кэша, отсутствие выигрыша от развёртки при упоре в память, неверная модель циклов из-за игнорирования OoO.
Скилл ссылается на соседние темы: предсказание переходов, иерархию памяти, оптимизацию кэша, профилировщики Intel VTune и AMD uProf, планирование инструкций в ARM. Отдельно предупреждает: задержки MMIO не настраивают вставкой NOP. Профилирование требует perf и доступа к аппаратным счётчикам, а на виртуалках и в контейнерах счётчики часто недоступны — это повод проверить окружение до того, как доверять цифрам.
Какие задачи решает
- объяснить, почему порядок инструкций меняет пропускную способность
- разобрать RAW-зависимость в цикле на ассемблере и разорвать её
- связать метрики простоев из VTune со стадиями конвейера
- отличить упор в память от конфликта данных в горячем цикле
- найти причину резкого падения производительности в цикле
Примеры запросов агенту
- /cpu-pipelines-and-hazards Explain RAW hazard in this ARM assembly loop and how to break it
- Покажи, где в этом цикле конфликт данных и как его убрать через несколько аккумуляторов
- Что означает высокий stalls-frontend в выводе perf stat для моего приложения?
Как установить cpu-pipelines-and-hazards
1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill cpu-pipelines-and-hazards -a claude-code2Вручную: положить файлы
~/.claude/skills/cpu-pipelines-and-hazards/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/cpu-pipelines-and-hazards/
1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill cpu-pipelines-and-hazards -a codex2Вручную: положить файлы
.agents/skills/cpu-pipelines-and-hazards/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill cpu-pipelines-and-hazards -a cursor2Вручную: положить файлы
.cursor/skills/cpu-pipelines-and-hazards/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install mohitmishra786/low-level-dev-skills cpu-pipelines-and-hazards2Вручную: положить файлы
.github/skills/cpu-pipelines-and-hazards/SKILL.md1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill cpu-pipelines-and-hazards -a gemini-cli2Командой платформы
gemini skills install https://github.com/mohitmishra786/low-level-dev-skills --path skills/computer-architecture/cpu-pipelines-and-hazardsВручную: положить файлы
.devin/skills/cpu-pipelines-and-hazards/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill cpu-pipelines-and-hazards -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о cpu-pipelines-and-hazards
Как установить cpu-pipelines-and-hazards в Claude?
Выполните npx skills add mohitmishra786/low-level-dev-skills --skill cpu-pipelines-and-hazards -a claude-code. Скилл окажется в ~/.claude/skills/cpu-pipelines-and-hazards/SKILL.md.
Что делает cpu-pipelines-and-hazards?
Объясняет стадии конвейера CPU, конфликты данных и управления, проброс, простои и обработку переходов. Помогает связать порядок инструкций с поведением железа и метриками профилировщика.
С какими скиллами он работает вместе?
Ссылается на предсказание переходов и спекуляцию, иерархию памяти и кэши, оптимизацию кэша, профилировщики Intel VTune и AMD uProf, а также планирование инструкций в ARM.
Исходный текст
SKILL.md · MIT
---
name: cpu-pipelines-and-hazards
description: CPU pipeline skill for hazards, forwarding, and stalls. Use when explaining pipeline stages, data/control hazards, forwarding paths, or branch stalls in performance analysis. Activates on queries about pipeline hazard, data hazard, control hazard, forwarding, pipeline stall, or superscalar basics.
---
# CPU Pipelines and Hazards
## Purpose
Explain classic and modern CPU pipeline concepts: stages, data and control hazards, forwarding/bypassing, stalls, and branch handling — foundational for optimization and understanding microarchitecture counters.
## When to Use
- Interpreting pipeline stall metrics from `skills/profilers/intel-vtune-amd-uprof`
- Teaching why instruction order affects throughput
- Relating assembly scheduling to hardware behavior
- Debugging unexpected performance cliffs in hot loops
## Workflow
### 1. Five-stage classic pipeline (MIPS-style mental model)
```
IF → ID → EX → MEM → WB
```
Overlapped execution: instruction N in EX while N+1 in ID.
### 2. Data hazards
| Type | Example | Mitigation |
|------|---------|------------|
| RAW (true) | `add r1,r2,r3` then `sub r4,r1,r5` | Forwarding from EX/MEM/WB |
| WAR / WAW | Rare in in-order; relevant in OoO rename | Register renaming |
Without forwarding:
```
stall until writeback completes
```
### 3. Control hazards (branches)
```
Branch in ID → target unknown until EX
├── Predict taken/not-taken (static or dynamic)
├── Flush wrong-path instructions on mispredict
└── Penalty = pipeline depth (varies by CPU)
```
See `skills/computer-architecture/branch-prediction-and-speculation`.
### 4. Structural hazards
Limited functional units (single memory port) cause stalls even without dependencies.
### 5. Practical optimization hints
```c
/* Bad — tight dependency chain */
for (int i = 0; i < n; i++)
acc = acc + data[i]; /* each iter waits on acc */
/* Better — multiple accumulators (ILP) */
acc0 = acc1 = 0;
for (int i = 0; i < n; i += 2) {
acc0 += data[i];
acc1 += data[i+1];
}
acc = acc0 + acc1;
```
Pair with `skills/low-level-programming/cpu-cache-opt` — memory often dominates.
### 6. Reading uops / ports (x86)
```bash
perf stat -e instructions,cycles,stalls-frontend,stalls-backend ./app
```
VTune "Microarchitecture Exploration" maps to pipeline slots.
### 7. Agent usage
```
/cpu-pipelines-and-hazards Explain RAW hazard in this ARM assembly loop and how to break it
```
## Common Problems
| Symptom | Cause | Fix |
|---------|-------|-----|
| High `stalls-frontend` | I-cache misses / branch mispredict | Align hot loop; see branch skill |
| No speedup from unroll | Memory bound | Profile loads; prefetch |
| Wrong cycle model | Ignored OoO execution | Use perf hardware counters |
| "NOP fixes it" | Timing-sensitive MMIO | Never tune device delays by NOP |
## Related Skills
- `skills/computer-architecture/branch-prediction-and-speculation` — mispredict cost
- `skills/computer-architecture/memory-hierarchy-and-caches` — load latency
- `skills/low-level-programming/cpu-cache-opt` — cache-line effects
- `skills/profilers/intel-vtune-amd-uprof` — pipeline analysis
- `skills/low-level-programming/assembly-arm` — instruction scheduling
© mohitmishra786 · MIT · mohitmishra786/low-level-dev-skills