Book Image

LLVM Essentials

By : Mayur Pandey, Suyog Sarda, David Farago
Book Image

LLVM Essentials

By: Mayur Pandey, Suyog Sarda, David Farago

Overview of this book

LLVM 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 independent of a target, and then map the code generated to a backend. The book also walks you through CLANG, IR to IR transformations, advanced IR block transformations, and target machines. By the end of this book, you’ll be able to easily utilize the LLVM libraries in your own projects.
Table of Contents (14 chapters)
LLVM Essentials
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Preface
Index

Emitting a function in a module


Now that we have created a module, the next step is to emit a function. LLVM has an IRBuilder class that is used to generate LLVM IR and print it using the dump function of the Module object. LLVM provides the class llvm::Function to create a function and llvm::FunctionType() to associate a return type for the function. Let's assume that our foo() function returns an integer type.

Function *createFunc(IRBuilder<> &Builder, std::string Name) {
  FunctionType *funcType = llvm::FunctionType::get(Builder.getInt32Ty(), false);
  Function *fooFunc = llvm::Function::Create(
      funcType, llvm::Function::ExternalLinkage, Name, ModuleOb);
  return fooFunc;
}

Finally, call function verifyFunction() on fooFunc. This function performs a variety of consistency checks on the generated code, to determine if our compiler is doing everything right.

int main(int argc, char *argv[]) {
  static IRBuilder<> Builder(Context);
  Function *fooFunc = createFunc(Builder...