AI guide
# LLVM Essentials: Become Familiar with the LLVM Infrastructure and Start Using LLVM Libraries to Design a Compiler
## 【One-Line Pitch】
A practical, hands-on guide for developers with basic compiler knowledge who want to quickly master LLVM's modular library design and build their own compiler frontends, optimization passes, and custom backends using the LLVM infrastructure.
## 【Book Arc】
- **Opening (~0%–10%)**: Introduces LLVM's core philosophy—a modular collection of libraries rather than a monolithic compiler—and walks through the LLVM intermediate representation (IR) fundamentals, including module structure, target data layout, and the naming conventions for global (@) and local (%) variables.
- **Early (~10%–20%)**: Dives into hands-on frontend development, showing how to use LLVM's C++ APIs (IRBuilder, Module, Function, BasicBlock) to emit IR programmatically, starting with simple function creation and progressing to global variables and function arguments.
- **Early-Middle (~20%–37%)**: Covers advanced IR emission patterns: if-else control flow with PHI nodes, loop construction with induction variables, and memory operations including getelementptr (GEP) for address calculation, load, and store instructions.
- **Middle (~40%–50%)**: Explores the optimization landscape—running opt at different levels (O1, O2) and understanding what passes do (inlining, dead code elimination, constant merging)—then transitions into writing custom optimization passes using the FunctionPass infrastructure.
- **Late Middle (~50%–60%)**: Details the PassManager architecture, pass scheduling, and the AnalysisUsage mechanism for declaring pass dependencies and preserved analyses, with practical examples of loading custom passes via opt's -load option.
## 【Key Takeaways】
- **LLVM is a library collection, not a monolithic compiler** (Early): Each optimization pass is a C++ class compiled into a .o file and archived into a .a library, allowing implementers to link only the passes they need and control execution order through explicit dependency declarations.
- **The LLVM IR has a clean, predictable syntax** (Early): Global variables start with @, locals with %, and the SSA form ensures each variable is assigned exactly once—this design eliminates name clashes with reserved words and simplifies compiler implementation.
- **IRBuilder is the primary API for IR emission** (Early): The Builder object manages instruction insertion points, and the pattern of createFunc → createBB → SetInsertPoint → verifyFunction → dump() forms the skeleton of every frontend you'll write.
- **PHI nodes are essential for control flow** (Early): When emitting if-else statements, a merge block with a phi instruction selects values from different predecessor blocks, and LLVM's SmallVector containers simplify managing lists of blocks and values.
- **GEP is the universal address calculation instruction** (Early): The getelementptr instruction computes addresses for arrays, structs, and vectors using type information to determine sizes—understanding its two-parameter form (base type and indices) is critical for memory operations.
- **Optimization levels compose different pass sets** (Middle): O2 runs always-inline, globaldce, constmerge, and global value numbering passes, which can dramatically transform code—inlining function calls and eliminating redundant loads and instructions.
- **Writing a custom pass follows a fixed pattern** (Middle): Subclass FunctionPass, implement runOnFunction, declare a static char ID, register with RegisterPass, build as a shared object, and load via opt -load path/to/pass.so -passname test.ll.
- **PassManager handles scheduling and dependencies** (Middle): The PassManager efficiently schedules passes based on declared dependencies, and AnalysisUsage::addPreserved<> lets passes declare which analyses they won't invalidate, avoiding redundant recomputation.
## 【Reading Tips】
- **Skim the LLVM IR syntax sections** (Early chapters) if you're already familiar with SSA form—focus instead on the API call patterns (Builder.CreateMul, CreateICmpULT, etc.) that you'll need for your own frontend.
- **Deep-read the if-else and loop emission sections** (Early-Middle): These are the most conceptually dense parts, especially the PHI node mechanics and the createLoop function's induction variable pattern—they're the foundation for all control flow in your compiler.
- **Pay close attention to the GEP explanation** (Early): The book references the official LLVM documentation for deeper understanding, but the worked example with vector types is essential—get this right and memory operations become straightforward.
- **Follow along with the code examples** (throughout): The book provides complete, compilable C++ programs with clang++ commands—actually building and running these will cement the API patterns far better than reading alone.
- **The pass-writing chapter is the practical climax** (Middle): Work through the FnNamePrint example step-by-step, then experiment with modifying it—this is where you'll internalize the pass infrastructure that makes LLVM so powerful.
## 【Coverage Limits】
The excerpts cover LLVM IR basics, frontend IR emission, control flow, memory operations, optimization passes, and custom pass development. They do not cover the later chapters on SelectionDAG, custom target implementation, or clang's AST dump and static analysis features mentioned in the book's description.
##
Passage locations
Excerpt 1
rt with the basics, where you'll get to know all about LLVM. We then cover how you can use LLVM library calls to emit intermediate representation (IR) of sim...
View in text
Excerpt 2
16, %rsp movl $0, -4(%rbp) movl $2, %edi callq add movl %eax, %ecx movl %ecx, -8(%rbp) movl $.L.str, %edi xorl %eax, %eax movl %ecx, ...
View in text
Excerpt 3
entry); Function::arg_iterator AI = fooFunc->arg_begin(); Value *Arg1 = AI++; Value *Arg2 = AI; Value *constant = Builder.getInt32(16); Value *val ...
View in text
Excerpt 4
n. Now, run the O1 and O2 levels of optimization, as shown: $ opt -O1 -S test.ll > 1.ll $ opt -O2 -S test.ll > 2.ll The following screenshot shows the differ...
View in text