Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "llvm/LLVMContext.h"
- #include "llvm/Module.h"
- #include "llvm/Constants.h"
- #include "llvm/Function.h"
- #include "llvm/BasicBlock.h"
- #include "llvm/ExecutionEngine/ExecutionEngine.h"
- #include "llvm/ExecutionEngine/GenericValue.h"
- #include "llvm/ExecutionEngine/JIT.h"
- #include "llvm/Target/TargetSelect.h"
- #include "llvm/Support/IRBuilder.h"
- #include <vector>
- #include <cstdio>
- #include <string>
- int main() {
- llvm::LLVMContext & context = llvm::getGlobalContext();
- llvm::Module *module = new llvm::Module("asdf", context);
- // Create the function we're going to write code into
- llvm::IRBuilder<> builder(context);
- llvm::FunctionType *funcType = llvm::FunctionType::get(builder.getVoidTy(), false);
- llvm::Function *mainFunc = llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, "main", module);
- llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entry", mainFunc);
- builder.SetInsertPoint(entry);
- // Get a function declaration for printf
- std::vector<const llvm::Type *> printfArgs;
- printfArgs.push_back(builder.getInt8Ty()->getPointerTo());
- llvm::FunctionType *printfType = llvm::FunctionType::get(builder.getInt32Ty(), printfArgs, true);
- llvm::Constant *printfFunc = module->getOrInsertFunction("printf", printfType);
- // Add our "hello world" string to the module
- llvm::Value *helloWorld = builder.CreateGlobalStringPtr("hello world!\n");
- // Now generate a call to printf and return out of the function
- builder.CreateCall(printfFunc, helloWorld);
- builder.CreateRetVoid();
- // Initialize the native target, which is required before we can JIT anything
- llvm::InitializeNativeTarget();
- // Create the execution engine, this takes ownership of the module
- std::string err_str;
- llvm::ExecutionEngine *engine = llvm::EngineBuilder(module).setErrorStr(&err_str).create();
- if (!engine) {
- fprintf(stderr, "err: %s\n", err_str.c_str());
- exit(1);
- }
- std::vector<llvm::GenericValue> void_arg;
- engine->runFunction(mainFunc, void_arg);
- // Delete the engine and not the module
- delete engine;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement