Book Image

Learn LLVM 12

By : Kai Nacke
Book Image

Learn LLVM 12

By: Kai Nacke

Overview of this book

LLVM was built to bridge the gap between compiler textbooks and actual compiler development. It provides a modular codebase and advanced tools which help developers to build compilers easily. This book provides a practical introduction to LLVM, gradually helping you navigate through complex scenarios with ease when it comes to building and working with compilers. You’ll start by configuring, building, and installing LLVM libraries, tools, and external projects. Next, the book will introduce you to LLVM design and how it works in practice during each LLVM compiler stage: frontend, optimizer, and backend. Using a subset of a real programming language as an example, you will then learn how to develop a frontend and generate LLVM IR, hand it over to the optimization pipeline, and generate machine code from it. Later chapters will show you how to extend LLVM with a new pass and how instruction selection in LLVM works. You’ll also focus on Just-in-Time compilation issues and the current state of JIT-compilation support that LLVM provides, before finally going on to understand how to develop a new backend for LLVM. By the end of this LLVM book, you will have gained real-world experience in working with the LLVM compiler development framework with the help of hands-on examples and source code snippets.
Table of Contents (17 chapters)
Section 1 – The Basics of Compiler Construction with LLVM
Section 2 – From Source to Machine Code Generation
Section 3 –Taking LLVM to the Next Level

Managing source files and user messages

A real compiler must deal with many files. Usually, the developer calls the compiler with the name of the main compilation unit. This compilation unit can refer to other files, for example, via #include directives in C or import statements in Python or Modula-2. An imported module can import other modules and so on. All these files must be loaded into memory and run through the analysis stages of the compiler. During development, a developer may make syntactical or semantical errors. When detected, an error message, including the source line and a marker, should be printed. At this point, it should be obvious that this essential component is not trivial.

Luckily, LLVM comes with a solution: the llvm::SourceMgr class. A new source file is added to SourceMgr with a call to the AddNewSourceBuffer() method. Alternatively, a file can be loaded with a call to the AddIncludeFile() method. Both methods return an ID to identify the buffer. You use...