BuildingAJIT1.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. =======================================================
  2. Building a JIT: Starting out with KaleidoscopeJIT
  3. =======================================================
  4. .. contents::
  5. :local:
  6. Chapter 1 Introduction
  7. ======================
  8. **Warning: This tutorial is currently being updated to account for ORC API
  9. changes. Only Chapters 1 and 2 are up-to-date.**
  10. **Example code from Chapters 3 to 5 will compile and run, but has not been
  11. updated**
  12. Welcome to Chapter 1 of the "Building an ORC-based JIT in LLVM" tutorial. This
  13. tutorial runs through the implementation of a JIT compiler using LLVM's
  14. On-Request-Compilation (ORC) APIs. It begins with a simplified version of the
  15. KaleidoscopeJIT class used in the
  16. `Implementing a language with LLVM <LangImpl01.html>`_ tutorials and then
  17. introduces new features like concurrent compilation, optimization, lazy
  18. compilation and remote execution.
  19. The goal of this tutorial is to introduce you to LLVM's ORC JIT APIs, show how
  20. these APIs interact with other parts of LLVM, and to teach you how to recombine
  21. them to build a custom JIT that is suited to your use-case.
  22. The structure of the tutorial is:
  23. - Chapter #1: Investigate the simple KaleidoscopeJIT class. This will
  24. introduce some of the basic concepts of the ORC JIT APIs, including the
  25. idea of an ORC *Layer*.
  26. - `Chapter #2 <BuildingAJIT2.html>`_: Extend the basic KaleidoscopeJIT by adding
  27. a new layer that will optimize IR and generated code.
  28. - `Chapter #3 <BuildingAJIT3.html>`_: Further extend the JIT by adding a
  29. Compile-On-Demand layer to lazily compile IR.
  30. - `Chapter #4 <BuildingAJIT4.html>`_: Improve the laziness of our JIT by
  31. replacing the Compile-On-Demand layer with a custom layer that uses the ORC
  32. Compile Callbacks API directly to defer IR-generation until functions are
  33. called.
  34. - `Chapter #5 <BuildingAJIT5.html>`_: Add process isolation by JITing code into
  35. a remote process with reduced privileges using the JIT Remote APIs.
  36. To provide input for our JIT we will use a lightly modified version of the
  37. Kaleidoscope REPL from `Chapter 7 <LangImpl07.html>`_ of the "Implementing a
  38. language in LLVM tutorial".
  39. Finally, a word on API generations: ORC is the 3rd generation of LLVM JIT API.
  40. It was preceded by MCJIT, and before that by the (now deleted) legacy JIT.
  41. These tutorials don't assume any experience with these earlier APIs, but
  42. readers acquainted with them will see many familiar elements. Where appropriate
  43. we will make this connection with the earlier APIs explicit to help people who
  44. are transitioning from them to ORC.
  45. JIT API Basics
  46. ==============
  47. The purpose of a JIT compiler is to compile code "on-the-fly" as it is needed,
  48. rather than compiling whole programs to disk ahead of time as a traditional
  49. compiler does. To support that aim our initial, bare-bones JIT API will have
  50. just two functions:
  51. 1. ``Error addModule(std::unique_ptr<Module> M)``: Make the given IR module
  52. available for execution.
  53. 2. ``Expected<JITEvaluatedSymbol> lookup()``: Search for pointers to
  54. symbols (functions or variables) that have been added to the JIT.
  55. A basic use-case for this API, executing the 'main' function from a module,
  56. will look like:
  57. .. code-block:: c++
  58. JIT J;
  59. J.addModule(buildModule());
  60. auto *Main = (int(*)(int, char*[]))J.lookup("main").getAddress();
  61. int Result = Main();
  62. The APIs that we build in these tutorials will all be variations on this simple
  63. theme. Behind this API we will refine the implementation of the JIT to add
  64. support for concurrent compilation, optimization and lazy compilation.
  65. Eventually we will extend the API itself to allow higher-level program
  66. representations (e.g. ASTs) to be added to the JIT.
  67. KaleidoscopeJIT
  68. ===============
  69. In the previous section we described our API, now we examine a simple
  70. implementation of it: The KaleidoscopeJIT class [1]_ that was used in the
  71. `Implementing a language with LLVM <LangImpl01.html>`_ tutorials. We will use
  72. the REPL code from `Chapter 7 <LangImpl07.html>`_ of that tutorial to supply the
  73. input for our JIT: Each time the user enters an expression the REPL will add a
  74. new IR module containing the code for that expression to the JIT. If the
  75. expression is a top-level expression like '1+1' or 'sin(x)', the REPL will also
  76. use the lookup method of our JIT class find and execute the code for the
  77. expression. In later chapters of this tutorial we will modify the REPL to enable
  78. new interactions with our JIT class, but for now we will take this setup for
  79. granted and focus our attention on the implementation of our JIT itself.
  80. Our KaleidoscopeJIT class is defined in the KaleidoscopeJIT.h header. After the
  81. usual include guards and #includes [2]_, we get to the definition of our class:
  82. .. code-block:: c++
  83. #ifndef LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
  84. #define LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
  85. #include "llvm/ADT/StringRef.h"
  86. #include "llvm/ExecutionEngine/JITSymbol.h"
  87. #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
  88. #include "llvm/ExecutionEngine/Orc/Core.h"
  89. #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
  90. #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
  91. #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
  92. #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
  93. #include "llvm/ExecutionEngine/SectionMemoryManager.h"
  94. #include "llvm/IR/DataLayout.h"
  95. #include "llvm/IR/LLVMContext.h"
  96. #include <memory>
  97. namespace llvm {
  98. namespace orc {
  99. class KaleidoscopeJIT {
  100. private:
  101. ExecutionSession ES;
  102. RTDyldObjectLinkingLayer ObjectLayer;
  103. IRCompileLayer CompileLayer;
  104. DataLayout DL;
  105. MangleAndInterner Mangle;
  106. ThreadSafeContext Ctx;
  107. public:
  108. KaleidoscopeJIT(JITTargetMachineBuilder JTMB, DataLayout DL)
  109. : ObjectLayer(ES,
  110. []() { return std::make_unique<SectionMemoryManager>(); }),
  111. CompileLayer(ES, ObjectLayer, ConcurrentIRCompiler(std::move(JTMB))),
  112. DL(std::move(DL)), Mangle(ES, this->DL),
  113. Ctx(std::make_unique<LLVMContext>()) {
  114. ES.getMainJITDylib().setGenerator(
  115. cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess(DL)));
  116. }
  117. Our class begins with six member variables: An ExecutionSession member, ``ES``,
  118. which provides context for our running JIT'd code (including the string pool,
  119. global mutex, and error reporting facilities); An RTDyldObjectLinkingLayer,
  120. ``ObjectLayer``, that can be used to add object files to our JIT (though we will
  121. not use it directly); An IRCompileLayer, ``CompileLayer``, that can be used to
  122. add LLVM Modules to our JIT (and which builds on the ObjectLayer), A DataLayout
  123. and MangleAndInterner, ``DL`` and ``Mangle``, that will be used for symbol mangling
  124. (more on that later); and finally an LLVMContext that clients will use when
  125. building IR files for the JIT.
  126. Next up we have our class constructor, which takes a `JITTargetMachineBuilder``
  127. that will be used by our IRCompiler, and a ``DataLayout`` that we will use to
  128. initialize our DL member. The constructor begins by initializing our
  129. ObjectLayer. The ObjectLayer requires a reference to the ExecutionSession, and
  130. a function object that will build a JIT memory manager for each module that is
  131. added (a JIT memory manager manages memory allocations, memory permissions, and
  132. registration of exception handlers for JIT'd code). For this we use a lambda
  133. that returns a SectionMemoryManager, an off-the-shelf utility that provides all
  134. the basic memory management functionality required for this chapter. Next we
  135. initialize our CompileLayer. The CompileLayer needs three things: (1) A
  136. reference to the ExecutionSession, (2) A reference to our object layer, and (3)
  137. a compiler instance to use to perform the actual compilation from IR to object
  138. files. We use the off-the-shelf ConcurrentIRCompiler utility as our compiler,
  139. which we construct using this constructor's JITTargetMachineBuilder argument.
  140. The ConcurrentIRCompiler utility will use the JITTargetMachineBuilder to build
  141. llvm TargetMachines (which are not thread safe) as needed for compiles. After
  142. this, we initialize our supporting members: ``DL``, ``Mangler`` and ``Ctx`` with
  143. the input DataLayout, the ExecutionSession and DL member, and a new default
  144. constucted LLVMContext respectively. Now that our members have been initialized,
  145. so the one thing that remains to do is to tweak the configuration of the
  146. *JITDylib* that we will store our code in. We want to modify this dylib to
  147. contain not only the symbols that we add to it, but also the symbols from our
  148. REPL process as well. We do this by attaching a
  149. ``DynamicLibrarySearchGenerator`` instance using the
  150. ``DynamicLibrarySearchGenerator::GetForCurrentProcess`` method.
  151. .. code-block:: c++
  152. static Expected<std::unique_ptr<KaleidoscopeJIT>> Create() {
  153. auto JTMB = JITTargetMachineBuilder::detectHost();
  154. if (!JTMB)
  155. return JTMB.takeError();
  156. auto DL = JTMB->getDefaultDataLayoutForTarget();
  157. if (!DL)
  158. return DL.takeError();
  159. return std::make_unique<KaleidoscopeJIT>(std::move(*JTMB), std::move(*DL));
  160. }
  161. const DataLayout &getDataLayout() const { return DL; }
  162. LLVMContext &getContext() { return *Ctx.getContext(); }
  163. Next we have a named constructor, ``Create``, which will build a KaleidoscopeJIT
  164. instance that is configured to generate code for our host process. It does this
  165. by first generating a JITTargetMachineBuilder instance using that clases's
  166. detectHost method and then using that instance to generate a datalayout for
  167. the target process. Each of these operations can fail, so each returns its
  168. result wrapped in an Expected value [3]_ that we must check for error before
  169. continuing. If both operations succeed we can unwrap their results (using the
  170. dereference operator) and pass them into KaleidoscopeJIT's constructor on the
  171. last line of the function.
  172. Following the named constructor we have the ``getDataLayout()`` and
  173. ``getContext()`` methods. These are used to make data structures created and
  174. managed by the JIT (especially the LLVMContext) available to the REPL code that
  175. will build our IR modules.
  176. .. code-block:: c++
  177. void addModule(std::unique_ptr<Module> M) {
  178. cantFail(CompileLayer.add(ES.getMainJITDylib(),
  179. ThreadSafeModule(std::move(M), Ctx)));
  180. }
  181. Expected<JITEvaluatedSymbol> lookup(StringRef Name) {
  182. return ES.lookup({&ES.getMainJITDylib()}, Mangle(Name.str()));
  183. }
  184. Now we come to the first of our JIT API methods: addModule. This method is
  185. responsible for adding IR to the JIT and making it available for execution. In
  186. this initial implementation of our JIT we will make our modules "available for
  187. execution" by adding them to the CompileLayer, which will it turn store the
  188. Module in the main JITDylib. This process will create new symbol table entries
  189. in the JITDylib for each definition in the module, and will defer compilation of
  190. the module until any of its definitions is looked up. Note that this is not lazy
  191. compilation: just referencing a definition, even if it is never used, will be
  192. enough to trigger compilation. In later chapters we will teach our JIT to defer
  193. compilation of functions until they're actually called. To add our Module we
  194. must first wrap it in a ThreadSafeModule instance, which manages the lifetime of
  195. the Module's LLVMContext (our Ctx member) in a thread-friendly way. In our
  196. example, all modules will share the Ctx member, which will exist for the
  197. duration of the JIT. Once we switch to concurrent compilation in later chapters
  198. we will use a new context per module.
  199. Our last method is ``lookup``, which allows us to look up addresses for
  200. function and variable definitions added to the JIT based on their symbol names.
  201. As noted above, lookup will implicitly trigger compilation for any symbol
  202. that has not already been compiled. Our lookup method calls through to
  203. `ExecutionSession::lookup`, passing in a list of dylibs to search (in our case
  204. just the main dylib), and the symbol name to search for, with a twist: We have
  205. to *mangle* the name of the symbol we're searching for first. The ORC JIT
  206. components use mangled symbols internally the same way a static compiler and
  207. linker would, rather than using plain IR symbol names. This allows JIT'd code
  208. to interoperate easily with precompiled code in the application or shared
  209. libraries. The kind of mangling will depend on the DataLayout, which in turn
  210. depends on the target platform. To allow us to remain portable and search based
  211. on the un-mangled name, we just re-produce this mangling ourselves using our
  212. ``Mangle`` member function object.
  213. This brings us to the end of Chapter 1 of Building a JIT. You now have a basic
  214. but fully functioning JIT stack that you can use to take LLVM IR and make it
  215. executable within the context of your JIT process. In the next chapter we'll
  216. look at how to extend this JIT to produce better quality code, and in the
  217. process take a deeper look at the ORC layer concept.
  218. `Next: Extending the KaleidoscopeJIT <BuildingAJIT2.html>`_
  219. Full Code Listing
  220. =================
  221. Here is the complete code listing for our running example. To build this
  222. example, use:
  223. .. code-block:: bash
  224. # Compile
  225. clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core orcjit native` -O3 -o toy
  226. # Run
  227. ./toy
  228. Here is the code:
  229. .. literalinclude:: ../../examples/Kaleidoscope/BuildingAJIT/Chapter1/KaleidoscopeJIT.h
  230. :language: c++
  231. .. [1] Actually we use a cut-down version of KaleidoscopeJIT that makes a
  232. simplifying assumption: symbols cannot be re-defined. This will make it
  233. impossible to re-define symbols in the REPL, but will make our symbol
  234. lookup logic simpler. Re-introducing support for symbol redefinition is
  235. left as an exercise for the reader. (The KaleidoscopeJIT.h used in the
  236. original tutorials will be a helpful reference).
  237. .. [2] +-----------------------------+-----------------------------------------------+
  238. | File | Reason for inclusion |
  239. +=============================+===============================================+
  240. | JITSymbol.h | Defines the lookup result type |
  241. | | JITEvaluatedSymbol |
  242. +-----------------------------+-----------------------------------------------+
  243. | CompileUtils.h | Provides the SimpleCompiler class. |
  244. +-----------------------------+-----------------------------------------------+
  245. | Core.h | Core utilities such as ExecutionSession and |
  246. | | JITDylib. |
  247. +-----------------------------+-----------------------------------------------+
  248. | ExecutionUtils.h | Provides the DynamicLibrarySearchGenerator |
  249. | | class. |
  250. +-----------------------------+-----------------------------------------------+
  251. | IRCompileLayer.h | Provides the IRCompileLayer class. |
  252. +-----------------------------+-----------------------------------------------+
  253. | JITTargetMachineBuilder.h | Provides the JITTargetMachineBuilder class. |
  254. +-----------------------------+-----------------------------------------------+
  255. | RTDyldObjectLinkingLayer.h | Provides the RTDyldObjectLinkingLayer class. |
  256. +-----------------------------+-----------------------------------------------+
  257. | SectionMemoryManager.h | Provides the SectionMemoryManager class. |
  258. +-----------------------------+-----------------------------------------------+
  259. | DataLayout.h | Provides the DataLayout class. |
  260. +-----------------------------+-----------------------------------------------+
  261. | LLVMContext.h | Provides the LLVMContext class. |
  262. +-----------------------------+-----------------------------------------------+
  263. .. [3] See the ErrorHandling section in the LLVM Programmer's Manual
  264. (http://llvm.org/docs/ProgrammersManual.html#error-handling)