Share E-Book
Scan to open this page

Scan with your phone to open this page

Author: Suyog Sarda, Mayur Pandey

Annotation Become familiar with the LLVM infrastructure and start using LLVM libraries to design a compiler About This Book Learn to use the LLVM libraries to emit intermediate representation (IR) from high-level language Build your own optimization pass for better code generation Understand AST generation and use it in a meaningful wayWho This Book Is ForThis book is intended for those who already know some of the concepts of compilers and want to quickly get familiar with the LLVM infrastructure and the rich set of libraries that it provides.What You Will Learn Get an introduction to LLVM modular design and LLVM tools Convert frontend code to LLVM IR Implement advanced LLVM IR paradigms Understand the LLVM IR Optimization Pass Manager infrastructure and write an optimization pass Absorb LLVM IR transformations Understand the steps involved in converting LLVM IR to Selection DAG Implement a custom target using the LLVM infrastructure Get a grasp of C's frontend clang, an AST dump, and static analysisIn DetailLLVM is currently the point of interest for many firms, and has a very active open source community. It provides us with a compiler infrastructure that can be used to write a compiler for a language. It provides us with a set of reusable libraries that can be used to optimize code, and a target-independent code generator to generate code for different backends. It also provides us with a lot of other utility tools that can be easily integrated into compiler projects.This book details how you can use the LLVM compiler infrastructure libraries effectively, and will enable you to design your own custom compiler with LLVM in a snap.We start 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 simple and complex high-level language paradigms. Moving on, we show you how to implement optimizations at different levels, write an optimization pass, generate code that is inde

AI Reading Assistant

Whole-book reading guide from stratified index samples; jump to passages in the text

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. ##
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
Excerpt 5
ring it as an i8 struct. If we vectorize loads/stores from // such a struct we read/write packed bits disagreeing with the // unvectorized version.
View in text
Excerpt 6
from physical register to memory is called spilling. There are various algorithms to calculate which variable should be spilled from register to memory. Anot...
View in text
Excerpt 7
nt and inserted copies and loads. For our sample target, we support passing arguments through registers or via stack (remember the calling convention defined...
View in text
Excerpt 8
OYInfo add_to_library_groups = TOY 16. Create a CMakeLists.txt file: add_llvm_library(LLVMTOYDesc TOYMCTargetDesc.cpp) Build the enitre LLVM project, as fol...
View in text
Tags
AI categories
ProgrammingcompilerBackend
ISBN: 1785280805
Publisher: Packt Publishing
Publish Year: 2015
Language: English
Pages: 236
File Format: PDF
File Size: 1.4 MB
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Generating text preview…