Book Image

LLVM Cookbook

Book Image

LLVM Cookbook

Overview of this book

Table of Contents (16 chapters)
LLVM Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Defining IR code generation methods for each AST class


Now, since the AST is ready with all the necessary information in its data structure, the next phase is to generate LLVM IR. LLVM APIs are used in this code generation. LLVM IR has a predefined format that is generated by the inbuilt APIs of LLVM.

Getting ready

You must have created the AST from any input code of the TOY language.

How to do it…

In order to generate LLVM IR, a virtual CodeGen function is defined in each AST class (the AST classes were defined earlier in the AST section; these functions are additional to those classes) as follows:

  1. Open the toy.cpp file as follows:

    $ vi toy.cpp
  2. In the BaseAST class defined earlier, append the Codegen() functions as follows:

    class BaseAST {
      …
      …
      virtual Value* Codegen() = 0;
    };
    class NumericAST : public BaseAST {
      …
      …
      virtual Value* Codegen();
    };
    class VariableAST : public BaseAST {
      …
      …
      virtual Value* Codegen();
    };

    This virtual Codegen() function is included in every AST class we...