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