pass machinemoduleinfo down into getSymbolForDwarfGlobalReference,
[llvm/avr.git] / docs / tutorial / LangImpl4.html
blobd05c7ca082a4ad017ec2dbea67bdb77f3e3452e5
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
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>
12 <body>
14 <div class="doc_title">Kaleidoscope: Adding JIT and Optimizer Support</div>
16 <ul>
17 <li><a href="index.html">Up to Tutorial Index</a></li>
18 <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>
27 <li><a href="LangImpl5.html">Chapter 5</a>: Extending the Language: Control
28 Flow</li>
29 </ul>
31 <div class="doc_author">
32 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
33 </div>
35 <!-- *********************************************************************** -->
36 <div class="doc_section"><a name="intro">Chapter 4 Introduction</a></div>
37 <!-- *********************************************************************** -->
39 <div class="doc_text">
41 <p>Welcome to Chapter 4 of the "<a href="index.html">Implementing a language
42 with LLVM</a>" tutorial. Chapters 1-3 described the implementation of a simple
43 language and added support for generating LLVM IR. This chapter describes
44 two new techniques: adding optimizer support to your language, and adding JIT
45 compiler support. These additions will demonstrate how to get nice, efficient code
46 for the Kaleidoscope language.</p>
48 </div>
50 <!-- *********************************************************************** -->
51 <div class="doc_section"><a name="trivialconstfold">Trivial Constant
52 Folding</a></div>
53 <!-- *********************************************************************** -->
55 <div class="doc_text">
57 <p>
58 Our demonstration for Chapter 3 is elegant and easy to extend. Unfortunately,
59 it does not produce wonderful code. The IRBuilder, however, does give us
60 obvious optimizations when compiling simple code:</p>
62 <div class="doc_code">
63 <pre>
64 ready&gt; <b>def test(x) 1+2+x;</b>
65 Read function definition:
66 define double @test(double %x) {
67 entry:
68 %addtmp = add double 3.000000e+00, %x
69 ret double %addtmp
71 </pre>
72 </div>
74 <p>This code is not a literal transcription of the AST built by parsing the
75 input. That would be:
77 <div class="doc_code">
78 <pre>
79 ready&gt; <b>def test(x) 1+2+x;</b>
80 Read function definition:
81 define double @test(double %x) {
82 entry:
83 %addtmp = add double 2.000000e+00, 1.000000e+00
84 %addtmp1 = add double %addtmp, %x
85 ret double %addtmp1
87 </pre>
88 </div>
90 <p>Constant folding, as seen above, in particular, is a very common and very
91 important optimization: so much so that many language implementors implement
92 constant folding support in their AST representation.</p>
94 <p>With LLVM, you don't need this support in the AST. Since all calls to build
95 LLVM IR go through the LLVM IR builder, the builder itself checked to see if
96 there was a constant folding opportunity when you call it. If so, it just does
97 the constant fold and return the constant instead of creating an instruction.
99 <p>Well, that was easy :). In practice, we recommend always using
100 <tt>IRBuilder</tt> when generating code like this. It has no
101 "syntactic overhead" for its use (you don't have to uglify your compiler with
102 constant checks everywhere) and it can dramatically reduce the amount of
103 LLVM IR that is generated in some cases (particular for languages with a macro
104 preprocessor or that use a lot of constants).</p>
106 <p>On the other hand, the <tt>IRBuilder</tt> is limited by the fact
107 that it does all of its analysis inline with the code as it is built. If you
108 take a slightly more complex example:</p>
110 <div class="doc_code">
111 <pre>
112 ready&gt; <b>def test(x) (1+2+x)*(x+(1+2));</b>
113 ready> Read function definition:
114 define double @test(double %x) {
115 entry:
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
121 </pre>
122 </div>
124 <p>In this case, the LHS and RHS of the multiplication are the same value. We'd
125 really like to see this generate "<tt>tmp = x+3; result = tmp*tmp;</tt>" instead
126 of computing "<tt>x+3</tt>" twice.</p>
128 <p>Unfortunately, no amount of local analysis will be able to detect and correct
129 this. This requires two transformations: reassociation of expressions (to
130 make the add's lexically identical) and Common Subexpression Elimination (CSE)
131 to delete the redundant add instruction. Fortunately, LLVM provides a broad
132 range of optimizations that you can use, in the form of "passes".</p>
134 </div>
136 <!-- *********************************************************************** -->
137 <div class="doc_section"><a name="optimizerpasses">LLVM Optimization
138 Passes</a></div>
139 <!-- *********************************************************************** -->
141 <div class="doc_text">
143 <p>LLVM provides many optimization passes, which do many different sorts of
144 things and have different tradeoffs. Unlike other systems, LLVM doesn't hold
145 to the mistaken notion that one set of optimizations is right for all languages
146 and for all situations. LLVM allows a compiler implementor to make complete
147 decisions about what optimizations to use, in which order, and in what
148 situation.</p>
150 <p>As a concrete example, LLVM supports both "whole module" passes, which look
151 across as large of body of code as they can (often a whole file, but if run
152 at link time, this can be a substantial portion of the whole program). It also
153 supports and includes "per-function" passes which just operate on a single
154 function at a time, without looking at other functions. For more information
155 on passes and how they are run, see the <a href="../WritingAnLLVMPass.html">How
156 to Write a Pass</a> document and the <a href="../Passes.html">List of LLVM
157 Passes</a>.</p>
159 <p>For Kaleidoscope, we are currently generating functions on the fly, one at
160 a time, as the user types them in. We aren't shooting for the ultimate
161 optimization experience in this setting, but we also want to catch the easy and
162 quick stuff where possible. As such, we will choose to run a few per-function
163 optimizations as the user types the function in. If we wanted to make a "static
164 Kaleidoscope compiler", we would use exactly the code we have now, except that
165 we would defer running the optimizer until the entire file has been parsed.</p>
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
169 organize the LLVM optimizations that we want to run. Once we have that, we can
170 add a set of optimizations to run. The code looks like this:</p>
172 <div class="doc_code">
173 <pre>
174 ExistingModuleProvider *OurModuleProvider =
175 new ExistingModuleProvider(TheModule);
177 FunctionPassManager OurFPM(OurModuleProvider);
179 // 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());
191 OurFPM.doInitialization();
193 // Set the global so the code gen can use this.
194 TheFPM = &amp;OurFPM;
196 // Run the main "interpreter loop" now.
197 MainLoop();
198 </pre>
199 </div>
201 <p>This code defines two objects, an <tt>ExistingModuleProvider</tt> and a
202 <tt>FunctionPassManager</tt>. The former is basically a wrapper around our
203 <tt>Module</tt> that the PassManager requires. It provides certain flexibility
204 that we're not going to take advantage of here, so I won't dive into any details
205 about it.</p>
207 <p>The meat of the matter here, is the definition of "<tt>OurFPM</tt>". It
208 requires a pointer to the <tt>Module</tt> (through the <tt>ModuleProvider</tt>)
209 to construct itself. Once it is set up, we use a series of "add" calls to add
210 a bunch of LLVM passes. The first pass is basically boilerplate, it adds a pass
211 so that later optimizations know how the data structures in the program are
212 layed out. The "<tt>TheExecutionEngine</tt>" variable is related to the JIT,
213 which we will get to in the next section.</p>
215 <p>In this case, we choose to add 4 optimization passes. The passes we chose
216 here are a pretty standard set of "cleanup" optimizations that are useful for
217 a wide variety of code. I won't delve into what they do but, believe me,
218 they are a good starting place :).</p>
220 <p>Once the PassManager is set up, we need to make use of it. We do this by
221 running it after our newly created function is constructed (in
222 <tt>FunctionAST::Codegen</tt>), but before it is returned to the client:</p>
224 <div class="doc_code">
225 <pre>
226 if (Value *RetVal = Body->Codegen()) {
227 // Finish off the function.
228 Builder.CreateRet(RetVal);
230 // Validate the generated code, checking for consistency.
231 verifyFunction(*TheFunction);
233 <b>// Optimize the function.
234 TheFPM-&gt;run(*TheFunction);</b>
236 return TheFunction;
238 </pre>
239 </div>
241 <p>As you can see, this is pretty straightforward. The
242 <tt>FunctionPassManager</tt> optimizes and updates the LLVM Function* in place,
243 improving (hopefully) its body. With this in place, we can try our test above
244 again:</p>
246 <div class="doc_code">
247 <pre>
248 ready&gt; <b>def test(x) (1+2+x)*(x+(1+2));</b>
249 ready> Read function definition:
250 define double @test(double %x) {
251 entry:
252 %addtmp = add double %x, 3.000000e+00
253 %multmp = mul double %addtmp, %addtmp
254 ret double %multmp
256 </pre>
257 </div>
259 <p>As expected, we now get our nicely optimized code, saving a floating point
260 add instruction from every execution of this function.</p>
262 <p>LLVM provides a wide variety of optimizations that can be used in certain
263 circumstances. Some <a href="../Passes.html">documentation about the various
264 passes</a> is available, but it isn't very complete. Another good source of
265 ideas can come from looking at the passes that <tt>llvm-gcc</tt> or
266 <tt>llvm-ld</tt> run to get started. The "<tt>opt</tt>" tool allows you to
267 experiment with passes from the command line, so you can see if they do
268 anything.</p>
270 <p>Now that we have reasonable code coming out of our front-end, lets talk about
271 executing it!</p>
273 </div>
275 <!-- *********************************************************************** -->
276 <div class="doc_section"><a name="jit">Adding a JIT Compiler</a></div>
277 <!-- *********************************************************************** -->
279 <div class="doc_text">
281 <p>Code that is available in LLVM IR can have a wide variety of tools
282 applied to it. For example, you can run optimizations on it (as we did above),
283 you can dump it out in textual or binary forms, you can compile the code to an
284 assembly file (.s) for some target, or you can JIT compile it. The nice thing
285 about the LLVM IR representation is that it is the "common currency" between
286 many different parts of the compiler.
287 </p>
289 <p>In this section, we'll add JIT compiler support to our interpreter. The
290 basic idea that we want for Kaleidoscope is to have the user enter function
291 bodies as they do now, but immediately evaluate the top-level expressions they
292 type in. For example, if they type in "1 + 2;", we should evaluate and print
293 out 3. If they define a function, they should be able to call it from the
294 command line.</p>
296 <p>In order to do this, we first declare and initialize the JIT. This is done
297 by adding a global variable and a call in <tt>main</tt>:</p>
299 <div class="doc_code">
300 <pre>
301 <b>static ExecutionEngine *TheExecutionEngine;</b>
303 int main() {
305 <b>// Create the JIT. This takes ownership of the module and module provider.
306 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();</b>
309 </pre>
310 </div>
312 <p>This creates an abstract "Execution Engine" which can be either a JIT
313 compiler or the LLVM interpreter. LLVM will automatically pick a JIT compiler
314 for you if one is available for your platform, otherwise it will fall back to
315 the interpreter.</p>
317 <p>Once the <tt>ExecutionEngine</tt> is created, the JIT is ready to be used.
318 There are a variety of APIs that are useful, but the simplest one is the
319 "<tt>getPointerToFunction(F)</tt>" method. This method JIT compiles the
320 specified LLVM Function and returns a function pointer to the generated machine
321 code. In our case, this means that we can change the code that parses a
322 top-level expression to look like this:</p>
324 <div class="doc_code">
325 <pre>
326 static void HandleTopLevelExpression() {
327 // Evaluate a top level expression into an anonymous function.
328 if (FunctionAST *F = ParseTopLevelExpr()) {
329 if (Function *LF = F-&gt;Codegen()) {
330 LF->dump(); // Dump the function for exposition purposes.
332 <b>// JIT the function, returning a function pointer.
333 void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
335 // Cast it to the right type (takes no arguments, returns a double) so we
336 // can call it as a native function.
337 double (*FP)() = (double (*)())FPtr;
338 fprintf(stderr, "Evaluated to %f\n", FP());</b>
340 </pre>
341 </div>
343 <p>Recall that we compile top-level expressions into a self-contained LLVM
344 function that takes no arguments and returns the computed double. Because the
345 LLVM JIT compiler matches the native platform ABI, this means that you can just
346 cast the result pointer to a function pointer of that type and call it directly.
347 This means, there is no difference between JIT compiled code and native machine
348 code that is statically linked into your application.</p>
350 <p>With just these two changes, lets see how Kaleidoscope works now!</p>
352 <div class="doc_code">
353 <pre>
354 ready&gt; <b>4+5;</b>
355 define double @""() {
356 entry:
357 ret double 9.000000e+00
360 <em>Evaluated to 9.000000</em>
361 </pre>
362 </div>
364 <p>Well this looks like it is basically working. The dump of the function
365 shows the "no argument function that always returns double" that we synthesize
366 for each top level expression that is typed in. This demonstrates very basic
367 functionality, but can we do more?</p>
369 <div class="doc_code">
370 <pre>
371 ready&gt; <b>def testfunc(x y) x + y*2; </b>
372 Read function definition:
373 define double @testfunc(double %x, double %y) {
374 entry:
375 %multmp = mul double %y, 2.000000e+00
376 %addtmp = add double %multmp, %x
377 ret double %addtmp
380 ready&gt; <b>testfunc(4, 10);</b>
381 define double @""() {
382 entry:
383 %calltmp = call double @testfunc( double 4.000000e+00, double 1.000000e+01 )
384 ret double %calltmp
387 <em>Evaluated to 24.000000</em>
388 </pre>
389 </div>
391 <p>This illustrates that we can now call user code, but there is something a bit subtle
392 going on here. Note that we only invoke the JIT on the anonymous functions
393 that <em>call testfunc</em>, but we never invoked it on <em>testfunc
394 </em>itself.</p>
396 <p>What actually happened here is that the anonymous function was
397 JIT'd when requested. When the Kaleidoscope app calls through the function
398 pointer that is returned, the anonymous function starts executing. It ends up
399 making the call to the "testfunc" function, and ends up in a stub that invokes
400 the JIT, lazily, on testfunc. Once the JIT finishes lazily compiling testfunc,
401 it returns and the code re-executes the call.</p>
403 <p>In summary, the JIT will lazily JIT code, on the fly, as it is needed. The
404 JIT provides a number of other more advanced interfaces for things like freeing
405 allocated machine code, rejit'ing functions to update them, etc. However, even
406 with this simple code, we get some surprisingly powerful capabilities - check
407 this out (I removed the dump of the anonymous functions, you should get the idea
408 by now :) :</p>
410 <div class="doc_code">
411 <pre>
412 ready&gt; <b>extern sin(x);</b>
413 Read extern:
414 declare double @sin(double)
416 ready&gt; <b>extern cos(x);</b>
417 Read extern:
418 declare double @cos(double)
420 ready&gt; <b>sin(1.0);</b>
421 <em>Evaluated to 0.841471</em>
423 ready&gt; <b>def foo(x) sin(x)*sin(x) + cos(x)*cos(x);</b>
424 Read function definition:
425 define double @foo(double %x) {
426 entry:
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
435 ready&gt; <b>foo(4.0);</b>
436 <em>Evaluated to 1.000000</em>
437 </pre>
438 </div>
440 <p>Whoa, how does the JIT know about sin and cos? The answer is surprisingly
441 simple: in this
442 example, the JIT started execution of a function and got to a function call. It
443 realized that the function was not yet JIT compiled and invoked the standard set
444 of routines to resolve the function. In this case, there is no body defined
445 for the function, so the JIT ended up calling "<tt>dlsym("sin")</tt>" on the
446 Kaleidoscope process itself.
447 Since "<tt>sin</tt>" is defined within the JIT's address space, it simply
448 patches up calls in the module to call the libm version of <tt>sin</tt>
449 directly.</p>
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
453 resolved. It allows you to establish explicit mappings between IR objects and
454 addresses (useful for LLVM global variables that you want to map to static
455 tables, for example), allows you to dynamically decide on the fly based on the
456 function name, and even allows you to have the JIT abort itself if any lazy
457 compilation is attempted.</p>
459 <p>One interesting application of this is that we can now extend the language
460 by writing arbitrary C++ code to implement operations. For example, if we add:
461 </p>
463 <div class="doc_code">
464 <pre>
465 /// putchard - putchar that takes a double and returns 0.
466 extern "C"
467 double putchard(double X) {
468 putchar((char)X);
469 return 0;
471 </pre>
472 </div>
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
476 the console (120 is the ASCII code for 'x'). Similar code could be used to
477 implement file I/O, console input, and many other capabilities in
478 Kaleidoscope.</p>
480 <p>This completes the JIT and optimizer chapter of the Kaleidoscope tutorial. At
481 this point, we can compile a non-Turing-complete programming language, optimize
482 and JIT compile it in a user-driven way. Next up we'll look into <a
483 href="LangImpl5.html">extending the language with control flow constructs</a>,
484 tackling some interesting LLVM IR issues along the way.</p>
486 </div>
488 <!-- *********************************************************************** -->
489 <div class="doc_section"><a name="code">Full Code Listing</a></div>
490 <!-- *********************************************************************** -->
492 <div class="doc_text">
495 Here is the complete code listing for our running example, enhanced with the
496 LLVM JIT and optimizer. To build this example, use:
497 </p>
499 <div class="doc_code">
500 <pre>
501 # Compile
502 g++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit native` -O3 -o toy
503 # Run
504 ./toy
505 </pre>
506 </div>
509 If you are compiling this on Linux, make sure to add the "-rdynamic" option
510 as well. This makes sure that the external functions are resolved properly
511 at runtime.</p>
513 <p>Here is the code:</p>
515 <div class="doc_code">
516 <pre>
517 #include "llvm/DerivedTypes.h"
518 #include "llvm/ExecutionEngine/ExecutionEngine.h"
519 #include "llvm/ExecutionEngine/Interpreter.h"
520 #include "llvm/ExecutionEngine/JIT.h"
521 #include "llvm/LLVMContext.h"
522 #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"
527 #include "llvm/Target/TargetSelect.h"
528 #include "llvm/Transforms/Scalar.h"
529 #include "llvm/Support/IRBuilder.h"
530 #include &lt;cstdio&gt;
531 #include &lt;string&gt;
532 #include &lt;map&gt;
533 #include &lt;vector&gt;
534 using namespace llvm;
536 //===----------------------------------------------------------------------===//
537 // Lexer
538 //===----------------------------------------------------------------------===//
540 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
541 // of these for known things.
542 enum Token {
543 tok_eof = -1,
545 // commands
546 tok_def = -2, tok_extern = -3,
548 // primary
549 tok_identifier = -4, tok_number = -5,
552 static std::string IdentifierStr; // Filled in if tok_identifier
553 static double NumVal; // Filled in if tok_number
555 /// gettok - Return the next token from standard input.
556 static int gettok() {
557 static int LastChar = ' ';
559 // Skip any whitespace.
560 while (isspace(LastChar))
561 LastChar = getchar();
563 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
564 IdentifierStr = LastChar;
565 while (isalnum((LastChar = getchar())))
566 IdentifierStr += LastChar;
568 if (IdentifierStr == "def") return tok_def;
569 if (IdentifierStr == "extern") return tok_extern;
570 return tok_identifier;
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 == '.');
580 NumVal = strtod(NumStr.c_str(), 0);
581 return tok_number;
584 if (LastChar == '#') {
585 // Comment until end of line.
586 do LastChar = getchar();
587 while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
589 if (LastChar != EOF)
590 return gettok();
593 // Check for end of file. Don't eat the EOF.
594 if (LastChar == EOF)
595 return tok_eof;
597 // Otherwise, just return the character as its ascii value.
598 int ThisChar = LastChar;
599 LastChar = getchar();
600 return ThisChar;
603 //===----------------------------------------------------------------------===//
604 // Abstract Syntax Tree (aka Parse Tree)
605 //===----------------------------------------------------------------------===//
607 /// ExprAST - Base class for all expression nodes.
608 class ExprAST {
609 public:
610 virtual ~ExprAST() {}
611 virtual Value *Codegen() = 0;
614 /// NumberExprAST - Expression class for numeric literals like "1.0".
615 class NumberExprAST : public ExprAST {
616 double Val;
617 public:
618 NumberExprAST(double val) : Val(val) {}
619 virtual Value *Codegen();
622 /// VariableExprAST - Expression class for referencing a variable, like "a".
623 class VariableExprAST : public ExprAST {
624 std::string Name;
625 public:
626 VariableExprAST(const std::string &amp;name) : Name(name) {}
627 virtual Value *Codegen();
630 /// BinaryExprAST - Expression class for a binary operator.
631 class BinaryExprAST : public ExprAST {
632 char Op;
633 ExprAST *LHS, *RHS;
634 public:
635 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
636 : Op(op), LHS(lhs), RHS(rhs) {}
637 virtual Value *Codegen();
640 /// CallExprAST - Expression class for function calls.
641 class CallExprAST : public ExprAST {
642 std::string Callee;
643 std::vector&lt;ExprAST*&gt; Args;
644 public:
645 CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
646 : Callee(callee), Args(args) {}
647 virtual Value *Codegen();
650 /// PrototypeAST - This class represents the "prototype" for a function,
651 /// which captures its argument names as well as if it is an operator.
652 class PrototypeAST {
653 std::string Name;
654 std::vector&lt;std::string&gt; Args;
655 public:
656 PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
657 : Name(name), Args(args) {}
659 Function *Codegen();
662 /// FunctionAST - This class represents a function definition itself.
663 class FunctionAST {
664 PrototypeAST *Proto;
665 ExprAST *Body;
666 public:
667 FunctionAST(PrototypeAST *proto, ExprAST *body)
668 : Proto(proto), Body(body) {}
670 Function *Codegen();
673 //===----------------------------------------------------------------------===//
674 // Parser
675 //===----------------------------------------------------------------------===//
677 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
678 /// token the parser it looking at. getNextToken reads another token from the
679 /// lexer and updates CurTok with its results.
680 static int CurTok;
681 static int getNextToken() {
682 return CurTok = gettok();
685 /// BinopPrecedence - This holds the precedence for each binary operator that is
686 /// defined.
687 static std::map&lt;char, int&gt; BinopPrecedence;
689 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
690 static int GetTokPrecedence() {
691 if (!isascii(CurTok))
692 return -1;
694 // Make sure it's a declared binop.
695 int TokPrec = BinopPrecedence[CurTok];
696 if (TokPrec &lt;= 0) return -1;
697 return TokPrec;
700 /// Error* - These are little helper functions for error handling.
701 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
702 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
703 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
705 static ExprAST *ParseExpression();
707 /// identifierexpr
708 /// ::= identifier
709 /// ::= identifier '(' expression* ')'
710 static ExprAST *ParseIdentifierExpr() {
711 std::string IdName = IdentifierStr;
713 getNextToken(); // eat identifier.
715 if (CurTok != '(') // Simple variable ref.
716 return new VariableExprAST(IdName);
718 // Call.
719 getNextToken(); // eat (
720 std::vector&lt;ExprAST*&gt; Args;
721 if (CurTok != ')') {
722 while (1) {
723 ExprAST *Arg = ParseExpression();
724 if (!Arg) return 0;
725 Args.push_back(Arg);
727 if (CurTok == ')') break;
729 if (CurTok != ',')
730 return Error("Expected ')' or ',' in argument list");
731 getNextToken();
735 // Eat the ')'.
736 getNextToken();
738 return new CallExprAST(IdName, Args);
741 /// numberexpr ::= number
742 static ExprAST *ParseNumberExpr() {
743 ExprAST *Result = new NumberExprAST(NumVal);
744 getNextToken(); // consume the number
745 return Result;
748 /// parenexpr ::= '(' expression ')'
749 static ExprAST *ParseParenExpr() {
750 getNextToken(); // eat (.
751 ExprAST *V = ParseExpression();
752 if (!V) return 0;
754 if (CurTok != ')')
755 return Error("expected ')'");
756 getNextToken(); // eat ).
757 return V;
760 /// primary
761 /// ::= identifierexpr
762 /// ::= numberexpr
763 /// ::= parenexpr
764 static ExprAST *ParsePrimary() {
765 switch (CurTok) {
766 default: return Error("unknown token when expecting an expression");
767 case tok_identifier: return ParseIdentifierExpr();
768 case tok_number: return ParseNumberExpr();
769 case '(': return ParseParenExpr();
773 /// binoprhs
774 /// ::= ('+' primary)*
775 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
776 // If this is a binop, find its precedence.
777 while (1) {
778 int TokPrec = GetTokPrecedence();
780 // If this is a binop that binds at least as tightly as the current binop,
781 // consume it, otherwise we are done.
782 if (TokPrec &lt; ExprPrec)
783 return LHS;
785 // Okay, we know this is a binop.
786 int BinOp = CurTok;
787 getNextToken(); // eat binop
789 // Parse the primary expression after the binary operator.
790 ExprAST *RHS = ParsePrimary();
791 if (!RHS) return 0;
793 // If BinOp binds less tightly with RHS than the operator after RHS, let
794 // the pending operator take RHS as its LHS.
795 int NextPrec = GetTokPrecedence();
796 if (TokPrec &lt; NextPrec) {
797 RHS = ParseBinOpRHS(TokPrec+1, RHS);
798 if (RHS == 0) return 0;
801 // Merge LHS/RHS.
802 LHS = new BinaryExprAST(BinOp, LHS, RHS);
806 /// expression
807 /// ::= primary binoprhs
809 static ExprAST *ParseExpression() {
810 ExprAST *LHS = ParsePrimary();
811 if (!LHS) return 0;
813 return ParseBinOpRHS(0, LHS);
816 /// prototype
817 /// ::= id '(' id* ')'
818 static PrototypeAST *ParsePrototype() {
819 if (CurTok != tok_identifier)
820 return ErrorP("Expected function name in prototype");
822 std::string FnName = IdentifierStr;
823 getNextToken();
825 if (CurTok != '(')
826 return ErrorP("Expected '(' in prototype");
828 std::vector&lt;std::string&gt; ArgNames;
829 while (getNextToken() == tok_identifier)
830 ArgNames.push_back(IdentifierStr);
831 if (CurTok != ')')
832 return ErrorP("Expected ')' in prototype");
834 // success.
835 getNextToken(); // eat ')'.
837 return new PrototypeAST(FnName, ArgNames);
840 /// definition ::= 'def' prototype expression
841 static FunctionAST *ParseDefinition() {
842 getNextToken(); // eat def.
843 PrototypeAST *Proto = ParsePrototype();
844 if (Proto == 0) return 0;
846 if (ExprAST *E = ParseExpression())
847 return new FunctionAST(Proto, E);
848 return 0;
851 /// toplevelexpr ::= expression
852 static FunctionAST *ParseTopLevelExpr() {
853 if (ExprAST *E = ParseExpression()) {
854 // Make an anonymous proto.
855 PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
856 return new FunctionAST(Proto, E);
858 return 0;
861 /// external ::= 'extern' prototype
862 static PrototypeAST *ParseExtern() {
863 getNextToken(); // eat extern.
864 return ParsePrototype();
867 //===----------------------------------------------------------------------===//
868 // Code Generation
869 //===----------------------------------------------------------------------===//
871 static Module *TheModule;
872 static IRBuilder&lt;&gt; Builder(getGlobalContext());
873 static std::map&lt;std::string, Value*&gt; NamedValues;
874 static FunctionPassManager *TheFPM;
876 Value *ErrorV(const char *Str) { Error(Str); return 0; }
878 Value *NumberExprAST::Codegen() {
879 return ConstantFP::get(getGlobalContext(), APFloat(Val));
882 Value *VariableExprAST::Codegen() {
883 // Look this variable up in the function.
884 Value *V = NamedValues[Name];
885 return V ? V : ErrorV("Unknown variable name");
888 Value *BinaryExprAST::Codegen() {
889 Value *L = LHS-&gt;Codegen();
890 Value *R = RHS-&gt;Codegen();
891 if (L == 0 || R == 0) return 0;
893 switch (Op) {
894 case '+': return Builder.CreateAdd(L, R, "addtmp");
895 case '-': return Builder.CreateSub(L, R, "subtmp");
896 case '*': return Builder.CreateMul(L, R, "multmp");
897 case '&lt;':
898 L = Builder.CreateFCmpULT(L, R, "cmptmp");
899 // Convert bool 0/1 to double 0.0 or 1.0
900 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
901 "booltmp");
902 default: return ErrorV("invalid binary operator");
906 Value *CallExprAST::Codegen() {
907 // Look up the name in the global module table.
908 Function *CalleeF = TheModule-&gt;getFunction(Callee);
909 if (CalleeF == 0)
910 return ErrorV("Unknown function referenced");
912 // If argument mismatch error.
913 if (CalleeF-&gt;arg_size() != Args.size())
914 return ErrorV("Incorrect # arguments passed");
916 std::vector&lt;Value*&gt; ArgsV;
917 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
918 ArgsV.push_back(Args[i]-&gt;Codegen());
919 if (ArgsV.back() == 0) return 0;
922 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
925 Function *PrototypeAST::Codegen() {
926 // Make the function type: double(double,double) etc.
927 std::vector&lt;const Type*&gt; Doubles(Args.size(),
928 Type::getDoubleTy(getGlobalContext()));
929 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
930 Doubles, false);
932 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
934 // If F conflicted, there was already something named 'Name'. If it has a
935 // body, don't allow redefinition or reextern.
936 if (F-&gt;getName() != Name) {
937 // Delete the one we just made and get the existing one.
938 F-&gt;eraseFromParent();
939 F = TheModule-&gt;getFunction(Name);
941 // If F already has a body, reject this.
942 if (!F-&gt;empty()) {
943 ErrorF("redefinition of function");
944 return 0;
947 // If F took a different number of args, reject.
948 if (F-&gt;arg_size() != Args.size()) {
949 ErrorF("redefinition of function with different # args");
950 return 0;
954 // Set names for all arguments.
955 unsigned Idx = 0;
956 for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
957 ++AI, ++Idx) {
958 AI-&gt;setName(Args[Idx]);
960 // Add arguments to variable symbol table.
961 NamedValues[Args[Idx]] = AI;
964 return F;
967 Function *FunctionAST::Codegen() {
968 NamedValues.clear();
970 Function *TheFunction = Proto-&gt;Codegen();
971 if (TheFunction == 0)
972 return 0;
974 // Create a new basic block to start insertion into.
975 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
976 Builder.SetInsertPoint(BB);
978 if (Value *RetVal = Body-&gt;Codegen()) {
979 // Finish off the function.
980 Builder.CreateRet(RetVal);
982 // Validate the generated code, checking for consistency.
983 verifyFunction(*TheFunction);
985 // Optimize the function.
986 TheFPM-&gt;run(*TheFunction);
988 return TheFunction;
991 // Error reading body, remove function.
992 TheFunction-&gt;eraseFromParent();
993 return 0;
996 //===----------------------------------------------------------------------===//
997 // Top-Level parsing and JIT Driver
998 //===----------------------------------------------------------------------===//
1000 static ExecutionEngine *TheExecutionEngine;
1002 static void HandleDefinition() {
1003 if (FunctionAST *F = ParseDefinition()) {
1004 if (Function *LF = F-&gt;Codegen()) {
1005 fprintf(stderr, "Read function definition:");
1006 LF-&gt;dump();
1008 } else {
1009 // Skip token for error recovery.
1010 getNextToken();
1014 static void HandleExtern() {
1015 if (PrototypeAST *P = ParseExtern()) {
1016 if (Function *F = P-&gt;Codegen()) {
1017 fprintf(stderr, "Read extern: ");
1018 F-&gt;dump();
1020 } else {
1021 // Skip token for error recovery.
1022 getNextToken();
1026 static void HandleTopLevelExpression() {
1027 // Evaluate a top level expression into an anonymous function.
1028 if (FunctionAST *F = ParseTopLevelExpr()) {
1029 if (Function *LF = F-&gt;Codegen()) {
1030 // JIT the function, returning a function pointer.
1031 void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
1033 // Cast it to the right type (takes no arguments, returns a double) so we
1034 // can call it as a native function.
1035 double (*FP)() = (double (*)())(intptr_t)FPtr;
1036 fprintf(stderr, "Evaluated to %f\n", FP());
1038 } else {
1039 // Skip token for error recovery.
1040 getNextToken();
1044 /// top ::= definition | external | expression | ';'
1045 static void MainLoop() {
1046 while (1) {
1047 fprintf(stderr, "ready&gt; ");
1048 switch (CurTok) {
1049 case tok_eof: return;
1050 case ';': getNextToken(); break; // ignore top level semicolons.
1051 case tok_def: HandleDefinition(); break;
1052 case tok_extern: HandleExtern(); break;
1053 default: HandleTopLevelExpression(); break;
1060 //===----------------------------------------------------------------------===//
1061 // "Library" functions that can be "extern'd" from user code.
1062 //===----------------------------------------------------------------------===//
1064 /// putchard - putchar that takes a double and returns 0.
1065 extern "C"
1066 double putchard(double X) {
1067 putchar((char)X);
1068 return 0;
1071 //===----------------------------------------------------------------------===//
1072 // Main driver code.
1073 //===----------------------------------------------------------------------===//
1075 int main() {
1076 InitializeNativeTarget();
1077 LLVMContext &amp;Context = getGlobalContext();
1079 // Install standard binary operators.
1080 // 1 is lowest precedence.
1081 BinopPrecedence['&lt;'] = 10;
1082 BinopPrecedence['+'] = 20;
1083 BinopPrecedence['-'] = 20;
1084 BinopPrecedence['*'] = 40; // highest.
1086 // Prime the first token.
1087 fprintf(stderr, "ready&gt; ");
1088 getNextToken();
1090 // Make the module, which holds all the code.
1091 TheModule = new Module("my cool jit", Context);
1093 ExistingModuleProvider *OurModuleProvider =
1094 new ExistingModuleProvider(TheModule);
1096 // Create the JIT. This takes ownership of the module and module provider.
1097 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
1099 FunctionPassManager OurFPM(OurModuleProvider);
1101 // Set up the optimizer pipeline. Start with registering info about how the
1102 // target lays out data structures.
1103 OurFPM.add(new TargetData(*TheExecutionEngine-&gt;getTargetData()));
1104 // Do simple "peephole" optimizations and bit-twiddling optzns.
1105 OurFPM.add(createInstructionCombiningPass());
1106 // Reassociate expressions.
1107 OurFPM.add(createReassociatePass());
1108 // Eliminate Common SubExpressions.
1109 OurFPM.add(createGVNPass());
1110 // Simplify the control flow graph (deleting unreachable blocks, etc).
1111 OurFPM.add(createCFGSimplificationPass());
1113 OurFPM.doInitialization();
1115 // Set the global so the code gen can use this.
1116 TheFPM = &amp;OurFPM;
1118 // Run the main "interpreter loop" now.
1119 MainLoop();
1121 TheFPM = 0;
1123 // Print out all of the generated code.
1124 TheModule-&gt;dump();
1126 return 0;
1128 </pre>
1129 </div>
1131 <a href="LangImpl5.html">Next: Extending the language: control flow</a>
1132 </div>
1134 <!-- *********************************************************************** -->
1135 <hr>
1136 <address>
1137 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1138 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1139 <a href="http://validator.w3.org/check/referer"><img
1140 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
1142 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1143 <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
1144 Last modified: $Date: 2007-10-17 11:05:13 -0700 (Wed, 17 Oct 2007) $
1145 </address>
1146 </body>
1147 </html>