Repository navigation
IR 12 writing a pass
Relevant source files
The following files were used as context for generating this wiki page:
A pass is a C++ class with a run method that the pass manager calls on a module, function or loop. LLVM's current ("new") pass manager has no base class with virtual methods: a pass is any type with the right run signature, plus a mixin that supplies its name. This page builds three passes: a function pass that counts instructions, an analysis that other passes can query, and a small peephole transformation. It then loads them into opt as a plugin.
All C++ on this page is illustrative: written against the headers at commit
a2171756but not compiled or run for this wiki, because the local build had noopt.
This page covers the pass interface (run, PreservedAnalyses, the info mixins), analyses and the analysis manager, registering passes through a plugin, and running them with opt -load-pass-plugin. Passes already in LLVM are described on Common Passes.
LLVM ships a minimal pass. The header declares it:
class HelloWorldPass : public OptionalPassInfoMixin<HelloWorldPass> {
public:
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
};and the implementation prints the function name and changes nothing:
PreservedAnalyses HelloWorldPass::run(Function &F,
FunctionAnalysisManager &AM) {
errs() << F.getName() << "\n";
return PreservedAnalyses::all();
}It is built into opt and registered as helloworld, so opt -disable-output -passes=helloworld in.ll prints every function name.
Sources: llvm/include/llvm/Transforms/Utils/HelloWorld.h:16-19, llvm/lib/Transforms/Utils/HelloWorld.cpp:14-18, llvm/lib/Passes/PassRegistry.def:456
| Piece | Meaning |
|---|---|
run(IRUnit &, AnalysisManager &) |
Called once per unit: Module, Function, Loop or call-graph SCC |
PreservedAnalyses return value |
Tells the manager which cached analyses are still valid. all() if nothing changed, none() if you are unsure |
OptionalPassInfoMixin<T> |
Supplies name(). The pass may be skipped, for example for optnone functions |
RequiredPassInfoMixin<T> |
Same, but the pass always runs (verifiers, printers) |
AnalysisInfoMixin<T> |
For analyses; also supplies the unique Key
|
PassManager.h notes that real passes should inherit from RequiredPassInfoMixin or OptionalPassInfoMixin rather than PassInfoMixin directly.
Returning the wrong PreservedAnalyses is the most common bug: if a pass changes the CFG but claims everything is preserved, later passes will use a stale dominator tree.
Sources: llvm/include/llvm/IR/PassManager.h:75-90, llvm/include/llvm/IR/PassManager.h:117
// CountInsts.cpp (illustrative)
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
struct CountInstsPass : OptionalPassInfoMixin<CountInstsPass> {
PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
unsigned N = 0, Loads = 0;
for (Instruction &I : instructions(F)) {
++N;
if (isa<LoadInst>(I)) ++Loads;
}
errs() << F.getName() << ": " << N << " instructions, "
<< Loads << " loads\n";
return PreservedAnalyses::all(); // read-only
}
};
} // namespaceinstructions(F) iterates over every instruction in every block. isa<>, dyn_cast<> and cast<> are LLVM's type tests for the Value hierarchy.
An analysis computes a result that the manager caches until a pass invalidates it.
// illustrative
struct BlockCountAnalysis : AnalysisInfoMixin<BlockCountAnalysis> {
using Result = unsigned;
Result run(Function &F, FunctionAnalysisManager &) { return F.size(); }
private:
friend AnalysisInfoMixin<BlockCountAnalysis>;
static AnalysisKey Key;
};
AnalysisKey BlockCountAnalysis::Key;
// A pass that uses it, and the dominator tree:
struct ReportPass : OptionalPassInfoMixin<ReportPass> {
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM) {
unsigned Blocks = AM.getResult<BlockCountAnalysis>(F);
DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
errs() << F.getName() << ": " << Blocks << " blocks, root "
<< DT.getRoot()->getName() << "\n";
return PreservedAnalyses::all();
}
};AM.getResult<X>(F) runs X if no valid result is cached. AM.getCachedResult<X>(F) returns null instead of computing.
This pass rewrites x * 2^k into x << k, an instcombine-style rewrite.
// illustrative
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/IRBuilder.h"
using namespace llvm::PatternMatch;
struct MulToShiftPass : OptionalPassInfoMixin<MulToShiftPass> {
PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
bool Changed = false;
for (Instruction &I : make_early_inc_range(instructions(F))) {
Value *X; const APInt *C;
if (!match(&I, m_Mul(m_Value(X), m_APInt(C))) || !C->isPowerOf2())
continue;
IRBuilder<> B(&I);
Value *Shl = B.CreateShl(X, C->logBase2(), I.getName());
I.replaceAllUsesWith(Shl);
I.eraseFromParent();
Changed = true;
}
if (!Changed) return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>(); // no blocks or edges changed
return PA;
}
};Points to notice:
-
make_early_inc_rangelets the loop erase the current instruction safely. -
match(..., m_Mul(m_Value(X), m_APInt(C)))is thePatternMatchlibrary, whichinstcombineuses throughout. -
IRBuilderinserts new instructions before&I. -
replaceAllUsesWiththeneraseFromParentis the standard replace-and-delete pattern. - The CFG is unchanged, so CFG analyses such as the dominator tree are preserved. The pass drops
nsw/nuwbecause it does not copy them, which is always safe.
Before and after (illustrative):
%y = mul i32 %x, 8 ; before
%y = shl i32 %x, 3 ; afterA plugin is a shared library exporting llvmGetPassPluginInfo, which returns a PassPluginLibraryInfo: an API version, a name, a version string and a callback that registers passes with the PassBuilder.
// illustrative
#include "llvm/Plugins/PassPlugin.h"
#include "llvm/Passes/PassBuilder.h"
extern "C" LLVM_ATTRIBUTE_WEAK ::llvm::PassPluginLibraryInfo
llvmGetPassPluginInfo() {
return {LLVM_PLUGIN_API_VERSION, "IRWikiPasses", "v0.1",
[](PassBuilder &PB) {
PB.registerAnalysisRegistrationCallback(
[](FunctionAnalysisManager &FAM) {
FAM.registerPass([] { return BlockCountAnalysis(); });
});
PB.registerPipelineParsingCallback(
[](StringRef Name, FunctionPassManager &FPM,
ArrayRef<PassBuilder::PipelineElement>) {
if (Name == "count-insts") { FPM.addPass(CountInstsPass()); return true; }
if (Name == "report") { FPM.addPass(ReportPass()); return true; }
if (Name == "mul-to-shift"){ FPM.addPass(MulToShiftPass()); return true; }
return false;
});
}};
}In this checkout the header is llvm/Plugins/PassPlugin.h; older tutorials use llvm/Passes/PassPlugin.h. LLVM_PLUGIN_API_VERSION is 2 here.
Sources: llvm/include/llvm/Plugins/PassPlugin.h:36, llvm/include/llvm/Plugins/PassPlugin.h:45-56, llvm/include/llvm/Plugins/PassPlugin.h:125-138, llvm/include/llvm/Passes/PassBuilder.h:586-610
A minimal out-of-tree CMake file (illustrative):
cmake_minimum_required(VERSION 3.20)
project(IRWikiPasses)
find_package(LLVM REQUIRED CONFIG)
include_directories(${LLVM_INCLUDE_DIRS})
add_definitions(${LLVM_DEFINITIONS})
add_library(IRWikiPasses MODULE CountInsts.cpp)Then:
opt -load-pass-plugin=./libIRWikiPasses.so -disable-output -passes=count-insts in.ll
opt -load-pass-plugin=./libIRWikiPasses.so -S -passes='mem2reg,mul-to-shift' in.ll
On Windows, plugins need an LLVM built with plugin support (LLVM_ENABLE_PLUGINS) and the .dll must link against the same LLVM. If that is not available, an alternative is to add the pass to LLVM itself: put it in lib/Transforms/Utils/, add a FUNCTION_PASS("count-insts", CountInstsPass()) line to PassRegistry.def next to helloworld, and rebuild opt.
Always run -passes='your-pass,verify' while developing: the verifier catches broken SSA, missing terminators and type errors right after your pass.
- A pass is a class with
run(Unit&, AnalysisManager&)returningPreservedAnalyses. - Analyses use
AnalysisInfoMixinand a staticAnalysisKey, and are fetched withAM.getResult<>. - A plugin exports
llvmGetPassPluginInfoand registers names withregisterPipelineParsingCallback.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look