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 defined.

    This function returns an LLVM Value object, which represents Static Single Assignment (SSA) value in LLVM. A few more static variables are defined that will be used during Codegen.

  3. Declare the following static variables in global scope as follows:
    static Module *Module_Ob;
    static IRBuilder<> Builder(getGlobalContext());
    static std::map<std::string, Value*>Named_Values;

How it works…

The Module_Ob module contains all the functions and variables in the code.

The Builder object helps to generate LLVM IR and keeps track of the current point in the program to insert LLVM instructions. The Builder object has functions to create new instructions.

The Named_Values map keeps track of all the values defined in the current scope like a symbol table. For our language, this map will contain function parameters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.172.146