HowToUseLLJIT.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "llvm/ExecutionEngine/Orc/LLJIT.h"
  2. #include "llvm/IR/Function.h"
  3. #include "llvm/IR/IRBuilder.h"
  4. #include "llvm/IR/Module.h"
  5. #include "llvm/Support/InitLLVM.h"
  6. #include "llvm/Support/TargetSelect.h"
  7. #include "llvm/Support/raw_ostream.h"
  8. using namespace llvm;
  9. using namespace llvm::orc;
  10. ExitOnError ExitOnErr;
  11. ThreadSafeModule createDemoModule() {
  12. auto Context = llvm::make_unique<LLVMContext>();
  13. auto M = make_unique<Module>("test", *Context);
  14. // Create the add1 function entry and insert this entry into module M. The
  15. // function will have a return type of "int" and take an argument of "int".
  16. Function *Add1F =
  17. Function::Create(FunctionType::get(Type::getInt32Ty(*Context),
  18. {Type::getInt32Ty(*Context)}, false),
  19. Function::ExternalLinkage, "add1", M.get());
  20. // Add a basic block to the function. As before, it automatically inserts
  21. // because of the last argument.
  22. BasicBlock *BB = BasicBlock::Create(*Context, "EntryBlock", Add1F);
  23. // Create a basic block builder with default parameters. The builder will
  24. // automatically append instructions to the basic block `BB'.
  25. IRBuilder<> builder(BB);
  26. // Get pointers to the constant `1'.
  27. Value *One = builder.getInt32(1);
  28. // Get pointers to the integer argument of the add1 function...
  29. assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
  30. Argument *ArgX = &*Add1F->arg_begin(); // Get the arg
  31. ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
  32. // Create the add instruction, inserting it into the end of BB.
  33. Value *Add = builder.CreateAdd(One, ArgX);
  34. // Create the return instruction and add it to the basic block
  35. builder.CreateRet(Add);
  36. return ThreadSafeModule(std::move(M), std::move(Context));
  37. }
  38. int main(int argc, char *argv[]) {
  39. // Initialize LLVM.
  40. InitLLVM X(argc, argv);
  41. InitializeNativeTarget();
  42. InitializeNativeTargetAsmPrinter();
  43. cl::ParseCommandLineOptions(argc, argv, "HowToUseLLJIT");
  44. ExitOnErr.setBanner(std::string(argv[0]) + ": ");
  45. // Create an LLJIT instance.
  46. auto J = ExitOnErr(LLJITBuilder().create());
  47. auto M = createDemoModule();
  48. ExitOnErr(J->addIRModule(std::move(M)));
  49. // Look up the JIT'd function, cast it to a function pointer, then call it.
  50. auto Add1Sym = ExitOnErr(J->lookup("add1"));
  51. int (*Add1)(int) = (int (*)(int))Add1Sym.getAddress();
  52. int Result = Add1(42);
  53. outs() << "add1(42) = " << Result << "\n";
  54. return 0;
  55. }