xref: /aosp_15_r20/external/llvm/docs/tutorial/LangImpl04.rst (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker==============================================
2*9880d681SAndroid Build Coastguard WorkerKaleidoscope: Adding JIT and Optimizer Support
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 4 Introduction
9*9880d681SAndroid Build Coastguard Worker======================
10*9880d681SAndroid Build Coastguard Worker
11*9880d681SAndroid Build Coastguard WorkerWelcome to Chapter 4 of the "`Implementing a language with
12*9880d681SAndroid Build Coastguard WorkerLLVM <index.html>`_" tutorial. Chapters 1-3 described the implementation
13*9880d681SAndroid Build Coastguard Workerof a simple language and added support for generating LLVM IR. This
14*9880d681SAndroid Build Coastguard Workerchapter describes two new techniques: adding optimizer support to your
15*9880d681SAndroid Build Coastguard Workerlanguage, and adding JIT compiler support. These additions will
16*9880d681SAndroid Build Coastguard Workerdemonstrate how to get nice, efficient code for the Kaleidoscope
17*9880d681SAndroid Build Coastguard Workerlanguage.
18*9880d681SAndroid Build Coastguard Worker
19*9880d681SAndroid Build Coastguard WorkerTrivial Constant Folding
20*9880d681SAndroid Build Coastguard Worker========================
21*9880d681SAndroid Build Coastguard Worker
22*9880d681SAndroid Build Coastguard WorkerOur demonstration for Chapter 3 is elegant and easy to extend.
23*9880d681SAndroid Build Coastguard WorkerUnfortunately, it does not produce wonderful code. The IRBuilder,
24*9880d681SAndroid Build Coastguard Workerhowever, does give us obvious optimizations when compiling simple code:
25*9880d681SAndroid Build Coastguard Worker
26*9880d681SAndroid Build Coastguard Worker::
27*9880d681SAndroid Build Coastguard Worker
28*9880d681SAndroid Build Coastguard Worker    ready> def test(x) 1+2+x;
29*9880d681SAndroid Build Coastguard Worker    Read function definition:
30*9880d681SAndroid Build Coastguard Worker    define double @test(double %x) {
31*9880d681SAndroid Build Coastguard Worker    entry:
32*9880d681SAndroid Build Coastguard Worker            %addtmp = fadd double 3.000000e+00, %x
33*9880d681SAndroid Build Coastguard Worker            ret double %addtmp
34*9880d681SAndroid Build Coastguard Worker    }
35*9880d681SAndroid Build Coastguard Worker
36*9880d681SAndroid Build Coastguard WorkerThis code is not a literal transcription of the AST built by parsing the
37*9880d681SAndroid Build Coastguard Workerinput. That would be:
38*9880d681SAndroid Build Coastguard Worker
39*9880d681SAndroid Build Coastguard Worker::
40*9880d681SAndroid Build Coastguard Worker
41*9880d681SAndroid Build Coastguard Worker    ready> def test(x) 1+2+x;
42*9880d681SAndroid Build Coastguard Worker    Read function definition:
43*9880d681SAndroid Build Coastguard Worker    define double @test(double %x) {
44*9880d681SAndroid Build Coastguard Worker    entry:
45*9880d681SAndroid Build Coastguard Worker            %addtmp = fadd double 2.000000e+00, 1.000000e+00
46*9880d681SAndroid Build Coastguard Worker            %addtmp1 = fadd double %addtmp, %x
47*9880d681SAndroid Build Coastguard Worker            ret double %addtmp1
48*9880d681SAndroid Build Coastguard Worker    }
49*9880d681SAndroid Build Coastguard Worker
50*9880d681SAndroid Build Coastguard WorkerConstant folding, as seen above, in particular, is a very common and
51*9880d681SAndroid Build Coastguard Workervery important optimization: so much so that many language implementors
52*9880d681SAndroid Build Coastguard Workerimplement constant folding support in their AST representation.
53*9880d681SAndroid Build Coastguard Worker
54*9880d681SAndroid Build Coastguard WorkerWith LLVM, you don't need this support in the AST. Since all calls to
55*9880d681SAndroid Build Coastguard Workerbuild LLVM IR go through the LLVM IR builder, the builder itself checked
56*9880d681SAndroid Build Coastguard Workerto see if there was a constant folding opportunity when you call it. If
57*9880d681SAndroid Build Coastguard Workerso, it just does the constant fold and return the constant instead of
58*9880d681SAndroid Build Coastguard Workercreating an instruction.
59*9880d681SAndroid Build Coastguard Worker
60*9880d681SAndroid Build Coastguard WorkerWell, that was easy :). In practice, we recommend always using
61*9880d681SAndroid Build Coastguard Worker``IRBuilder`` when generating code like this. It has no "syntactic
62*9880d681SAndroid Build Coastguard Workeroverhead" for its use (you don't have to uglify your compiler with
63*9880d681SAndroid Build Coastguard Workerconstant checks everywhere) and it can dramatically reduce the amount of
64*9880d681SAndroid Build Coastguard WorkerLLVM IR that is generated in some cases (particular for languages with a
65*9880d681SAndroid Build Coastguard Workermacro preprocessor or that use a lot of constants).
66*9880d681SAndroid Build Coastguard Worker
67*9880d681SAndroid Build Coastguard WorkerOn the other hand, the ``IRBuilder`` is limited by the fact that it does
68*9880d681SAndroid Build Coastguard Workerall of its analysis inline with the code as it is built. If you take a
69*9880d681SAndroid Build Coastguard Workerslightly more complex example:
70*9880d681SAndroid Build Coastguard Worker
71*9880d681SAndroid Build Coastguard Worker::
72*9880d681SAndroid Build Coastguard Worker
73*9880d681SAndroid Build Coastguard Worker    ready> def test(x) (1+2+x)*(x+(1+2));
74*9880d681SAndroid Build Coastguard Worker    ready> Read function definition:
75*9880d681SAndroid Build Coastguard Worker    define double @test(double %x) {
76*9880d681SAndroid Build Coastguard Worker    entry:
77*9880d681SAndroid Build Coastguard Worker            %addtmp = fadd double 3.000000e+00, %x
78*9880d681SAndroid Build Coastguard Worker            %addtmp1 = fadd double %x, 3.000000e+00
79*9880d681SAndroid Build Coastguard Worker            %multmp = fmul double %addtmp, %addtmp1
80*9880d681SAndroid Build Coastguard Worker            ret double %multmp
81*9880d681SAndroid Build Coastguard Worker    }
82*9880d681SAndroid Build Coastguard Worker
83*9880d681SAndroid Build Coastguard WorkerIn this case, the LHS and RHS of the multiplication are the same value.
84*9880d681SAndroid Build Coastguard WorkerWe'd really like to see this generate "``tmp = x+3; result = tmp*tmp;``"
85*9880d681SAndroid Build Coastguard Workerinstead of computing "``x+3``" twice.
86*9880d681SAndroid Build Coastguard Worker
87*9880d681SAndroid Build Coastguard WorkerUnfortunately, no amount of local analysis will be able to detect and
88*9880d681SAndroid Build Coastguard Workercorrect this. This requires two transformations: reassociation of
89*9880d681SAndroid Build Coastguard Workerexpressions (to make the add's lexically identical) and Common
90*9880d681SAndroid Build Coastguard WorkerSubexpression Elimination (CSE) to delete the redundant add instruction.
91*9880d681SAndroid Build Coastguard WorkerFortunately, LLVM provides a broad range of optimizations that you can
92*9880d681SAndroid Build Coastguard Workeruse, in the form of "passes".
93*9880d681SAndroid Build Coastguard Worker
94*9880d681SAndroid Build Coastguard WorkerLLVM Optimization Passes
95*9880d681SAndroid Build Coastguard Worker========================
96*9880d681SAndroid Build Coastguard Worker
97*9880d681SAndroid Build Coastguard WorkerLLVM provides many optimization passes, which do many different sorts of
98*9880d681SAndroid Build Coastguard Workerthings and have different tradeoffs. Unlike other systems, LLVM doesn't
99*9880d681SAndroid Build Coastguard Workerhold to the mistaken notion that one set of optimizations is right for
100*9880d681SAndroid Build Coastguard Workerall languages and for all situations. LLVM allows a compiler implementor
101*9880d681SAndroid Build Coastguard Workerto make complete decisions about what optimizations to use, in which
102*9880d681SAndroid Build Coastguard Workerorder, and in what situation.
103*9880d681SAndroid Build Coastguard Worker
104*9880d681SAndroid Build Coastguard WorkerAs a concrete example, LLVM supports both "whole module" passes, which
105*9880d681SAndroid Build Coastguard Workerlook across as large of body of code as they can (often a whole file,
106*9880d681SAndroid Build Coastguard Workerbut if run at link time, this can be a substantial portion of the whole
107*9880d681SAndroid Build Coastguard Workerprogram). It also supports and includes "per-function" passes which just
108*9880d681SAndroid Build Coastguard Workeroperate on a single function at a time, without looking at other
109*9880d681SAndroid Build Coastguard Workerfunctions. For more information on passes and how they are run, see the
110*9880d681SAndroid Build Coastguard Worker`How to Write a Pass <../WritingAnLLVMPass.html>`_ document and the
111*9880d681SAndroid Build Coastguard Worker`List of LLVM Passes <../Passes.html>`_.
112*9880d681SAndroid Build Coastguard Worker
113*9880d681SAndroid Build Coastguard WorkerFor Kaleidoscope, we are currently generating functions on the fly, one
114*9880d681SAndroid Build Coastguard Workerat a time, as the user types them in. We aren't shooting for the
115*9880d681SAndroid Build Coastguard Workerultimate optimization experience in this setting, but we also want to
116*9880d681SAndroid Build Coastguard Workercatch the easy and quick stuff where possible. As such, we will choose
117*9880d681SAndroid Build Coastguard Workerto run a few per-function optimizations as the user types the function
118*9880d681SAndroid Build Coastguard Workerin. If we wanted to make a "static Kaleidoscope compiler", we would use
119*9880d681SAndroid Build Coastguard Workerexactly the code we have now, except that we would defer running the
120*9880d681SAndroid Build Coastguard Workeroptimizer until the entire file has been parsed.
121*9880d681SAndroid Build Coastguard Worker
122*9880d681SAndroid Build Coastguard WorkerIn order to get per-function optimizations going, we need to set up a
123*9880d681SAndroid Build Coastguard Worker`FunctionPassManager <../WritingAnLLVMPass.html#what-passmanager-doesr>`_ to hold
124*9880d681SAndroid Build Coastguard Workerand organize the LLVM optimizations that we want to run. Once we have
125*9880d681SAndroid Build Coastguard Workerthat, we can add a set of optimizations to run. We'll need a new
126*9880d681SAndroid Build Coastguard WorkerFunctionPassManager for each module that we want to optimize, so we'll
127*9880d681SAndroid Build Coastguard Workerwrite a function to create and initialize both the module and pass manager
128*9880d681SAndroid Build Coastguard Workerfor us:
129*9880d681SAndroid Build Coastguard Worker
130*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
131*9880d681SAndroid Build Coastguard Worker
132*9880d681SAndroid Build Coastguard Worker    void InitializeModuleAndPassManager(void) {
133*9880d681SAndroid Build Coastguard Worker      // Open a new module.
134*9880d681SAndroid Build Coastguard Worker      Context LLVMContext;
135*9880d681SAndroid Build Coastguard Worker      TheModule = llvm::make_unique<Module>("my cool jit", LLVMContext);
136*9880d681SAndroid Build Coastguard Worker      TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
137*9880d681SAndroid Build Coastguard Worker
138*9880d681SAndroid Build Coastguard Worker      // Create a new pass manager attached to it.
139*9880d681SAndroid Build Coastguard Worker      TheFPM = llvm::make_unique<FunctionPassManager>(TheModule.get());
140*9880d681SAndroid Build Coastguard Worker
141*9880d681SAndroid Build Coastguard Worker      // Provide basic AliasAnalysis support for GVN.
142*9880d681SAndroid Build Coastguard Worker      TheFPM.add(createBasicAliasAnalysisPass());
143*9880d681SAndroid Build Coastguard Worker      // Do simple "peephole" optimizations and bit-twiddling optzns.
144*9880d681SAndroid Build Coastguard Worker      TheFPM.add(createInstructionCombiningPass());
145*9880d681SAndroid Build Coastguard Worker      // Reassociate expressions.
146*9880d681SAndroid Build Coastguard Worker      TheFPM.add(createReassociatePass());
147*9880d681SAndroid Build Coastguard Worker      // Eliminate Common SubExpressions.
148*9880d681SAndroid Build Coastguard Worker      TheFPM.add(createGVNPass());
149*9880d681SAndroid Build Coastguard Worker      // Simplify the control flow graph (deleting unreachable blocks, etc).
150*9880d681SAndroid Build Coastguard Worker      TheFPM.add(createCFGSimplificationPass());
151*9880d681SAndroid Build Coastguard Worker
152*9880d681SAndroid Build Coastguard Worker      TheFPM.doInitialization();
153*9880d681SAndroid Build Coastguard Worker    }
154*9880d681SAndroid Build Coastguard Worker
155*9880d681SAndroid Build Coastguard WorkerThis code initializes the global module ``TheModule``, and the function pass
156*9880d681SAndroid Build Coastguard Workermanager ``TheFPM``, which is attached to ``TheModule``. Once the pass manager is
157*9880d681SAndroid Build Coastguard Workerset up, we use a series of "add" calls to add a bunch of LLVM passes.
158*9880d681SAndroid Build Coastguard Worker
159*9880d681SAndroid Build Coastguard WorkerIn this case, we choose to add five passes: one analysis pass (alias analysis),
160*9880d681SAndroid Build Coastguard Workerand four optimization passes. The passes we choose here are a pretty standard set
161*9880d681SAndroid Build Coastguard Workerof "cleanup" optimizations that are useful for a wide variety of code. I won't
162*9880d681SAndroid Build Coastguard Workerdelve into what they do but, believe me, they are a good starting place :).
163*9880d681SAndroid Build Coastguard Worker
164*9880d681SAndroid Build Coastguard WorkerOnce the PassManager is set up, we need to make use of it. We do this by
165*9880d681SAndroid Build Coastguard Workerrunning it after our newly created function is constructed (in
166*9880d681SAndroid Build Coastguard Worker``FunctionAST::codegen()``), but before it is returned to the client:
167*9880d681SAndroid Build Coastguard Worker
168*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
169*9880d681SAndroid Build Coastguard Worker
170*9880d681SAndroid Build Coastguard Worker      if (Value *RetVal = Body->codegen()) {
171*9880d681SAndroid Build Coastguard Worker        // Finish off the function.
172*9880d681SAndroid Build Coastguard Worker        Builder.CreateRet(RetVal);
173*9880d681SAndroid Build Coastguard Worker
174*9880d681SAndroid Build Coastguard Worker        // Validate the generated code, checking for consistency.
175*9880d681SAndroid Build Coastguard Worker        verifyFunction(*TheFunction);
176*9880d681SAndroid Build Coastguard Worker
177*9880d681SAndroid Build Coastguard Worker        // Optimize the function.
178*9880d681SAndroid Build Coastguard Worker        TheFPM->run(*TheFunction);
179*9880d681SAndroid Build Coastguard Worker
180*9880d681SAndroid Build Coastguard Worker        return TheFunction;
181*9880d681SAndroid Build Coastguard Worker      }
182*9880d681SAndroid Build Coastguard Worker
183*9880d681SAndroid Build Coastguard WorkerAs you can see, this is pretty straightforward. The
184*9880d681SAndroid Build Coastguard Worker``FunctionPassManager`` optimizes and updates the LLVM Function\* in
185*9880d681SAndroid Build Coastguard Workerplace, improving (hopefully) its body. With this in place, we can try
186*9880d681SAndroid Build Coastguard Workerour test above again:
187*9880d681SAndroid Build Coastguard Worker
188*9880d681SAndroid Build Coastguard Worker::
189*9880d681SAndroid Build Coastguard Worker
190*9880d681SAndroid Build Coastguard Worker    ready> def test(x) (1+2+x)*(x+(1+2));
191*9880d681SAndroid Build Coastguard Worker    ready> Read function definition:
192*9880d681SAndroid Build Coastguard Worker    define double @test(double %x) {
193*9880d681SAndroid Build Coastguard Worker    entry:
194*9880d681SAndroid Build Coastguard Worker            %addtmp = fadd double %x, 3.000000e+00
195*9880d681SAndroid Build Coastguard Worker            %multmp = fmul double %addtmp, %addtmp
196*9880d681SAndroid Build Coastguard Worker            ret double %multmp
197*9880d681SAndroid Build Coastguard Worker    }
198*9880d681SAndroid Build Coastguard Worker
199*9880d681SAndroid Build Coastguard WorkerAs expected, we now get our nicely optimized code, saving a floating
200*9880d681SAndroid Build Coastguard Workerpoint add instruction from every execution of this function.
201*9880d681SAndroid Build Coastguard Worker
202*9880d681SAndroid Build Coastguard WorkerLLVM provides a wide variety of optimizations that can be used in
203*9880d681SAndroid Build Coastguard Workercertain circumstances. Some `documentation about the various
204*9880d681SAndroid Build Coastguard Workerpasses <../Passes.html>`_ is available, but it isn't very complete.
205*9880d681SAndroid Build Coastguard WorkerAnother good source of ideas can come from looking at the passes that
206*9880d681SAndroid Build Coastguard Worker``Clang`` runs to get started. The "``opt``" tool allows you to
207*9880d681SAndroid Build Coastguard Workerexperiment with passes from the command line, so you can see if they do
208*9880d681SAndroid Build Coastguard Workeranything.
209*9880d681SAndroid Build Coastguard Worker
210*9880d681SAndroid Build Coastguard WorkerNow that we have reasonable code coming out of our front-end, lets talk
211*9880d681SAndroid Build Coastguard Workerabout executing it!
212*9880d681SAndroid Build Coastguard Worker
213*9880d681SAndroid Build Coastguard WorkerAdding a JIT Compiler
214*9880d681SAndroid Build Coastguard Worker=====================
215*9880d681SAndroid Build Coastguard Worker
216*9880d681SAndroid Build Coastguard WorkerCode that is available in LLVM IR can have a wide variety of tools
217*9880d681SAndroid Build Coastguard Workerapplied to it. For example, you can run optimizations on it (as we did
218*9880d681SAndroid Build Coastguard Workerabove), you can dump it out in textual or binary forms, you can compile
219*9880d681SAndroid Build Coastguard Workerthe code to an assembly file (.s) for some target, or you can JIT
220*9880d681SAndroid Build Coastguard Workercompile it. The nice thing about the LLVM IR representation is that it
221*9880d681SAndroid Build Coastguard Workeris the "common currency" between many different parts of the compiler.
222*9880d681SAndroid Build Coastguard Worker
223*9880d681SAndroid Build Coastguard WorkerIn this section, we'll add JIT compiler support to our interpreter. The
224*9880d681SAndroid Build Coastguard Workerbasic idea that we want for Kaleidoscope is to have the user enter
225*9880d681SAndroid Build Coastguard Workerfunction bodies as they do now, but immediately evaluate the top-level
226*9880d681SAndroid Build Coastguard Workerexpressions they type in. For example, if they type in "1 + 2;", we
227*9880d681SAndroid Build Coastguard Workershould evaluate and print out 3. If they define a function, they should
228*9880d681SAndroid Build Coastguard Workerbe able to call it from the command line.
229*9880d681SAndroid Build Coastguard Worker
230*9880d681SAndroid Build Coastguard WorkerIn order to do this, we first declare and initialize the JIT. This is
231*9880d681SAndroid Build Coastguard Workerdone by adding a global variable ``TheJIT``, and initializing it in
232*9880d681SAndroid Build Coastguard Worker``main``:
233*9880d681SAndroid Build Coastguard Worker
234*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
235*9880d681SAndroid Build Coastguard Worker
236*9880d681SAndroid Build Coastguard Worker    static std::unique_ptr<KaleidoscopeJIT> TheJIT;
237*9880d681SAndroid Build Coastguard Worker    ...
238*9880d681SAndroid Build Coastguard Worker    int main() {
239*9880d681SAndroid Build Coastguard Worker      ..
240*9880d681SAndroid Build Coastguard Worker      TheJIT = llvm::make_unique<KaleidoscopeJIT>();
241*9880d681SAndroid Build Coastguard Worker
242*9880d681SAndroid Build Coastguard Worker      // Run the main "interpreter loop" now.
243*9880d681SAndroid Build Coastguard Worker      MainLoop();
244*9880d681SAndroid Build Coastguard Worker
245*9880d681SAndroid Build Coastguard Worker      return 0;
246*9880d681SAndroid Build Coastguard Worker    }
247*9880d681SAndroid Build Coastguard Worker
248*9880d681SAndroid Build Coastguard WorkerThe KaleidoscopeJIT class is a simple JIT built specifically for these
249*9880d681SAndroid Build Coastguard Workertutorials. In later chapters we will look at how it works and extend it with
250*9880d681SAndroid Build Coastguard Workernew features, but for now we will take it as given. Its API is very simple::
251*9880d681SAndroid Build Coastguard Worker``addModule`` adds an LLVM IR module to the JIT, making its functions
252*9880d681SAndroid Build Coastguard Workeravailable for execution; ``removeModule`` removes a module, freeing any
253*9880d681SAndroid Build Coastguard Workermemory associated with the code in that module; and ``findSymbol`` allows us
254*9880d681SAndroid Build Coastguard Workerto look up pointers to the compiled code.
255*9880d681SAndroid Build Coastguard Worker
256*9880d681SAndroid Build Coastguard WorkerWe can take this simple API and change our code that parses top-level expressions to
257*9880d681SAndroid Build Coastguard Workerlook like this:
258*9880d681SAndroid Build Coastguard Worker
259*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
260*9880d681SAndroid Build Coastguard Worker
261*9880d681SAndroid Build Coastguard Worker    static void HandleTopLevelExpression() {
262*9880d681SAndroid Build Coastguard Worker      // Evaluate a top-level expression into an anonymous function.
263*9880d681SAndroid Build Coastguard Worker      if (auto FnAST = ParseTopLevelExpr()) {
264*9880d681SAndroid Build Coastguard Worker        if (FnAST->codegen()) {
265*9880d681SAndroid Build Coastguard Worker
266*9880d681SAndroid Build Coastguard Worker          // JIT the module containing the anonymous expression, keeping a handle so
267*9880d681SAndroid Build Coastguard Worker          // we can free it later.
268*9880d681SAndroid Build Coastguard Worker          auto H = TheJIT->addModule(std::move(TheModule));
269*9880d681SAndroid Build Coastguard Worker          InitializeModuleAndPassManager();
270*9880d681SAndroid Build Coastguard Worker
271*9880d681SAndroid Build Coastguard Worker          // Search the JIT for the __anon_expr symbol.
272*9880d681SAndroid Build Coastguard Worker          auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
273*9880d681SAndroid Build Coastguard Worker          assert(ExprSymbol && "Function not found");
274*9880d681SAndroid Build Coastguard Worker
275*9880d681SAndroid Build Coastguard Worker          // Get the symbol's address and cast it to the right type (takes no
276*9880d681SAndroid Build Coastguard Worker          // arguments, returns a double) so we can call it as a native function.
277*9880d681SAndroid Build Coastguard Worker          double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
278*9880d681SAndroid Build Coastguard Worker          fprintf(stderr, "Evaluated to %f\n", FP());
279*9880d681SAndroid Build Coastguard Worker
280*9880d681SAndroid Build Coastguard Worker          // Delete the anonymous expression module from the JIT.
281*9880d681SAndroid Build Coastguard Worker          TheJIT->removeModule(H);
282*9880d681SAndroid Build Coastguard Worker        }
283*9880d681SAndroid Build Coastguard Worker
284*9880d681SAndroid Build Coastguard WorkerIf parsing and codegen succeeed, the next step is to add the module containing
285*9880d681SAndroid Build Coastguard Workerthe top-level expression to the JIT. We do this by calling addModule, which
286*9880d681SAndroid Build Coastguard Workertriggers code generation for all the functions in the module, and returns a
287*9880d681SAndroid Build Coastguard Workerhandle that can be used to remove the module from the JIT later. Once the module
288*9880d681SAndroid Build Coastguard Workerhas been added to the JIT it can no longer be modified, so we also open a new
289*9880d681SAndroid Build Coastguard Workermodule to hold subsequent code by calling ``InitializeModuleAndPassManager()``.
290*9880d681SAndroid Build Coastguard Worker
291*9880d681SAndroid Build Coastguard WorkerOnce we've added the module to the JIT we need to get a pointer to the final
292*9880d681SAndroid Build Coastguard Workergenerated code. We do this by calling the JIT's findSymbol method, and passing
293*9880d681SAndroid Build Coastguard Workerthe name of the top-level expression function: ``__anon_expr``. Since we just
294*9880d681SAndroid Build Coastguard Workeradded this function, we assert that findSymbol returned a result.
295*9880d681SAndroid Build Coastguard Worker
296*9880d681SAndroid Build Coastguard WorkerNext, we get the in-memory address of the ``__anon_expr`` function by calling
297*9880d681SAndroid Build Coastguard Worker``getAddress()`` on the symbol. Recall that we compile top-level expressions
298*9880d681SAndroid Build Coastguard Workerinto a self-contained LLVM function that takes no arguments and returns the
299*9880d681SAndroid Build Coastguard Workercomputed double. Because the LLVM JIT compiler matches the native platform ABI,
300*9880d681SAndroid Build Coastguard Workerthis means that you can just cast the result pointer to a function pointer of
301*9880d681SAndroid Build Coastguard Workerthat type and call it directly. This means, there is no difference between JIT
302*9880d681SAndroid Build Coastguard Workercompiled code and native machine code that is statically linked into your
303*9880d681SAndroid Build Coastguard Workerapplication.
304*9880d681SAndroid Build Coastguard Worker
305*9880d681SAndroid Build Coastguard WorkerFinally, since we don't support re-evaluation of top-level expressions, we
306*9880d681SAndroid Build Coastguard Workerremove the module from the JIT when we're done to free the associated memory.
307*9880d681SAndroid Build Coastguard WorkerRecall, however, that the module we created a few lines earlier (via
308*9880d681SAndroid Build Coastguard Worker``InitializeModuleAndPassManager``) is still open and waiting for new code to be
309*9880d681SAndroid Build Coastguard Workeradded.
310*9880d681SAndroid Build Coastguard Worker
311*9880d681SAndroid Build Coastguard WorkerWith just these two changes, lets see how Kaleidoscope works now!
312*9880d681SAndroid Build Coastguard Worker
313*9880d681SAndroid Build Coastguard Worker::
314*9880d681SAndroid Build Coastguard Worker
315*9880d681SAndroid Build Coastguard Worker    ready> 4+5;
316*9880d681SAndroid Build Coastguard Worker    Read top-level expression:
317*9880d681SAndroid Build Coastguard Worker    define double @0() {
318*9880d681SAndroid Build Coastguard Worker    entry:
319*9880d681SAndroid Build Coastguard Worker      ret double 9.000000e+00
320*9880d681SAndroid Build Coastguard Worker    }
321*9880d681SAndroid Build Coastguard Worker
322*9880d681SAndroid Build Coastguard Worker    Evaluated to 9.000000
323*9880d681SAndroid Build Coastguard Worker
324*9880d681SAndroid Build Coastguard WorkerWell this looks like it is basically working. The dump of the function
325*9880d681SAndroid Build Coastguard Workershows the "no argument function that always returns double" that we
326*9880d681SAndroid Build Coastguard Workersynthesize for each top-level expression that is typed in. This
327*9880d681SAndroid Build Coastguard Workerdemonstrates very basic functionality, but can we do more?
328*9880d681SAndroid Build Coastguard Worker
329*9880d681SAndroid Build Coastguard Worker::
330*9880d681SAndroid Build Coastguard Worker
331*9880d681SAndroid Build Coastguard Worker    ready> def testfunc(x y) x + y*2;
332*9880d681SAndroid Build Coastguard Worker    Read function definition:
333*9880d681SAndroid Build Coastguard Worker    define double @testfunc(double %x, double %y) {
334*9880d681SAndroid Build Coastguard Worker    entry:
335*9880d681SAndroid Build Coastguard Worker      %multmp = fmul double %y, 2.000000e+00
336*9880d681SAndroid Build Coastguard Worker      %addtmp = fadd double %multmp, %x
337*9880d681SAndroid Build Coastguard Worker      ret double %addtmp
338*9880d681SAndroid Build Coastguard Worker    }
339*9880d681SAndroid Build Coastguard Worker
340*9880d681SAndroid Build Coastguard Worker    ready> testfunc(4, 10);
341*9880d681SAndroid Build Coastguard Worker    Read top-level expression:
342*9880d681SAndroid Build Coastguard Worker    define double @1() {
343*9880d681SAndroid Build Coastguard Worker    entry:
344*9880d681SAndroid Build Coastguard Worker      %calltmp = call double @testfunc(double 4.000000e+00, double 1.000000e+01)
345*9880d681SAndroid Build Coastguard Worker      ret double %calltmp
346*9880d681SAndroid Build Coastguard Worker    }
347*9880d681SAndroid Build Coastguard Worker
348*9880d681SAndroid Build Coastguard Worker    Evaluated to 24.000000
349*9880d681SAndroid Build Coastguard Worker
350*9880d681SAndroid Build Coastguard Worker    ready> testfunc(5, 10);
351*9880d681SAndroid Build Coastguard Worker    ready> LLVM ERROR: Program used external function 'testfunc' which could not be resolved!
352*9880d681SAndroid Build Coastguard Worker
353*9880d681SAndroid Build Coastguard Worker
354*9880d681SAndroid Build Coastguard WorkerFunction definitions and calls also work, but something went very wrong on that
355*9880d681SAndroid Build Coastguard Workerlast line. The call looks valid, so what happened? As you may have guessed from
356*9880d681SAndroid Build Coastguard Workerthe the API a Module is a unit of allocation for the JIT, and testfunc was part
357*9880d681SAndroid Build Coastguard Workerof the same module that contained anonymous expression. When we removed that
358*9880d681SAndroid Build Coastguard Workermodule from the JIT to free the memory for the anonymous expression, we deleted
359*9880d681SAndroid Build Coastguard Workerthe definition of ``testfunc`` along with it. Then, when we tried to call
360*9880d681SAndroid Build Coastguard Workertestfunc a second time, the JIT could no longer find it.
361*9880d681SAndroid Build Coastguard Worker
362*9880d681SAndroid Build Coastguard WorkerThe easiest way to fix this is to put the anonymous expression in a separate
363*9880d681SAndroid Build Coastguard Workermodule from the rest of the function definitions. The JIT will happily resolve
364*9880d681SAndroid Build Coastguard Workerfunction calls across module boundaries, as long as each of the functions called
365*9880d681SAndroid Build Coastguard Workerhas a prototype, and is added to the JIT before it is called. By putting the
366*9880d681SAndroid Build Coastguard Workeranonymous expression in a different module we can delete it without affecting
367*9880d681SAndroid Build Coastguard Workerthe rest of the functions.
368*9880d681SAndroid Build Coastguard Worker
369*9880d681SAndroid Build Coastguard WorkerIn fact, we're going to go a step further and put every function in its own
370*9880d681SAndroid Build Coastguard Workermodule. Doing so allows us to exploit a useful property of the KaleidoscopeJIT
371*9880d681SAndroid Build Coastguard Workerthat will make our environment more REPL-like: Functions can be added to the
372*9880d681SAndroid Build Coastguard WorkerJIT more than once (unlike a module where every function must have a unique
373*9880d681SAndroid Build Coastguard Workerdefinition). When you look up a symbol in KaleidoscopeJIT it will always return
374*9880d681SAndroid Build Coastguard Workerthe most recent definition:
375*9880d681SAndroid Build Coastguard Worker
376*9880d681SAndroid Build Coastguard Worker::
377*9880d681SAndroid Build Coastguard Worker
378*9880d681SAndroid Build Coastguard Worker    ready> def foo(x) x + 1;
379*9880d681SAndroid Build Coastguard Worker    Read function definition:
380*9880d681SAndroid Build Coastguard Worker    define double @foo(double %x) {
381*9880d681SAndroid Build Coastguard Worker    entry:
382*9880d681SAndroid Build Coastguard Worker      %addtmp = fadd double %x, 1.000000e+00
383*9880d681SAndroid Build Coastguard Worker      ret double %addtmp
384*9880d681SAndroid Build Coastguard Worker    }
385*9880d681SAndroid Build Coastguard Worker
386*9880d681SAndroid Build Coastguard Worker    ready> foo(2);
387*9880d681SAndroid Build Coastguard Worker    Evaluated to 3.000000
388*9880d681SAndroid Build Coastguard Worker
389*9880d681SAndroid Build Coastguard Worker    ready> def foo(x) x + 2;
390*9880d681SAndroid Build Coastguard Worker    define double @foo(double %x) {
391*9880d681SAndroid Build Coastguard Worker    entry:
392*9880d681SAndroid Build Coastguard Worker      %addtmp = fadd double %x, 2.000000e+00
393*9880d681SAndroid Build Coastguard Worker      ret double %addtmp
394*9880d681SAndroid Build Coastguard Worker    }
395*9880d681SAndroid Build Coastguard Worker
396*9880d681SAndroid Build Coastguard Worker    ready> foo(2);
397*9880d681SAndroid Build Coastguard Worker    Evaluated to 4.000000
398*9880d681SAndroid Build Coastguard Worker
399*9880d681SAndroid Build Coastguard Worker
400*9880d681SAndroid Build Coastguard WorkerTo allow each function to live in its own module we'll need a way to
401*9880d681SAndroid Build Coastguard Workerre-generate previous function declarations into each new module we open:
402*9880d681SAndroid Build Coastguard Worker
403*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
404*9880d681SAndroid Build Coastguard Worker
405*9880d681SAndroid Build Coastguard Worker    static std::unique_ptr<KaleidoscopeJIT> TheJIT;
406*9880d681SAndroid Build Coastguard Worker
407*9880d681SAndroid Build Coastguard Worker    ...
408*9880d681SAndroid Build Coastguard Worker
409*9880d681SAndroid Build Coastguard Worker    Function *getFunction(std::string Name) {
410*9880d681SAndroid Build Coastguard Worker      // First, see if the function has already been added to the current module.
411*9880d681SAndroid Build Coastguard Worker      if (auto *F = TheModule->getFunction(Name))
412*9880d681SAndroid Build Coastguard Worker        return F;
413*9880d681SAndroid Build Coastguard Worker
414*9880d681SAndroid Build Coastguard Worker      // If not, check whether we can codegen the declaration from some existing
415*9880d681SAndroid Build Coastguard Worker      // prototype.
416*9880d681SAndroid Build Coastguard Worker      auto FI = FunctionProtos.find(Name);
417*9880d681SAndroid Build Coastguard Worker      if (FI != FunctionProtos.end())
418*9880d681SAndroid Build Coastguard Worker        return FI->second->codegen();
419*9880d681SAndroid Build Coastguard Worker
420*9880d681SAndroid Build Coastguard Worker      // If no existing prototype exists, return null.
421*9880d681SAndroid Build Coastguard Worker      return nullptr;
422*9880d681SAndroid Build Coastguard Worker    }
423*9880d681SAndroid Build Coastguard Worker
424*9880d681SAndroid Build Coastguard Worker    ...
425*9880d681SAndroid Build Coastguard Worker
426*9880d681SAndroid Build Coastguard Worker    Value *CallExprAST::codegen() {
427*9880d681SAndroid Build Coastguard Worker      // Look up the name in the global module table.
428*9880d681SAndroid Build Coastguard Worker      Function *CalleeF = getFunction(Callee);
429*9880d681SAndroid Build Coastguard Worker
430*9880d681SAndroid Build Coastguard Worker    ...
431*9880d681SAndroid Build Coastguard Worker
432*9880d681SAndroid Build Coastguard Worker    Function *FunctionAST::codegen() {
433*9880d681SAndroid Build Coastguard Worker      // Transfer ownership of the prototype to the FunctionProtos map, but keep a
434*9880d681SAndroid Build Coastguard Worker      // reference to it for use below.
435*9880d681SAndroid Build Coastguard Worker      auto &P = *Proto;
436*9880d681SAndroid Build Coastguard Worker      FunctionProtos[Proto->getName()] = std::move(Proto);
437*9880d681SAndroid Build Coastguard Worker      Function *TheFunction = getFunction(P.getName());
438*9880d681SAndroid Build Coastguard Worker      if (!TheFunction)
439*9880d681SAndroid Build Coastguard Worker        return nullptr;
440*9880d681SAndroid Build Coastguard Worker
441*9880d681SAndroid Build Coastguard Worker
442*9880d681SAndroid Build Coastguard WorkerTo enable this, we'll start by adding a new global, ``FunctionProtos``, that
443*9880d681SAndroid Build Coastguard Workerholds the most recent prototype for each function. We'll also add a convenience
444*9880d681SAndroid Build Coastguard Workermethod, ``getFunction()``, to replace calls to ``TheModule->getFunction()``.
445*9880d681SAndroid Build Coastguard WorkerOur convenience method searches ``TheModule`` for an existing function
446*9880d681SAndroid Build Coastguard Workerdeclaration, falling back to generating a new declaration from FunctionProtos if
447*9880d681SAndroid Build Coastguard Workerit doesn't find one. In ``CallExprAST::codegen()`` we just need to replace the
448*9880d681SAndroid Build Coastguard Workercall to ``TheModule->getFunction()``. In ``FunctionAST::codegen()`` we need to
449*9880d681SAndroid Build Coastguard Workerupdate the FunctionProtos map first, then call ``getFunction()``. With this
450*9880d681SAndroid Build Coastguard Workerdone, we can always obtain a function declaration in the current module for any
451*9880d681SAndroid Build Coastguard Workerpreviously declared function.
452*9880d681SAndroid Build Coastguard Worker
453*9880d681SAndroid Build Coastguard WorkerWe also need to update HandleDefinition and HandleExtern:
454*9880d681SAndroid Build Coastguard Worker
455*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
456*9880d681SAndroid Build Coastguard Worker
457*9880d681SAndroid Build Coastguard Worker    static void HandleDefinition() {
458*9880d681SAndroid Build Coastguard Worker      if (auto FnAST = ParseDefinition()) {
459*9880d681SAndroid Build Coastguard Worker        if (auto *FnIR = FnAST->codegen()) {
460*9880d681SAndroid Build Coastguard Worker          fprintf(stderr, "Read function definition:");
461*9880d681SAndroid Build Coastguard Worker          FnIR->dump();
462*9880d681SAndroid Build Coastguard Worker          TheJIT->addModule(std::move(TheModule));
463*9880d681SAndroid Build Coastguard Worker          InitializeModuleAndPassManager();
464*9880d681SAndroid Build Coastguard Worker        }
465*9880d681SAndroid Build Coastguard Worker      } else {
466*9880d681SAndroid Build Coastguard Worker        // Skip token for error recovery.
467*9880d681SAndroid Build Coastguard Worker         getNextToken();
468*9880d681SAndroid Build Coastguard Worker      }
469*9880d681SAndroid Build Coastguard Worker    }
470*9880d681SAndroid Build Coastguard Worker
471*9880d681SAndroid Build Coastguard Worker    static void HandleExtern() {
472*9880d681SAndroid Build Coastguard Worker      if (auto ProtoAST = ParseExtern()) {
473*9880d681SAndroid Build Coastguard Worker        if (auto *FnIR = ProtoAST->codegen()) {
474*9880d681SAndroid Build Coastguard Worker          fprintf(stderr, "Read extern: ");
475*9880d681SAndroid Build Coastguard Worker          FnIR->dump();
476*9880d681SAndroid Build Coastguard Worker          FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
477*9880d681SAndroid Build Coastguard Worker        }
478*9880d681SAndroid Build Coastguard Worker      } else {
479*9880d681SAndroid Build Coastguard Worker        // Skip token for error recovery.
480*9880d681SAndroid Build Coastguard Worker        getNextToken();
481*9880d681SAndroid Build Coastguard Worker      }
482*9880d681SAndroid Build Coastguard Worker    }
483*9880d681SAndroid Build Coastguard Worker
484*9880d681SAndroid Build Coastguard WorkerIn HandleDefinition, we add two lines to transfer the newly defined function to
485*9880d681SAndroid Build Coastguard Workerthe JIT and open a new module. In HandleExtern, we just need to add one line to
486*9880d681SAndroid Build Coastguard Workeradd the prototype to FunctionProtos.
487*9880d681SAndroid Build Coastguard Worker
488*9880d681SAndroid Build Coastguard WorkerWith these changes made, lets try our REPL again (I removed the dump of the
489*9880d681SAndroid Build Coastguard Workeranonymous functions this time, you should get the idea by now :) :
490*9880d681SAndroid Build Coastguard Worker
491*9880d681SAndroid Build Coastguard Worker::
492*9880d681SAndroid Build Coastguard Worker
493*9880d681SAndroid Build Coastguard Worker    ready> def foo(x) x + 1;
494*9880d681SAndroid Build Coastguard Worker    ready> foo(2);
495*9880d681SAndroid Build Coastguard Worker    Evaluated to 3.000000
496*9880d681SAndroid Build Coastguard Worker
497*9880d681SAndroid Build Coastguard Worker    ready> def foo(x) x + 2;
498*9880d681SAndroid Build Coastguard Worker    ready> foo(2);
499*9880d681SAndroid Build Coastguard Worker    Evaluated to 4.000000
500*9880d681SAndroid Build Coastguard Worker
501*9880d681SAndroid Build Coastguard WorkerIt works!
502*9880d681SAndroid Build Coastguard Worker
503*9880d681SAndroid Build Coastguard WorkerEven with this simple code, we get some surprisingly powerful capabilities -
504*9880d681SAndroid Build Coastguard Workercheck this out:
505*9880d681SAndroid Build Coastguard Worker
506*9880d681SAndroid Build Coastguard Worker::
507*9880d681SAndroid Build Coastguard Worker
508*9880d681SAndroid Build Coastguard Worker    ready> extern sin(x);
509*9880d681SAndroid Build Coastguard Worker    Read extern:
510*9880d681SAndroid Build Coastguard Worker    declare double @sin(double)
511*9880d681SAndroid Build Coastguard Worker
512*9880d681SAndroid Build Coastguard Worker    ready> extern cos(x);
513*9880d681SAndroid Build Coastguard Worker    Read extern:
514*9880d681SAndroid Build Coastguard Worker    declare double @cos(double)
515*9880d681SAndroid Build Coastguard Worker
516*9880d681SAndroid Build Coastguard Worker    ready> sin(1.0);
517*9880d681SAndroid Build Coastguard Worker    Read top-level expression:
518*9880d681SAndroid Build Coastguard Worker    define double @2() {
519*9880d681SAndroid Build Coastguard Worker    entry:
520*9880d681SAndroid Build Coastguard Worker      ret double 0x3FEAED548F090CEE
521*9880d681SAndroid Build Coastguard Worker    }
522*9880d681SAndroid Build Coastguard Worker
523*9880d681SAndroid Build Coastguard Worker    Evaluated to 0.841471
524*9880d681SAndroid Build Coastguard Worker
525*9880d681SAndroid Build Coastguard Worker    ready> def foo(x) sin(x)*sin(x) + cos(x)*cos(x);
526*9880d681SAndroid Build Coastguard Worker    Read function definition:
527*9880d681SAndroid Build Coastguard Worker    define double @foo(double %x) {
528*9880d681SAndroid Build Coastguard Worker    entry:
529*9880d681SAndroid Build Coastguard Worker      %calltmp = call double @sin(double %x)
530*9880d681SAndroid Build Coastguard Worker      %multmp = fmul double %calltmp, %calltmp
531*9880d681SAndroid Build Coastguard Worker      %calltmp2 = call double @cos(double %x)
532*9880d681SAndroid Build Coastguard Worker      %multmp4 = fmul double %calltmp2, %calltmp2
533*9880d681SAndroid Build Coastguard Worker      %addtmp = fadd double %multmp, %multmp4
534*9880d681SAndroid Build Coastguard Worker      ret double %addtmp
535*9880d681SAndroid Build Coastguard Worker    }
536*9880d681SAndroid Build Coastguard Worker
537*9880d681SAndroid Build Coastguard Worker    ready> foo(4.0);
538*9880d681SAndroid Build Coastguard Worker    Read top-level expression:
539*9880d681SAndroid Build Coastguard Worker    define double @3() {
540*9880d681SAndroid Build Coastguard Worker    entry:
541*9880d681SAndroid Build Coastguard Worker      %calltmp = call double @foo(double 4.000000e+00)
542*9880d681SAndroid Build Coastguard Worker      ret double %calltmp
543*9880d681SAndroid Build Coastguard Worker    }
544*9880d681SAndroid Build Coastguard Worker
545*9880d681SAndroid Build Coastguard Worker    Evaluated to 1.000000
546*9880d681SAndroid Build Coastguard Worker
547*9880d681SAndroid Build Coastguard WorkerWhoa, how does the JIT know about sin and cos? The answer is surprisingly
548*9880d681SAndroid Build Coastguard Workersimple: The KaleidoscopeJIT has a straightforward symbol resolution rule that
549*9880d681SAndroid Build Coastguard Workerit uses to find symbols that aren't available in any given module: First
550*9880d681SAndroid Build Coastguard Workerit searches all the modules that have already been added to the JIT, from the
551*9880d681SAndroid Build Coastguard Workermost recent to the oldest, to find the newest definition. If no definition is
552*9880d681SAndroid Build Coastguard Workerfound inside the JIT, it falls back to calling "``dlsym("sin")``" on the
553*9880d681SAndroid Build Coastguard WorkerKaleidoscope process itself. Since "``sin``" is defined within the JIT's
554*9880d681SAndroid Build Coastguard Workeraddress space, it simply patches up calls in the module to call the libm
555*9880d681SAndroid Build Coastguard Workerversion of ``sin`` directly.
556*9880d681SAndroid Build Coastguard Worker
557*9880d681SAndroid Build Coastguard WorkerIn the future we'll see how tweaking this symbol resolution rule can be used to
558*9880d681SAndroid Build Coastguard Workerenable all sorts of useful features, from security (restricting the set of
559*9880d681SAndroid Build Coastguard Workersymbols available to JIT'd code), to dynamic code generation based on symbol
560*9880d681SAndroid Build Coastguard Workernames, and even lazy compilation.
561*9880d681SAndroid Build Coastguard Worker
562*9880d681SAndroid Build Coastguard WorkerOne immediate benefit of the symbol resolution rule is that we can now extend
563*9880d681SAndroid Build Coastguard Workerthe language by writing arbitrary C++ code to implement operations. For example,
564*9880d681SAndroid Build Coastguard Workerif we add:
565*9880d681SAndroid Build Coastguard Worker
566*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
567*9880d681SAndroid Build Coastguard Worker
568*9880d681SAndroid Build Coastguard Worker    /// putchard - putchar that takes a double and returns 0.
569*9880d681SAndroid Build Coastguard Worker    extern "C" double putchard(double X) {
570*9880d681SAndroid Build Coastguard Worker      fputc((char)X, stderr);
571*9880d681SAndroid Build Coastguard Worker      return 0;
572*9880d681SAndroid Build Coastguard Worker    }
573*9880d681SAndroid Build Coastguard Worker
574*9880d681SAndroid Build Coastguard WorkerNow we can produce simple output to the console by using things like:
575*9880d681SAndroid Build Coastguard Worker"``extern putchard(x); putchard(120);``", which prints a lowercase 'x'
576*9880d681SAndroid Build Coastguard Workeron the console (120 is the ASCII code for 'x'). Similar code could be
577*9880d681SAndroid Build Coastguard Workerused to implement file I/O, console input, and many other capabilities
578*9880d681SAndroid Build Coastguard Workerin Kaleidoscope.
579*9880d681SAndroid Build Coastguard Worker
580*9880d681SAndroid Build Coastguard WorkerThis completes the JIT and optimizer chapter of the Kaleidoscope
581*9880d681SAndroid Build Coastguard Workertutorial. At this point, we can compile a non-Turing-complete
582*9880d681SAndroid Build Coastguard Workerprogramming language, optimize and JIT compile it in a user-driven way.
583*9880d681SAndroid Build Coastguard WorkerNext up we'll look into `extending the language with control flow
584*9880d681SAndroid Build Coastguard Workerconstructs <LangImpl5.html>`_, tackling some interesting LLVM IR issues
585*9880d681SAndroid Build Coastguard Workeralong the way.
586*9880d681SAndroid Build Coastguard Worker
587*9880d681SAndroid Build Coastguard WorkerFull Code Listing
588*9880d681SAndroid Build Coastguard Worker=================
589*9880d681SAndroid Build Coastguard Worker
590*9880d681SAndroid Build Coastguard WorkerHere is the complete code listing for our running example, enhanced with
591*9880d681SAndroid Build Coastguard Workerthe LLVM JIT and optimizer. To build this example, use:
592*9880d681SAndroid Build Coastguard Worker
593*9880d681SAndroid Build Coastguard Worker.. code-block:: bash
594*9880d681SAndroid Build Coastguard Worker
595*9880d681SAndroid Build Coastguard Worker    # Compile
596*9880d681SAndroid Build Coastguard Worker    clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy
597*9880d681SAndroid Build Coastguard Worker    # Run
598*9880d681SAndroid Build Coastguard Worker    ./toy
599*9880d681SAndroid Build Coastguard Worker
600*9880d681SAndroid Build Coastguard WorkerIf you are compiling this on Linux, make sure to add the "-rdynamic"
601*9880d681SAndroid Build Coastguard Workeroption as well. This makes sure that the external functions are resolved
602*9880d681SAndroid Build Coastguard Workerproperly at runtime.
603*9880d681SAndroid Build Coastguard Worker
604*9880d681SAndroid Build Coastguard WorkerHere is the code:
605*9880d681SAndroid Build Coastguard Worker
606*9880d681SAndroid Build Coastguard Worker.. literalinclude:: ../../examples/Kaleidoscope/Chapter4/toy.cpp
607*9880d681SAndroid Build Coastguard Worker   :language: c++
608*9880d681SAndroid Build Coastguard Worker
609*9880d681SAndroid Build Coastguard Worker`Next: Extending the language: control flow <LangImpl05.html>`_
610*9880d681SAndroid Build Coastguard Worker
611