Book Image

LLVM Techniques, Tips, and Best Practices Clang and Middle-End Libraries

By : Min-Yih Hsu
Book Image

LLVM Techniques, Tips, and Best Practices Clang and Middle-End Libraries

By: Min-Yih Hsu

Overview of this book

Every programmer or engineer, at some point in their career, works with compilers to optimize their applications. Compilers convert a high-level programming language into low-level machine-executable code. LLVM provides the infrastructure, reusable libraries, and tools needed for developers to build their own compilers. With LLVM’s extensive set of tooling, you can effectively generate code for different backends as well as optimize them. In this book, you’ll explore the LLVM compiler infrastructure and understand how to use it to solve different problems. You’ll start by looking at the structure and design philosophy of important components of LLVM and gradually move on to using Clang libraries to build tools that help you analyze high-level source code. As you advance, the book will show you how to process LLVM IR – a powerful way to transform and optimize the source program for various purposes. Equipped with this knowledge, you’ll be able to leverage LLVM and Clang to create a wide range of useful programming language tools, including compilers, interpreters, IDEs, and source code analyzers. By the end of this LLVM book, you’ll have developed the skills to create powerful tools using the LLVM framework to overcome different real-world challenges.
Table of Contents (18 chapters)
1
Section 1: Build System and LLVM-Specific Tooling
6
Section 2: Frontend Development
11
Section 3: "Middle-End" Development

Learning about the Expected and ErrorOr classes

As we briefly mentioned in the introduction of this section, in LLVM's code base it's pretty common to see a coding pattern where an API wants to return a result or an error if something goes wrong. LLVM tries to make this pattern more accessible by creating utilities that multiplex results and errors in a single object—they are the Expected and ErrorOr classes. Let's begin with the first one.

The Expected class

The Expected class carries either a Success result or an error—for instance, the JSON library in LLVM uses it to represent the outcome of parsing an incoming string, as shown next:

#include "llvm/Support/JSON.h"
 using namespace llvm;
…
// `InputStr` has the type of `StringRef`
Expected<json::Value> JsonOrErr = json::parse(InputStr);
if (JsonOrErr) {
  // Success!
  json::Value &Json = *JsonOrErr;
  …
} else {
  // Something...