blob: 3188135384e0e218621ef6aa1a6bf67bbf5c39ab [file] [log] [blame]
Chris Lattnerc0b42e92007-10-23 06:27:55 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
3
4<html>
5<head>
6 <title>Kaleidoscope: Adding JIT and Optimizer Support</title>
7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
8 <meta name="author" content="Chris Lattner">
9 <link rel="stylesheet" href="../llvm.css" type="text/css">
10</head>
11
12<body>
13
14<div class="doc_title">Kaleidoscope: Adding JIT and Optimizer Support</div>
15
Chris Lattner128eb862007-11-05 19:06:59 +000016<ul>
Chris Lattner0e555b12007-11-05 20:04:56 +000017<li><a href="index.html">Up to Tutorial Index</a></li>
Chris Lattner128eb862007-11-05 19:06:59 +000018<li>Chapter 4
19 <ol>
20 <li><a href="#intro">Chapter 4 Introduction</a></li>
21 <li><a href="#trivialconstfold">Trivial Constant Folding</a></li>
22 <li><a href="#optimizerpasses">LLVM Optimization Passes</a></li>
23 <li><a href="#jit">Adding a JIT Compiler</a></li>
24 <li><a href="#code">Full Code Listing</a></li>
25 </ol>
26</li>
Chris Lattner0e555b12007-11-05 20:04:56 +000027<li><a href="LangImpl5.html">Chapter 5</a>: Extending the Language: Control
28Flow</li>
Chris Lattner128eb862007-11-05 19:06:59 +000029</ul>
30
Chris Lattnerc0b42e92007-10-23 06:27:55 +000031<div class="doc_author">
32 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
33</div>
34
35<!-- *********************************************************************** -->
Chris Lattner128eb862007-11-05 19:06:59 +000036<div class="doc_section"><a name="intro">Chapter 4 Introduction</a></div>
Chris Lattnerc0b42e92007-10-23 06:27:55 +000037<!-- *********************************************************************** -->
38
39<div class="doc_text">
40
Chris Lattner128eb862007-11-05 19:06:59 +000041<p>Welcome to Chapter 4 of the "<a href="index.html">Implementing a language
Chris Lattnera54c2012007-11-07 05:28:43 +000042with LLVM</a>" tutorial. Chapters 1-3 described the implementation of a simple
43language and added support for generating LLVM IR. This chapter describes
Chris Lattner128eb862007-11-05 19:06:59 +000044two new techniques: adding optimizer support to your language, and adding JIT
Chris Lattner41fcea32007-11-13 07:06:30 +000045compiler support. These additions will demonstrate how to get nice, efficient code
46for the Kaleidoscope language.</p>
Chris Lattnerc0b42e92007-10-23 06:27:55 +000047
48</div>
49
50<!-- *********************************************************************** -->
Chris Lattner118749e2007-10-25 06:23:36 +000051<div class="doc_section"><a name="trivialconstfold">Trivial Constant
52Folding</a></div>
Chris Lattnerc0b42e92007-10-23 06:27:55 +000053<!-- *********************************************************************** -->
54
55<div class="doc_text">
56
57<p>
Chris Lattner118749e2007-10-25 06:23:36 +000058Our demonstration for Chapter 3 is elegant and easy to extend. Unfortunately,
Duncan Sands89f6d882008-04-13 06:22:09 +000059it does not produce wonderful code. The IRBuilder, however, does give us
60obvious optimizations when compiling simple code:</p>
Chris Lattner118749e2007-10-25 06:23:36 +000061
62<div class="doc_code">
63<pre>
64ready&gt; <b>def test(x) 1+2+x;</b>
65Read function definition:
66define double @test(double %x) {
67entry:
68 %addtmp = add double 3.000000e+00, %x
69 ret double %addtmp
70}
71</pre>
72</div>
73
Duncan Sands89f6d882008-04-13 06:22:09 +000074<p>This code is not a literal transcription of the AST built by parsing the
75input. That would be:
76
77<div class="doc_code">
78<pre>
79ready&gt; <b>def test(x) 1+2+x;</b>
80Read function definition:
81define double @test(double %x) {
82entry:
83 %addtmp = add double 2.000000e+00, 1.000000e+00
84 %addtmp1 = add double %addtmp, %x
85 ret double %addtmp1
86}
87</pre>
88</div>
89
Gabor Greif94244f32009-03-11 20:04:08 +000090<p>Constant folding, as seen above, in particular, is a very common and very
Duncan Sands89f6d882008-04-13 06:22:09 +000091important optimization: so much so that many language implementors implement
92constant folding support in their AST representation.</p>
93
94<p>With LLVM, you don't need this support in the AST. Since all calls to build
95LLVM IR go through the LLVM IR builder, the builder itself checked to see if
96there was a constant folding opportunity when you call it. If so, it just does
97the constant fold and return the constant instead of creating an instruction.
98
Chris Lattnera54c2012007-11-07 05:28:43 +000099<p>Well, that was easy :). In practice, we recommend always using
Duncan Sands89f6d882008-04-13 06:22:09 +0000100<tt>IRBuilder</tt> when generating code like this. It has no
Chris Lattner118749e2007-10-25 06:23:36 +0000101"syntactic overhead" for its use (you don't have to uglify your compiler with
102constant checks everywhere) and it can dramatically reduce the amount of
103LLVM IR that is generated in some cases (particular for languages with a macro
104preprocessor or that use a lot of constants).</p>
105
Duncan Sands89f6d882008-04-13 06:22:09 +0000106<p>On the other hand, the <tt>IRBuilder</tt> is limited by the fact
Chris Lattner118749e2007-10-25 06:23:36 +0000107that it does all of its analysis inline with the code as it is built. If you
108take a slightly more complex example:</p>
109
110<div class="doc_code">
111<pre>
112ready&gt; <b>def test(x) (1+2+x)*(x+(1+2));</b>
113ready> Read function definition:
114define double @test(double %x) {
115entry:
116 %addtmp = add double 3.000000e+00, %x
117 %addtmp1 = add double %x, 3.000000e+00
118 %multmp = mul double %addtmp, %addtmp1
119 ret double %multmp
120}
121</pre>
122</div>
123
124<p>In this case, the LHS and RHS of the multiplication are the same value. We'd
125really like to see this generate "<tt>tmp = x+3; result = tmp*tmp;</tt>" instead
Chris Lattner1ace67c2008-04-15 16:59:22 +0000126of computing "<tt>x+3</tt>" twice.</p>
Chris Lattner118749e2007-10-25 06:23:36 +0000127
128<p>Unfortunately, no amount of local analysis will be able to detect and correct
129this. This requires two transformations: reassociation of expressions (to
130make the add's lexically identical) and Common Subexpression Elimination (CSE)
131to delete the redundant add instruction. Fortunately, LLVM provides a broad
132range of optimizations that you can use, in the form of "passes".</p>
133
134</div>
135
136<!-- *********************************************************************** -->
137<div class="doc_section"><a name="optimizerpasses">LLVM Optimization
138 Passes</a></div>
139<!-- *********************************************************************** -->
140
141<div class="doc_text">
142
Chris Lattner41fcea32007-11-13 07:06:30 +0000143<p>LLVM provides many optimization passes, which do many different sorts of
Chris Lattner118749e2007-10-25 06:23:36 +0000144things and have different tradeoffs. Unlike other systems, LLVM doesn't hold
145to the mistaken notion that one set of optimizations is right for all languages
146and for all situations. LLVM allows a compiler implementor to make complete
147decisions about what optimizations to use, in which order, and in what
148situation.</p>
149
150<p>As a concrete example, LLVM supports both "whole module" passes, which look
151across as large of body of code as they can (often a whole file, but if run
152at link time, this can be a substantial portion of the whole program). It also
153supports and includes "per-function" passes which just operate on a single
154function at a time, without looking at other functions. For more information
Chris Lattner41fcea32007-11-13 07:06:30 +0000155on passes and how they are run, see the <a href="../WritingAnLLVMPass.html">How
Chris Lattnera54c2012007-11-07 05:28:43 +0000156to Write a Pass</a> document and the <a href="../Passes.html">List of LLVM
157Passes</a>.</p>
Chris Lattner118749e2007-10-25 06:23:36 +0000158
159<p>For Kaleidoscope, we are currently generating functions on the fly, one at
160a time, as the user types them in. We aren't shooting for the ultimate
161optimization experience in this setting, but we also want to catch the easy and
162quick stuff where possible. As such, we will choose to run a few per-function
163optimizations as the user types the function in. If we wanted to make a "static
164Kaleidoscope compiler", we would use exactly the code we have now, except that
165we would defer running the optimizer until the entire file has been parsed.</p>
166
167<p>In order to get per-function optimizations going, we need to set up a
168<a href="../WritingAnLLVMPass.html#passmanager">FunctionPassManager</a> to hold and
169organize the LLVM optimizations that we want to run. Once we have that, we can
170add a set of optimizations to run. The code looks like this:</p>
171
172<div class="doc_code">
173<pre>
Reid Kleckner60130f02009-08-26 20:58:25 +0000174 ExistingModuleProvider *OurModuleProvider =
175 new ExistingModuleProvider(TheModule);
Chris Lattner118749e2007-10-25 06:23:36 +0000176
Reid Kleckner60130f02009-08-26 20:58:25 +0000177 FunctionPassManager OurFPM(OurModuleProvider);
Chris Lattner118749e2007-10-25 06:23:36 +0000178
Reid Kleckner60130f02009-08-26 20:58:25 +0000179 // Set up the optimizer pipeline. Start with registering info about how the
180 // target lays out data structures.
181 OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
182 // Do simple "peephole" optimizations and bit-twiddling optzns.
183 OurFPM.add(createInstructionCombiningPass());
184 // Reassociate expressions.
185 OurFPM.add(createReassociatePass());
186 // Eliminate Common SubExpressions.
187 OurFPM.add(createGVNPass());
188 // Simplify the control flow graph (deleting unreachable blocks, etc).
189 OurFPM.add(createCFGSimplificationPass());
190
Nick Lewycky422094c2009-09-13 21:38:54 +0000191 OurFPM.doInitialization();
192
Reid Kleckner60130f02009-08-26 20:58:25 +0000193 // Set the global so the code gen can use this.
194 TheFPM = &amp;OurFPM;
195
196 // Run the main "interpreter loop" now.
197 MainLoop();
Chris Lattner118749e2007-10-25 06:23:36 +0000198</pre>
199</div>
200
Chris Lattner41fcea32007-11-13 07:06:30 +0000201<p>This code defines two objects, an <tt>ExistingModuleProvider</tt> and a
Chris Lattner118749e2007-10-25 06:23:36 +0000202<tt>FunctionPassManager</tt>. The former is basically a wrapper around our
203<tt>Module</tt> that the PassManager requires. It provides certain flexibility
Chris Lattner41fcea32007-11-13 07:06:30 +0000204that we're not going to take advantage of here, so I won't dive into any details
205about it.</p>
Chris Lattner118749e2007-10-25 06:23:36 +0000206
Chris Lattner41fcea32007-11-13 07:06:30 +0000207<p>The meat of the matter here, is the definition of "<tt>OurFPM</tt>". It
Chris Lattner118749e2007-10-25 06:23:36 +0000208requires a pointer to the <tt>Module</tt> (through the <tt>ModuleProvider</tt>)
209to construct itself. Once it is set up, we use a series of "add" calls to add
210a bunch of LLVM passes. The first pass is basically boilerplate, it adds a pass
211so that later optimizations know how the data structures in the program are
Benjamin Kramer8040cd32009-10-12 14:46:08 +0000212laid out. The "<tt>TheExecutionEngine</tt>" variable is related to the JIT,
Chris Lattner118749e2007-10-25 06:23:36 +0000213which we will get to in the next section.</p>
214
215<p>In this case, we choose to add 4 optimization passes. The passes we chose
216here are a pretty standard set of "cleanup" optimizations that are useful for
Chris Lattner41fcea32007-11-13 07:06:30 +0000217a wide variety of code. I won't delve into what they do but, believe me,
Chris Lattnera54c2012007-11-07 05:28:43 +0000218they are a good starting place :).</p>
Chris Lattner118749e2007-10-25 06:23:36 +0000219
Chris Lattnera54c2012007-11-07 05:28:43 +0000220<p>Once the PassManager is set up, we need to make use of it. We do this by
Chris Lattner118749e2007-10-25 06:23:36 +0000221running it after our newly created function is constructed (in
222<tt>FunctionAST::Codegen</tt>), but before it is returned to the client:</p>
223
224<div class="doc_code">
225<pre>
226 if (Value *RetVal = Body->Codegen()) {
227 // Finish off the function.
228 Builder.CreateRet(RetVal);
229
230 // Validate the generated code, checking for consistency.
231 verifyFunction(*TheFunction);
232
Chris Lattnera54c2012007-11-07 05:28:43 +0000233 <b>// Optimize the function.
234 TheFPM-&gt;run(*TheFunction);</b>
Chris Lattner118749e2007-10-25 06:23:36 +0000235
236 return TheFunction;
237 }
238</pre>
239</div>
240
Chris Lattner41fcea32007-11-13 07:06:30 +0000241<p>As you can see, this is pretty straightforward. The
Chris Lattner118749e2007-10-25 06:23:36 +0000242<tt>FunctionPassManager</tt> optimizes and updates the LLVM Function* in place,
243improving (hopefully) its body. With this in place, we can try our test above
244again:</p>
245
246<div class="doc_code">
247<pre>
248ready&gt; <b>def test(x) (1+2+x)*(x+(1+2));</b>
249ready> Read function definition:
250define double @test(double %x) {
251entry:
252 %addtmp = add double %x, 3.000000e+00
253 %multmp = mul double %addtmp, %addtmp
254 ret double %multmp
255}
256</pre>
257</div>
258
259<p>As expected, we now get our nicely optimized code, saving a floating point
Chris Lattnera54c2012007-11-07 05:28:43 +0000260add instruction from every execution of this function.</p>
Chris Lattner118749e2007-10-25 06:23:36 +0000261
262<p>LLVM provides a wide variety of optimizations that can be used in certain
Chris Lattner72714232007-10-25 17:52:39 +0000263circumstances. Some <a href="../Passes.html">documentation about the various
264passes</a> is available, but it isn't very complete. Another good source of
Chris Lattner41fcea32007-11-13 07:06:30 +0000265ideas can come from looking at the passes that <tt>llvm-gcc</tt> or
Chris Lattner118749e2007-10-25 06:23:36 +0000266<tt>llvm-ld</tt> run to get started. The "<tt>opt</tt>" tool allows you to
267experiment with passes from the command line, so you can see if they do
268anything.</p>
269
270<p>Now that we have reasonable code coming out of our front-end, lets talk about
271executing it!</p>
272
273</div>
274
275<!-- *********************************************************************** -->
276<div class="doc_section"><a name="jit">Adding a JIT Compiler</a></div>
277<!-- *********************************************************************** -->
278
279<div class="doc_text">
280
Chris Lattnera54c2012007-11-07 05:28:43 +0000281<p>Code that is available in LLVM IR can have a wide variety of tools
Chris Lattner118749e2007-10-25 06:23:36 +0000282applied to it. For example, you can run optimizations on it (as we did above),
283you can dump it out in textual or binary forms, you can compile the code to an
284assembly file (.s) for some target, or you can JIT compile it. The nice thing
Chris Lattnera54c2012007-11-07 05:28:43 +0000285about the LLVM IR representation is that it is the "common currency" between
286many different parts of the compiler.
Chris Lattner118749e2007-10-25 06:23:36 +0000287</p>
288
Chris Lattnera54c2012007-11-07 05:28:43 +0000289<p>In this section, we'll add JIT compiler support to our interpreter. The
Chris Lattner118749e2007-10-25 06:23:36 +0000290basic idea that we want for Kaleidoscope is to have the user enter function
291bodies as they do now, but immediately evaluate the top-level expressions they
292type in. For example, if they type in "1 + 2;", we should evaluate and print
293out 3. If they define a function, they should be able to call it from the
294command line.</p>
295
296<p>In order to do this, we first declare and initialize the JIT. This is done
297by adding a global variable and a call in <tt>main</tt>:</p>
298
299<div class="doc_code">
300<pre>
Chris Lattnera54c2012007-11-07 05:28:43 +0000301<b>static ExecutionEngine *TheExecutionEngine;</b>
Chris Lattner118749e2007-10-25 06:23:36 +0000302...
303int main() {
304 ..
Reid Kleckner60130f02009-08-26 20:58:25 +0000305 <b>// Create the JIT. This takes ownership of the module and module provider.
306 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();</b>
Chris Lattner118749e2007-10-25 06:23:36 +0000307 ..
308}
309</pre>
310</div>
311
312<p>This creates an abstract "Execution Engine" which can be either a JIT
313compiler or the LLVM interpreter. LLVM will automatically pick a JIT compiler
314for you if one is available for your platform, otherwise it will fall back to
315the interpreter.</p>
316
317<p>Once the <tt>ExecutionEngine</tt> is created, the JIT is ready to be used.
Chris Lattner41fcea32007-11-13 07:06:30 +0000318There are a variety of APIs that are useful, but the simplest one is the
Chris Lattner118749e2007-10-25 06:23:36 +0000319"<tt>getPointerToFunction(F)</tt>" method. This method JIT compiles the
320specified LLVM Function and returns a function pointer to the generated machine
321code. In our case, this means that we can change the code that parses a
322top-level expression to look like this:</p>
323
324<div class="doc_code">
325<pre>
326static void HandleTopLevelExpression() {
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000327 // Evaluate a top-level expression into an anonymous function.
Chris Lattner118749e2007-10-25 06:23:36 +0000328 if (FunctionAST *F = ParseTopLevelExpr()) {
329 if (Function *LF = F-&gt;Codegen()) {
330 LF->dump(); // Dump the function for exposition purposes.
331
Chris Lattnera54c2012007-11-07 05:28:43 +0000332 <b>// JIT the function, returning a function pointer.
Chris Lattner118749e2007-10-25 06:23:36 +0000333 void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
334
335 // Cast it to the right type (takes no arguments, returns a double) so we
336 // can call it as a native function.
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000337 double (*FP)() = (double (*)())(intptr_t)FPtr;
Chris Lattnera54c2012007-11-07 05:28:43 +0000338 fprintf(stderr, "Evaluated to %f\n", FP());</b>
Chris Lattner118749e2007-10-25 06:23:36 +0000339 }
340</pre>
341</div>
342
343<p>Recall that we compile top-level expressions into a self-contained LLVM
344function that takes no arguments and returns the computed double. Because the
345LLVM JIT compiler matches the native platform ABI, this means that you can just
346cast the result pointer to a function pointer of that type and call it directly.
Chris Lattner41fcea32007-11-13 07:06:30 +0000347This means, there is no difference between JIT compiled code and native machine
Chris Lattner118749e2007-10-25 06:23:36 +0000348code that is statically linked into your application.</p>
349
350<p>With just these two changes, lets see how Kaleidoscope works now!</p>
351
352<div class="doc_code">
353<pre>
354ready&gt; <b>4+5;</b>
355define double @""() {
356entry:
357 ret double 9.000000e+00
358}
359
360<em>Evaluated to 9.000000</em>
361</pre>
362</div>
363
364<p>Well this looks like it is basically working. The dump of the function
365shows the "no argument function that always returns double" that we synthesize
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000366for each top-level expression that is typed in. This demonstrates very basic
Chris Lattner118749e2007-10-25 06:23:36 +0000367functionality, but can we do more?</p>
368
369<div class="doc_code">
370<pre>
Chris Lattner2e89f3a2007-10-31 07:30:39 +0000371ready&gt; <b>def testfunc(x y) x + y*2; </b>
Chris Lattner118749e2007-10-25 06:23:36 +0000372Read function definition:
373define double @testfunc(double %x, double %y) {
374entry:
375 %multmp = mul double %y, 2.000000e+00
376 %addtmp = add double %multmp, %x
377 ret double %addtmp
378}
379
380ready&gt; <b>testfunc(4, 10);</b>
381define double @""() {
382entry:
383 %calltmp = call double @testfunc( double 4.000000e+00, double 1.000000e+01 )
384 ret double %calltmp
385}
386
387<em>Evaluated to 24.000000</em>
388</pre>
389</div>
390
Chris Lattner41fcea32007-11-13 07:06:30 +0000391<p>This illustrates that we can now call user code, but there is something a bit subtle
392going on here. Note that we only invoke the JIT on the anonymous functions
393that <em>call testfunc</em>, but we never invoked it on <em>testfunc
394</em>itself.</p>
Chris Lattner118749e2007-10-25 06:23:36 +0000395
Chris Lattner41fcea32007-11-13 07:06:30 +0000396<p>What actually happened here is that the anonymous function was
Chris Lattner118749e2007-10-25 06:23:36 +0000397JIT'd when requested. When the Kaleidoscope app calls through the function
398pointer that is returned, the anonymous function starts executing. It ends up
Chris Lattnera54c2012007-11-07 05:28:43 +0000399making the call to the "testfunc" function, and ends up in a stub that invokes
Chris Lattner118749e2007-10-25 06:23:36 +0000400the JIT, lazily, on testfunc. Once the JIT finishes lazily compiling testfunc,
Chris Lattnera54c2012007-11-07 05:28:43 +0000401it returns and the code re-executes the call.</p>
Chris Lattner118749e2007-10-25 06:23:36 +0000402
Chris Lattner41fcea32007-11-13 07:06:30 +0000403<p>In summary, the JIT will lazily JIT code, on the fly, as it is needed. The
Chris Lattner118749e2007-10-25 06:23:36 +0000404JIT provides a number of other more advanced interfaces for things like freeing
405allocated machine code, rejit'ing functions to update them, etc. However, even
406with this simple code, we get some surprisingly powerful capabilities - check
407this out (I removed the dump of the anonymous functions, you should get the idea
408by now :) :</p>
409
410<div class="doc_code">
411<pre>
412ready&gt; <b>extern sin(x);</b>
413Read extern:
414declare double @sin(double)
415
416ready&gt; <b>extern cos(x);</b>
417Read extern:
418declare double @cos(double)
419
420ready&gt; <b>sin(1.0);</b>
421<em>Evaluated to 0.841471</em>
Chris Lattner72714232007-10-25 17:52:39 +0000422
Chris Lattner118749e2007-10-25 06:23:36 +0000423ready&gt; <b>def foo(x) sin(x)*sin(x) + cos(x)*cos(x);</b>
424Read function definition:
425define double @foo(double %x) {
426entry:
427 %calltmp = call double @sin( double %x )
428 %multmp = mul double %calltmp, %calltmp
429 %calltmp2 = call double @cos( double %x )
430 %multmp4 = mul double %calltmp2, %calltmp2
431 %addtmp = add double %multmp, %multmp4
432 ret double %addtmp
433}
434
435ready&gt; <b>foo(4.0);</b>
436<em>Evaluated to 1.000000</em>
437</pre>
438</div>
439
Chris Lattnera54c2012007-11-07 05:28:43 +0000440<p>Whoa, how does the JIT know about sin and cos? The answer is surprisingly
441simple: in this
Chris Lattner118749e2007-10-25 06:23:36 +0000442example, the JIT started execution of a function and got to a function call. It
443realized that the function was not yet JIT compiled and invoked the standard set
444of routines to resolve the function. In this case, there is no body defined
Chris Lattnera54c2012007-11-07 05:28:43 +0000445for the function, so the JIT ended up calling "<tt>dlsym("sin")</tt>" on the
446Kaleidoscope process itself.
Chris Lattner118749e2007-10-25 06:23:36 +0000447Since "<tt>sin</tt>" is defined within the JIT's address space, it simply
448patches up calls in the module to call the libm version of <tt>sin</tt>
449directly.</p>
450
451<p>The LLVM JIT provides a number of interfaces (look in the
452<tt>ExecutionEngine.h</tt> file) for controlling how unknown functions get
453resolved. It allows you to establish explicit mappings between IR objects and
454addresses (useful for LLVM global variables that you want to map to static
455tables, for example), allows you to dynamically decide on the fly based on the
456function name, and even allows you to have the JIT abort itself if any lazy
457compilation is attempted.</p>
458
Chris Lattner72714232007-10-25 17:52:39 +0000459<p>One interesting application of this is that we can now extend the language
460by writing arbitrary C++ code to implement operations. For example, if we add:
461</p>
462
463<div class="doc_code">
464<pre>
465/// putchard - putchar that takes a double and returns 0.
466extern "C"
467double putchard(double X) {
468 putchar((char)X);
469 return 0;
470}
471</pre>
472</div>
473
474<p>Now we can produce simple output to the console by using things like:
475"<tt>extern putchard(x); putchard(120);</tt>", which prints a lowercase 'x' on
Chris Lattnera54c2012007-11-07 05:28:43 +0000476the console (120 is the ASCII code for 'x'). Similar code could be used to
Chris Lattner72714232007-10-25 17:52:39 +0000477implement file I/O, console input, and many other capabilities in
478Kaleidoscope.</p>
479
Chris Lattner118749e2007-10-25 06:23:36 +0000480<p>This completes the JIT and optimizer chapter of the Kaleidoscope tutorial. At
481this point, we can compile a non-Turing-complete programming language, optimize
482and JIT compile it in a user-driven way. Next up we'll look into <a
483href="LangImpl5.html">extending the language with control flow constructs</a>,
484tackling some interesting LLVM IR issues along the way.</p>
485
486</div>
487
488<!-- *********************************************************************** -->
489<div class="doc_section"><a name="code">Full Code Listing</a></div>
490<!-- *********************************************************************** -->
491
492<div class="doc_text">
493
494<p>
495Here is the complete code listing for our running example, enhanced with the
496LLVM JIT and optimizer. To build this example, use:
497</p>
498
499<div class="doc_code">
500<pre>
501 # Compile
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000502 g++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit interpreter native` -O3 -o toy
Chris Lattner118749e2007-10-25 06:23:36 +0000503 # Run
504 ./toy
505</pre>
506</div>
507
Chris Lattner7c770892009-02-09 00:04:40 +0000508<p>
509If you are compiling this on Linux, make sure to add the "-rdynamic" option
510as well. This makes sure that the external functions are resolved properly
511at runtime.</p>
512
Chris Lattner118749e2007-10-25 06:23:36 +0000513<p>Here is the code:</p>
514
515<div class="doc_code">
516<pre>
517#include "llvm/DerivedTypes.h"
518#include "llvm/ExecutionEngine/ExecutionEngine.h"
Nick Lewycky422094c2009-09-13 21:38:54 +0000519#include "llvm/ExecutionEngine/Interpreter.h"
520#include "llvm/ExecutionEngine/JIT.h"
Owen Andersond1fbd142009-07-08 20:50:47 +0000521#include "llvm/LLVMContext.h"
Chris Lattner118749e2007-10-25 06:23:36 +0000522#include "llvm/Module.h"
523#include "llvm/ModuleProvider.h"
524#include "llvm/PassManager.h"
525#include "llvm/Analysis/Verifier.h"
526#include "llvm/Target/TargetData.h"
Nick Lewycky422094c2009-09-13 21:38:54 +0000527#include "llvm/Target/TargetSelect.h"
Chris Lattner118749e2007-10-25 06:23:36 +0000528#include "llvm/Transforms/Scalar.h"
Duncan Sands89f6d882008-04-13 06:22:09 +0000529#include "llvm/Support/IRBuilder.h"
Chris Lattner118749e2007-10-25 06:23:36 +0000530#include &lt;cstdio&gt;
531#include &lt;string&gt;
532#include &lt;map&gt;
533#include &lt;vector&gt;
534using namespace llvm;
535
536//===----------------------------------------------------------------------===//
537// Lexer
538//===----------------------------------------------------------------------===//
539
540// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
541// of these for known things.
542enum Token {
543 tok_eof = -1,
544
545 // commands
546 tok_def = -2, tok_extern = -3,
547
548 // primary
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000549 tok_identifier = -4, tok_number = -5
Chris Lattner118749e2007-10-25 06:23:36 +0000550};
551
552static std::string IdentifierStr; // Filled in if tok_identifier
553static double NumVal; // Filled in if tok_number
554
555/// gettok - Return the next token from standard input.
556static int gettok() {
557 static int LastChar = ' ';
558
559 // Skip any whitespace.
560 while (isspace(LastChar))
561 LastChar = getchar();
562
563 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
564 IdentifierStr = LastChar;
565 while (isalnum((LastChar = getchar())))
566 IdentifierStr += LastChar;
567
568 if (IdentifierStr == "def") return tok_def;
569 if (IdentifierStr == "extern") return tok_extern;
570 return tok_identifier;
571 }
572
573 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
574 std::string NumStr;
575 do {
576 NumStr += LastChar;
577 LastChar = getchar();
578 } while (isdigit(LastChar) || LastChar == '.');
579
580 NumVal = strtod(NumStr.c_str(), 0);
581 return tok_number;
582 }
583
584 if (LastChar == '#') {
585 // Comment until end of line.
586 do LastChar = getchar();
Chris Lattnerc80c23f2007-12-02 22:46:01 +0000587 while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
Chris Lattner118749e2007-10-25 06:23:36 +0000588
589 if (LastChar != EOF)
590 return gettok();
591 }
592
593 // Check for end of file. Don't eat the EOF.
594 if (LastChar == EOF)
595 return tok_eof;
596
597 // Otherwise, just return the character as its ascii value.
598 int ThisChar = LastChar;
599 LastChar = getchar();
600 return ThisChar;
601}
602
603//===----------------------------------------------------------------------===//
604// Abstract Syntax Tree (aka Parse Tree)
605//===----------------------------------------------------------------------===//
606
Chris Lattnerc0b42e92007-10-23 06:27:55 +0000607/// ExprAST - Base class for all expression nodes.
608class ExprAST {
609public:
610 virtual ~ExprAST() {}
611 virtual Value *Codegen() = 0;
612};
613
614/// NumberExprAST - Expression class for numeric literals like "1.0".
615class NumberExprAST : public ExprAST {
616 double Val;
617public:
Chris Lattner118749e2007-10-25 06:23:36 +0000618 NumberExprAST(double val) : Val(val) {}
Chris Lattnerc0b42e92007-10-23 06:27:55 +0000619 virtual Value *Codegen();
620};
Chris Lattner118749e2007-10-25 06:23:36 +0000621
622/// VariableExprAST - Expression class for referencing a variable, like "a".
623class VariableExprAST : public ExprAST {
624 std::string Name;
625public:
626 VariableExprAST(const std::string &amp;name) : Name(name) {}
627 virtual Value *Codegen();
628};
629
630/// BinaryExprAST - Expression class for a binary operator.
631class BinaryExprAST : public ExprAST {
632 char Op;
633 ExprAST *LHS, *RHS;
634public:
635 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
636 : Op(op), LHS(lhs), RHS(rhs) {}
637 virtual Value *Codegen();
638};
639
640/// CallExprAST - Expression class for function calls.
641class CallExprAST : public ExprAST {
642 std::string Callee;
643 std::vector&lt;ExprAST*&gt; Args;
644public:
645 CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
646 : Callee(callee), Args(args) {}
647 virtual Value *Codegen();
648};
649
650/// PrototypeAST - This class represents the "prototype" for a function,
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000651/// which captures its name, and its argument names (thus implicitly the number
652/// of arguments the function takes).
Chris Lattner118749e2007-10-25 06:23:36 +0000653class PrototypeAST {
654 std::string Name;
655 std::vector&lt;std::string&gt; Args;
656public:
657 PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
658 : Name(name), Args(args) {}
659
660 Function *Codegen();
661};
662
663/// FunctionAST - This class represents a function definition itself.
664class FunctionAST {
665 PrototypeAST *Proto;
666 ExprAST *Body;
667public:
668 FunctionAST(PrototypeAST *proto, ExprAST *body)
669 : Proto(proto), Body(body) {}
670
671 Function *Codegen();
672};
673
674//===----------------------------------------------------------------------===//
675// Parser
676//===----------------------------------------------------------------------===//
677
678/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000679/// token the parser is looking at. getNextToken reads another token from the
Chris Lattner118749e2007-10-25 06:23:36 +0000680/// lexer and updates CurTok with its results.
681static int CurTok;
682static int getNextToken() {
683 return CurTok = gettok();
684}
685
686/// BinopPrecedence - This holds the precedence for each binary operator that is
687/// defined.
688static std::map&lt;char, int&gt; BinopPrecedence;
689
690/// GetTokPrecedence - Get the precedence of the pending binary operator token.
691static int GetTokPrecedence() {
692 if (!isascii(CurTok))
693 return -1;
694
695 // Make sure it's a declared binop.
696 int TokPrec = BinopPrecedence[CurTok];
697 if (TokPrec &lt;= 0) return -1;
698 return TokPrec;
699}
700
701/// Error* - These are little helper functions for error handling.
702ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
703PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
704FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
705
706static ExprAST *ParseExpression();
707
708/// identifierexpr
Chris Lattner20a0c802007-11-05 17:54:34 +0000709/// ::= identifier
710/// ::= identifier '(' expression* ')'
Chris Lattner118749e2007-10-25 06:23:36 +0000711static ExprAST *ParseIdentifierExpr() {
712 std::string IdName = IdentifierStr;
713
Chris Lattner20a0c802007-11-05 17:54:34 +0000714 getNextToken(); // eat identifier.
Chris Lattner118749e2007-10-25 06:23:36 +0000715
716 if (CurTok != '(') // Simple variable ref.
717 return new VariableExprAST(IdName);
718
719 // Call.
720 getNextToken(); // eat (
721 std::vector&lt;ExprAST*&gt; Args;
Chris Lattner71155212007-11-06 01:39:12 +0000722 if (CurTok != ')') {
723 while (1) {
724 ExprAST *Arg = ParseExpression();
725 if (!Arg) return 0;
726 Args.push_back(Arg);
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000727
Chris Lattner71155212007-11-06 01:39:12 +0000728 if (CurTok == ')') break;
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000729
Chris Lattner71155212007-11-06 01:39:12 +0000730 if (CurTok != ',')
Chris Lattner6c4be9c2008-04-14 16:44:41 +0000731 return Error("Expected ')' or ',' in argument list");
Chris Lattner71155212007-11-06 01:39:12 +0000732 getNextToken();
733 }
Chris Lattner118749e2007-10-25 06:23:36 +0000734 }
735
736 // Eat the ')'.
737 getNextToken();
738
739 return new CallExprAST(IdName, Args);
740}
741
742/// numberexpr ::= number
743static ExprAST *ParseNumberExpr() {
744 ExprAST *Result = new NumberExprAST(NumVal);
745 getNextToken(); // consume the number
746 return Result;
747}
748
749/// parenexpr ::= '(' expression ')'
750static ExprAST *ParseParenExpr() {
751 getNextToken(); // eat (.
752 ExprAST *V = ParseExpression();
753 if (!V) return 0;
754
755 if (CurTok != ')')
756 return Error("expected ')'");
757 getNextToken(); // eat ).
758 return V;
759}
760
761/// primary
762/// ::= identifierexpr
763/// ::= numberexpr
764/// ::= parenexpr
765static ExprAST *ParsePrimary() {
766 switch (CurTok) {
767 default: return Error("unknown token when expecting an expression");
768 case tok_identifier: return ParseIdentifierExpr();
769 case tok_number: return ParseNumberExpr();
770 case '(': return ParseParenExpr();
771 }
772}
773
774/// binoprhs
775/// ::= ('+' primary)*
776static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
777 // If this is a binop, find its precedence.
778 while (1) {
779 int TokPrec = GetTokPrecedence();
780
781 // If this is a binop that binds at least as tightly as the current binop,
782 // consume it, otherwise we are done.
783 if (TokPrec &lt; ExprPrec)
784 return LHS;
785
786 // Okay, we know this is a binop.
787 int BinOp = CurTok;
788 getNextToken(); // eat binop
789
790 // Parse the primary expression after the binary operator.
791 ExprAST *RHS = ParsePrimary();
792 if (!RHS) return 0;
793
794 // If BinOp binds less tightly with RHS than the operator after RHS, let
795 // the pending operator take RHS as its LHS.
796 int NextPrec = GetTokPrecedence();
797 if (TokPrec &lt; NextPrec) {
798 RHS = ParseBinOpRHS(TokPrec+1, RHS);
799 if (RHS == 0) return 0;
800 }
801
802 // Merge LHS/RHS.
803 LHS = new BinaryExprAST(BinOp, LHS, RHS);
804 }
805}
806
807/// expression
808/// ::= primary binoprhs
809///
810static ExprAST *ParseExpression() {
811 ExprAST *LHS = ParsePrimary();
812 if (!LHS) return 0;
813
814 return ParseBinOpRHS(0, LHS);
815}
816
817/// prototype
818/// ::= id '(' id* ')'
819static PrototypeAST *ParsePrototype() {
820 if (CurTok != tok_identifier)
821 return ErrorP("Expected function name in prototype");
822
823 std::string FnName = IdentifierStr;
824 getNextToken();
825
826 if (CurTok != '(')
827 return ErrorP("Expected '(' in prototype");
828
829 std::vector&lt;std::string&gt; ArgNames;
830 while (getNextToken() == tok_identifier)
831 ArgNames.push_back(IdentifierStr);
832 if (CurTok != ')')
833 return ErrorP("Expected ')' in prototype");
834
835 // success.
836 getNextToken(); // eat ')'.
837
838 return new PrototypeAST(FnName, ArgNames);
839}
840
841/// definition ::= 'def' prototype expression
842static FunctionAST *ParseDefinition() {
843 getNextToken(); // eat def.
844 PrototypeAST *Proto = ParsePrototype();
845 if (Proto == 0) return 0;
846
847 if (ExprAST *E = ParseExpression())
848 return new FunctionAST(Proto, E);
849 return 0;
850}
851
852/// toplevelexpr ::= expression
853static FunctionAST *ParseTopLevelExpr() {
854 if (ExprAST *E = ParseExpression()) {
855 // Make an anonymous proto.
856 PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
857 return new FunctionAST(Proto, E);
858 }
859 return 0;
860}
861
862/// external ::= 'extern' prototype
863static PrototypeAST *ParseExtern() {
864 getNextToken(); // eat extern.
865 return ParsePrototype();
866}
867
868//===----------------------------------------------------------------------===//
869// Code Generation
870//===----------------------------------------------------------------------===//
871
872static Module *TheModule;
Owen Andersond1fbd142009-07-08 20:50:47 +0000873static IRBuilder&lt;&gt; Builder(getGlobalContext());
Chris Lattner118749e2007-10-25 06:23:36 +0000874static std::map&lt;std::string, Value*&gt; NamedValues;
875static FunctionPassManager *TheFPM;
876
877Value *ErrorV(const char *Str) { Error(Str); return 0; }
878
879Value *NumberExprAST::Codegen() {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000880 return ConstantFP::get(getGlobalContext(), APFloat(Val));
Chris Lattner118749e2007-10-25 06:23:36 +0000881}
882
883Value *VariableExprAST::Codegen() {
884 // Look this variable up in the function.
885 Value *V = NamedValues[Name];
886 return V ? V : ErrorV("Unknown variable name");
887}
888
889Value *BinaryExprAST::Codegen() {
890 Value *L = LHS-&gt;Codegen();
891 Value *R = RHS-&gt;Codegen();
892 if (L == 0 || R == 0) return 0;
893
894 switch (Op) {
895 case '+': return Builder.CreateAdd(L, R, "addtmp");
896 case '-': return Builder.CreateSub(L, R, "subtmp");
897 case '*': return Builder.CreateMul(L, R, "multmp");
898 case '&lt;':
Chris Lattner71155212007-11-06 01:39:12 +0000899 L = Builder.CreateFCmpULT(L, R, "cmptmp");
Chris Lattner118749e2007-10-25 06:23:36 +0000900 // Convert bool 0/1 to double 0.0 or 1.0
Nick Lewycky422094c2009-09-13 21:38:54 +0000901 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
902 "booltmp");
Chris Lattner118749e2007-10-25 06:23:36 +0000903 default: return ErrorV("invalid binary operator");
904 }
905}
906
907Value *CallExprAST::Codegen() {
908 // Look up the name in the global module table.
909 Function *CalleeF = TheModule-&gt;getFunction(Callee);
910 if (CalleeF == 0)
911 return ErrorV("Unknown function referenced");
912
913 // If argument mismatch error.
914 if (CalleeF-&gt;arg_size() != Args.size())
915 return ErrorV("Incorrect # arguments passed");
916
917 std::vector&lt;Value*&gt; ArgsV;
918 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
919 ArgsV.push_back(Args[i]-&gt;Codegen());
920 if (ArgsV.back() == 0) return 0;
921 }
922
923 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
924}
925
926Function *PrototypeAST::Codegen() {
927 // Make the function type: double(double,double) etc.
Nick Lewycky422094c2009-09-13 21:38:54 +0000928 std::vector&lt;const Type*&gt; Doubles(Args.size(),
929 Type::getDoubleTy(getGlobalContext()));
930 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
931 Doubles, false);
Chris Lattner118749e2007-10-25 06:23:36 +0000932
Gabor Greifdf7d2b42008-04-19 22:25:09 +0000933 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
Chris Lattner118749e2007-10-25 06:23:36 +0000934
935 // If F conflicted, there was already something named 'Name'. If it has a
936 // body, don't allow redefinition or reextern.
937 if (F-&gt;getName() != Name) {
938 // Delete the one we just made and get the existing one.
939 F-&gt;eraseFromParent();
940 F = TheModule-&gt;getFunction(Name);
941
942 // If F already has a body, reject this.
943 if (!F-&gt;empty()) {
944 ErrorF("redefinition of function");
945 return 0;
946 }
947
948 // If F took a different number of args, reject.
949 if (F-&gt;arg_size() != Args.size()) {
950 ErrorF("redefinition of function with different # args");
951 return 0;
952 }
953 }
954
955 // Set names for all arguments.
956 unsigned Idx = 0;
957 for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
958 ++AI, ++Idx) {
959 AI-&gt;setName(Args[Idx]);
960
961 // Add arguments to variable symbol table.
962 NamedValues[Args[Idx]] = AI;
963 }
964
965 return F;
966}
967
968Function *FunctionAST::Codegen() {
969 NamedValues.clear();
970
971 Function *TheFunction = Proto-&gt;Codegen();
972 if (TheFunction == 0)
973 return 0;
974
975 // Create a new basic block to start insertion into.
Owen Anderson1d0be152009-08-13 21:58:54 +0000976 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
Chris Lattner118749e2007-10-25 06:23:36 +0000977 Builder.SetInsertPoint(BB);
978
979 if (Value *RetVal = Body-&gt;Codegen()) {
980 // Finish off the function.
981 Builder.CreateRet(RetVal);
982
983 // Validate the generated code, checking for consistency.
984 verifyFunction(*TheFunction);
985
986 // Optimize the function.
987 TheFPM-&gt;run(*TheFunction);
988
989 return TheFunction;
990 }
991
992 // Error reading body, remove function.
993 TheFunction-&gt;eraseFromParent();
994 return 0;
995}
996
997//===----------------------------------------------------------------------===//
998// Top-Level parsing and JIT Driver
999//===----------------------------------------------------------------------===//
1000
1001static ExecutionEngine *TheExecutionEngine;
1002
1003static void HandleDefinition() {
1004 if (FunctionAST *F = ParseDefinition()) {
1005 if (Function *LF = F-&gt;Codegen()) {
1006 fprintf(stderr, "Read function definition:");
1007 LF-&gt;dump();
1008 }
1009 } else {
1010 // Skip token for error recovery.
1011 getNextToken();
1012 }
1013}
1014
1015static void HandleExtern() {
1016 if (PrototypeAST *P = ParseExtern()) {
1017 if (Function *F = P-&gt;Codegen()) {
1018 fprintf(stderr, "Read extern: ");
1019 F-&gt;dump();
1020 }
1021 } else {
1022 // Skip token for error recovery.
1023 getNextToken();
1024 }
1025}
1026
1027static void HandleTopLevelExpression() {
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +00001028 // Evaluate a top-level expression into an anonymous function.
Chris Lattner118749e2007-10-25 06:23:36 +00001029 if (FunctionAST *F = ParseTopLevelExpr()) {
1030 if (Function *LF = F-&gt;Codegen()) {
1031 // JIT the function, returning a function pointer.
1032 void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
1033
1034 // Cast it to the right type (takes no arguments, returns a double) so we
1035 // can call it as a native function.
Nick Lewycky422094c2009-09-13 21:38:54 +00001036 double (*FP)() = (double (*)())(intptr_t)FPtr;
Chris Lattner118749e2007-10-25 06:23:36 +00001037 fprintf(stderr, "Evaluated to %f\n", FP());
1038 }
1039 } else {
1040 // Skip token for error recovery.
1041 getNextToken();
1042 }
1043}
1044
1045/// top ::= definition | external | expression | ';'
1046static void MainLoop() {
1047 while (1) {
1048 fprintf(stderr, "ready&gt; ");
1049 switch (CurTok) {
1050 case tok_eof: return;
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +00001051 case ';': getNextToken(); break; // ignore top-level semicolons.
Chris Lattner118749e2007-10-25 06:23:36 +00001052 case tok_def: HandleDefinition(); break;
1053 case tok_extern: HandleExtern(); break;
1054 default: HandleTopLevelExpression(); break;
1055 }
1056 }
1057}
1058
Chris Lattner118749e2007-10-25 06:23:36 +00001059//===----------------------------------------------------------------------===//
1060// "Library" functions that can be "extern'd" from user code.
1061//===----------------------------------------------------------------------===//
1062
1063/// putchard - putchar that takes a double and returns 0.
1064extern "C"
1065double putchard(double X) {
1066 putchar((char)X);
1067 return 0;
1068}
1069
1070//===----------------------------------------------------------------------===//
1071// Main driver code.
1072//===----------------------------------------------------------------------===//
1073
1074int main() {
Nick Lewycky422094c2009-09-13 21:38:54 +00001075 InitializeNativeTarget();
1076 LLVMContext &amp;Context = getGlobalContext();
1077
Chris Lattner118749e2007-10-25 06:23:36 +00001078 // Install standard binary operators.
1079 // 1 is lowest precedence.
1080 BinopPrecedence['&lt;'] = 10;
1081 BinopPrecedence['+'] = 20;
1082 BinopPrecedence['-'] = 20;
1083 BinopPrecedence['*'] = 40; // highest.
1084
1085 // Prime the first token.
1086 fprintf(stderr, "ready&gt; ");
1087 getNextToken();
1088
1089 // Make the module, which holds all the code.
Nick Lewycky422094c2009-09-13 21:38:54 +00001090 TheModule = new Module("my cool jit", Context);
Chris Lattner118749e2007-10-25 06:23:36 +00001091
Reid Kleckner60130f02009-08-26 20:58:25 +00001092 ExistingModuleProvider *OurModuleProvider =
1093 new ExistingModuleProvider(TheModule);
Chris Lattner118749e2007-10-25 06:23:36 +00001094
Reid Kleckner60130f02009-08-26 20:58:25 +00001095 // Create the JIT. This takes ownership of the module and module provider.
1096 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
Chris Lattner118749e2007-10-25 06:23:36 +00001097
Reid Kleckner60130f02009-08-26 20:58:25 +00001098 FunctionPassManager OurFPM(OurModuleProvider);
1099
1100 // Set up the optimizer pipeline. Start with registering info about how the
1101 // target lays out data structures.
1102 OurFPM.add(new TargetData(*TheExecutionEngine-&gt;getTargetData()));
1103 // Do simple "peephole" optimizations and bit-twiddling optzns.
1104 OurFPM.add(createInstructionCombiningPass());
1105 // Reassociate expressions.
1106 OurFPM.add(createReassociatePass());
1107 // Eliminate Common SubExpressions.
1108 OurFPM.add(createGVNPass());
1109 // Simplify the control flow graph (deleting unreachable blocks, etc).
1110 OurFPM.add(createCFGSimplificationPass());
1111
Nick Lewycky422094c2009-09-13 21:38:54 +00001112 OurFPM.doInitialization();
1113
Reid Kleckner60130f02009-08-26 20:58:25 +00001114 // Set the global so the code gen can use this.
1115 TheFPM = &amp;OurFPM;
1116
1117 // Run the main "interpreter loop" now.
1118 MainLoop();
1119
1120 TheFPM = 0;
1121
1122 // Print out all of the generated code.
1123 TheModule-&gt;dump();
1124
Chris Lattner118749e2007-10-25 06:23:36 +00001125 return 0;
1126}
Chris Lattnerc0b42e92007-10-23 06:27:55 +00001127</pre>
1128</div>
1129
Chris Lattner729eb142008-02-10 19:11:04 +00001130<a href="LangImpl5.html">Next: Extending the language: control flow</a>
Chris Lattnerc0b42e92007-10-23 06:27:55 +00001131</div>
1132
1133<!-- *********************************************************************** -->
1134<hr>
1135<address>
1136 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1137 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1138 <a href="http://validator.w3.org/check/referer"><img
Chris Lattner8eef4b22007-10-23 06:30:50 +00001139 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
Chris Lattnerc0b42e92007-10-23 06:27:55 +00001140
1141 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1142 <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
1143 Last modified: $Date: 2007-10-17 11:05:13 -0700 (Wed, 17 Oct 2007) $
1144</address>
1145</body>
1146</html>