xref: /llvm-project/llvm/examples/HowToUseJIT/HowToUseJIT.cpp (revision f47d6b38c7a61d50db4566b02719de05492dcef1)
1 //===-- examples/HowToUseJIT/HowToUseJIT.cpp - An example use of the JIT --===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This small program provides an example of how to quickly build a small
10 //  module with two functions and execute it with the JIT.
11 //
12 // Goal:
13 //  The goal of this snippet is to create in the memory
14 //  the LLVM module consisting of two functions as follow:
15 //
16 // int add1(int x) {
17 //   return x+1;
18 // }
19 //
20 // int foo() {
21 //   return add1(10);
22 // }
23 //
24 // then compile the module via JIT, then execute the `foo'
25 // function and return result to a driver, i.e. to a "host program".
26 //
27 // Some remarks and questions:
28 //
29 // - could we invoke some code using noname functions too?
30 //   e.g. evaluate "foo()+foo()" without fears to introduce
31 //   conflict of temporary function name with some real
32 //   existing function name?
33 //
34 //===----------------------------------------------------------------------===//
35 
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ExecutionEngine/ExecutionEngine.h"
38 #include "llvm/ExecutionEngine/GenericValue.h"
39 #include "llvm/IR/Argument.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/IRBuilder.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/IR/Type.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/ManagedStatic.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <memory>
56 #include <vector>
57 
58 using namespace llvm;
59 
60 int main() {
61   InitializeNativeTarget();
62 
63   LLVMContext Context;
64 
65   // Create some module to put our function into it.
66   std::unique_ptr<Module> Owner = make_unique<Module>("test", Context);
67   Module *M = Owner.get();
68 
69   // Create the add1 function entry and insert this entry into module M.  The
70   // function will have a return type of "int" and take an argument of "int".
71   Function *Add1F =
72       Function::Create(FunctionType::get(Type::getInt32Ty(Context),
73                                          {Type::getInt32Ty(Context)}, false),
74                        Function::ExternalLinkage, "add1", M);
75 
76   // Add a basic block to the function. As before, it automatically inserts
77   // because of the last argument.
78   BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", Add1F);
79 
80   // Create a basic block builder with default parameters.  The builder will
81   // automatically append instructions to the basic block `BB'.
82   IRBuilder<> builder(BB);
83 
84   // Get pointers to the constant `1'.
85   Value *One = builder.getInt32(1);
86 
87   // Get pointers to the integer argument of the add1 function...
88   assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
89   Argument *ArgX = &*Add1F->arg_begin();          // Get the arg
90   ArgX->setName("AnArg");            // Give it a nice symbolic name for fun.
91 
92   // Create the add instruction, inserting it into the end of BB.
93   Value *Add = builder.CreateAdd(One, ArgX);
94 
95   // Create the return instruction and add it to the basic block
96   builder.CreateRet(Add);
97 
98   // Now, function add1 is ready.
99 
100   // Now we're going to create function `foo', which returns an int and takes no
101   // arguments.
102   Function *FooF =
103       Function::Create(FunctionType::get(Type::getInt32Ty(Context), {}, false),
104                        Function::ExternalLinkage, "foo", M);
105 
106   // Add a basic block to the FooF function.
107   BB = BasicBlock::Create(Context, "EntryBlock", FooF);
108 
109   // Tell the basic block builder to attach itself to the new basic block
110   builder.SetInsertPoint(BB);
111 
112   // Get pointer to the constant `10'.
113   Value *Ten = builder.getInt32(10);
114 
115   // Pass Ten to the call to Add1F
116   CallInst *Add1CallRes = builder.CreateCall(Add1F, Ten);
117   Add1CallRes->setTailCall(true);
118 
119   // Create the return instruction and add it to the basic block.
120   builder.CreateRet(Add1CallRes);
121 
122   // Now we create the JIT.
123   ExecutionEngine* EE = EngineBuilder(std::move(Owner)).create();
124 
125   outs() << "We just constructed this LLVM module:\n\n" << *M;
126   outs() << "\n\nRunning foo: ";
127   outs().flush();
128 
129   // Call the `foo' function with no arguments:
130   std::vector<GenericValue> noargs;
131   GenericValue gv = EE->runFunction(FooF, noargs);
132 
133   // Import result of execution:
134   outs() << "Result: " << gv.IntVal << "\n";
135   delete EE;
136   llvm_shutdown();
137   return 0;
138 }
139