Skip to content

Instantly share code, notes, and snippets.

@kaushiks
Last active February 19, 2018 06:23
Show Gist options
  • Save kaushiks/ecdf3e80a03813414de9c1791014d636 to your computer and use it in GitHub Desktop.
Save kaushiks/ecdf3e80a03813414de9c1791014d636 to your computer and use it in GitHub Desktop.
A simple LLVM based backend compiler: Emitting a module
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/raw_ostream.h"
static llvm::LLVMContext g_context;
#define getGlobalContext() (g_context)
int main(int argc, char const* const* argv) {
using namespace std;
using namespace llvm;
auto module = unique_ptr<Module>(new Module("adder", getGlobalContext()));
auto int64 = IntegerType::get(getGlobalContext(), 64);
auto adder = cast<Function>(module->getOrInsertFunction("add", int64, int64, int64, NULL));
adder->setCallingConv(CallingConv::C);
auto args = adder->arg_begin();
auto arg0 = args++;
arg0->setName("x");
auto arg1 = args++;
arg1->setName("y");
auto block = BasicBlock::Create(getGlobalContext(), "entry", adder);
IRBuilder<> ir(block);
auto t0 = ir.CreateBinOp(Instruction::Add, &(*arg0), &(*arg1), "t0");
ir.CreateRet(t0);
module->dump();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment