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

Generating IR code for expressions


In this recipe, you will see how IR code gets generated for an expression using the compiler frontend.

How to do it…

To implement LLVM IR code generation for our TOY language, proceed with the following code flow:

  1. Open the toy.cpp file as follows:

    $ vi toy.cpp
  2. The function to generate code for numeric values can be defined as follows:

    Value *NumericAST::Codegen() {
      return ConstantInt::get(Type::getInt32Ty(getGlobalContext()), numeric_val);
    }

    In LLVM IR, integer constants are represented by the ConstantInt class whose numeric value is held by the APInt class.

  3. The function for generating code for variable expressions can be defined as follows:

    Value *VariableAST::Codegen() {
      Value *V = Named_Values[Var_Name];
      return V ? V : 0;
    }
  4. The Codegen() function for binary expression can be defined as follows:

    Value *BinaryAST::Codegen() {
      Value *L = LHS->Codegen();
      Value *R = RHS->Codegen();
      if(L == 0 || R == 0) return 0;
      
      switch(atoi(Bin_Operator.c_str...