C++ for LLVM Development: Overview
Relevant source files
The following files were used as context for generating this wiki page:
LLVM is written in modern C++ (C++17 at the commit this wiki uses). You do not need to know all of C++ to work on it, but you do need a particular subset, and LLVM adds its own replacements for some standard features. This wiki teaches exactly that subset, from the beginning, with small programs you can compile.
> How the examples were checked. Every code block whose first line is // example: name is a complete program. Each one was compiled with MSVC 19.51 (/std:c++17) against the LLVM headers and LLVMSupport.lib from the local build at commit a2171756, run, and its output compared with the text block shown under it. Other snippets are short fragments and are marked illustrative.
Purpose and Scope
| # | Page | What you learn |
|---|---|---|
| 1 | Overview | Why LLVM's C++ looks different, and a learning path |
| 2 | C++ Basics | Values, pointers, references, const, headers, namespaces |
| 3 | Classes and RAII | Constructors, destructors, inheritance, virtual, RAII |
| 4 | Ownership and Move | Stack vs heap, unique_ptr, move semantics, who owns IR objects |
| 5 | Templates and Lambdas | Function and class templates, lambdas, function_ref |
| 6 | LLVM Data Structures | SmallVector, ArrayRef, StringRef, DenseMap, Twine |
| 7 | LLVM-Style RTTI | isa<>, cast<>, dyn_cast<>, classof |
| 8 | Errors and Output | Error, Expected<T>, raw_ostream, assert, llvm_unreachable |
| 9 | Iterators and Ranges | Range-for, auto, STLExtras, deleting while iterating |
| 10 | Building, Debugging, Exercises | Building against LLVM, sanitizers, exercises, glossary |
Once comfortable, continue with the LLVM IR wiki and its Writing a Pass page.
Why LLVM's C++ Looks Different
flowchart TD
G["Goals: fast compile times, fast compiler,<br/>small binaries, portable"] --> NE["No exceptions<br/>→ llvm::Error / Expected"]
G --> NR["No C++ RTTI (dynamic_cast)<br/>→ isa / cast / dyn_cast"]
G --> AD["Avoid heap allocation in hot code<br/>→ SmallVector, StringRef, ArrayRef"]
G --> IO["No iostream in libraries<br/>→ raw_ostream: outs(), errs()"]
| Standard C++ habit | LLVM's choice | Page |
|---|---|---|
throw / try / catch | Built with exceptions off; return llvm::Error or Expected<T> | Errors and Output |
dynamic_cast, typeid | Built with RTTI off; use isa<>, cast<>, dyn_cast<> | LLVM-Style RTTI |
std::vector everywhere | SmallVector<T, N> keeps the first N elements without a heap allocation | LLVM Data Structures |
const std::string & parameters | StringRef (pointer + length, never copies) | LLVM Data Structures |
std::cout | llvm::outs(), llvm::errs(), dbgs() | Errors and Output |
std::map / std::unordered_map | DenseMap (open addressing, cache-friendly) | LLVM Data Structures |
These rules are stated in the LLVM Coding Standards; the data structures and casting are explained in the Programmer's Manual.
A First Taste
This is what everyday LLVM code looks like. Each piece is explained on a later page.
// example: taste
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
int main() {
SmallVector<StringRef, 4> Names = {"add", "mul", "load"};
for (StringRef N : Names)
if (N.starts_with("l"))
outs() << N << " is a memory op\n";
outs() << Names.size() << " names\n";
}
load is a memory op
3 names
Sources: llvm/include/llvm/ADT/SmallVector.h:1249, llvm/include/llvm/Support/Casting.h:547, llvm/include/llvm/Support/Error.h:159
A Learning Path
flowchart LR
A["1. C++ basics<br/>pointers, references, const"] --> B["2. Classes, RAII,<br/>virtual functions"]
B --> C["3. Ownership:<br/>unique_ptr, move"]
C --> D["4. Templates, lambdas"]
D --> E["5. LLVM ADT + casting<br/>+ Error"]
E --> F["6. Read and modify<br/>a real pass"]
| Stage | Practise by |
|---|---|
| Basics to templates | Writing the small programs on pages 2-5 yourself |
| LLVM libraries | Compiling the examples on pages 6-9 against your LLVM build |
| Real code | Reading llvm/lib/Transforms/Utils/HelloWorld.cpp, then DCE.cpp, then writing a pass |
Recommended Books and References
| Resource | Good for |
|---|---|
| Bjarne Stroustrup, A Tour of C++ | A short modern overview for programmers |
| Bjarne Stroustrup, Programming: Principles and Practice Using C++ | A full beginner course |
| Scott Meyers, Effective Modern C++ | auto, move semantics, smart pointers, lambdas: exactly the C++11/14 features LLVM uses |
| cppreference.com | Precise reference for every language feature |
| LLVM Programmer's Manual | LLVM's own data structures and idioms |
| LLVM Coding Standards | The style and rules reviewers will expect |
Key Points
- LLVM uses a disciplined subset of C++17 with exceptions and RTTI turned off.
- It replaces several standard tools with faster ones:
SmallVector,StringRef,DenseMap,raw_ostream,Error,isa/cast/dyn_cast. - Learn the language basics first, then the LLVM libraries, then read real passes.
C++ Basics
Relevant source files
The following references were used as context for generating this wiki page:
- cppreference: References
- cppreference: Undefined behavior
- Wikipedia: One Definition Rule
- Book: Bjarne Stroustrup, A Tour of C++, chapters 1-3
This page covers the parts of C++ you meet on every line of LLVM code: values, pointers and references, const, headers and namespaces. If you already write C, most of it is familiar; the new parts are references and const-correctness, which LLVM uses everywhere.
Purpose and Scope
This page covers variables and types, pointers, references, const, passing arguments, nullptr, headers and the one-definition rule, namespaces, and undefined behaviour. Classes are on Classes and RAII.
The House and Address Analogy
| Everyday | C++ |
|---|---|
| A house | An object in memory |
| The house's street address written on paper | A pointer (T *): can be changed, can be blank (nullptr) |
| A nickname for the house | A reference (T &): always refers to the same house, never blank |
| "Look but don't touch" sign | const |
Pointers and References
// example: refs
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
void addOnePtr(int *P) { if (P) *P += 1; } // may be null: must check
void addOneRef(int &R) { R += 1; } // never null
int twice(const int &R) { return R * 2; } // read-only
int main() {
int X = 10;
int *P = &X; // P holds X's address
int &R = X; // R is another name for X
addOnePtr(P);
addOneRef(R);
outs() << "X = " << X << ", twice = " << twice(X) << "\n";
addOnePtr(nullptr); // safe: the function checks
outs() << "done\n";
}
X = 12, twice = 24
done
flowchart LR
P["P (int *)<br/>holds address of X"] --> X["X = 12"]
R["R (int &)<br/>another name"] -.-> X
Pointer T * |
Reference T & |
|
|---|---|---|
| Can be null | Yes | No |
| Can be re-pointed | Yes | No |
| Access syntax | *P, P->field | R, R.field |
| LLVM convention | "May be null" or "optional" | "Always valid" |
LLVM convention: a function taking Function &F guarantees F exists; one taking Instruction *I might receive null (check the documentation). Most IR objects are passed around as pointers, e.g. Value *, BasicBlock *.
Sources: cppreference: References
const
| Declaration | Meaning |
|---|---|
const int X = 5; | X cannot change |
const Value *V | Can't modify the value V points to; V itself can be reassigned |
Value *const V | V can't be reassigned; the pointee can change |
int size() const; (member function) | The function does not modify the object |
LLVM is const-correct: F.getName() works on a const Function & because getName is a const member. Getting this wrong produces confusing errors like "cannot convert const Value * to Value *" — the fix is usually to use the const version of a type throughout, not to cast const away.
Passing Arguments
flowchart TD
Q["How should a function take T?"] --> S{"Small and cheap to copy?<br/>(int, pointer, StringRef, ArrayRef)"}
S -->|"yes"| V["By value: T"]
S -->|"no"| M{"Will the function modify it?"}
M -->|"yes"| R["By reference: T &"]
M -->|"no"| C["By const reference: const T &"]
M -->|"it takes ownership"| U["By value and move: std::unique_ptr<T>"]
Headers, Declarations and the ODR
C++ code is split into headers (.h, declarations) and source files (.cpp, definitions).
// illustrative: Counter.h
#ifndef MYPASS_COUNTER_H // include guard: header body seen once per .cpp
#define MYPASS_COUNTER_H
namespace mypass {
int countDown(int N); // declaration: "this exists somewhere"
}
#endif
// Counter.cpp
#include "Counter.h"
int mypass::countDown(int N) { return N > 0 ? N - 1 : 0; } // definition
flowchart LR
H["Counter.h<br/>declarations"] -->|"#include"| A["Counter.cpp"]
H -->|"#include"| B["Main.cpp"]
A -->|"compile"| AO["Counter.obj"]
B -->|"compile"| BO["Main.obj"]
AO --> L["linker"]
BO --> L
L --> EXE["program"]
The one-definition rule (ODR): a non-inline function or global variable must be defined exactly once in the whole program. Defining a normal function in a header that two .cpp files include gives "multiply defined symbol" link errors; mark it inline or move it to a .cpp.
LLVM's include order rule (from the Coding Standards): the file's own header first, then LLVM headers, then system headers.
Sources: Wikipedia: One Definition Rule
Namespaces
Everything in LLVM is in namespace llvm. In .cpp files LLVM code writes using namespace llvm;; in headers it never does, because that would leak into every includer. Helpers private to one .cpp go in an anonymous namespace, which gives them internal linkage:
// illustrative
namespace { // only visible in this .cpp file
struct MyHelperPass { /* ... */ };
} // end anonymous namespace
Undefined Behaviour
Some mistakes are not errors but undefined behaviour (UB): the program may do anything, including appear to work.
| Example | Why it is UB |
|---|---|
| Reading an uninitialised variable | No defined value |
| Dereferencing null or a dangling pointer | No object there |
| Out-of-bounds array access | Past the object |
| Signed integer overflow | The standard says so (LLVM's nsw flag exploits this, see LLVM IR: Arithmetic) |
Use the sanitizers described on Building, Debugging, Exercises to catch UB.
Sources: cppreference: Undefined behavior
Common Traps
int &R;without initialising is an error: references must bind at once.- Returning a reference or pointer to a local variable gives a dangling reference.
using namespacein a header.- Forgetting
conston member functions, so they can't be called on const objects.
Key Points
- Pointers may be null and can be re-pointed; references are always-valid aliases.
- Be
const-correct; pass small things by value, big things byconst &. - Declarations in headers, definitions once in
.cpp(ODR); LLVM lives innamespace llvm.
Classes and RAII
Relevant source files
The following files were used as context for generating this wiki page:
A class bundles data with the functions that work on it. LLVM's IR is a big class hierarchy (Value → User → Instruction → AllocaInst, ...), and almost every helper in LLVM relies on RAII: an object's destructor automatically cleans up when it goes out of scope. This page explains both.
Purpose and Scope
This page covers classes and structs, constructors and destructors, member initialiser lists, access control, inheritance, virtual functions and the vtable, RAII, and the rule of zero/three/five. Ownership with unique_ptr is on Ownership and Move.
The Hotel Key Card Analogy
| Hotel | RAII |
|---|---|
| Checking in gives you a key card | The constructor acquires a resource |
| Checking out returns it automatically, whatever happened during the stay | The destructor releases it when the object goes out of scope |
| You can't forget to return it | No leaks, even on early return |
A Class
// example: classes
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
class Counter {
public:
explicit Counter(int Start) : Value(Start) {} // member initialiser list
void increment() { ++Value; }
int get() const { return Value; } // const: doesn't modify
private:
int Value; // hidden from outside
};
int main() {
Counter C(5);
C.increment();
C.increment();
outs() << "count = " << C.get() << "\n";
}
count = 7
| Piece | Meaning |
|---|---|
public: / private: | Who may use the members; struct defaults to public, class to private |
Constructor Counter(int) | Runs when an object is created |
: Value(Start) | Initialiser list: initialises members before the body runs (prefer it to assignment in the body) |
explicit | Forbids silent conversion Counter C = 5; |
const after get() | Callable on const Counter & |
Constructors and Destructors: RAII
// example: raii
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
struct Scope {
const char *Name;
explicit Scope(const char *N) : Name(N) { outs() << "enter " << Name << "\n"; }
~Scope() { outs() << "leave " << Name << "\n"; } // destructor
};
int work(bool EarlyExit) {
Scope S("work");
if (EarlyExit)
return 1; // destructor still runs
Scope Inner("inner");
return 2; // destroyed in reverse order: inner, then work
}
int main() {
work(true);
work(false);
}
enter work
leave work
enter work
enter inner
leave inner
leave work
sequenceDiagram
participant F as work(false)
F->>F: construct S("work")
F->>F: construct Inner("inner")
F->>F: return 2
F->>F: ~Inner() (last created, first destroyed)
F->>F: ~S()
RAII is how C++ manages every resource: memory (std::unique_ptr), files, locks (std::lock_guard). In LLVM, IRBuilder insertion points, timers, and LLVMContext all use it. LLVM is compiled without exceptions, but RAII still matters for early returns.
Sources: cppreference: RAII
Inheritance and Virtual Functions
// example: virtual
#include "llvm/Support/raw_ostream.h"
#include <memory>
using namespace llvm;
struct Pass {
virtual ~Pass() = default; // virtual destructor in any base class
virtual const char *name() const = 0; // pure virtual: must override
virtual void run() { outs() << name() << ": default run\n"; }
};
struct DCE : Pass {
const char *name() const override { return "dce"; }
void run() override { outs() << "dce: removing dead code\n"; }
};
struct Verify : Pass {
const char *name() const override { return "verify"; } // uses default run()
};
int main() {
std::unique_ptr<Pass> Passes[] = {std::make_unique<DCE>(), std::make_unique<Verify>()};
for (auto &P : Passes)
P->run(); // calls the right version through the vtable
}
dce: removing dead code
verify: default run
flowchart LR
P["Pass object<br/>(hidden vtable pointer)"] --> VT["DCE vtable"]
VT --> R["run → DCE::run"]
VT --> N["name → DCE::name"]
VT --> D["~ → DCE::~DCE"]
| Keyword | Meaning |
|---|---|
virtual | Call is resolved at run time from the object's real type |
= 0 | Pure virtual; the class is abstract |
override | Compiler checks this really overrides a base function; always write it |
final | Cannot be overridden further |
virtual ~Base() | Needed so delete through a base pointer runs the derived destructor |
Each class with virtual functions has a vtable (table of function pointers); each object holds a hidden pointer to it. A virtual call costs one indirect call.
LLVM note: the IR hierarchy (Value, Instruction, ...) deliberately does not use virtual functions for most operations, to save memory and time. Instead each object stores a kind number and uses LLVM-Style RTTI. Virtual functions appear in other places, e.g. TargetLowering, raw_ostream and legacy passes.
Sources: cppreference: virtual function specifier, Wikipedia: Virtual method table
A Real Hierarchy
AllocaInst derives from UnaryInstruction, which derives from Instruction:
class AllocaInst : public UnaryInstruction {
classDiagram
Value <|-- User
User <|-- Instruction
Instruction <|-- UnaryInstruction
UnaryInstruction <|-- AllocaInst
UnaryInstruction <|-- LoadInst
Instruction <|-- StoreInst
Sources: llvm/include/llvm/IR/Instructions.h:65
The Rule of Zero, Three and Five
A class that manages a resource directly may need five special members: destructor, copy constructor, copy assignment, move constructor, move assignment.
| Rule | Advice |
|---|---|
| Zero | Prefer members that manage themselves (std::unique_ptr, SmallVector, std::string); then write none of the five |
| Three / Five | If you write one of them, think about all of them |
= delete | Forbid copying when it makes no sense: LLVM IR objects such as Instruction cannot be copied |
// illustrative
struct NoCopy {
NoCopy() = default;
NoCopy(const NoCopy &) = delete; // no copies
NoCopy &operator=(const NoCopy &) = delete;
};
Sources: cppreference: The rule of three/five/zero
Common Traps
- Forgetting
virtualon a base destructor. - Forgetting
override, so a typo silently creates a new function instead of overriding. - Calling a virtual function from a constructor: it calls the base version.
- Slicing: copying a
Derivedinto aBasevalue drops the derived part; use pointers or references.
Key Points
- Constructors acquire, destructors release, automatically and in reverse order: that is RAII.
virtual+overridegive run-time dispatch through a vtable; base classes need virtual destructors.- LLVM IR classes avoid virtual functions and copying; they use kind numbers and
isa/cast.
Ownership and Move Semantics
Relevant source files
The following files were used as context for generating this wiki page:
- llvm/include/llvm/Support/Casting.h
- cppreference: std::unique_ptr
- cppreference: std::move
- cppreference: Move constructors
- cppreference: Value categories
- Book: Scott Meyers, Effective Modern C++, chapters 4-5
Every object must eventually be destroyed exactly once. Ownership answers "who destroys it?". Modern C++ makes the owner explicit with std::unique_ptr and transfers ownership cheaply with move semantics. LLVM adds its own rule on top: most IR objects are owned by their parent (a module owns its functions, a block owns its instructions), so you rarely delete anything yourself.
Purpose and Scope
This page covers stack versus heap, raw pointers versus owning pointers, std::unique_ptr, std::move and rvalue references, moved-from objects, and how ownership works for LLVM IR objects. Containers are on LLVM Data Structures.
The House Deed Analogy
| Property | C++ |
|---|---|
| A house has exactly one deed | An object has exactly one owner (unique_ptr) |
| Visitors may know the address without owning it | Raw pointers and references are non-owning |
| Selling the house hands over the deed; the seller has none left | Moving a unique_ptr |
| When the owner leaves for good, the house is demolished | The owner's destructor deletes the object |
Stack and Heap
flowchart LR
subgraph Stack["Stack: automatic"]
S1["int X = 5;"]
S2["SmallVector<int, 8> V;"]
end
subgraph Heap["Heap: dynamic"]
H1["new Node / make_unique<Node>()"]
end
S1 -.->|"freed when scope ends"| E1["automatic"]
H1 -.->|"freed when the owner is destroyed"| E2["unique_ptr destructor"]
| Stack | Heap | |
|---|---|---|
| Lifetime | Ends at the closing } | Until someone deletes it |
| Speed | Very fast | Allocation costs time |
| Size | Must be known at compile time, keep it modest | Any |
Prefer the stack. When you need the heap, let a unique_ptr own the object. Avoid writing new and delete by hand.
unique_ptr and Move
// example: move
#include "llvm/Support/raw_ostream.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
struct Node {
std::string Name;
explicit Node(std::string N) : Name(std::move(N)) { outs() << "make " << Name << "\n"; }
~Node() { outs() << "free " << Name << "\n"; }
};
std::unique_ptr<Node> build(const char *N) { return std::make_unique<Node>(N); }
int main() {
std::unique_ptr<Node> A = build("a");
std::unique_ptr<Node> B = std::move(A); // ownership moves to B
outs() << "A is " << (A ? "set" : "empty") << ", B owns " << B->Name << "\n";
std::vector<std::unique_ptr<Node>> List;
List.push_back(std::move(B)); // now the vector owns it
List.push_back(build("b"));
outs() << "list size " << List.size() << "\n";
} // vector destroyed: frees both
make a
A is empty, B owns a
make b
list size 2
free a
free b
sequenceDiagram
participant A as A
participant B as B
participant L as List
A->>B: std::move(A): B owns "a", A is null
B->>L: push_back(std::move(B)): List owns "a"
L->>L: end of main: List destroys its elements
| Operation | Allowed? | Why |
|---|---|---|
auto B = A; (copy a unique_ptr) | No, compile error | Two owners would delete twice |
auto B = std::move(A); | Yes | Ownership transfers; A becomes null |
Node *Raw = B.get(); | Yes | A non-owning pointer for looking |
B.release() | Yes, but rarely | Gives up ownership without deleting: now you must delete |
Sources: cppreference: std::unique_ptr
What std::move Really Does
std::move(X) does not move anything by itself. It only casts X to an rvalue reference (T &&), meaning "you may steal from this". The type's move constructor then steals the contents, for example a std::string's heap buffer, instead of copying them.
| Expression | Category | Meaning |
|---|---|---|
X (a named variable) | lvalue | Has a name; still used later, so copy it |
std::move(X), a returned temporary | rvalue | About to disappear, so its insides can be taken |
After a move, the source is in a "valid but unspecified" state: you may assign to it or destroy it, but don't read its value. (unique_ptr is a special case: a moved-from one is guaranteed to be null.)
Returning a local by value (return Result;) moves or elides the copy automatically; don't write return std::move(Result);.
Sources: cppreference: std::move, cppreference: Value categories
Ownership in LLVM IR
flowchart TD
C["LLVMContext<br/>owns types and constants"] --- M["Module<br/>(often held in std::unique_ptr<Module>)"]
M -->|"owns"| F["Function"]
F -->|"owns"| BB["BasicBlock"]
BB -->|"owns"| I["Instruction"]
| Task | Call | Effect |
|---|---|---|
| Create and insert an instruction | IRBuilder or X::Create(..., InsertBefore) | The parent block owns it |
| Unlink and destroy | I->eraseFromParent() | Removes from the block and deletes |
| Unlink but keep | I->removeFromParent() | Now you own it and must insert or delete it |
| Load a module | parseIRFile(...) returns std::unique_ptr<Module> | You own the module |
So in a pass you hold plain Instruction * pointers that don't own anything, and you never delete an instruction directly. Before erasing, make sure nothing still uses it: call I->replaceAllUsesWith(New) first. Keeping a pointer to an erased instruction is a dangling pointer, the most common crash in new passes.
LLVM's casting functions even have a unique_ptr overload, cast<To>(std::unique_ptr<From> &&), which moves ownership while it casts.
Sources: llvm/include/llvm/Support/Casting.h:577
Common Traps
- Using a variable after
std::movefrom it. - Keeping
Instruction *pointers in a container and then erasing those instructions. std::shared_ptr"to be safe": LLVM code almost never needs shared ownership, and it costs reference counting.- Taking a
StringReforArrayRefto a temporary that dies at the end of the statement (see LLVM Data Structures).
Key Points
- Every object has one owner;
unique_ptrmakes that explicit and deletes automatically. std::movecasts to an rvalue so the contents can be taken; don't read a moved-from object.- IR objects are owned by their parent; use
eraseFromParent, notdelete, and replace uses first.
Templates and Lambdas
Relevant source files
The following files were used as context for generating this wiki page:
A template is code written once for any type: the compiler stamps out a separate copy for each type you use it with. A lambda is a small unnamed function written inline. LLVM uses both constantly: SmallVector<T, N>, DenseMap<K, V>, isa<T>, cast<T> are templates, and analysis code passes lambdas to helpers like any_of.
Purpose and Scope
This page covers function templates, class templates and non-type parameters, reading template error messages, lambdas and captures, function_ref, and the CRTP pattern LLVM uses for passes. The containers themselves are on LLVM Data Structures.
The Cookie Cutter Analogy
| Kitchen | Templates |
|---|---|
| A cookie cutter | The template |
| Pressing it into chocolate dough or ginger dough | Instantiating it with int or StringRef |
| Each cookie is a separate object | Each instantiation is separate compiled code |
| A cutter that needs a size | A non-type parameter, like the N in SmallVector<T, N> |
Templates and Lambdas in One Program
// example: templates
#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;
template <typename T> T biggest(T A, T B) { return A < B ? B : A; } // function template
template <typename T, unsigned N> struct Box { // class template
T Items[N];
unsigned size() const { return N; }
};
int countIf(const SmallVectorImpl<int> &V, function_ref<bool(int)> Pred) {
int C = 0;
for (int X : V)
if (Pred(X)) ++C;
return C;
}
int main() {
outs() << biggest(3, 7) << " " << biggest('a', 'z') << "\n";
Box<int, 3> B{{1, 2, 3}};
outs() << "box " << B.size() << "\n";
SmallVector<int, 8> V = {5, 12, 7, 20, 3};
int Limit = 6;
auto Big = [Limit](int X) { return X > Limit; }; // captures Limit by value
outs() << "big " << countIf(V, Big) << "\n";
int Sum = 0;
std::for_each(V.begin(), V.end(), [&Sum](int X) { Sum += X; }); // by reference
outs() << "sum " << Sum << "\n";
std::sort(V.begin(), V.end());
outs() << "sorted:";
for (int X : V) outs() << " " << X;
outs() << "\n";
}
7 z
box 3
big 3
sum 47
sorted: 3 5 7 12 20
flowchart LR
T["template biggest<T>"] -->|"biggest(3, 7)"| I1["biggest<int> compiled"]
T -->|"biggest('a', 'z')"| I2["biggest<char> compiled"]
The compiler deduced T from the arguments. Templates must be visible where they are used, which is why LLVM's ADT headers contain all their code.
Sources: cppreference: Templates
Function Signatures Use the Base Class
countIf takes const SmallVectorImpl<int> &, not SmallVector<int, 8>. SmallVectorImpl<T> is the base class of every SmallVector<T, N> whatever its N, so one function accepts them all. This is LLVM's own rule: don't put the small size N into function parameter types.
Sources: llvm/include/llvm/ADT/SmallVector.h:592, llvm/include/llvm/ADT/SmallVector.h:1249
Lambdas and Captures
[captures](parameters) -> return_type { body }
| Capture | Meaning | Watch out |
|---|---|---|
[] | Nothing | |
[X] | Copy of X | Copy made when the lambda is created |
[&X] | Reference to X | X must outlive the lambda |
[=] / [&] | Everything used, by copy / by reference | Convenient; LLVM code usually lists captures explicitly |
[this] | The current object |
Sources: cppreference: Lambda expressions
function_ref
function_ref<bool(int)> is LLVM's cheap, non-owning reference to "anything callable with this signature" (lambda, function, functor). Unlike std::function it never allocates. Like StringRef, it doesn't own what it points to, so only use it as a parameter, never store it after the call returns.
Sources: llvm/include/llvm/ADT/STLFunctionalExtras.h:37
CRTP: How Passes Get Their Name
New-pass-manager passes derive from a template instantiated with themselves:
// illustrative
struct MyPass : OptionalPassInfoMixin<MyPass> { ... };
This is the curiously recurring template pattern: the base class template knows the derived type at compile time, so it can supply name() and other boilerplate without virtual functions. See LLVM IR: Writing a Pass.
Sources: Wikipedia: Curiously recurring template pattern
Reading Template Errors
Template errors are long because they show every step of instantiation. Read them like this:
flowchart TD
E["Long error output"] --> F["Find the FIRST 'error' line"]
F --> L["Find the line in YOUR file<br/>('required from here' / 'see reference to ... being compiled')"]
L --> W["Ask: what type did I pass,<br/>and what does the template need from it?"]
Common Traps
- Capturing a local by reference in a lambda that outlives it.
- Storing a
function_ref(orStringRef/ArrayRef) in a member. - Putting template definitions in a
.cppfile: other files can't instantiate them.
Key Points
- Templates generate code per type; class templates can take values like
N. - Lambdas capture by copy or reference;
function_refpasses them cheaply. - Take
SmallVectorImpl<T> &in function signatures; passes use CRTP mixins.
LLVM Data Structures (ADT)
Relevant source files
The following files were used as context for generating this wiki page:
LLVM's llvm/ADT/ directory ("abstract data types") holds containers tuned for compilers: lots of small collections, lots of string lookups, and no time to waste on heap allocation. You will use five of them every day.
Purpose and Scope
This page covers SmallVector, ArrayRef, StringRef, DenseMap and Twine, when to use each, and their lifetime traps. Iterating over them is on Iterators and Ranges.
The Five Everyday Types
| Type | Owns data? | Think of it as | Use for |
|---|---|---|---|
SmallVector<T, N> | Yes | std::vector with room for N elements inside the object | Local lists that are usually short |
ArrayRef<T> | No | (pointer, length) view of any array | Read-only array parameters |
StringRef | No | (pointer, length) view of characters | String parameters and names |
DenseMap<K, V> | Yes | Fast hash map | Pointer- or integer-keyed maps |
Twine | No | A lazy "string to be built" | Building messages and names as arguments |
// example: adt
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
int sum(ArrayRef<int> A) { int S = 0; for (int X : A) S += X; return S; }
void report(const Twine &Msg) { outs() << Msg.str() << "\n"; }
int main() {
SmallVector<int, 4> V = {1, 2, 3, 4};
outs() << "capacity " << V.capacity() << "\n";
V.push_back(5); // 5th element: moves to the heap
outs() << "size " << V.size() << ", grew to heap\n";
int Arr[] = {10, 20};
outs() << "sum " << sum(V) << " " << sum(Arr) << " " << sum({7, 8}) << "\n";
StringRef S = "llvm.memcpy.p0";
auto [Head, Rest] = S.split('.');
outs() << Head << " | " << Rest << " | " << S.size() << " | " << S.drop_front(5) << "\n";
DenseMap<StringRef, unsigned> Counts;
for (StringRef Op : {"add", "load", "add", "store", "add"})
++Counts[Op];
outs() << "add " << Counts["add"] << ", lookup mul found " << Counts.count("mul") << "\n";
report("pass " + Twine(3) + " of " + Twine(7));
}
capacity 4
size 5, grew to heap
sum 15 30 15
llvm | memcpy.p0 | 14 | memcpy.p0
add 3, lookup mul found 0
pass 3 of 7
SmallVector
flowchart LR
subgraph Small["SmallVector<int, 4> with 3 elements"]
H1["begin, size, capacity"] --> I1["inline storage: 1 2 3 _"]
end
subgraph Big["after growing past 4"]
H2["begin, size, capacity"] --> HP["heap buffer: 1 2 3 4 5 ..."]
end
The first N elements live inside the object, usually on the stack. Only when it grows past N does it allocate. Pick N so the common case fits (LLVM code often writes SmallVector<Value *, 8>, or leaves N out to let LLVM choose). In function parameters write SmallVectorImpl<T> &, see Templates and Lambdas.
Sources: llvm/include/llvm/ADT/SmallVector.h:592, llvm/include/llvm/ADT/SmallVector.h:1249
ArrayRef and StringRef: Views
Both are just a pointer and a length. Copying them is free, which is why they are passed by value. One ArrayRef<int> parameter accepts a SmallVector, a std::vector, a C array or {7, 8}.
flowchart LR
SR["StringRef<br/>Data ptr | Length = 6"] --> BUF["...'m' 'e' 'm' 'c' 'p' 'y'... (owned by someone else)"]
StringRef methods you will use: starts_with, ends_with, split, drop_front, substr, trim, getAsInteger, str() (copy to std::string), ==.
The lifetime trap. A view must not outlive the data it points to:
// illustrative: BUG
StringRef getName() {
std::string S = "temp";
return S; // StringRef to S, but S is destroyed here: dangling
}
Store a std::string (or SmallString) when you need to keep text; use StringRef to look at it.
Sources: llvm/include/llvm/ADT/StringRef.h:56-69, llvm/include/llvm/ADT/ArrayRef.h:40
DenseMap
A hash map stored in one flat array (open addressing), which makes it much faster and more cache-friendly than std::map or std::unordered_map for small keys such as pointers.
| Do | Don't |
|---|---|
Key by Value *, BasicBlock *, integers, StringRef | Key by large objects |
Use count(K) or find(K) to test membership | Use M[K] just to look: it inserts a default value |
| Re-find after inserting | Keep pointers/iterators across insertions: they may move |
Related: DenseSet, SmallPtrSet (small set of pointers), StringMap (owns its string keys), MapVector (insertion order).
Sources: llvm/include/llvm/ADT/DenseMap.h:831
Twine
A Twine is a tree of pieces to concatenate, built on the stack and only turned into a string when someone needs it. Functions that take names (setName, createStringError, IRBuilder::CreateAdd(..., "sum")) take const Twine &, so callers can write "x." + Twine(I) without building a temporary string.
Rule: only use Twine as a const Twine & parameter; never store one in a variable, because its pieces are temporaries.
Sources: llvm/include/llvm/ADT/Twine.h:82
Choosing a Container
flowchart TD
Q["What do you need?"] --> L["A list"]
Q --> M["A map / set"]
Q --> S["Text"]
L --> L1{"Own it?"}
L1 -->|"yes"| SV["SmallVector<T, N>"]
L1 -->|"no, just read"| AR["ArrayRef<T>"]
M --> M1{"Key type"}
M1 -->|"pointer / int"| DM["DenseMap / DenseSet / SmallPtrSet"]
M1 -->|"string, owned"| SM["StringMap"]
S --> S1{"Own it?"}
S1 -->|"yes"| ST["std::string / SmallString"]
S1 -->|"no, parameter"| SR2["StringRef (or const Twine & to build)"]
Key Points
SmallVectoravoids heap allocation for short lists; takeSmallVectorImpl<T> &in APIs.ArrayRef,StringRefandTwineare non-owning views: pass them, don't store them past their data's life.DenseMapis the default map;M[K]inserts, so usefind/countto look.
LLVM-Style RTTI: isa, cast, dyn_cast
Relevant source files
The following files were used as context for generating this wiki page:
In a pass you constantly hold a Value * or Instruction * and need to ask "is this actually a load?". Standard C++ answers with dynamic_cast, but LLVM is built with C++ RTTI turned off. Instead, every class in a hierarchy stores a small kind number, and three templates use it: isa<>, cast<> and dyn_cast<>. You will write these more than almost anything else.
Purpose and Scope
This page covers the three casting operators and their null-tolerant variants, how classof makes them work, how to add LLVM-style RTTI to your own classes, and how IR classes do it. Class hierarchies in general are on Classes and RAII.
The Badge Analogy
| Office | LLVM-style RTTI |
|---|---|
| Everyone wears a badge with their job printed on it | Each object stores a kind (ValueID) |
| "Are you a nurse?" — look at the badge | isa<Nurse>(P) |
| "You're a nurse, take this patient" — wrong if not | cast<Nurse>(P) (asserts) |
| "If you're a nurse, take this patient; otherwise no one" | dyn_cast<Nurse>(P) (returns null) |
The Three Operators
| Call | Returns | If the type is wrong | Use when |
|---|---|---|---|
isa<T>(V) | bool | false | You only need to test |
cast<T>(V) | T * | Assertion failure in debug builds | You know it's a T |
dyn_cast<T>(V) | T * or nullptr | nullptr | It might be a T |
isa_and_nonnull<T>(V) | bool | false, also false if V is null | V may be null |
dyn_cast_if_present<T>(V) | T * or nullptr | nullptr, also if V is null | V may be null |
isa, cast and dyn_cast themselves must not be given a null pointer.
// illustrative: the everyday pattern in a pass
for (Instruction &I : instructions(F)) {
if (auto *LI = dyn_cast<LoadInst>(&I)) { // "if it is a load..."
Value *Ptr = LI->getPointerOperand();
...
} else if (isa<StoreInst>(I)) {
...
}
}
Sources: llvm/include/llvm/Support/Casting.h:547, llvm/include/llvm/Support/Casting.h:559-577, llvm/include/llvm/Support/Casting.h:643-655
How It Works: classof
isa<T>(V) simply calls the static function T::classof(V). Each class answers by looking at the kind stored in the object.
flowchart LR
C["isa<AllocaInst>(V)"] --> CO["AllocaInst::classof(V)"]
CO --> Q1{"isa<Instruction>(V)?"}
Q1 -->|"no"| F["false"]
Q1 -->|"yes"| Q2{"getOpcode() == Alloca?"}
Q2 -->|"yes"| T["true"]
Q2 -->|"no"| F
Here is the real code from AllocaInst:
// Methods for support type inquiry through isa, cast, and dyn_cast:
static bool classof(const Instruction *I) {
return (I->getOpcode() == Instruction::Alloca);
}
static bool classof(const Value *V) {
return isa<Instruction>(V) && classof(cast<Instruction>(V));
}
The kind lives in Value: an enum ValueTy lists every value kind, and getValueID() returns it. Checking a kind is one load and a compare, much cheaper than dynamic_cast, and it needs no vtable.
Sources: llvm/include/llvm/IR/Instructions.h:165-171, llvm/include/llvm/IR/Value.h:524, llvm/include/llvm/IR/Value.h:543
Adding It to Your Own Classes
The recipe from How to set up LLVM-style RTTI:
- Put an enum of kinds in the base class, one entry per concrete class.
- Store the kind in the base; the constructor takes it.
- Give each derived class
static bool classof(const Base *)that checks the kind.
// example: casting
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
class Shape {
public:
enum ShapeKind { SK_Circle, SK_Square };
ShapeKind getKind() const { return Kind; }
protected:
explicit Shape(ShapeKind K) : Kind(K) {}
private:
const ShapeKind Kind;
};
class Circle : public Shape {
public:
explicit Circle(int R) : Shape(SK_Circle), Radius(R) {}
int Radius;
static bool classof(const Shape *S) { return S->getKind() == SK_Circle; }
};
class Square : public Shape {
public:
explicit Square(int S) : Shape(SK_Square), Side(S) {}
int Side;
static bool classof(const Shape *S) { return S->getKind() == SK_Square; }
};
void describe(const Shape *S) {
if (const auto *C = dyn_cast<Circle>(S))
outs() << "circle radius " << C->Radius << "\n";
else
outs() << "square side " << cast<Square>(S)->Side << "\n";
}
int main() {
Circle C(3);
Square Q(4);
const Shape *All[] = {&C, &Q};
for (const Shape *S : All)
describe(S);
outs() << "isa circle: " << isa<Circle>(All[0]) << " " << isa<Circle>(All[1]) << "\n";
const Shape *None = nullptr;
outs() << "nonnull: " << isa_and_nonnull<Circle>(None) << "\n";
}
circle radius 3
square side 4
isa circle: 1 0
nonnull: 0
For a class with subclasses of its own, classof checks a range of kinds (K >= SK_FirstX && K <= SK_LastX); this is exactly how Value.h handles groups such as constants.
Comparison with dynamic_cast
dynamic_cast |
dyn_cast |
|
|---|---|---|
| Needs C++ RTTI and virtual functions | Yes | No |
| Cost | Walks type info at run time | One compare on a stored kind |
| Works on classes you add | Automatically | After you write classof |
| Available in LLVM builds | No (RTTI off) | Yes |
Sources: cppreference: dynamic_cast, Wikipedia: Run-time type information
Common Traps
- Using
castwhen you aren't sure: release builds don't check, so a wrongcastis undefined behaviour. - Testing with
isaand then callingcastagain: write onedyn_castinstead. - Passing null to
isa/cast/dyn_cast: use the_and_nonnull/_if_presentforms. - Forgetting
classofin a new subclass: compile errors mentionclassof.
Key Points
isatests,castconverts and asserts,dyn_castconverts or returns null.- They work through static
classoffunctions checking a kind stored in the object, with no C++ RTTI. - Add LLVM-style RTTI to your own hierarchy with a kind enum and
classof.
Errors, Output and Assertions
Relevant source files
The following files were used as context for generating this wiki page:
LLVM is compiled without C++ exceptions, so functions that can fail return their error as a value: llvm::Error when there is nothing else to return, llvm::Expected<T> when there is. For programmer mistakes ("this can never happen") LLVM uses assert and llvm_unreachable instead. For printing it uses raw_ostream rather than iostream. This page shows all three.
Purpose and Scope
This page covers recoverable errors (Error, Expected<T>, createStringError, toString, handleAllErrors, cantFail), programmer errors (assert, llvm_unreachable, report_fatal_error) and output (outs(), errs(), dbgs(), raw_string_ostream).
The Parcel Delivery Analogy
| Delivery | LLVM |
|---|---|
| You get either the parcel or a "sorry, we missed you" card | Expected<T>: either a T or an Error |
| You must read the card; you can't just throw it away | An Error must be checked or LLVM aborts in debug builds |
| The van falling off a bridge | A bug: assert / llvm_unreachable crash immediately |
Two Kinds of Failure
flowchart TD
F["Something went wrong"] --> Q{"Could correct input cause it?<br/>(bad file, invalid IR, user typo)"}
Q -->|"yes: recoverable"| E["Return Error / Expected<T><br/>caller decides what to do"]
Q -->|"no: a bug in our code"| A["assert(cond && \"msg\")<br/>or llvm_unreachable(\"msg\")"]
Error and Expected
// example: errors
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
Expected<int> parseCount(StringRef S) {
int V;
if (S.getAsInteger(10, V)) // returns true on failure
return createStringError("not a number: '" + S + "'");
if (V < 0)
return createStringError("negative count: " + Twine(V));
return V; // success: implicit Expected<int>
}
Error checkAll(ArrayRef<StringRef> Inputs) {
for (StringRef In : Inputs) {
Expected<int> N = parseCount(In);
if (!N)
return N.takeError(); // pass the error up
}
return Error::success();
}
int main() {
for (StringRef In : {"12", "abc", "-4"}) {
Expected<int> N = parseCount(In);
if (N)
outs() << "ok " << *N << "\n";
else
outs() << "error: " << toString(N.takeError()) << "\n";
}
if (Error E = checkAll({"1", "2", "x"}))
outs() << "checkAll failed: " << toString(std::move(E)) << "\n";
int Sure = cantFail(parseCount("7")); // "this cannot fail"
outs() << "sure " << Sure << "\n";
}
ok 12
error: not a number: 'abc'
error: negative count: -4
checkAll failed: not a number: 'x'
sure 7
| Tool | Meaning |
|---|---|
Expected<T> | Holds a T or an error; if (N) tests success, *N reads the value |
N.takeError() | Take the error out (to return it or handle it) |
Error::success() | "No error" |
if (Error E = f()) | An Error is true when it holds a failure |
createStringError(Twine) | Make a simple error with a message |
toString(Error) | Consume the error and get its message |
handleAllErrors(E, handlers...) | Dispatch on error type |
logAllUnhandledErrors(E, errs(), "prefix: ") | Print and consume |
cantFail(X) | Assert X succeeded and unwrap it |
flowchart LR
C["Expected<int> N = parseCount(s)"] --> T{"if (N)"}
T -->|"true"| V["use *N"]
T -->|"false"| E["N.takeError()"]
E --> H1["return it upward"]
E --> H2["toString / log it"]
The checked rule. Every Error must be looked at before it is destroyed, and every Expected checked before use. In builds with LLVM's ABI-breaking checks (debug builds by default) forgetting this aborts with "Program aborted due to an unhandled Error". This catches ignored failures early.
Sources: llvm/include/llvm/Support/Error.h:159, llvm/include/llvm/Support/Error.h:485, llvm/include/llvm/Support/Error.h:769, llvm/include/llvm/Support/Error.h:1013, llvm/include/llvm/Support/Error.h:1088, llvm/include/llvm/Support/Error.h:1339
Programmer Errors: assert and llvm_unreachable
// illustrative
assert(Idx < Ops.size() && "operand index out of range"); // message as a string literal
switch (Kind) {
case SK_Circle: return area(cast<Circle>(S));
case SK_Square: return area(cast<Square>(S));
}
llvm_unreachable("unknown shape kind"); // after a fully covered switch
| Tool | When it fires | In release builds |
|---|---|---|
assert(cond && "msg") | cond is false | Removed (NDEBUG) |
llvm_unreachable("msg") | Control reaches it | Becomes an optimisation hint; reaching it is UB |
report_fatal_error("msg") | Always | Always prints and exits; for unrecoverable user-facing problems in tools |
Many LLVM developers build with -DLLVM_ENABLE_ASSERTIONS=ON while developing so these checks run; release compilers usually ship without them.
Sources: llvm/include/llvm/Support/ErrorHandling.h:164-171
Output: raw_ostream
// example: output
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Format.h"
#include <string>
using namespace llvm;
int main() {
outs() << "count " << 42 << ", hex " << format_hex(255, 6) << "\n";
std::string Buf;
raw_string_ostream OS(Buf); // write into a std::string
OS << "inst" << 3;
outs() << "built '" << OS.str() << "'\n";
outs().indent(4) << "indented\n";
}
count 42, hex 0x00ff
built 'inst3'
indented
| Stream | Goes to | Use |
|---|---|---|
outs() | stdout | Normal tool output |
errs() | stderr, unbuffered | Warnings, errors |
dbgs() | stderr, only with -debug | Debug traces inside LLVM_DEBUG(...) |
raw_string_ostream | A std::string | Building text |
raw_fd_ostream | A file | Writing output files |
Every IR object can print itself: errs() << *I << "\n"; prints an instruction, F.print(errs()) a function, and I->dump() (in assertion builds) prints to stderr from a debugger.
// illustrative: debug output that only appears with -debug-only=my-pass
#define DEBUG_TYPE "my-pass"
LLVM_DEBUG(dbgs() << "visiting " << *I << "\n");
Sources: llvm/include/llvm/Support/raw_ostream.h:53, llvm/include/llvm/Support/raw_ostream.h:613-620, llvm/include/llvm/Support/raw_ostream.h:664
Common Traps
- Ignoring an
ErrororExpectedreturn: aborts in debug builds. - Reading
*Nwithout checkingif (N)first. - Side effects inside
assert(...): they disappear in release builds. - Using
std::coutin LLVM library code; useraw_ostream.
Key Points
- Recoverable failures return
Error/Expected<T>, which must always be checked. - Bugs are caught with
assert(cond && "msg")andllvm_unreachable. - Print with
outs(),errs(),dbgs(); every IR object can be streamed with<<.
Iterators and Ranges
Relevant source files
The following files were used as context for generating this wiki page:
Most of a pass is loops: over the functions in a module, the blocks in a function, the instructions in a block, the users of a value. Modern C++ writes these with range-based for and auto, and LLVM's STLExtras.h adds helpers such as any_of, enumerate and make_early_inc_range. This page shows them, and the classic bug of deleting while iterating.
Purpose and Scope
This page covers iterators, range-based for, auto and auto &, the IR's nested ranges, STLExtras helpers, and iterator invalidation. Containers are on LLVM Data Structures.
The Bookmark Analogy
| Reading | Iterators |
|---|---|
| A bookmark marking your place | An iterator |
| Moving it to the next page | ++It |
| Reading the page it marks | *It |
| The back cover | end(): one past the last element |
| Tearing out the page the bookmark is on | Erasing the current element: the bookmark is now invalid |
Range-based for and auto
// example: ranges
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
int main() {
SmallVector<int, 8> V = {4, 8, 15, 16, 23, 42};
for (int X : V) outs() << X << " "; // copy each element
outs() << "\n";
for (int &X : V) X *= 2; // reference: modify in place
for (const auto &X : V) outs() << X << " "; // read-only, any type
outs() << "\n";
outs() << "any > 80: " << any_of(V, [](int X) { return X > 80; })
<< ", all even: " << all_of(V, [](int X) { return X % 2 == 0; }) << "\n";
for (auto [Idx, X] : enumerate(V))
if (Idx < 2) outs() << "#" << Idx << " = " << X << "\n";
SmallVector<int, 8> W = {1, 2, 3, 4, 5, 6};
erase_if(W, [](int X) { return X % 2 == 0; }); // remove evens safely
outs() << "odd:";
for (int X : W) outs() << " " << X;
outs() << "\n";
}
4 8 15 16 23 42
8 16 30 32 46 84
any > 80: 1, all even: 1
#0 = 8
#1 = 16
odd: 1 3 5
| Loop variable | Copies? | Can modify? | Use for |
|---|---|---|---|
for (int X : V) | Yes | Only the copy | Small values |
for (auto &X : V) | No | Yes | Changing elements |
for (const auto &X : V) | No | No | Large elements, read-only |
for (auto *I : Ptrs) | Copies the pointer | The pointee | Lists of pointers |
LLVM's rule for auto: use it when the type is obvious from the right-hand side (auto *LI = dyn_cast<LoadInst>(V)) or very long; write the type when it helps the reader. Always write * and & explicitly with auto.
Sources: cppreference: Range-based for loop, cppreference: auto
Walking the IR
The IR containers are all ranges, nested like this:
flowchart LR
M["for (Function &F : M)"] --> F["for (BasicBlock &BB : F)"]
F --> B["for (Instruction &I : BB)"]
B --> U["for (User *U : I.users())"]
B --> O["for (Use &Op : I.operands())"]
// illustrative
for (Function &F : M) {
if (F.isDeclaration()) continue; // no body
for (BasicBlock &BB : F)
for (Instruction &I : BB)
if (auto *CI = dyn_cast<CallInst>(&I))
errs() << F.getName() << " calls " << *CI->getCalledOperand() << "\n";
}
// instructions(F) flattens the two inner loops; successors(&BB), predecessors(&BB) walk the CFG
Functions, blocks and instructions are iterated by reference (Function &), never by value: they can't be copied.
STLExtras Helpers
| Helper | Does |
|---|---|
any_of, all_of, none_of | Test a predicate over a whole range |
find_if, count_if, is_contained | Search |
enumerate(R) | Gives (index, element) pairs |
zip(A, B) | Walks two ranges together |
reverse(R) | Backwards |
erase_if(C, Pred) | Removes matching elements from a container |
make_early_inc_range(R) | Lets you erase the current element while looping |
All of them take the whole range instead of begin()/end() pairs.
Sources: llvm/include/llvm/ADT/STLExtras.h:1739-1746, llvm/include/llvm/ADT/STLExtras.h:2554
Deleting While Iterating
// illustrative: BUG
for (Instruction &I : BB)
if (isInstructionTriviallyDead(&I))
I.eraseFromParent(); // the loop's iterator pointed at I: now dangling
sequenceDiagram
participant L as Loop iterator
participant I as Current instruction
L->>I: points at I
I->>I: eraseFromParent(): I is deleted
L->>L: ++It reads I's "next" pointer: use after free
The fix is to advance before the body runs:
// illustrative: correct
for (Instruction &I : make_early_inc_range(BB))
if (isInstructionTriviallyDead(&I))
I.eraseFromParent(); // iterator already moved on to the next instruction
The same invalidation rules apply to containers: push_back on a SmallVector or std::vector may reallocate and invalidate all iterators, pointers and references into it; inserting into a DenseMap may move every entry. Collect changes in a separate list first, then apply them after the loop, when in doubt.
Sources: llvm/include/llvm/ADT/STLExtras.h:633, cppreference: std::vector
Common Traps
for (auto X : BigThings)copies each element; useconst auto &.- Erasing inside a plain range-for: use
make_early_inc_range. - Holding
&V[0]across apush_back. - Modifying users while iterating
V->users(): copy them into aSmallVectorfirst.
Key Points
- Range-for with
auto &/const auto &is the normal loop; IR objects are iterated by reference. STLExtrasgives whole-range helpers likeany_of,enumerate,erase_if.- Erasing invalidates iterators: use
make_early_inc_range, or collect first and change after.
Building, Debugging and Exercises
Relevant source files
The following references were used as context for generating this wiki page:
This page shows how to compile your own small programs against an LLVM build, how to debug the usual crashes, a set of exercises that follow the wiki, and a glossary.
Purpose and Scope
This page covers compiling against LLVM headers and libraries, the build settings that matter (assertions, exceptions, RTTI), debugging tools, coding style, exercises with hints, and a glossary. Writing a full pass is in the LLVM IR wiki.
Compiling Against LLVM
flowchart LR
S["your.cpp"] --> C["compiler<br/>+ -I llvm/include<br/>+ -I build/include (generated config)"]
C --> O["your.obj"]
O --> L["linker<br/>+ LLVMSupport.lib (+ LLVMCore.lib for IR)<br/>+ system libraries"]
L --> E["your.exe"]
Every // example: program in this wiki was built on Windows with exactly this command, from a Visual Studio x64 developer prompt (vcvars64.bat):
cl /nologo /std:c++17 /O2 /MD /EHs-c- /D_HAS_EXCEPTIONS=0 ^
/I C:\source\llvm-project\llvm\include /I C:\source\llvm-project\build\include ^
example.cpp ^
/link /LIBPATH:C:\source\llvm-project\build\Release\lib ^
LLVMSupport.lib LLVMDemangle.lib ntdll.lib ws2_32.lib psapi.lib shell32.lib ole32.lib uuid.lib advapi32.lib
| Part | Why |
|---|---|
/std:c++17 | LLVM's language level at this commit |
two /I paths | Source headers, plus generated headers such as llvm/Config/llvm-config.h in the build directory |
/MD | Must match the runtime library LLVM was built with |
/EHs-c- /D_HAS_EXCEPTIONS=0 | LLVM is built without exceptions; match it |
LLVMSupport.lib | raw_ostream, Error, StringRef helpers, and more |
On Linux or macOS the easiest route is llvm-config:
clang++ example.cpp $(llvm-config --cxxflags --ldflags --libs support core) -o example
For anything bigger, use CMake with find_package(LLVM REQUIRED CONFIG), as on the LLVM IR: Writing a Pass page.
Sources: LLVM: Getting Started
Build Settings That Change Behaviour
| CMake option | Effect for you |
|---|---|
-DLLVM_ENABLE_ASSERTIONS=ON | assert, cast<> checks and dump() work; strongly recommended while learning |
-DCMAKE_BUILD_TYPE=Debug | Debug info, no optimisation; large and slow but debuggable |
RelWithDebInfo | Optimised with debug info: a good everyday choice |
LLVM_ENABLE_RTTI (default OFF) | Your code must be built without RTTI too, or link errors about typeinfo appear |
The local build used for this wiki is a Release build, so its cast<> assertions are compiled out.
Debugging Common Crashes
flowchart TD
C["Crash or wrong output"] --> A{"Assertion message?"}
A -->|"yes"| R["Read it: it names the broken rule<br/>(e.g. 'cast<Ty>() argument of incompatible type')"]
A -->|"no"| D["Run in a debugger; get a backtrace"]
D --> U{"Use-after-free / garbage values?"}
U -->|"yes"| S["Build with AddressSanitizer;<br/>check erase-while-iterating and dangling StringRef/ArrayRef"]
U -->|"no"| V["Print state: errs() << *I, F.dump();<br/>run 'opt -passes=verify'"]
| Tool | Catches |
|---|---|
Debugger (Visual Studio, gdb, lldb) | Where it crashed, values of variables |
AddressSanitizer (-fsanitize=address, MSVC /fsanitize=address) | Use-after-free, out-of-bounds, dangling pointers |
UndefinedBehaviorSanitizer (-fsanitize=undefined) | Signed overflow, bad shifts, misaligned access |
opt -passes='my-pass,verify' | IR your pass broke |
LLVM_DEBUG(dbgs() << ...) with -debug-only=my-pass | Tracing your pass |
Style Reviewers Expect
From the LLVM Coding Standards:
| Rule | Example |
|---|---|
Variables and types CamelCase, starting upper case | BasicBlock *EntryBB; |
| Functions start lower case | getOperand(), eraseFromParent() |
| Early returns instead of deep nesting | if (!F.hasBody()) return false; |
No using namespace in headers | |
Format with clang-format | git clang-format before sending a patch |
| Comments are full sentences |
Modern C++ Features You Will Also See
| Feature | One-line meaning |
|---|---|
constexpr | Computed at compile time (cppreference) |
std::optional<T> | A value or nothing |
Structured bindings auto [A, B] = Pair; | Unpack a pair or struct (used on LLVM Data Structures) |
std::string_view | The standard equivalent of StringRef (cppreference) |
[[nodiscard]] | Warn if a return value is ignored; LLVM puts it on Error, Expected, isa, cast |
enum class | Scoped, strongly typed enum |
Exercises
- Pointers (Basics). Write
swapInts(int &A, int &B)andswapPtrs(int *A, int *B). Why must the pointer version check for null? - RAII (Classes). Write a
Timerclass that prints how long its scope took when destroyed. Return early from a function using it and check the message still prints. - Virtual (Classes). Remove
virtualfrom~Pass()in thevirtualexample. Why is deleting throughPass *now wrong? - Move (Ownership). Add a
std::vector<std::unique_ptr<Node>>to a class and try to copy the class. Read the error, then fix it by moving instead. - Templates (Templates). Write
template <typename T> T sumAll(ArrayRef<T>)and call it withintanddouble. - SmallVector (ADT). Make
SmallVector<int, 2>, push 3 elements, and printcapacity()after each push. Then change N to 8. (Theadtexample showed capacity 4 before growing.) - StringRef lifetime (ADT). Write a function that returns a
StringRefto a localstd::string, build it with AddressSanitizer, and watch it report the bug. - DenseMap (ADT). Count word frequencies in a sentence. Then check membership with
M["x"]and show it changedM.size(). - LLVM RTTI (Casting). Add a
Triangleto thecastingexample. Then add an abstractPolygonbetweenShapeandSquare/Triangleand give it a range-basedclassof. - Error (Errors). Write
Expected<std::pair<int,int>> parseRange(StringRef S)for"3-7", rejecting bad input andlo > hi. - Ranges (Ranges). Remove all negative numbers from a
SmallVectortwo ways: witherase_if, and with a manual loop that is correct about invalidation. - Read real code. Open
llvm/lib/Transforms/Scalar/DCE.cppand find each of: aSmallSetVector, anisa/dyn_cast, a worklist loop, andPreservedAnalyses. Then move on to LLVM IR: Writing a Pass.
Glossary
| Term | Meaning | Page |
|---|---|---|
ArrayRef<T> | Non-owning view of a contiguous array | ADT |
assert | Check a condition in builds with assertions on | Errors |
auto | Let the compiler deduce a variable's type | Ranges |
cast<T> | Convert, asserting the type is right | Casting |
classof | Static function that makes isa work for a class | Casting |
const | Cannot be modified through this name | Basics |
| CRTP | A base class template parameterised by its derived class | Templates |
DenseMap | LLVM's fast open-addressing hash map | ADT |
| Destructor | Runs automatically when an object is destroyed | Classes |
dyn_cast<T> | Convert, or null if the type is wrong | Casting |
Error / Expected<T> | LLVM's checked error values | Errors |
function_ref | Non-owning reference to something callable | Templates |
isa<T> | Test the dynamic type | Casting |
| Iterator invalidation | An iterator becoming unusable after the container changes | Ranges |
| Lambda | An inline, unnamed function object | Templates |
| lvalue / rvalue | Has a name and persists / a temporary that can be moved from | Ownership |
make_early_inc_range | Iterate while allowing erasure of the current element | Ranges |
| Move semantics | Transferring resources instead of copying | Ownership |
| ODR | One definition rule | Basics |
override | Mark a function as overriding a virtual base function | Classes |
| RAII | Resources released by destructors automatically | Classes |
| Reference | An alias that must always refer to an object | Basics |
raw_ostream | LLVM's output stream: outs(), errs(), dbgs() | Errors |
| RTTI | Run-time type information; turned off in LLVM | Casting |
SmallVector<T, N> | Vector with N elements of inline storage | ADT |
StringRef | Non-owning view of characters | ADT |
| Template | Code parameterised by types or values | Templates |
Twine | Lazy string concatenation for parameters | ADT |
| UB | Undefined behaviour | Basics |
unique_ptr | Single-owner smart pointer | Ownership |
virtual / vtable | Run-time dispatch / table of function pointers | Classes |