BuildingAJIT2.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. =====================================================================
  2. Building a JIT: Adding Optimizations -- An introduction to ORC Layers
  3. =====================================================================
  4. .. contents::
  5. :local:
  6. **This tutorial is under active development. It is incomplete and details may
  7. change frequently.** Nonetheless we invite you to try it out as it stands, and
  8. we welcome any feedback.
  9. Chapter 2 Introduction
  10. ======================
  11. **Warning: This tutorial is currently being updated to account for ORC API
  12. changes. Only Chapters 1 and 2 are up-to-date.**
  13. **Example code from Chapters 3 to 5 will compile and run, but has not been
  14. updated**
  15. Welcome to Chapter 2 of the "Building an ORC-based JIT in LLVM" tutorial. In
  16. `Chapter 1 <BuildingAJIT1.html>`_ of this series we examined a basic JIT
  17. class, KaleidoscopeJIT, that could take LLVM IR modules as input and produce
  18. executable code in memory. KaleidoscopeJIT was able to do this with relatively
  19. little code by composing two off-the-shelf *ORC layers*: IRCompileLayer and
  20. ObjectLinkingLayer, to do much of the heavy lifting.
  21. In this layer we'll learn more about the ORC layer concept by using a new layer,
  22. IRTransformLayer, to add IR optimization support to KaleidoscopeJIT.
  23. Optimizing Modules using the IRTransformLayer
  24. =============================================
  25. In `Chapter 4 <LangImpl04.html>`_ of the "Implementing a language with LLVM"
  26. tutorial series the llvm *FunctionPassManager* is introduced as a means for
  27. optimizing LLVM IR. Interested readers may read that chapter for details, but
  28. in short: to optimize a Module we create an llvm::FunctionPassManager
  29. instance, configure it with a set of optimizations, then run the PassManager on
  30. a Module to mutate it into a (hopefully) more optimized but semantically
  31. equivalent form. In the original tutorial series the FunctionPassManager was
  32. created outside the KaleidoscopeJIT and modules were optimized before being
  33. added to it. In this Chapter we will make optimization a phase of our JIT
  34. instead. For now this will provide us a motivation to learn more about ORC
  35. layers, but in the long term making optimization part of our JIT will yield an
  36. important benefit: When we begin lazily compiling code (i.e. deferring
  37. compilation of each function until the first time it's run) having
  38. optimization managed by our JIT will allow us to optimize lazily too, rather
  39. than having to do all our optimization up-front.
  40. To add optimization support to our JIT we will take the KaleidoscopeJIT from
  41. Chapter 1 and compose an ORC *IRTransformLayer* on top. We will look at how the
  42. IRTransformLayer works in more detail below, but the interface is simple: the
  43. constructor for this layer takes a reference to the execution session and the
  44. layer below (as all layers do) plus an *IR optimization function* that it will
  45. apply to each Module that is added via addModule:
  46. .. code-block:: c++
  47. class KaleidoscopeJIT {
  48. private:
  49. ExecutionSession ES;
  50. RTDyldObjectLinkingLayer ObjectLayer;
  51. IRCompileLayer CompileLayer;
  52. IRTransformLayer TransformLayer;
  53. DataLayout DL;
  54. MangleAndInterner Mangle;
  55. ThreadSafeContext Ctx;
  56. public:
  57. KaleidoscopeJIT(JITTargetMachineBuilder JTMB, DataLayout DL)
  58. : ObjectLayer(ES,
  59. []() { return std::make_unique<SectionMemoryManager>(); }),
  60. CompileLayer(ES, ObjectLayer, ConcurrentIRCompiler(std::move(JTMB))),
  61. TransformLayer(ES, CompileLayer, optimizeModule),
  62. DL(std::move(DL)), Mangle(ES, this->DL),
  63. Ctx(std::make_unique<LLVMContext>()) {
  64. ES.getMainJITDylib().setGenerator(
  65. cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess(DL)));
  66. }
  67. Our extended KaleidoscopeJIT class starts out the same as it did in Chapter 1,
  68. but after the CompileLayer we introduce a new member, TransformLayer, which sits
  69. on top of our CompileLayer. We initialize our OptimizeLayer with a reference to
  70. the ExecutionSession and output layer (standard practice for layers), along with
  71. a *transform function*. For our transform function we supply our classes
  72. optimizeModule static method.
  73. .. code-block:: c++
  74. // ...
  75. return cantFail(OptimizeLayer.addModule(std::move(M),
  76. std::move(Resolver)));
  77. // ...
  78. Next we need to update our addModule method to replace the call to
  79. ``CompileLayer::add`` with a call to ``OptimizeLayer::add`` instead.
  80. .. code-block:: c++
  81. static Expected<ThreadSafeModule>
  82. optimizeModule(ThreadSafeModule M, const MaterializationResponsibility &R) {
  83. // Create a function pass manager.
  84. auto FPM = std::make_unique<legacy::FunctionPassManager>(M.get());
  85. // Add some optimizations.
  86. FPM->add(createInstructionCombiningPass());
  87. FPM->add(createReassociatePass());
  88. FPM->add(createGVNPass());
  89. FPM->add(createCFGSimplificationPass());
  90. FPM->doInitialization();
  91. // Run the optimizations over all functions in the module being added to
  92. // the JIT.
  93. for (auto &F : *M)
  94. FPM->run(F);
  95. return M;
  96. }
  97. At the bottom of our JIT we add a private method to do the actual optimization:
  98. *optimizeModule*. This function takes the module to be transformed as input (as
  99. a ThreadSafeModule) along with a reference to a reference to a new class:
  100. ``MaterializationResponsibility``. The MaterializationResponsibility argument
  101. can be used to query JIT state for the module being transformed, such as the set
  102. of definitions in the module that JIT'd code is actively trying to call/access.
  103. For now we will ignore this argument and use a standard optimization
  104. pipeline. To do this we set up a FunctionPassManager, add some passes to it, run
  105. it over every function in the module, and then return the mutated module. The
  106. specific optimizations are the same ones used in `Chapter 4 <LangImpl04.html>`_
  107. of the "Implementing a language with LLVM" tutorial series. Readers may visit
  108. that chapter for a more in-depth discussion of these, and of IR optimization in
  109. general.
  110. And that's it in terms of changes to KaleidoscopeJIT: When a module is added via
  111. addModule the OptimizeLayer will call our optimizeModule function before passing
  112. the transformed module on to the CompileLayer below. Of course, we could have
  113. called optimizeModule directly in our addModule function and not gone to the
  114. bother of using the IRTransformLayer, but doing so gives us another opportunity
  115. to see how layers compose. It also provides a neat entry point to the *layer*
  116. concept itself, because IRTransformLayer is one of the simplest layers that
  117. can be implemented.
  118. .. code-block:: c++
  119. // From IRTransformLayer.h:
  120. class IRTransformLayer : public IRLayer {
  121. public:
  122. using TransformFunction = std::function<Expected<ThreadSafeModule>(
  123. ThreadSafeModule, const MaterializationResponsibility &R)>;
  124. IRTransformLayer(ExecutionSession &ES, IRLayer &BaseLayer,
  125. TransformFunction Transform = identityTransform);
  126. void setTransform(TransformFunction Transform) {
  127. this->Transform = std::move(Transform);
  128. }
  129. static ThreadSafeModule
  130. identityTransform(ThreadSafeModule TSM,
  131. const MaterializationResponsibility &R) {
  132. return TSM;
  133. }
  134. void emit(MaterializationResponsibility R, ThreadSafeModule TSM) override;
  135. private:
  136. IRLayer &BaseLayer;
  137. TransformFunction Transform;
  138. };
  139. // From IRTransfomrLayer.cpp:
  140. IRTransformLayer::IRTransformLayer(ExecutionSession &ES,
  141. IRLayer &BaseLayer,
  142. TransformFunction Transform)
  143. : IRLayer(ES), BaseLayer(BaseLayer), Transform(std::move(Transform)) {}
  144. void IRTransformLayer::emit(MaterializationResponsibility R,
  145. ThreadSafeModule TSM) {
  146. assert(TSM.getModule() && "Module must not be null");
  147. if (auto TransformedTSM = Transform(std::move(TSM), R))
  148. BaseLayer.emit(std::move(R), std::move(*TransformedTSM));
  149. else {
  150. R.failMaterialization();
  151. getExecutionSession().reportError(TransformedTSM.takeError());
  152. }
  153. }
  154. This is the whole definition of IRTransformLayer, from
  155. ``llvm/include/llvm/ExecutionEngine/Orc/IRTransformLayer.h`` and
  156. ``llvm/lib/ExecutionEngine/Orc/IRTransformLayer.cpp``. This class is concerned
  157. with two very simple jobs: (1) Running every IR Module that is emitted via this
  158. layer through the transform function object, and (2) implementing the ORC
  159. ``IRLayer`` interface (which itself conforms to the general ORC Layer concept,
  160. more on that below). Most of the class is straightforward: a typedef for the
  161. transform function, a constructor to initialize the members, a setter for the
  162. transform function value, and a default no-op transform. The most important
  163. method is ``emit`` as this is half of our IRLayer interface. The emit method
  164. applies our transform to each module that it is called on and, if the transform
  165. succeeds, passes the transformed module to the base layer. If the transform
  166. fails, our emit function calls
  167. ``MaterializationResponsibility::failMaterialization`` (this JIT clients who
  168. may be waiting on other threads know that the code they were waiting for has
  169. failed to compile) and logs the error with the execution session before bailing
  170. out.
  171. The other half of the IRLayer interface we inherit unmodified from the IRLayer
  172. class:
  173. .. code-block:: c++
  174. Error IRLayer::add(JITDylib &JD, ThreadSafeModule TSM, VModuleKey K) {
  175. return JD.define(std::make_unique<BasicIRLayerMaterializationUnit>(
  176. *this, std::move(K), std::move(TSM)));
  177. }
  178. This code, from ``llvm/lib/ExecutionEngine/Orc/Layer.cpp``, adds a
  179. ThreadSafeModule to a given JITDylib by wrapping it up in a
  180. ``MaterializationUnit`` (in this case a ``BasicIRLayerMaterializationUnit``).
  181. Most layers that derived from IRLayer can rely on this default implementation
  182. of the ``add`` method.
  183. These two operations, ``add`` and ``emit``, together constitute the layer
  184. concept: A layer is a way to wrap a portion of a compiler pipeline (in this case
  185. the "opt" phase of an LLVM compiler) whose API is is opaque to ORC in an
  186. interface that allows ORC to invoke it when needed. The add method takes an
  187. module in some input program representation (in this case an LLVM IR module) and
  188. stores it in the target JITDylib, arranging for it to be passed back to the
  189. Layer's emit method when any symbol defined by that module is requested. Layers
  190. can compose neatly by calling the 'emit' method of a base layer to complete
  191. their work. For example, in this tutorial our IRTransformLayer calls through to
  192. our IRCompileLayer to compile the transformed IR, and our IRCompileLayer in turn
  193. calls our ObjectLayer to link the object file produced by our compiler.
  194. So far we have learned how to optimize and compile our LLVM IR, but we have not
  195. focused on when compilation happens. Our current REPL is eager: Each function
  196. definition is optimized and compiled as soon as it is referenced by any other
  197. code, regardless of whether it is ever called at runtime. In the next chapter we
  198. will introduce fully lazy compilation, in which functions are not compiled until
  199. they are first called at run-time. At this point the trade-offs get much more
  200. interesting: the lazier we are, the quicker we can start executing the first
  201. function, but the more often we will have to pause to compile newly encountered
  202. functions. If we only code-gen lazily, but optimize eagerly, we will have a
  203. longer startup time (as everything is optimized) but relatively short pauses as
  204. each function just passes through code-gen. If we both optimize and code-gen
  205. lazily we can start executing the first function more quickly, but we will have
  206. longer pauses as each function has to be both optimized and code-gen'd when it
  207. is first executed. Things become even more interesting if we consider
  208. interproceedural optimizations like inlining, which must be performed eagerly.
  209. These are complex trade-offs, and there is no one-size-fits all solution to
  210. them, but by providing composable layers we leave the decisions to the person
  211. implementing the JIT, and make it easy for them to experiment with different
  212. configurations.
  213. `Next: Adding Per-function Lazy Compilation <BuildingAJIT3.html>`_
  214. Full Code Listing
  215. =================
  216. Here is the complete code listing for our running example with an
  217. IRTransformLayer added to enable optimization. To build this example, use:
  218. .. code-block:: bash
  219. # Compile
  220. clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core orcjit native` -O3 -o toy
  221. # Run
  222. ./toy
  223. Here is the code:
  224. .. literalinclude:: ../../examples/Kaleidoscope/BuildingAJIT/Chapter2/KaleidoscopeJIT.h
  225. :language: c++