Repository navigation
Cpp 10 build 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.
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.
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
| 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.
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 |
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 |
| 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 |
-
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.
| 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 |
- 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