Created
January 19, 2016 01:49
-
-
Save gligneul/c0901904738d81c63ea3 to your computer and use it in GitHub Desktop.
LLVM MCJIT Code Samples (Working!)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* LLVM 3.5 code sample using MCJit | |
* | |
* To compile, execute on terminal: | |
* clang++ -o mcjit mcjit.cpp `llvm-config --cxxflags --ldflags --libs all --system-libs` | |
*/ | |
#include <iostream> | |
#include <memory> | |
#include <llvm/ADT/StringRef.h> | |
#include <llvm/ExecutionEngine/ExecutionEngine.h> | |
#include <llvm/ExecutionEngine/MCJIT.h> | |
#include <llvm/IR/Constant.h> | |
#include <llvm/IR/IRBuilder.h> | |
#include <llvm/IR/LLVMContext.h> | |
#include <llvm/IR/Module.h> | |
#include <llvm/IR/Verifier.h> | |
#include <llvm/Support/DynamicLibrary.h> | |
#include <llvm/Support/raw_ostream.h> | |
#include <llvm/Support/TargetSelect.h> | |
void foo() { | |
std::cout << "foo()\n"; | |
} | |
int main() { | |
llvm::InitializeNativeTarget(); | |
llvm::InitializeNativeTargetAsmPrinter(); | |
llvm::InitializeNativeTargetAsmParser(); | |
auto& context = llvm::getGlobalContext(); | |
auto module = new llvm::Module("top", context); | |
llvm::IRBuilder<> builder(context); | |
auto footype = llvm::FunctionType::get(builder.getVoidTy(), false); | |
auto foofunc = llvm::Function::Create(footype, | |
llvm::Function::ExternalLinkage, "foo", module); | |
llvm::sys::DynamicLibrary::AddSymbol("foo", reinterpret_cast<void*>(foo)); | |
auto functype = llvm::FunctionType::get(builder.getInt32Ty(), false); | |
auto mainfunc = llvm::Function::Create(functype, | |
llvm::Function::ExternalLinkage, "main", module); | |
auto entryblock = llvm::BasicBlock::Create(context, "entry", mainfunc); | |
builder.SetInsertPoint(entryblock); | |
builder.CreateCall(foofunc); | |
builder.CreateRet(llvm::ConstantInt::get(builder.getInt32Ty(), 0)); | |
std::string error; | |
llvm::raw_string_ostream error_os(error); | |
if (llvm::verifyModule(*module, &error_os)) { | |
std::cerr << "Module Error: " << error << '\n'; | |
module->dump(); | |
return 1; | |
} | |
auto engine = llvm::EngineBuilder(module) | |
.setErrorStr(&error) | |
.setOptLevel(llvm::CodeGenOpt::Aggressive) | |
.setEngineKind(llvm::EngineKind::JIT) | |
.setUseMCJIT(true) | |
.create(); | |
if (!engine) { | |
std::cerr << "EE Error: " << error << '\n'; | |
return 1; | |
} | |
engine->finalizeObject(); | |
typedef void (*Function)(); | |
Function f = reinterpret_cast<Function>( | |
engine->getPointerToNamedFunction("main")); | |
f(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment