In this recipe, you will see how IR code gets generated for an expression using the compiler frontend.
To implement LLVM IR code generation for our TOY language, proceed with the following code flow:
Open the
toy.cpp
file as follows:$ vi toy.cpp
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 theAPInt
class.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; }
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...