OSDN Git Service

Retire VS2015 Support
[android-x86/external-llvm.git] / docs / ORCv2DesignAndImplementation.rst
1 ===============================
2 ORC Design and Implementation
3 ===============================
4
5 Introduction
6 ============
7
8 This document aims to provide a high-level overview of the design and
9 implementation of the ORC JIT APIs. Except where otherwise stated, all
10 discussion applies to the design of the APIs as of LLVM verison 9 (ORCv2).
11
12 .. contents::
13    :local:
14
15 Use-cases
16 =========
17
18 ORC provides a modular API for building JIT compilers. There are a range
19 of use cases for such an API:
20
21 1. The LLVM tutorials use a simple ORC-based JIT class to execute expressions
22 compiled from a toy languge: Kaleidoscope.
23
24 2. The LLVM debugger, LLDB, uses a cross-compiling JIT for expression
25 evaluation. In this use case, cross compilation allows expressions compiled
26 in the debugger process to be executed on the debug target process, which may
27 be on a different device/architecture.
28
29 3. In high-performance JITs (e.g. JVMs, Julia) that want to make use of LLVM's
30 optimizations within an existing JIT infrastructure.
31
32 4. In interpreters and REPLs, e.g. Cling (C++) and the Swift interpreter.
33
34 By adoping a modular, library-based design we aim to make ORC useful in as many
35 of these contexts as possible.
36
37 Features
38 ========
39
40 ORC provides the following features:
41
42 - *JIT-linking* links relocatable object files (COFF, ELF, MachO) [1]_ into a
43   target process an runtime. The target process may be the same process that
44   contains the JIT session object and jit-linker, or may be another process
45   (even one running on a different machine or architecture) that communicates
46   with the JIT via RPC.
47
48 - *LLVM IR compilation*, which is provided by off the shelf components
49   (IRCompileLayer, SimpleCompiler, ConcurrentIRCompiler) that make it easy to
50   add LLVM IR to a JIT'd process.
51
52 - *Eager and lazy compilation*. By default, ORC will compile symbols as soon as
53   they are looked up in the JIT session object (``ExecutionSession``). Compiling
54   eagerly by default makes it easy to use ORC as a simple in-memory compiler for
55   an existing JIT. ORC also provides a simple mechanism, lazy-reexports, for
56   deferring compilation until first call.
57
58 - *Support for custom compilers and program representations*. Clients can supply
59    custom compilers for each symbol that they define in their JIT session. ORC
60    will run the user-supplied compiler when the a definition of a symbol is
61    needed. ORC is actually fully language agnostic: LLVM IR is not treated
62    specially, and is supported via the same wrapper mechanism (the
63    ``MaterializationUnit`` class) that is used for custom compilers.
64
65 - *Concurrent JIT'd code* and *concurrent compilation*. JIT'd code may spawn
66   multiple threads, and may re-enter the JIT (e.g. for lazy compilation)
67   concurrently from multiple threads. The ORC APIs also support running multiple
68   compilers concurrently, and provides off-the-shelf infrastructure to track
69   dependencies on running compiles (e.g. to ensure that we never call into code
70   until it is safe to do so, even if that involves waiting on multiple
71   compiles).
72
73 - *Orthogonality* and *composability*: Each of the features above can be used (or
74   not) independently. It is possible to put ORC components together to make a
75   non-lazy, in-process, single threaded JIT or a lazy, out-of-process,
76   concurrent JIT, or anything in between.
77
78 LLJIT and LLLazyJIT
79 ===================
80
81 ORC provides two basic JIT classes off-the-shelf. These are useful both as
82 examples of how to assemble ORC components to make a JIT, and as replacements
83 for earlier LLVM JIT APIs (e.g. MCJIT).
84
85 The LLJIT class uses an IRCompileLayer and RTDyldObjectLinkingLayer to support
86 compilation of LLVM IR and linking of relocatable object files. All operations
87 are performed eagerly on symbol lookup (i.e. a symbol's definition is compiled
88 as soon as you attempt to look up its address). LLJIT is a suitable replacement
89 for MCJIT in most cases (note: some more advanced features, e.g.
90 JITEventListeners are not supported yet).
91
92 The LLLazyJIT extends LLJIT and adds a CompileOnDemandLayer to enable lazy
93 compilation of LLVM IR. When an LLVM IR module is added via the addLazyIRModule
94 method, function bodies in that module will not be compiled until they are first
95 called. LLLazyJIT aims to provide a replacement of LLVM's original (pre-MCJIT)
96 JIT API.
97
98 LLJIT and LLLazyJIT instances can be created using their respective builder
99 classes: LLJITBuilder and LLazyJITBuilder. For example, assuming you have a
100 module ``M`` loaded on an ThreadSafeContext ``Ctx``:
101
102 .. code-block:: c++
103
104   // Try to detect the host arch and construct an LLJIT instance.
105   auto JIT = LLJITBuilder().create();
106
107   // If we could not construct an instance, return an error.
108   if (!JIT)
109     return JIT.takeError();
110
111   // Add the module.
112   if (auto Err = JIT->addIRModule(TheadSafeModule(std::move(M), Ctx)))
113     return Err;
114
115   // Look up the JIT'd code entry point.
116   auto EntrySym = JIT->lookup("entry");
117   if (!EntrySym)
118     return EntrySym.takeError();
119
120   auto *Entry = (void(*)())EntrySym.getAddress();
121
122   Entry();
123
124 The builder clasess provide a number of configuration options that can be
125 specified before the JIT instance is constructed. For example:
126
127 .. code-block:: c++
128
129   // Build an LLLazyJIT instance that uses four worker threads for compilation,
130   // and jumps to a specific error handler (rather than null) on lazy compile
131   // failures.
132
133   void handleLazyCompileFailure() {
134     // JIT'd code will jump here if lazy compilation fails, giving us an
135     // opportunity to exit or throw an exception into JIT'd code.
136     throw JITFailed();
137   }
138
139   auto JIT = LLLazyJITBuilder()
140                .setNumCompileThreads(4)
141                .setLazyCompileFailureAddr(
142                    toJITTargetAddress(&handleLazyCompileFailure))
143                .create();
144
145   // ...
146
147 For users wanting to get started with LLJIT a minimal example program can be
148 found at ``llvm/examples/HowToUseLLJIT``.
149
150 Design Overview
151 ===============
152
153 ORC's JIT'd program model aims to emulate the linking and symbol resolution
154 rules used by the static and dynamic linkers. This allows ORC to JIT
155 arbitrary LLVM IR, including IR produced by an ordinary static compiler (e.g.
156 clang) that uses constructs like symbol linkage and visibility, and weak and
157 common symbol definitions.
158
159 To see how this works, imagine a program ``foo`` which links against a pair
160 of dynamic libraries: ``libA`` and ``libB``. On the command line, building this
161 system might look like:
162
163 .. code-block:: bash
164
165   $ clang++ -shared -o libA.dylib a1.cpp a2.cpp
166   $ clang++ -shared -o libB.dylib b1.cpp b2.cpp
167   $ clang++ -o myapp myapp.cpp -L. -lA -lB
168   $ ./myapp
169
170 In ORC, this would translate into API calls on a "CXXCompilingLayer" (with error
171 checking omitted for brevity) as:
172
173 .. code-block:: c++
174
175   ExecutionSession ES;
176   RTDyldObjectLinkingLayer ObjLinkingLayer(
177       ES, []() { return llvm::make_unique<SectionMemoryManager>(); });
178   CXXCompileLayer CXXLayer(ES, ObjLinkingLayer);
179
180   // Create JITDylib "A" and add code to it using the CXX layer.
181   auto &LibA = ES.createJITDylib("A");
182   CXXLayer.add(LibA, MemoryBuffer::getFile("a1.cpp"));
183   CXXLayer.add(LibA, MemoryBuffer::getFile("a2.cpp"));
184
185   // Create JITDylib "B" and add code to it using the CXX layer.
186   auto &LibB = ES.createJITDylib("B");
187   CXXLayer.add(LibB, MemoryBuffer::getFile("b1.cpp"));
188   CXXLayer.add(LibB, MemoryBuffer::getFile("b2.cpp"));
189
190   // Specify the search order for the main JITDylib. This is equivalent to a
191   // "links against" relationship in a command-line link.
192   ES.getMainJITDylib().setSearchOrder({{&LibA, false}, {&LibB, false}});
193   CXXLayer.add(ES.getMainJITDylib(), MemoryBuffer::getFile("main.cpp"));
194
195   // Look up the JIT'd main, cast it to a function pointer, then call it.
196   auto MainSym = ExitOnErr(ES.lookup({&ES.getMainJITDylib()}, "main"));
197   auto *Main = (int(*)(int, char*[]))MainSym.getAddress();
198
199   int Result = Main(...);
200
201
202 This example tells us nothing about *how* or *when* compilation will happen.
203 That will depend on the implementation of the hypothetical CXXCompilingLayer,
204 but the linking rules will be the same regardless. For example, if a1.cpp and
205 a2.cpp both define a function "foo" the API should generate a duplicate
206 definition error. On the other hand, if a1.cpp and b1.cpp both define "foo"
207 there is no error (different dynamic libraries may define the same symbol). If
208 main.cpp refers to "foo", it should bind to the definition in LibA rather than
209 the one in LibB, since main.cpp is part of the "main" dylib, and the main dylib
210 links against LibA before LibB.
211
212 Many JIT clients will have no need for this strict adherence to the usual
213 ahead-of-time linking rules and should be able to get by just fine by putting
214 all of their code in a single JITDylib. However, clients who want to JIT code
215 for languages/projects that traditionally rely on ahead-of-time linking (e.g.
216 C++) will find that this feature makes life much easier.
217
218 Symbol lookup in ORC serves two other important functions, beyond basic lookup:
219 (1) It triggers compilation of the symbol(s) searched for, and (2) it provides
220 the synchronization mechanism for concurrent compilation. The pseudo-code for
221 the lookup process is:
222
223 .. code-block:: none
224
225   construct a query object from a query set and query handler
226   lock the session
227   lodge query against requested symbols, collect required materializers (if any)
228   unlock the session
229   dispatch materializers (if any)
230
231 In this context a materializer is something that provides a working definition
232 of a symbol upon request. Generally materializers wrap compilers, but they may
233 also wrap a linker directly (if the program representation backing the
234 definitions is an object file), or even just a class that writes bits directly
235 into memory (if the definitions are stubs). Materialization is the blanket term
236 for any actions (compiling, linking, splatting bits, registering with runtimes,
237 etc.) that is requried to generate a symbol definition that is safe to call or
238 access.
239
240 As each materializer completes its work it notifies the JITDylib, which in turn
241 notifies any query objects that are waiting on the newly materialized
242 definitions. Each query object maintains a count of the number of symbols that
243 it is still waiting on, and once this count reaches zero the query object calls
244 the query handler with a *SymbolMap* (a map of symbol names to addresses)
245 describing the result. If any symbol fails to materialize the query immediately
246 calls the query handler with an error.
247
248 The collected materialization units are sent to the ExecutionSession to be
249 dispatched, and the dispatch behavior can be set by the client. By default each
250 materializer is run on the calling thread. Clients are free to create new
251 threads to run materializers, or to send the work to a work queue for a thread
252 pool (this is what LLJIT/LLLazyJIT do).
253
254 Top Level APIs
255 ==============
256
257 Many of ORC's top-level APIs are visible in the example above:
258
259 - *ExecutionSession* represents the JIT'd program and provides context for the
260   JIT: It contains the JITDylibs, error reporting mechanisms, and dispatches the
261   materializers.
262
263 - *JITDylibs* provide the symbol tables.
264
265 - *Layers* (ObjLinkingLayer and CXXLayer) are wrappers around compilers and
266   allow clients to add uncompiled program representations supported by those
267   compilers to JITDylibs.
268
269 Several other important APIs are used explicitly. JIT clients need not be aware
270 of them, but Layer authors will use them:
271
272 - *MaterializationUnit* - When XXXLayer::add is invoked it wraps the given
273   program representation (in this example, C++ source) in a MaterializationUnit,
274   which is then stored in the JITDylib. MaterializationUnits are responsible for
275   describing the definitions they provide, and for unwrapping the program
276   representation and passing it back to the layer when compilation is required
277   (this ownership shuffle makes writing thread-safe layers easier, since the
278   ownership of the program representation will be passed back on the stack,
279   rather than having to be fished out of a Layer member, which would require
280   synchronization).
281
282 - *MaterializationResponsibility* - When a MaterializationUnit hands a program
283   representation back to the layer it comes with an associated
284   MaterializationResponsibility object. This object tracks the definitions
285   that must be materialized and provides a way to notify the JITDylib once they
286   are either successfully materialized or a failure occurs.
287
288 Handy utilities
289 ===============
290
291 TBD: absolute symbols, aliases, off-the-shelf layers.
292
293 Laziness
294 ========
295
296 Laziness in ORC is provided by a utility called "lazy-reexports". The aim of
297 this utility is to re-use the synchronization provided by the symbol lookup
298 mechanism to make it safe to lazily compile functions, even if calls to the
299 stub occur simultaneously on multiple threads of JIT'd code. It does this by
300 reducing lazy compilation to symbol lookup: The lazy stub performs a lookup of
301 its underlying definition on first call, updating the function body pointer
302 once the definition is available. If additional calls arrive on other threads
303 while compilation is ongoing they will be safely blocked by the normal lookup
304 synchronization guarantee (no result until the result is safe) and can also
305 proceed as soon as compilation completes.
306
307 TBD: Usage example.
308
309 Supporting Custom Compilers
310 ===========================
311
312 TBD.
313
314 Low Level (MCJIT style) Use
315 ===========================
316
317 TBD.
318
319 Future Features
320 ===============
321
322 TBD: Speculative compilation. Object Caches.
323
324 .. [1] Formats/architectures vary in terms of supported features. MachO and
325        ELF tend to have better support than COFF. Patches very welcome!