Skip to content

IR 12 writing a pass

Mugundan edited this page Nov 27, 2026 · 1 revision

Writing an IR 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 a2171756 but not compiled or run for this wiki, because the local build had no opt.

Purpose and Scope

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.

The Smallest Pass: HelloWorld

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

The Pass Interface

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

Pass 1: Count Instructions

// 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
  }
};
} // namespace

instructions(F) iterates over every instruction in every block. isa<>, dyn_cast<> and cast<> are LLVM's type tests for the Value hierarchy.

Pass 2: An Analysis

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.

Pass 3: A Peephole Transformation

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_range lets the loop erase the current instruction safely.
  • match(..., m_Mul(m_Value(X), m_APInt(C))) is the PatternMatch library, which instcombine uses throughout.
  • IRBuilder inserts new instructions before &I.
  • replaceAllUsesWith then eraseFromParent is the standard replace-and-delete pattern.
  • The CFG is unchanged, so CFG analyses such as the dominator tree are preserved. The pass drops nsw/nuw because it does not copy them, which is always safe.

Before and after (illustrative):

%y = mul i32 %x, 8      ; before
%y = shl i32 %x, 3      ; after

Registering as a Plugin

A 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

Building and Running

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.

Key Points

  • A pass is a class with run(Unit&, AnalysisManager&) returning PreservedAnalyses.
  • Analyses use AnalysisInfoMixin and a static AnalysisKey, and are fetched with AM.getResult<>.
  • A plugin exports llvmGetPassPluginInfo and registers names with registerPipelineParsingCallback.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally