Skip to main content
skill CX Codex

llvm-passes — Claude Code skill: what it does, how to install

llvm-passes guides coding agents in creating, building, and verifying LLVM optimization passes with the New Pass Manager.

MIT 373 installs ★ 298 updated 2026-06-27

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add mohitmishra786/low-level-dev-skills --skill llvm-passes -a claude-code
Open on GitHub

What llvm-passes does

The skill supplies reference implementations for C++ FunctionPass and ModulePass components, registration patterns via PassPluginLibraryInfo, and minimal CMakeLists.txt build configurations. It instructs the agent on executing passes with opt -load-pass-plugin, building pass pipelines, and tracing IR changes with -print-after-all.

Included workflows cover query analyses such as DominatorTree, LoopInfo, and AliasAnalysis, along with basic SSA modification patterns through IRBuilder. It also details test setup using llvm-lit combined with FileCheck assertions.

Building against a mismatched LLVM version will break plugin loading in opt instantly due to binary interface differences.

What it helps with

  • implement custom FunctionPass or ModulePass classes for the New Pass Manager
  • register dynamic pass plugins for execution via opt -load-pass-plugin
  • query control flow structures using DominatorTree and LoopInfo analyses
  • write regression test cases powered by llvm-lit and FileCheck
  • diagnose broken SSA structures with verify-each and debug flags

Example prompts for the agent

  • Write a FunctionPass that replaces target instructions and configure its CMakeLists file
  • Show how to request DominatorTreeAnalysis inside a pass and handle PreservedAnalyses
  • Set up an llvm-lit test file with FileCheck directives for a custom pass

How to install llvm-passes

1Skills CLI (Vercel)

npx skills add mohitmishra786/low-level-dev-skills --skill llvm-passes -a claude-code

2Manually: put the files in place

~/.claude/skills/llvm-passes/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/llvm-passes/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about llvm-passes

How to install llvm-passes in Claude Code?

Run npx skills add mohitmishra786/low-level-dev-skills --skill llvm-passes -a claude-code in your terminal.

What does the llvm-passes skill cover?

It guides the agent through authoring LLVM New Pass Manager extensions, handling IR modifications, running passes via opt, and testing with llvm-lit.

How does the New Pass Manager handle analysis invalidation?

Passes must return PreservedAnalyses::all() if the IR was untouched, or return PreservedAnalyses::none() so cached analyses recalculate after mutations.

Source text

SKILL.md · MIT
---
name: llvm-passes
description: LLVM passes skill for writing compiler optimizations. Use when writing FunctionPass or ModulePass, registering PassPlugins, running with opt, using analysis utilities, or testing with llvm-lit. Activates on queries about LLVM pass, PassPlugin, opt -passes, DominatorTree, llvm-lit, or New Pass Manager.
---

# LLVM Passes

## Purpose

Guide agents through writing LLVM optimization passes with the New Pass Manager: `FunctionPass` and `ModulePass` structure, `PassPluginLibraryInfo` registration, running via `opt -load-pass-plugin`, common analysis utilities (`DominatorTree`, `LoopInfo`, `AliasAnalysis`), IR modification patterns, `llvm-lit` testing, and debugging with `opt -print-after-all`.

## When to Use

- Adding a custom optimization to an LLVM-based compiler
- Writing an IR transformation pass (inlining, DCE, custom lowering)
- Analyzing control flow with dominator trees or loop info
- Testing passes with FileCheck and llvm-lit
- Debugging pass ordering and IR corruption
- Integrating passes into Clang via plugin

## Workflow

### 1. New Pass Manager architecture

```
opt / clang
├── ModulePassManager
│   └── FunctionPassManager (per function)
│       └── FunctionPass instances
└── AnalysisManager (cached analyses)
```

Passes declare analysis usage; analyses are invalidated on IR mutation.

### 2. Minimal FunctionPass (C++ plugin)

