Advertisement
Guest User

Untitled

a guest
Jan 1st, 2011
897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1.  
  2. #include "llvm/LLVMContext.h"
  3. #include "llvm/Module.h"
  4. #include "llvm/Constants.h"
  5. #include "llvm/Function.h"
  6. #include "llvm/BasicBlock.h"
  7. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  8. #include "llvm/ExecutionEngine/GenericValue.h"
  9. #include "llvm/ExecutionEngine/JIT.h"
  10. #include "llvm/Target/TargetSelect.h"
  11. #include "llvm/Support/IRBuilder.h"
  12.  
  13. #include <vector>
  14. #include <cstdio>
  15. #include <string>
  16.  
  17. int main() {
  18.     llvm::LLVMContext & context = llvm::getGlobalContext();
  19.     llvm::Module *module = new llvm::Module("asdf", context);
  20.    
  21.     // Create the function we're going to write code into
  22.     llvm::IRBuilder<> builder(context);
  23.     llvm::FunctionType *funcType = llvm::FunctionType::get(builder.getVoidTy(), false);
  24.     llvm::Function *mainFunc = llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, "main", module);
  25.     llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entry", mainFunc);
  26.     builder.SetInsertPoint(entry);
  27.    
  28.     // Get a function declaration for printf
  29.     std::vector<const llvm::Type *> printfArgs;
  30.     printfArgs.push_back(builder.getInt8Ty()->getPointerTo());
  31.    
  32.     llvm::FunctionType *printfType = llvm::FunctionType::get(builder.getInt32Ty(), printfArgs, true);
  33.     llvm::Constant *printfFunc = module->getOrInsertFunction("printf", printfType);
  34.    
  35.     // Add our "hello world" string to the module
  36.     llvm::Value *helloWorld = builder.CreateGlobalStringPtr("hello world!\n");
  37.    
  38.     // Now generate a call to printf and return out of the function
  39.     builder.CreateCall(printfFunc, helloWorld);
  40.     builder.CreateRetVoid();
  41.    
  42.     // Initialize the native target, which is required before we can JIT anything
  43.     llvm::InitializeNativeTarget();
  44.    
  45.     // Create the execution engine, this takes ownership of the module
  46.     std::string err_str;
  47.     llvm::ExecutionEngine *engine = llvm::EngineBuilder(module).setErrorStr(&err_str).create();
  48.     if (!engine) {
  49.         fprintf(stderr, "err: %s\n", err_str.c_str());
  50.         exit(1);
  51.     }
  52.    
  53.     std::vector<llvm::GenericValue> void_arg;
  54.     engine->runFunction(mainFunc, void_arg);
  55.    
  56.     // Delete the engine and not the module
  57.     delete engine;
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement