xref: /aosp_15_r20/external/llvm/docs/tutorial/BuildingAJIT1.rst (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker=======================================================
2*9880d681SAndroid Build Coastguard WorkerBuilding a JIT: Starting out with KaleidoscopeJIT
3*9880d681SAndroid Build Coastguard Worker=======================================================
4*9880d681SAndroid Build Coastguard Worker
5*9880d681SAndroid Build Coastguard Worker.. contents::
6*9880d681SAndroid Build Coastguard Worker   :local:
7*9880d681SAndroid Build Coastguard Worker
8*9880d681SAndroid Build Coastguard WorkerChapter 1 Introduction
9*9880d681SAndroid Build Coastguard Worker======================
10*9880d681SAndroid Build Coastguard Worker
11*9880d681SAndroid Build Coastguard WorkerWelcome to Chapter 1 of the "Building an ORC-based JIT in LLVM" tutorial. This
12*9880d681SAndroid Build Coastguard Workertutorial runs through the implementation of a JIT compiler using LLVM's
13*9880d681SAndroid Build Coastguard WorkerOn-Request-Compilation (ORC) APIs. It begins with a simplified version of the
14*9880d681SAndroid Build Coastguard WorkerKaleidoscopeJIT class used in the
15*9880d681SAndroid Build Coastguard Worker`Implementing a language with LLVM <LangImpl1.html>`_ tutorials and then
16*9880d681SAndroid Build Coastguard Workerintroduces new features like optimization, lazy compilation and remote
17*9880d681SAndroid Build Coastguard Workerexecution.
18*9880d681SAndroid Build Coastguard Worker
19*9880d681SAndroid Build Coastguard WorkerThe goal of this tutorial is to introduce you to LLVM's ORC JIT APIs, show how
20*9880d681SAndroid Build Coastguard Workerthese APIs interact with other parts of LLVM, and to teach you how to recombine
21*9880d681SAndroid Build Coastguard Workerthem to build a custom JIT that is suited to your use-case.
22*9880d681SAndroid Build Coastguard Worker
23*9880d681SAndroid Build Coastguard WorkerThe structure of the tutorial is:
24*9880d681SAndroid Build Coastguard Worker
25*9880d681SAndroid Build Coastguard Worker- Chapter #1: Investigate the simple KaleidoscopeJIT class. This will
26*9880d681SAndroid Build Coastguard Worker  introduce some of the basic concepts of the ORC JIT APIs, including the
27*9880d681SAndroid Build Coastguard Worker  idea of an ORC *Layer*.
28*9880d681SAndroid Build Coastguard Worker
29*9880d681SAndroid Build Coastguard Worker- `Chapter #2 <BuildingAJIT2.html>`_: Extend the basic KaleidoscopeJIT by adding
30*9880d681SAndroid Build Coastguard Worker  a new layer that will optimize IR and generated code.
31*9880d681SAndroid Build Coastguard Worker
32*9880d681SAndroid Build Coastguard Worker- `Chapter #3 <BuildingAJIT3.html>`_: Further extend the JIT by adding a
33*9880d681SAndroid Build Coastguard Worker  Compile-On-Demand layer to lazily compile IR.
34*9880d681SAndroid Build Coastguard Worker
35*9880d681SAndroid Build Coastguard Worker- `Chapter #4 <BuildingAJIT4.html>`_: Improve the laziness of our JIT by
36*9880d681SAndroid Build Coastguard Worker  replacing the Compile-On-Demand layer with a custom layer that uses the ORC
37*9880d681SAndroid Build Coastguard Worker  Compile Callbacks API directly to defer IR-generation until functions are
38*9880d681SAndroid Build Coastguard Worker  called.
39*9880d681SAndroid Build Coastguard Worker
40*9880d681SAndroid Build Coastguard Worker- `Chapter #5 <BuildingAJIT5.html>`_: Add process isolation by JITing code into
41*9880d681SAndroid Build Coastguard Worker  a remote process with reduced privileges using the JIT Remote APIs.
42*9880d681SAndroid Build Coastguard Worker
43*9880d681SAndroid Build Coastguard WorkerTo provide input for our JIT we will use the Kaleidoscope REPL from
44*9880d681SAndroid Build Coastguard Worker`Chapter 7 <LangImpl7.html>`_ of the "Implementing a language in LLVM tutorial",
45*9880d681SAndroid Build Coastguard Workerwith one minor modification: We will remove the FunctionPassManager from the
46*9880d681SAndroid Build Coastguard Workercode for that chapter and replace it with optimization support in our JIT class
47*9880d681SAndroid Build Coastguard Workerin Chapter #2.
48*9880d681SAndroid Build Coastguard Worker
49*9880d681SAndroid Build Coastguard WorkerFinally, a word on API generations: ORC is the 3rd generation of LLVM JIT API.
50*9880d681SAndroid Build Coastguard WorkerIt was preceded by MCJIT, and before that by the (now deleted) legacy JIT.
51*9880d681SAndroid Build Coastguard WorkerThese tutorials don't assume any experience with these earlier APIs, but
52*9880d681SAndroid Build Coastguard Workerreaders acquainted with them will see many familiar elements. Where appropriate
53*9880d681SAndroid Build Coastguard Workerwe will make this connection with the earlier APIs explicit to help people who
54*9880d681SAndroid Build Coastguard Workerare transitioning from them to ORC.
55*9880d681SAndroid Build Coastguard Worker
56*9880d681SAndroid Build Coastguard WorkerJIT API Basics
57*9880d681SAndroid Build Coastguard Worker==============
58*9880d681SAndroid Build Coastguard Worker
59*9880d681SAndroid Build Coastguard WorkerThe purpose of a JIT compiler is to compile code "on-the-fly" as it is needed,
60*9880d681SAndroid Build Coastguard Workerrather than compiling whole programs to disk ahead of time as a traditional
61*9880d681SAndroid Build Coastguard Workercompiler does. To support that aim our initial, bare-bones JIT API will be:
62*9880d681SAndroid Build Coastguard Worker
63*9880d681SAndroid Build Coastguard Worker1. Handle addModule(Module &M) -- Make the given IR module available for
64*9880d681SAndroid Build Coastguard Worker   execution.
65*9880d681SAndroid Build Coastguard Worker2. JITSymbol findSymbol(const std::string &Name) -- Search for pointers to
66*9880d681SAndroid Build Coastguard Worker   symbols (functions or variables) that have been added to the JIT.
67*9880d681SAndroid Build Coastguard Worker3. void removeModule(Handle H) -- Remove a module from the JIT, releasing any
68*9880d681SAndroid Build Coastguard Worker   memory that had been used for the compiled code.
69*9880d681SAndroid Build Coastguard Worker
70*9880d681SAndroid Build Coastguard WorkerA basic use-case for this API, executing the 'main' function from a module,
71*9880d681SAndroid Build Coastguard Workerwill look like:
72*9880d681SAndroid Build Coastguard Worker
73*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
74*9880d681SAndroid Build Coastguard Worker
75*9880d681SAndroid Build Coastguard Worker  std::unique_ptr<Module> M = buildModule();
76*9880d681SAndroid Build Coastguard Worker  JIT J;
77*9880d681SAndroid Build Coastguard Worker  Handle H = J.addModule(*M);
78*9880d681SAndroid Build Coastguard Worker  int (*Main)(int, char*[]) =
79*9880d681SAndroid Build Coastguard Worker    (int(*)(int, char*[])J.findSymbol("main").getAddress();
80*9880d681SAndroid Build Coastguard Worker  int Result = Main();
81*9880d681SAndroid Build Coastguard Worker  J.removeModule(H);
82*9880d681SAndroid Build Coastguard Worker
83*9880d681SAndroid Build Coastguard WorkerThe APIs that we build in these tutorials will all be variations on this simple
84*9880d681SAndroid Build Coastguard Workertheme. Behind the API we will refine the implementation of the JIT to add
85*9880d681SAndroid Build Coastguard Workersupport for optimization and lazy compilation. Eventually we will extend the
86*9880d681SAndroid Build Coastguard WorkerAPI itself to allow higher-level program representations (e.g. ASTs) to be
87*9880d681SAndroid Build Coastguard Workeradded to the JIT.
88*9880d681SAndroid Build Coastguard Worker
89*9880d681SAndroid Build Coastguard WorkerKaleidoscopeJIT
90*9880d681SAndroid Build Coastguard Worker===============
91*9880d681SAndroid Build Coastguard Worker
92*9880d681SAndroid Build Coastguard WorkerIn the previous section we described our API, now we examine a simple
93*9880d681SAndroid Build Coastguard Workerimplementation of it: The KaleidoscopeJIT class [1]_ that was used in the
94*9880d681SAndroid Build Coastguard Worker`Implementing a language with LLVM <LangImpl1.html>`_ tutorials. We will use
95*9880d681SAndroid Build Coastguard Workerthe REPL code from `Chapter 7 <LangImpl7.html>`_ of that tutorial to supply the
96*9880d681SAndroid Build Coastguard Workerinput for our JIT: Each time the user enters an expression the REPL will add a
97*9880d681SAndroid Build Coastguard Workernew IR module containing the code for that expression to the JIT. If the
98*9880d681SAndroid Build Coastguard Workerexpression is a top-level expression like '1+1' or 'sin(x)', the REPL will also
99*9880d681SAndroid Build Coastguard Workeruse the findSymbol method of our JIT class find and execute the code for the
100*9880d681SAndroid Build Coastguard Workerexpression, and then use the removeModule method to remove the code again
101*9880d681SAndroid Build Coastguard Worker(since there's no way to re-invoke an anonymous expression). In later chapters
102*9880d681SAndroid Build Coastguard Workerof this tutorial we'll modify the REPL to enable new interactions with our JIT
103*9880d681SAndroid Build Coastguard Workerclass, but for now we will take this setup for granted and focus our attention on
104*9880d681SAndroid Build Coastguard Workerthe implementation of our JIT itself.
105*9880d681SAndroid Build Coastguard Worker
106*9880d681SAndroid Build Coastguard WorkerOur KaleidoscopeJIT class is defined in the KaleidoscopeJIT.h header. After the
107*9880d681SAndroid Build Coastguard Workerusual include guards and #includes [2]_, we get to the definition of our class:
108*9880d681SAndroid Build Coastguard Worker
109*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
110*9880d681SAndroid Build Coastguard Worker
111*9880d681SAndroid Build Coastguard Worker  #ifndef LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
112*9880d681SAndroid Build Coastguard Worker  #define LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
113*9880d681SAndroid Build Coastguard Worker
114*9880d681SAndroid Build Coastguard Worker  #include "llvm/ExecutionEngine/ExecutionEngine.h"
115*9880d681SAndroid Build Coastguard Worker  #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
116*9880d681SAndroid Build Coastguard Worker  #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
117*9880d681SAndroid Build Coastguard Worker  #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
118*9880d681SAndroid Build Coastguard Worker  #include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
119*9880d681SAndroid Build Coastguard Worker  #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
120*9880d681SAndroid Build Coastguard Worker  #include "llvm/IR/Mangler.h"
121*9880d681SAndroid Build Coastguard Worker  #include "llvm/Support/DynamicLibrary.h"
122*9880d681SAndroid Build Coastguard Worker
123*9880d681SAndroid Build Coastguard Worker  namespace llvm {
124*9880d681SAndroid Build Coastguard Worker  namespace orc {
125*9880d681SAndroid Build Coastguard Worker
126*9880d681SAndroid Build Coastguard Worker  class KaleidoscopeJIT {
127*9880d681SAndroid Build Coastguard Worker  private:
128*9880d681SAndroid Build Coastguard Worker
129*9880d681SAndroid Build Coastguard Worker    std::unique_ptr<TargetMachine> TM;
130*9880d681SAndroid Build Coastguard Worker    const DataLayout DL;
131*9880d681SAndroid Build Coastguard Worker    ObjectLinkingLayer<> ObjectLayer;
132*9880d681SAndroid Build Coastguard Worker    IRCompileLayer<decltype(ObjectLayer)> CompileLayer;
133*9880d681SAndroid Build Coastguard Worker
134*9880d681SAndroid Build Coastguard Worker  public:
135*9880d681SAndroid Build Coastguard Worker
136*9880d681SAndroid Build Coastguard Worker    typedef decltype(CompileLayer)::ModuleSetHandleT ModuleHandleT;
137*9880d681SAndroid Build Coastguard Worker
138*9880d681SAndroid Build Coastguard WorkerOur class begins with four members: A TargetMachine, TM, which will be used
139*9880d681SAndroid Build Coastguard Workerto build our LLVM compiler instance; A DataLayout, DL, which will be used for
140*9880d681SAndroid Build Coastguard Workersymbol mangling (more on that later), and two ORC *layers*: an
141*9880d681SAndroid Build Coastguard WorkerObjectLinkingLayer and a IRCompileLayer. We'll be talking more about layers in
142*9880d681SAndroid Build Coastguard Workerthe next chapter, but for now you can think of them as analogous to LLVM
143*9880d681SAndroid Build Coastguard WorkerPasses: they wrap up useful JIT utilities behind an easy to compose interface.
144*9880d681SAndroid Build Coastguard WorkerThe first layer, ObjectLinkingLayer, is the foundation of our JIT: it takes
145*9880d681SAndroid Build Coastguard Workerin-memory object files produced by a compiler and links them on the fly to make
146*9880d681SAndroid Build Coastguard Workerthem executable. This JIT-on-top-of-a-linker design was introduced in MCJIT,
147*9880d681SAndroid Build Coastguard Workerhowever the linker was hidden inside the MCJIT class. In ORC we expose the
148*9880d681SAndroid Build Coastguard Workerlinker so that clients can access and configure it directly if they need to. In
149*9880d681SAndroid Build Coastguard Workerthis tutorial our ObjectLinkingLayer will just be used to support the next layer
150*9880d681SAndroid Build Coastguard Workerin our stack: the IRCompileLayer, which will be responsible for taking LLVM IR,
151*9880d681SAndroid Build Coastguard Workercompiling it, and passing the resulting in-memory object files down to the
152*9880d681SAndroid Build Coastguard Workerobject linking layer below.
153*9880d681SAndroid Build Coastguard Worker
154*9880d681SAndroid Build Coastguard WorkerThat's it for member variables, after that we have a single typedef:
155*9880d681SAndroid Build Coastguard WorkerModuleHandle. This is the handle type that will be returned from our JIT's
156*9880d681SAndroid Build Coastguard WorkeraddModule method, and can be passed to the removeModule method to remove a
157*9880d681SAndroid Build Coastguard Workermodule. The IRCompileLayer class already provides a convenient handle type
158*9880d681SAndroid Build Coastguard Worker(IRCompileLayer::ModuleSetHandleT), so we just alias our ModuleHandle to this.
159*9880d681SAndroid Build Coastguard Worker
160*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
161*9880d681SAndroid Build Coastguard Worker
162*9880d681SAndroid Build Coastguard Worker  KaleidoscopeJIT()
163*9880d681SAndroid Build Coastguard Worker      : TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),
164*9880d681SAndroid Build Coastguard Worker    CompileLayer(ObjectLayer, SimpleCompiler(*TM)) {
165*9880d681SAndroid Build Coastguard Worker    llvm::sys::DynamicLibrary::LoadLibraryPermanently(nullptr);
166*9880d681SAndroid Build Coastguard Worker  }
167*9880d681SAndroid Build Coastguard Worker
168*9880d681SAndroid Build Coastguard Worker  TargetMachine &getTargetMachine() { return *TM; }
169*9880d681SAndroid Build Coastguard Worker
170*9880d681SAndroid Build Coastguard WorkerNext up we have our class constructor. We begin by initializing TM using the
171*9880d681SAndroid Build Coastguard WorkerEngineBuilder::selectTarget helper method, which constructs a TargetMachine for
172*9880d681SAndroid Build Coastguard Workerthe current process. Next we use our newly created TargetMachine to initialize
173*9880d681SAndroid Build Coastguard WorkerDL, our DataLayout. Then we initialize our IRCompileLayer. Our IRCompile layer
174*9880d681SAndroid Build Coastguard Workerneeds two things: (1) A reference to our object linking layer, and (2) a
175*9880d681SAndroid Build Coastguard Workercompiler instance to use to perform the actual compilation from IR to object
176*9880d681SAndroid Build Coastguard Workerfiles. We use the off-the-shelf SimpleCompiler instance for now. Finally, in
177*9880d681SAndroid Build Coastguard Workerthe body of the constructor, we call the DynamicLibrary::LoadLibraryPermanently
178*9880d681SAndroid Build Coastguard Workermethod with a nullptr argument. Normally the LoadLibraryPermanently method is
179*9880d681SAndroid Build Coastguard Workercalled with the path of a dynamic library to load, but when passed a null
180*9880d681SAndroid Build Coastguard Workerpointer it will 'load' the host process itself, making its exported symbols
181*9880d681SAndroid Build Coastguard Workeravailable for execution.
182*9880d681SAndroid Build Coastguard Worker
183*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
184*9880d681SAndroid Build Coastguard Worker
185*9880d681SAndroid Build Coastguard Worker  ModuleHandle addModule(std::unique_ptr<Module> M) {
186*9880d681SAndroid Build Coastguard Worker    // Build our symbol resolver:
187*9880d681SAndroid Build Coastguard Worker    // Lambda 1: Look back into the JIT itself to find symbols that are part of
188*9880d681SAndroid Build Coastguard Worker    //           the same "logical dylib".
189*9880d681SAndroid Build Coastguard Worker    // Lambda 2: Search for external symbols in the host process.
190*9880d681SAndroid Build Coastguard Worker    auto Resolver = createLambdaResolver(
191*9880d681SAndroid Build Coastguard Worker        [&](const std::string &Name) {
192*9880d681SAndroid Build Coastguard Worker          if (auto Sym = CompileLayer.findSymbol(Name, false))
193*9880d681SAndroid Build Coastguard Worker            return Sym.toRuntimeDyldSymbol();
194*9880d681SAndroid Build Coastguard Worker          return RuntimeDyld::SymbolInfo(nullptr);
195*9880d681SAndroid Build Coastguard Worker        },
196*9880d681SAndroid Build Coastguard Worker        [](const std::string &S) {
197*9880d681SAndroid Build Coastguard Worker          if (auto SymAddr =
198*9880d681SAndroid Build Coastguard Worker                RTDyldMemoryManager::getSymbolAddressInProcess(Name))
199*9880d681SAndroid Build Coastguard Worker            return RuntimeDyld::SymbolInfo(SymAddr, JITSymbolFlags::Exported);
200*9880d681SAndroid Build Coastguard Worker          return RuntimeDyld::SymbolInfo(nullptr);
201*9880d681SAndroid Build Coastguard Worker        });
202*9880d681SAndroid Build Coastguard Worker
203*9880d681SAndroid Build Coastguard Worker    // Build a singlton module set to hold our module.
204*9880d681SAndroid Build Coastguard Worker    std::vector<std::unique_ptr<Module>> Ms;
205*9880d681SAndroid Build Coastguard Worker    Ms.push_back(std::move(M));
206*9880d681SAndroid Build Coastguard Worker
207*9880d681SAndroid Build Coastguard Worker    // Add the set to the JIT with the resolver we created above and a newly
208*9880d681SAndroid Build Coastguard Worker    // created SectionMemoryManager.
209*9880d681SAndroid Build Coastguard Worker    return CompileLayer.addModuleSet(std::move(Ms),
210*9880d681SAndroid Build Coastguard Worker                                     make_unique<SectionMemoryManager>(),
211*9880d681SAndroid Build Coastguard Worker                                     std::move(Resolver));
212*9880d681SAndroid Build Coastguard Worker  }
213*9880d681SAndroid Build Coastguard Worker
214*9880d681SAndroid Build Coastguard WorkerNow we come to the first of our JIT API methods: addModule. This method is
215*9880d681SAndroid Build Coastguard Workerresponsible for adding IR to the JIT and making it available for execution. In
216*9880d681SAndroid Build Coastguard Workerthis initial implementation of our JIT we will make our modules "available for
217*9880d681SAndroid Build Coastguard Workerexecution" by adding them straight to the IRCompileLayer, which will
218*9880d681SAndroid Build Coastguard Workerimmediately compile them. In later chapters we will teach our JIT to be lazier
219*9880d681SAndroid Build Coastguard Workerand instead add the Modules to a "pending" list to be compiled if and when they
220*9880d681SAndroid Build Coastguard Workerare first executed.
221*9880d681SAndroid Build Coastguard Worker
222*9880d681SAndroid Build Coastguard WorkerTo add our module to the IRCompileLayer we need to supply two auxiliary objects
223*9880d681SAndroid Build Coastguard Worker(as well as the module itself): a memory manager and a symbol resolver.  The
224*9880d681SAndroid Build Coastguard Workermemory manager will be responsible for managing the memory allocated to JIT'd
225*9880d681SAndroid Build Coastguard Workermachine code, setting memory permissions, and registering exception handling
226*9880d681SAndroid Build Coastguard Workertables (if the JIT'd code uses exceptions). For our memory manager we will use
227*9880d681SAndroid Build Coastguard Workerthe SectionMemoryManager class: another off-the-shelf utility that provides all
228*9880d681SAndroid Build Coastguard Workerthe basic functionality we need. The second auxiliary class, the symbol
229*9880d681SAndroid Build Coastguard Workerresolver, is more interesting for us. It exists to tell the JIT where to look
230*9880d681SAndroid Build Coastguard Workerwhen it encounters an *external symbol* in the module we are adding.  External
231*9880d681SAndroid Build Coastguard Workersymbols are any symbol not defined within the module itself, including calls to
232*9880d681SAndroid Build Coastguard Workerfunctions outside the JIT and calls to functions defined in other modules that
233*9880d681SAndroid Build Coastguard Workerhave already been added to the JIT. It may seem as though modules added to the
234*9880d681SAndroid Build Coastguard WorkerJIT should "know about one another" by default, but since we would still have to
235*9880d681SAndroid Build Coastguard Workersupply a symbol resolver for references to code outside the JIT it turns out to
236*9880d681SAndroid Build Coastguard Workerbe easier to just re-use this one mechanism for all symbol resolution. This has
237*9880d681SAndroid Build Coastguard Workerthe added benefit that the user has full control over the symbol resolution
238*9880d681SAndroid Build Coastguard Workerprocess. Should we search for definitions within the JIT first, then fall back
239*9880d681SAndroid Build Coastguard Workeron external definitions? Or should we prefer external definitions where
240*9880d681SAndroid Build Coastguard Workeravailable and only JIT code if we don't already have an available
241*9880d681SAndroid Build Coastguard Workerimplementation? By using a single symbol resolution scheme we are free to choose
242*9880d681SAndroid Build Coastguard Workerwhatever makes the most sense for any given use case.
243*9880d681SAndroid Build Coastguard Worker
244*9880d681SAndroid Build Coastguard WorkerBuilding a symbol resolver is made especially easy by the *createLambdaResolver*
245*9880d681SAndroid Build Coastguard Workerfunction. This function takes two lambdas [3]_ and returns a
246*9880d681SAndroid Build Coastguard WorkerRuntimeDyld::SymbolResolver instance. The first lambda is used as the
247*9880d681SAndroid Build Coastguard Workerimplementation of the resolver's findSymbolInLogicalDylib method, which searches
248*9880d681SAndroid Build Coastguard Workerfor symbol definitions that should be thought of as being part of the same
249*9880d681SAndroid Build Coastguard Worker"logical" dynamic library as this Module. If you are familiar with static
250*9880d681SAndroid Build Coastguard Workerlinking: this means that findSymbolInLogicalDylib should expose symbols with
251*9880d681SAndroid Build Coastguard Workercommon linkage and hidden visibility. If all this sounds foreign you can ignore
252*9880d681SAndroid Build Coastguard Workerthe details and just remember that this is the first method that the linker will
253*9880d681SAndroid Build Coastguard Workeruse to try to find a symbol definition. If the findSymbolInLogicalDylib method
254*9880d681SAndroid Build Coastguard Workerreturns a null result then the linker will call the second symbol resolver
255*9880d681SAndroid Build Coastguard Workermethod, called findSymbol, which searches for symbols that should be thought of
256*9880d681SAndroid Build Coastguard Workeras external to (but visibile from) the module and its logical dylib. In this
257*9880d681SAndroid Build Coastguard Workertutorial we will adopt the following simple scheme: All modules added to the JIT
258*9880d681SAndroid Build Coastguard Workerwill behave as if they were linked into a single, ever-growing logical dylib. To
259*9880d681SAndroid Build Coastguard Workerimplement this our first lambda (the one defining findSymbolInLogicalDylib) will
260*9880d681SAndroid Build Coastguard Workerjust search for JIT'd code by calling the CompileLayer's findSymbol method. If
261*9880d681SAndroid Build Coastguard Workerwe don't find a symbol in the JIT itself we'll fall back to our second lambda,
262*9880d681SAndroid Build Coastguard Workerwhich implements findSymbol. This will use the
263*9880d681SAndroid Build Coastguard WorkerRTDyldMemoyrManager::getSymbolAddressInProcess method to search for the symbol
264*9880d681SAndroid Build Coastguard Workerwithin the program itself. If we can't find a symbol definition via either of
265*9880d681SAndroid Build Coastguard Workerthese paths the JIT will refuse to accept our module, returning a "symbol not
266*9880d681SAndroid Build Coastguard Workerfound" error.
267*9880d681SAndroid Build Coastguard Worker
268*9880d681SAndroid Build Coastguard WorkerNow that we've built our symbol resolver we're ready to add our module to the
269*9880d681SAndroid Build Coastguard WorkerJIT. We do this by calling the CompileLayer's addModuleSet method [4]_. Since
270*9880d681SAndroid Build Coastguard Workerwe only have a single Module and addModuleSet expects a collection, we will
271*9880d681SAndroid Build Coastguard Workercreate a vector of modules and add our module as the only member. Since we
272*9880d681SAndroid Build Coastguard Workerhave already typedef'd our ModuleHandle type to be the same as the
273*9880d681SAndroid Build Coastguard WorkerCompileLayer's handle type, we can return the handle from addModuleSet
274*9880d681SAndroid Build Coastguard Workerdirectly from our addModule method.
275*9880d681SAndroid Build Coastguard Worker
276*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
277*9880d681SAndroid Build Coastguard Worker
278*9880d681SAndroid Build Coastguard Worker  JITSymbol findSymbol(const std::string Name) {
279*9880d681SAndroid Build Coastguard Worker    std::string MangledName;
280*9880d681SAndroid Build Coastguard Worker    raw_string_ostream MangledNameStream(MangledName);
281*9880d681SAndroid Build Coastguard Worker    Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
282*9880d681SAndroid Build Coastguard Worker    return CompileLayer.findSymbol(MangledNameStream.str(), true);
283*9880d681SAndroid Build Coastguard Worker  }
284*9880d681SAndroid Build Coastguard Worker
285*9880d681SAndroid Build Coastguard Worker  void removeModule(ModuleHandle H) {
286*9880d681SAndroid Build Coastguard Worker    CompileLayer.removeModuleSet(H);
287*9880d681SAndroid Build Coastguard Worker  }
288*9880d681SAndroid Build Coastguard Worker
289*9880d681SAndroid Build Coastguard WorkerNow that we can add code to our JIT, we need a way to find the symbols we've
290*9880d681SAndroid Build Coastguard Workeradded to it. To do that we call the findSymbol method on our IRCompileLayer,
291*9880d681SAndroid Build Coastguard Workerbut with a twist: We have to *mangle* the name of the symbol we're searching
292*9880d681SAndroid Build Coastguard Workerfor first. The reason for this is that the ORC JIT components use mangled
293*9880d681SAndroid Build Coastguard Workersymbols internally the same way a static compiler and linker would, rather
294*9880d681SAndroid Build Coastguard Workerthan using plain IR symbol names. The kind of mangling will depend on the
295*9880d681SAndroid Build Coastguard WorkerDataLayout, which in turn depends on the target platform. To allow us to
296*9880d681SAndroid Build Coastguard Workerremain portable and search based on the un-mangled name, we just re-produce
297*9880d681SAndroid Build Coastguard Workerthis mangling ourselves.
298*9880d681SAndroid Build Coastguard Worker
299*9880d681SAndroid Build Coastguard WorkerWe now come to the last method in our JIT API: removeModule. This method is
300*9880d681SAndroid Build Coastguard Workerresponsible for destructing the MemoryManager and SymbolResolver that were
301*9880d681SAndroid Build Coastguard Workeradded with a given module, freeing any resources they were using in the
302*9880d681SAndroid Build Coastguard Workerprocess. In our Kaleidoscope demo we rely on this method to remove the module
303*9880d681SAndroid Build Coastguard Workerrepresenting the most recent top-level expression, preventing it from being
304*9880d681SAndroid Build Coastguard Workertreated as a duplicate definition when the next top-level expression is
305*9880d681SAndroid Build Coastguard Workerentered. It is generally good to free any module that you know you won't need
306*9880d681SAndroid Build Coastguard Workerto call further, just to free up the resources dedicated to it. However, you
307*9880d681SAndroid Build Coastguard Workerdon't strictly need to do this: All resources will be cleaned up when your
308*9880d681SAndroid Build Coastguard WorkerJIT class is destructed, if the haven't been freed before then.
309*9880d681SAndroid Build Coastguard Worker
310*9880d681SAndroid Build Coastguard WorkerThis brings us to the end of Chapter 1 of Building a JIT. You now have a basic
311*9880d681SAndroid Build Coastguard Workerbut fully functioning JIT stack that you can use to take LLVM IR and make it
312*9880d681SAndroid Build Coastguard Workerexecutable within the context of your JIT process. In the next chapter we'll
313*9880d681SAndroid Build Coastguard Workerlook at how to extend this JIT to produce better quality code, and in the
314*9880d681SAndroid Build Coastguard Workerprocess take a deeper look at the ORC layer concept.
315*9880d681SAndroid Build Coastguard Worker
316*9880d681SAndroid Build Coastguard Worker`Next: Extending the KaleidoscopeJIT <BuildingAJIT2.html>`_
317*9880d681SAndroid Build Coastguard Worker
318*9880d681SAndroid Build Coastguard WorkerFull Code Listing
319*9880d681SAndroid Build Coastguard Worker=================
320*9880d681SAndroid Build Coastguard Worker
321*9880d681SAndroid Build Coastguard WorkerHere is the complete code listing for our running example. To build this
322*9880d681SAndroid Build Coastguard Workerexample, use:
323*9880d681SAndroid Build Coastguard Worker
324*9880d681SAndroid Build Coastguard Worker.. code-block:: bash
325*9880d681SAndroid Build Coastguard Worker
326*9880d681SAndroid Build Coastguard Worker    # Compile
327*9880d681SAndroid Build Coastguard Worker    clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core orc native` -O3 -o toy
328*9880d681SAndroid Build Coastguard Worker    # Run
329*9880d681SAndroid Build Coastguard Worker    ./toy
330*9880d681SAndroid Build Coastguard Worker
331*9880d681SAndroid Build Coastguard WorkerHere is the code:
332*9880d681SAndroid Build Coastguard Worker
333*9880d681SAndroid Build Coastguard Worker.. literalinclude:: ../../examples/Kaleidoscope/BuildingAJIT/Chapter1/KaleidoscopeJIT.h
334*9880d681SAndroid Build Coastguard Worker   :language: c++
335*9880d681SAndroid Build Coastguard Worker
336*9880d681SAndroid Build Coastguard Worker.. [1] Actually we use a cut-down version of KaleidoscopeJIT that makes a
337*9880d681SAndroid Build Coastguard Worker       simplifying assumption: symbols cannot be re-defined. This will make it
338*9880d681SAndroid Build Coastguard Worker       impossible to re-define symbols in the REPL, but will make our symbol
339*9880d681SAndroid Build Coastguard Worker       lookup logic simpler. Re-introducing support for symbol redefinition is
340*9880d681SAndroid Build Coastguard Worker       left as an exercise for the reader. (The KaleidoscopeJIT.h used in the
341*9880d681SAndroid Build Coastguard Worker       original tutorials will be a helpful reference).
342*9880d681SAndroid Build Coastguard Worker
343*9880d681SAndroid Build Coastguard Worker.. [2] +-----------------------+-----------------------------------------------+
344*9880d681SAndroid Build Coastguard Worker       |         File          |               Reason for inclusion            |
345*9880d681SAndroid Build Coastguard Worker       +=======================+===============================================+
346*9880d681SAndroid Build Coastguard Worker       |   ExecutionEngine.h   | Access to the EngineBuilder::selectTarget     |
347*9880d681SAndroid Build Coastguard Worker       |                       | method.                                       |
348*9880d681SAndroid Build Coastguard Worker       +-----------------------+-----------------------------------------------+
349*9880d681SAndroid Build Coastguard Worker       |                       | Access to the                                 |
350*9880d681SAndroid Build Coastguard Worker       | RTDyldMemoryManager.h | RTDyldMemoryManager::getSymbolAddressInProcess|
351*9880d681SAndroid Build Coastguard Worker       |                       | method.                                       |
352*9880d681SAndroid Build Coastguard Worker       +-----------------------+-----------------------------------------------+
353*9880d681SAndroid Build Coastguard Worker       |    CompileUtils.h     | Provides the SimpleCompiler class.            |
354*9880d681SAndroid Build Coastguard Worker       +-----------------------+-----------------------------------------------+
355*9880d681SAndroid Build Coastguard Worker       |   IRCompileLayer.h    | Provides the IRCompileLayer class.            |
356*9880d681SAndroid Build Coastguard Worker       +-----------------------+-----------------------------------------------+
357*9880d681SAndroid Build Coastguard Worker       |                       | Access the createLambdaResolver function,     |
358*9880d681SAndroid Build Coastguard Worker       |   LambdaResolver.h    | which provides easy construction of symbol    |
359*9880d681SAndroid Build Coastguard Worker       |                       | resolvers.                                    |
360*9880d681SAndroid Build Coastguard Worker       +-----------------------+-----------------------------------------------+
361*9880d681SAndroid Build Coastguard Worker       |  ObjectLinkingLayer.h | Provides the ObjectLinkingLayer class.        |
362*9880d681SAndroid Build Coastguard Worker       +-----------------------+-----------------------------------------------+
363*9880d681SAndroid Build Coastguard Worker       |       Mangler.h       | Provides the Mangler class for platform       |
364*9880d681SAndroid Build Coastguard Worker       |                       | specific name-mangling.                       |
365*9880d681SAndroid Build Coastguard Worker       +-----------------------+-----------------------------------------------+
366*9880d681SAndroid Build Coastguard Worker       |   DynamicLibrary.h    | Provides the DynamicLibrary class, which      |
367*9880d681SAndroid Build Coastguard Worker       |                       | makes symbols in the host process searchable. |
368*9880d681SAndroid Build Coastguard Worker       +-----------------------+-----------------------------------------------+
369*9880d681SAndroid Build Coastguard Worker
370*9880d681SAndroid Build Coastguard Worker.. [3] Actually they don't have to be lambdas, any object with a call operator
371*9880d681SAndroid Build Coastguard Worker       will do, including plain old functions or std::functions.
372*9880d681SAndroid Build Coastguard Worker
373*9880d681SAndroid Build Coastguard Worker.. [4] ORC layers accept sets of Modules, rather than individual ones, so that
374*9880d681SAndroid Build Coastguard Worker       all Modules in the set could be co-located by the memory manager, though
375*9880d681SAndroid Build Coastguard Worker       this feature is not yet implemented.
376