```cpp
// MyPass.cpp
#include "llvm/IR/PassManager.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Passes/PassPlugin.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

namespace {

struct MyPass : PassInfoMixin<MyPass> {
    PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM) {
        bool changed = false;
        for (BasicBlock &BB : F) {
            for (Instruction &I : BB) {
                if (auto *Call = dyn_cast<CallInst>(&I)) {
                    if (Call->getCalledFunction() &&
                        Call->getCalledFunction()->getName() == "dead_func") {
                        Call->eraseFromParent();
                        changed = true;
                    }
                }
            }
        }
        return changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
    }
};

} // namespace

extern "C" LLVM_ATTRIBUTE_WEAK PassPluginLibraryInfo llvmGetPassPluginInfo() {
    return {
        LLVM_PLUGIN_API_VERSION, "MyPass", "v0.1",
        [](PassBuilder &PB) {
            PB.registerPipelineParsingCallback(
                [](StringRef Name, FunctionPassManager &FPM,
                   ArrayRef<PassBuilder::PipelineElement>) {
                    if (Name == "my-pass") {
                        FPM.addPass(MyPass());
                        return true;
                    }
                    return false;
                });
        }
    };
}
```

```cmake
# CMakeLists.txt
find_package(LLVM REQUIRED CONFIG)
add_library(MyPass MODULE MyPass.cpp)
target_include_directories(MyPass SYSTEM PRIVATE ${LLVM_INCLUDE_DIRS})
target_compile_definitions(MyPass PRIVATE ${LLVM_DEFINITIONS})
llvm_map_components_to_libnames(llvm_libs core passes support)
target_link_libraries(MyPass PRIVATE ${llvm_libs})
```

```bash
cmake -B build -DLLVM_DIR=$(llvm-config --cmakedir)
cmake --build build
```

### 3. Running with opt

```bash
# Run pass on IR file
opt -load-pass-plugin ./build/MyPass.so -passes=my-pass -S input.ll -o output.ll

# Print IR after each pass
opt -load-pass-plugin ./build/MyPass.so -passes=my-pass -print-after-all input.ll -o /dev/null

# Pass pipeline string
opt -passes="function(instcombine),my-pass,function(dce)" input.ll -S -o out.ll
```

### 4. ModulePass example

```cpp
struct MyModulePass : PassInfoMixin<MyModulePass> {
    PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM) {
        for (Function &F : M) {
            if (F.isDeclaration()) continue;
            // module-level transformation
        }
        return PreservedAnalyses::none();
    }
};
```

Register on `ModulePassManager` in plugin callback.

### 5. Analysis utilities

```cpp
#include "llvm/Analysis/DominatorTree.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/AliasAnalysis.h"

PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM) {
    auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
    auto &LI = AM.getResult<LoopAnalysis>(F);
    auto &AA = AM.getResult<AAManager>(F);

    for (Loop *L : LI) {
        BasicBlock *Header = L->getHeader();
        // Loop invariant code motion, etc.
    }

    DominatorTreeNode *IDom = DT.getNode(&F.getEntryBlock());
    (void)IDom;
    return PreservedAnalyses::all();
}
```

Declare analyses used:

```cpp
AnalysisUsage MyLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
    AU.addRequired<DominatorTreeWrapperPass>();
    AU.addRequired<LoopInfoWrapperPass>();
    return AU;
}
```

(New PM: analyses requested via `AM.getResult<>` — dependency auto-tracked.)

### 6. IR modification patterns

```cpp
// Insert instruction before iterator
IRBuilder<> Builder(&*I.getIterator());
Value *NewVal = Builder.CreateAdd(I.getOperand(0), ConstantInt::get(I.getType(), 1));
I.replaceAllUsesWith(NewVal);
I.eraseFromParent();

// Clone basic block
BasicBlock *Clone = CloneBasicBlock(OrigBB, VMap, ".clone", &F);

// Create function
FunctionCallee Fn = M.getOrInsertFunction("my_fn",
    FunctionType::get(Builder.getVoidTy(), false));
```

Always update SSA and invalidate analyses after structural changes.

### 7. llvm-lit testing

```
test/
├── lit.cfg.py
└── my-pass.test
```

```
# my-pass.test
# RUN: opt -load-pass-plugin %shlibdir/MyPass.so -passes=my-pass -S %s | FileCheck %s

define void @test() {
  call void @dead_func()
  ret void
}

; CHECK-NOT: dead_func
```

```bash
llvm-lit test/my-pass.test -v
```

### 8. Debugging passes

```bash
# Verify IR after pass
opt -load-pass-plugin ./MyPass.so -passes=my-pass input.ll -o out.ll
opt -verify-each out.ll

# Time passes
opt -passes=my-pass -time-passes input.ll -o /dev/null

# Debug pass manager
OPT_DEBUG=1 opt -passes=my-pass input.ll -o /dev/null
```

## Common Problems

| Symptom | Cause | Fix |
|---------|-------|-----|
| `Pass not found: my-pass` | Plugin not loaded or name mismatch | Check `registerPipelineParsingCallback` name |
| Verify module failed | Broken SSA after transform | Run `-verify-each`; check use-def chains |
| Analysis stale | Modified IR without invalidation | Return `PreservedAnalyses::none()` |
| Plugin load error | LLVM version mismatch | Build against same LLVM as opt |
| Empty opt output | Forgot `-S` | Add `-S` for textual IR |
| lit test FAIL | CHECK line mismatch | `opt -S` and compare manually |

## Related Skills

- `skills/compilers/llvm` — LLVM IR inspection and opt pipeline as user
- `skills/compiler-internals/compiler-frontend` — IR generation feeding passes
- `skills/compiler-internals/jit-compilation` — ORC JIT running optimized IR
- `skills/compiler-internals/mlir` — MLIR passes (similar concepts)
- `skills/compilers/clang` — Clang optimization flags
- `skills/build-systems/cmake` — building pass plugins

© mohitmishra786 · MIT · mohitmishra786/low-level-dev-skills

Similar skills

All skills for Programming languages →

From the same set140

The whole set →
platform-device-model The platform-device-model skill explains Linux platform-driver binding, probe and remove, sysfs, device properties, and deferred probing for kernel work. CX Codex +1 378installs writing-char-drivers writing-char-drivers — a skill for writing Linux character drivers: cdev registration, file_operations implementation, safe userspace copies, ioctl and mmap. CX Codex +1 378installs adc-dac-baremetal adc-dac-baremetal — a skill for bare-metal ADC and DAC setup on MCUs: channel selection, sampling time, calibration, DMA buffers, and voltage output. Essential when working with analog sensors, audio signals, or control voltages. CX Codex +1 378installs resource-optimization-lowend The resource-optimization-lowend skill helps trim flash and RAM use in MCU firmware, inspect linker maps, and measure stack depth when embedded resources are tight. CX Codex +1 376installs openmp Teaches the agent to write and fix OpenMP code: parallel loops, reductions, tasks, SIMD hints and GPU offload. CX Codex +1 371installs numa-programming Skill teaches the agent NUMA programming: detect topology with numactl and lstopo, bind processes to local memory, use libnuma API, build per-node data structures, and diagnose remote access penalties. CX Codex +1 369installs dpdk Skill for DPDK work: EAL init, poll-mode driver setup, mbuf pools, rte_ring, huge pages, RSS, and testpmd validation. CX Codex +1 369installs timers-pwm-baremetal timers-pwm-baremetal — a skill to configure MCU timers without an OS: PWM for LED dimming and motor control, input capture for pulse measurement, and periodic interrupts via SysTick. Works on STM32 and other bare-metal platforms. CX Codex +1 367installs

Project sponsors

Companies that keep this analytics open