1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
6 <title>Kaleidoscope: Implementing code generation to LLVM IR</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">
14 <div class="doc_title">Kaleidoscope: Code generation to LLVM IR</div>
17 <li><a href="index.html">Up to Tutorial Index</a></li>
20 <li><a href="#intro">Chapter 3 Introduction</a></li>
21 <li><a href="#basics">Code Generation setup</a></li>
22 <li><a href="#exprs">Expression Code Generation</a></li>
23 <li><a href="#funcs">Function Code Generation</a></li>
24 <li><a href="#driver">Driver Changes and Closing Thoughts</a></li>
25 <li><a href="#code">Full Code Listing</a></li>
28 <li><a href="LangImpl4.html">Chapter 4</a>: Adding JIT and Optimizer
32 <div class="doc_author">
33 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
36 <!-- *********************************************************************** -->
37 <div class="doc_section"><a name="intro">Chapter 3 Introduction</a></div>
38 <!-- *********************************************************************** -->
40 <div class="doc_text">
42 <p>Welcome to Chapter 3 of the "<a href="index.html">Implementing a language
43 with LLVM</a>" tutorial. This chapter shows you how to transform the <a
44 href="LangImpl2.html">Abstract Syntax Tree built in Chapter 2</a> into LLVM IR.
45 This will teach you a little bit about how LLVM does things, as well as
46 demonstrate how easy it is to use. It's much more work to build a lexer and
47 parser than it is to generate LLVM IR code.
52 <!-- *********************************************************************** -->
53 <div class="doc_section"><a name="basics">Code Generation setup</a></div>
54 <!-- *********************************************************************** -->
56 <div class="doc_text">
59 In order to generate LLVM IR, we want some simple setup to get started. First,
60 we define virtual codegen methods in each AST class:</p>
62 <div class="doc_code">
64 /// ExprAST - Base class for all expression nodes.
68 <b>virtual Value *Codegen() = 0;</b>
71 /// NumberExprAST - Expression class for numeric literals like "1.0".
72 class NumberExprAST : public ExprAST {
75 explicit NumberExprAST(double val) : Val(val) {}
76 <b>virtual Value *Codegen();</b>
82 <p>The Codegen() method says to emit IR for that AST node and all things it
83 depends on, and they all return an LLVM Value object.
84 "Value" is the class used to represent a "<a
85 href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
86 Assignment (SSA)</a> register" or "SSA value" in LLVM. The most distinct aspect
87 of SSA values is that their value is computed as the related instruction
88 executes, and it does not get a new value until (and if) the instruction
89 re-executes. In order words, there is no way to "change" an SSA value. For
90 more information, please read up on <a
91 href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
92 Assignment</a> - the concepts are really quite natural once you grok them.</p>
94 <p>Note that instead of adding virtual methods to the ExprAST class hierarchy,
95 it could also make sense to use a visitor pattern or some other way to model
96 this. Again, this tutorial won't dwell on good software engineering practices:
97 for our purposes, adding a virtual method is simplest.</p>
100 second thing we want is an "Error" method like we used for parser, which will
101 be used to report errors found during code generation (for example, use of an
102 undeclared parameter):</p>
104 <div class="doc_code">
106 Value *ErrorV(const char *Str) { Error(Str); return 0; }
108 static Module *TheModule;
109 static LLVMBuilder Builder;
110 static std::map<std::string, Value*> NamedValues;
114 <p>The static variables will be used during code generation. <tt>TheModule</tt>
115 is the LLVM construct that contains all of the functions and global variables in
116 a chunk of code. In many ways, it is the top-level structure that the LLVM IR
117 uses to contain code.</p>
119 <p>The <tt>Builder</tt> object is a helper object that makes it easy to generate
120 LLVM instructions. Instances of the <a
121 href="http://llvm.org/doxygen/LLVMBuilder_8h-source.html"><tt>LLVMBuilder</tt>
122 class</a> keeps track of the current place to
123 insert instructions and has methods to create new instructions.</p>
125 <p>The <tt>NamedValues</tt> map keeps track of which values are defined in the
126 current scope and what their LLVM representation is. In this form of
127 Kaleidoscope, the only things that can be referenced are function parameters.
128 As such, function parameters will be in this map when generating code for their
132 With these basics in place, we can start talking about how to generate code for
133 each expression. Note that this assumes that the <tt>Builder</tt> has been set
134 up to generate code <em>into</em> something. For now, we'll assume that this
135 has already been done, and we'll just use it to emit code.
140 <!-- *********************************************************************** -->
141 <div class="doc_section"><a name="exprs">Expression Code Generation</a></div>
142 <!-- *********************************************************************** -->
144 <div class="doc_text">
146 <p>Generating LLVM code for expression nodes is very straight-forward: less
147 than 45 lines of commented code for all four of our expression nodes. First,
148 we'll do numeric literals:</p>
150 <div class="doc_code">
152 Value *NumberExprAST::Codegen() {
153 return ConstantFP::get(Type::DoubleTy, APFloat(Val));
158 <p>In the LLVM IR, numeric constants are represented with the
159 <tt>ConstantFP</tt> class, which holds the numeric value in an <tt>APFloat</tt>
160 internally (<tt>APFloat</tt> has the capability of holding floating point
161 constants of <em>A</em>rbitrary <em>P</em>recision). This code basically just
162 creates and returns a <tt>ConstantFP</tt>. Note that in the LLVM IR
163 that constants are all uniqued together and shared. For this reason, the API
164 uses "the foo::get(..)" idiom instead of "new foo(..)" or "foo::create(..).</p>
166 <div class="doc_code">
168 Value *VariableExprAST::Codegen() {
169 // Look this variable up in the function.
170 Value *V = NamedValues[Name];
171 return V ? V : ErrorV("Unknown variable name");
176 <p>References to variables is also quite simple here. In the simple version
177 of Kaleidoscope, we assume that the variable has already been emited somewhere
178 and its value is available. In practice, the only values that can be in the
179 <tt>NamedValues</tt> map are function arguments. This
180 code simply checks to see that the specified name is in the map (if not, an
181 unknown variable is being referenced) and returns the value for it.</p>
183 <div class="doc_code">
185 Value *BinaryExprAST::Codegen() {
186 Value *L = LHS->Codegen();
187 Value *R = RHS->Codegen();
188 if (L == 0 || R == 0) return 0;
191 case '+': return Builder.CreateAdd(L, R, "addtmp");
192 case '-': return Builder.CreateSub(L, R, "subtmp");
193 case '*': return Builder.CreateMul(L, R, "multmp");
195 L = Builder.CreateFCmpULT(L, R, "multmp");
196 // Convert bool 0/1 to double 0.0 or 1.0
197 return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
198 default: return ErrorV("invalid binary operator");
204 <p>Binary operators start to get more interesting. The basic idea here is that
205 we recursively emit code for the left-hand side of the expression, then the
206 right-hand side, then we compute the result of the binary expression. In this
207 code, we do a simple switch on the opcode to create the right LLVM instruction.
210 <p>In this example, the LLVM builder class is starting to show its value.
211 Because it knows where to insert the newly created instruction, you just have to
212 specificy what instruction to create (e.g. with <tt>CreateAdd</tt>), which
213 operands to use (<tt>L</tt> and <tt>R</tt> here) and optionally provide a name
214 for the generated instruction. One nice thing about LLVM is that the name is
215 just a hint: if there are multiple additions in a single function, the first
216 will be named "addtmp" and the second will be "autorenamed" by adding a suffix,
217 giving it a name like "addtmp42". Local value names for instructions are purely
218 optional, but it makes it much easier to read the IR dumps.</p>
220 <p><a href="../LangRef.html#instref">LLVM instructions</a> are constrained to
221 have very strict type properties: for example, the Left and Right operators of
222 an <a href="../LangRef.html#i_add">add instruction</a> have to have the same
223 type, and that the result of the add matches the operands. Because all values
224 in Kaleidoscope are doubles, this makes for very simple code for add, sub and
227 <p>On the other hand, LLVM specifies that the <a
228 href="../LangRef.html#i_fcmp">fcmp instruction</a> always returns an 'i1' value
229 (a one bit integer). However, Kaleidoscope wants the value to be a 0.0 or 1.0
230 value. In order to get these semantics, we combine the fcmp instruction with
231 a <a href="../LangRef.html#i_uitofp">uitofp instruction</a>. This instruction
232 converts its input integer into a floating point value by treating the input
233 as an unsigned value. In contrast, if we used the <a
234 href="../LangRef.html#i_sitofp">sitofp instruction</a>, the Kaleidoscope '<'
235 operator would return 0.0 and -1.0, depending on the input value.</p>
237 <div class="doc_code">
239 Value *CallExprAST::Codegen() {
240 // Look up the name in the global module table.
241 Function *CalleeF = TheModule->getFunction(Callee);
243 return ErrorV("Unknown function referenced");
245 // If argument mismatch error.
246 if (CalleeF->arg_size() != Args.size())
247 return ErrorV("Incorrect # arguments passed");
249 std::vector<Value*> ArgsV;
250 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
251 ArgsV.push_back(Args[i]->Codegen());
252 if (ArgsV.back() == 0) return 0;
255 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
260 <p>Code generation for function calls is quite straight-forward with LLVM. The
261 code above first looks the name of the function up in the LLVM Module's symbol
262 table. Recall that the LLVM Module is the container that holds all of the
263 functions we are JIT'ing. By giving each function the same name as what the
264 user specifies, we can use the LLVM symbol table to resolve function names for
267 <p>Once we have the function to call, we recursively codegen each argument that
268 is to be passed in, and create an LLVM <a href="../LangRef.html#i_call">call
269 instruction</a>. Note that LLVM uses the native C calling conventions by
270 default, allowing these calls to call into standard library functions like
271 "sin" and "cos" with no additional effort.</p>
273 <p>This wraps up our handling of the four basic expressions that we have so far
274 in Kaleidoscope. Feel free to go in and add some more. For example, by
275 browsing the <a href="../LangRef.html">LLVM language reference</a> you'll find
276 several other interesting instructions that are really easy to plug into our
281 <!-- *********************************************************************** -->
282 <div class="doc_section"><a name="funcs">Function Code Generation</a></div>
283 <!-- *********************************************************************** -->
285 <div class="doc_text">
287 <p>Code generation for prototypes and functions has to handle a number of
288 details, which make their code less beautiful and elegant than expression code
289 generation, but they illustrate some important points. First, lets talk about
290 code generation for prototypes: this is used both for function bodies as well
291 as external function declarations. The code starts with:</p>
293 <div class="doc_code">
295 Function *PrototypeAST::Codegen() {
296 // Make the function type: double(double,double) etc.
297 std::vector<const Type*> Doubles(Args.size(), Type::DoubleTy);
298 FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
300 Function *F = new Function(FT, Function::ExternalLinkage, Name, TheModule);
304 <p>This code packs a lot of power into a few lines. Note first that this
305 function returns a Function* instead of a Value*. Because a "prototype" really
306 talks about the external interface for a function (not the value computed by
307 an expression), it makes sense for it to return the LLVM Function it corresponds
308 to when codegen'd.</p>
310 <p>The next step is to create
311 the <tt>FunctionType</tt> that should be used for a given Prototype. Since all
312 function arguments in Kaleidoscope are of type double, the first line creates
313 a vector of "N" LLVM Double types. It then uses the <tt>FunctionType::get</tt>
314 method to create a function type that takes "N" doubles as arguments, returns
315 one double as a result, and that is not vararg (the false parameter indicates
316 this). Note that Types in LLVM are uniqued just like Constants are, so you
317 don't "new" a type, you "get" it.</p>
319 <p>The final line above actually creates the function that the prototype will
320 correspond to. This indicates which type, linkage, and name to use, and which
321 module to insert into. "<a href="LangRef.html#linkage">external linkage</a>"
322 means that the function may be defined outside the current module and/or that it
323 is callable by functions outside the module. The Name passed in is the name the
324 user specified: since "<tt>TheModule</tt>" is specified, this name is registered
325 in "<tt>TheModule</tt>"s symbol table, which is used by the function call code
328 <div class="doc_code">
330 // If F conflicted, there was already something named 'Name'. If it has a
331 // body, don't allow redefinition or reextern.
332 if (F->getName() != Name) {
333 // Delete the one we just made and get the existing one.
334 F->eraseFromParent();
335 F = TheModule->getFunction(Name);
339 <p>The Module symbol table works just like the Function symbol table when it
340 comes to name conflicts: if a new function is created with a name was previously
341 added to the symbol table, it will get implicitly renamed when added to the
342 Module. The code above exploits this fact to tell if there was a previous
343 definition of this function.</p>
345 <p>In Kaleidoscope, I choose to allow redefinitions of functions in two cases:
346 first, we want to allow 'extern'ing a function more than once, so long as the
347 prototypes for the externs match (since all arguments have the same type, we
348 just have to check that the number of arguments match). Second, we want to
349 allow 'extern'ing a function and then definining a body for it. This is useful
350 when defining mutually recursive functions.</p>
352 <p>In order to implement this, the code above first checks to see if there is
353 a collision on the name of the function. If so, it deletes the function we just
354 created (by calling <tt>eraseFromParent</tt>) and then calling
355 <tt>getFunction</tt> to get the existing function with the specified name. Note
356 that many APIs in LLVM have "erase" forms and "remove" forms. The "remove" form
357 unlinks the object from its parent (e.g. a Function from a Module) and returns
358 it. The "erase" form unlinks the object and then deletes it.</p>
360 <div class="doc_code">
362 // If F already has a body, reject this.
363 if (!F->empty()) {
364 ErrorF("redefinition of function");
368 // If F took a different number of args, reject.
369 if (F->arg_size() != Args.size()) {
370 ErrorF("redefinition of function with different # args");
377 <p>In order to verify the logic above, we first check to see if the preexisting
378 function is "empty". In this case, empty means that it has no basic blocks in
379 it, which means it has no body. If it has no body, this means its a forward
380 declaration. Since we don't allow anything after a full definition of the
381 function, the code rejects this case. If the previous reference to a function
382 was an 'extern', we simply verify that the number of arguments for that
383 definition and this one match up. If not, we emit an error.</p>
385 <div class="doc_code">
387 // Set names for all arguments.
389 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
391 AI->setName(Args[Idx]);
393 // Add arguments to variable symbol table.
394 NamedValues[Args[Idx]] = AI;
401 <p>The last bit of code for prototypes loops over all of the arguments in the
402 function, setting the name of the LLVM Argument objects to match and registering
403 the arguments in the <tt>NamedValues</tt> map for future use by the
404 <tt>VariableExprAST</tt> AST node. Once this is set up, it returns the Function
405 object to the caller. Note that we don't check for conflicting
406 argument names here (e.g. "extern foo(a b a)"). Doing so would be very
407 straight-forward.</p>
409 <div class="doc_code">
411 Function *FunctionAST::Codegen() {
414 Function *TheFunction = Proto->Codegen();
415 if (TheFunction == 0)
420 <p>Code generation for function definitions starts out simply enough: first we
421 codegen the prototype and verify that it is ok. We also clear out the
422 <tt>NamedValues</tt> map to make sure that there isn't anything in it from the
423 last function we compiled.</p>
425 <div class="doc_code">
427 // Create a new basic block to start insertion into.
428 BasicBlock *BB = new BasicBlock("entry", TheFunction);
429 Builder.SetInsertPoint(BB);
431 if (Value *RetVal = Body->Codegen()) {
435 <p>Now we get to the point where the <tt>Builder</tt> is set up. The first
436 line creates a new <a href="http://en.wikipedia.org/wiki/Basic_block">basic
437 block</a> (named "entry"), which is inserted into <tt>TheFunction</tt>. The
438 second line then tells the builder that new instructions should be inserted into
439 the end of the new basic block. Basic blocks in LLVM are an important part
440 of functions that define the <a
441 href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow Graph</a>.
442 Since we don't have any control flow, our functions will only contain one
443 block so far. We'll fix this in a future installment :).</p>
445 <div class="doc_code">
447 if (Value *RetVal = Body->Codegen()) {
448 // Finish off the function.
449 Builder.CreateRet(RetVal);
451 // Validate the generated code, checking for consistency.
452 verifyFunction(*TheFunction);
458 <p>Once the insertion point is set up, we call the <tt>CodeGen()</tt> method for
459 the root expression of the function. If no error happens, this emits code to
460 compute the expression into the entry block and returns the value that was
461 computed. Assuming no error, we then create an LLVM <a
462 href="../LangRef.html#i_ret">ret instruction</a>, which completes the function.
463 Once the function is built, we call the <tt>verifyFunction</tt> function, which
464 is provided by LLVM. This function does a variety of consistency checks on the
465 generated code, to determine if our compiler is doing everything right. Using
466 this is important: it can catch a lot of bugs. Once the function is finished
467 and validated, we return it.</p>
469 <div class="doc_code">
471 // Error reading body, remove function.
472 TheFunction->eraseFromParent();
478 <p>The only piece left here is handling of the error case. For simplicity, we
479 simply handle this by deleting the function we produced with the
480 <tt>eraseFromParent</tt> method. This allows the user to redefine a function
481 that they incorrectly typed in before: if we didn't delete it, it would live in
482 the symbol table, with a body, preventing future redefinition.</p>
484 <p>This code does have a bug though. Since the <tt>PrototypeAST::Codegen</tt>
485 can return a previously defined forward declaration, this can actually delete
486 a forward declaration. There are a number of ways to fix this bug, see what you
487 can come up with! Here is a testcase:</p>
489 <div class="doc_code">
491 extern foo(a b); # ok, defines foo.
492 def foo(a b) c; # error, 'c' is invalid.
493 def bar() foo(1, 2); # error, unknown function "foo"
499 <!-- *********************************************************************** -->
500 <div class="doc_section"><a name="driver">Driver Changes and
501 Closing Thoughts</a></div>
502 <!-- *********************************************************************** -->
504 <div class="doc_text">
507 For now, code generation to LLVM doesn't really get us much, except that we can
508 look at the pretty IR calls. The sample code inserts calls to Codegen into the
509 "<tt>HandleDefinition</tt>", "<tt>HandleExtern</tt>" etc functions, and then
510 dumps out the LLVM IR. This gives a nice way to look at the LLVM IR for simple
511 functions. For example:
514 <div class="doc_code">
517 ready> Read top-level expression:
518 define double @""() {
520 %addtmp = add double 4.000000e+00, 5.000000e+00
526 <p>Note how the parser turns the top-level expression into anonymous functions
527 for us. This will be handy when we add JIT support in the next chapter. Also
528 note that the code is very literally transcribed, no optimizations are being
529 performed. We will add optimizations explicitly in the next chapter.</p>
531 <div class="doc_code">
533 ready> <b>def foo(a b) a*a + 2*a*b + b*b;</b>
534 ready> Read function definition:
535 define double @foo(double %a, double %b) {
537 %multmp = mul double %a, %a
538 %multmp1 = mul double 2.000000e+00, %a
539 %multmp2 = mul double %multmp1, %b
540 %addtmp = add double %multmp, %multmp2
541 %multmp3 = mul double %b, %b
542 %addtmp4 = add double %addtmp, %multmp3
548 <p>This shows some simple arithmetic. Notice the striking similarity to the
549 LLVM builder calls that we use to create the instructions.</p>
551 <div class="doc_code">
553 ready> <b>def bar(a) foo(a, 4.0) + bar(31337);</b>
554 ready> Read function definition:
555 define double @bar(double %a) {
557 %calltmp = call double @foo( double %a, double 4.000000e+00 )
558 %calltmp1 = call double @bar( double 3.133700e+04 )
559 %addtmp = add double %calltmp, %calltmp1
565 <p>This shows some function calls. Note that this function will take a long
566 time to execute if you call it. In the future we'll add conditional control
567 flow to make recursion actually be useful :).</p>
569 <div class="doc_code">
571 ready> <b>extern cos(x);</b>
572 ready> Read extern:
573 declare double @cos(double)
575 ready> <b>cos(1.234);</b>
576 ready> Read top-level expression:
577 define double @""() {
579 %calltmp = call double @cos( double 1.234000e+00 )
585 <p>This shows an extern for the libm "cos" function, and a call to it.</p>
588 <div class="doc_code">
591 ; ModuleID = 'my cool jit'
593 define double @""() {
595 %addtmp = add double 4.000000e+00, 5.000000e+00
599 define double @foo(double %a, double %b) {
601 %multmp = mul double %a, %a
602 %multmp1 = mul double 2.000000e+00, %a
603 %multmp2 = mul double %multmp1, %b
604 %addtmp = add double %multmp, %multmp2
605 %multmp3 = mul double %b, %b
606 %addtmp4 = add double %addtmp, %multmp3
610 define double @bar(double %a) {
612 %calltmp = call double @foo( double %a, double 4.000000e+00 )
613 %calltmp1 = call double @bar( double 3.133700e+04 )
614 %addtmp = add double %calltmp, %calltmp1
618 declare double @cos(double)
620 define double @""() {
622 %calltmp = call double @cos( double 1.234000e+00 )
628 <p>When you quit the current demo, it dumps out the IR for the entire module
629 generated. Here you can see the big picture with all the functions referencing
632 <p>This wraps up this chapter of the Kaleidoscope tutorial. Up next we'll
633 describe how to <a href="LangImpl4.html">add JIT codegen and optimizer
634 support</a> to this so we can actually start running code!</p>
639 <!-- *********************************************************************** -->
640 <div class="doc_section"><a name="code">Full Code Listing</a></div>
641 <!-- *********************************************************************** -->
643 <div class="doc_text">
646 Here is the complete code listing for our running example, enhanced with the
647 LLVM code generator. Because this uses the LLVM libraries, we need to link
648 them in. To do this, we use the <a
649 href="http://llvm.org/cmds/llvm-config.html">llvm-config</a> tool to inform
650 our makefile/command line about which options to use:</p>
652 <div class="doc_code">
655 g++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core` -o toy
661 <p>Here is the code:</p>
663 <div class="doc_code">
666 // See example below.
668 #include "llvm/DerivedTypes.h"
669 #include "llvm/Module.h"
670 #include "llvm/Analysis/Verifier.h"
671 #include "llvm/Support/LLVMBuilder.h"
672 #include <cstdio>
673 #include <string>
675 #include <vector>
676 using namespace llvm;
678 //===----------------------------------------------------------------------===//
680 //===----------------------------------------------------------------------===//
682 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
683 // of these for known things.
688 tok_def = -2, tok_extern = -3,
691 tok_identifier = -4, tok_number = -5,
694 static std::string IdentifierStr; // Filled in if tok_identifier
695 static double NumVal; // Filled in if tok_number
697 /// gettok - Return the next token from standard input.
698 static int gettok() {
699 static int LastChar = ' ';
701 // Skip any whitespace.
702 while (isspace(LastChar))
703 LastChar = getchar();
705 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
706 IdentifierStr = LastChar;
707 while (isalnum((LastChar = getchar())))
708 IdentifierStr += LastChar;
710 if (IdentifierStr == "def") return tok_def;
711 if (IdentifierStr == "extern") return tok_extern;
712 return tok_identifier;
715 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
719 LastChar = getchar();
720 } while (isdigit(LastChar) || LastChar == '.');
722 NumVal = strtod(NumStr.c_str(), 0);
726 if (LastChar == '#') {
727 // Comment until end of line.
728 do LastChar = getchar();
729 while (LastChar != EOF && LastChar != '\n' & LastChar != '\r');
735 // Check for end of file. Don't eat the EOF.
739 // Otherwise, just return the character as its ascii value.
740 int ThisChar = LastChar;
741 LastChar = getchar();
745 //===----------------------------------------------------------------------===//
746 // Abstract Syntax Tree (aka Parse Tree)
747 //===----------------------------------------------------------------------===//
749 /// ExprAST - Base class for all expression nodes.
752 virtual ~ExprAST() {}
753 virtual Value *Codegen() = 0;
756 /// NumberExprAST - Expression class for numeric literals like "1.0".
757 class NumberExprAST : public ExprAST {
760 explicit NumberExprAST(double val) : Val(val) {}
761 virtual Value *Codegen();
764 /// VariableExprAST - Expression class for referencing a variable, like "a".
765 class VariableExprAST : public ExprAST {
768 explicit VariableExprAST(const std::string &name) : Name(name) {}
769 virtual Value *Codegen();
772 /// BinaryExprAST - Expression class for a binary operator.
773 class BinaryExprAST : public ExprAST {
777 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
778 : Op(op), LHS(lhs), RHS(rhs) {}
779 virtual Value *Codegen();
782 /// CallExprAST - Expression class for function calls.
783 class CallExprAST : public ExprAST {
785 std::vector<ExprAST*> Args;
787 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
788 : Callee(callee), Args(args) {}
789 virtual Value *Codegen();
792 /// PrototypeAST - This class represents the "prototype" for a function,
793 /// which captures its argument names as well as if it is an operator.
796 std::vector<std::string> Args;
798 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
799 : Name(name), Args(args) {}
804 /// FunctionAST - This class represents a function definition itself.
809 FunctionAST(PrototypeAST *proto, ExprAST *body)
810 : Proto(proto), Body(body) {}
815 //===----------------------------------------------------------------------===//
817 //===----------------------------------------------------------------------===//
819 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
820 /// token the parser it looking at. getNextToken reads another token from the
821 /// lexer and updates CurTok with its results.
823 static int getNextToken() {
824 return CurTok = gettok();
827 /// BinopPrecedence - This holds the precedence for each binary operator that is
829 static std::map<char, int> BinopPrecedence;
831 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
832 static int GetTokPrecedence() {
833 if (!isascii(CurTok))
836 // Make sure it's a declared binop.
837 int TokPrec = BinopPrecedence[CurTok];
838 if (TokPrec <= 0) return -1;
842 /// Error* - These are little helper functions for error handling.
843 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
844 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
845 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
847 static ExprAST *ParseExpression();
851 /// ::= identifier '(' expression* ')'
852 static ExprAST *ParseIdentifierExpr() {
853 std::string IdName = IdentifierStr;
855 getNextToken(); // eat identifier.
857 if (CurTok != '(') // Simple variable ref.
858 return new VariableExprAST(IdName);
861 getNextToken(); // eat (
862 std::vector<ExprAST*> Args;
864 ExprAST *Arg = ParseExpression();
868 if (CurTok == ')') break;
871 return Error("Expected ')'");
878 return new CallExprAST(IdName, Args);
881 /// numberexpr ::= number
882 static ExprAST *ParseNumberExpr() {
883 ExprAST *Result = new NumberExprAST(NumVal);
884 getNextToken(); // consume the number
888 /// parenexpr ::= '(' expression ')'
889 static ExprAST *ParseParenExpr() {
890 getNextToken(); // eat (.
891 ExprAST *V = ParseExpression();
895 return Error("expected ')'");
896 getNextToken(); // eat ).
901 /// ::= identifierexpr
904 static ExprAST *ParsePrimary() {
906 default: return Error("unknown token when expecting an expression");
907 case tok_identifier: return ParseIdentifierExpr();
908 case tok_number: return ParseNumberExpr();
909 case '(': return ParseParenExpr();
914 /// ::= ('+' primary)*
915 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
916 // If this is a binop, find its precedence.
918 int TokPrec = GetTokPrecedence();
920 // If this is a binop that binds at least as tightly as the current binop,
921 // consume it, otherwise we are done.
922 if (TokPrec < ExprPrec)
925 // Okay, we know this is a binop.
927 getNextToken(); // eat binop
929 // Parse the primary expression after the binary operator.
930 ExprAST *RHS = ParsePrimary();
933 // If BinOp binds less tightly with RHS than the operator after RHS, let
934 // the pending operator take RHS as its LHS.
935 int NextPrec = GetTokPrecedence();
936 if (TokPrec < NextPrec) {
937 RHS = ParseBinOpRHS(TokPrec+1, RHS);
938 if (RHS == 0) return 0;
942 LHS = new BinaryExprAST(BinOp, LHS, RHS);
947 /// ::= primary binoprhs
949 static ExprAST *ParseExpression() {
950 ExprAST *LHS = ParsePrimary();
953 return ParseBinOpRHS(0, LHS);
957 /// ::= id '(' id* ')'
958 static PrototypeAST *ParsePrototype() {
959 if (CurTok != tok_identifier)
960 return ErrorP("Expected function name in prototype");
962 std::string FnName = IdentifierStr;
966 return ErrorP("Expected '(' in prototype");
968 std::vector<std::string> ArgNames;
969 while (getNextToken() == tok_identifier)
970 ArgNames.push_back(IdentifierStr);
972 return ErrorP("Expected ')' in prototype");
975 getNextToken(); // eat ')'.
977 return new PrototypeAST(FnName, ArgNames);
980 /// definition ::= 'def' prototype expression
981 static FunctionAST *ParseDefinition() {
982 getNextToken(); // eat def.
983 PrototypeAST *Proto = ParsePrototype();
984 if (Proto == 0) return 0;
986 if (ExprAST *E = ParseExpression())
987 return new FunctionAST(Proto, E);
991 /// toplevelexpr ::= expression
992 static FunctionAST *ParseTopLevelExpr() {
993 if (ExprAST *E = ParseExpression()) {
994 // Make an anonymous proto.
995 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
996 return new FunctionAST(Proto, E);
1001 /// external ::= 'extern' prototype
1002 static PrototypeAST *ParseExtern() {
1003 getNextToken(); // eat extern.
1004 return ParsePrototype();
1007 //===----------------------------------------------------------------------===//
1009 //===----------------------------------------------------------------------===//
1011 static Module *TheModule;
1012 static LLVMBuilder Builder;
1013 static std::map<std::string, Value*> NamedValues;
1015 Value *ErrorV(const char *Str) { Error(Str); return 0; }
1017 Value *NumberExprAST::Codegen() {
1018 return ConstantFP::get(Type::DoubleTy, APFloat(Val));
1021 Value *VariableExprAST::Codegen() {
1022 // Look this variable up in the function.
1023 Value *V = NamedValues[Name];
1024 return V ? V : ErrorV("Unknown variable name");
1027 Value *BinaryExprAST::Codegen() {
1028 Value *L = LHS->Codegen();
1029 Value *R = RHS->Codegen();
1030 if (L == 0 || R == 0) return 0;
1033 case '+': return Builder.CreateAdd(L, R, "addtmp");
1034 case '-': return Builder.CreateSub(L, R, "subtmp");
1035 case '*': return Builder.CreateMul(L, R, "multmp");
1037 L = Builder.CreateFCmpULT(L, R, "multmp");
1038 // Convert bool 0/1 to double 0.0 or 1.0
1039 return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
1040 default: return ErrorV("invalid binary operator");
1044 Value *CallExprAST::Codegen() {
1045 // Look up the name in the global module table.
1046 Function *CalleeF = TheModule->getFunction(Callee);
1048 return ErrorV("Unknown function referenced");
1050 // If argument mismatch error.
1051 if (CalleeF->arg_size() != Args.size())
1052 return ErrorV("Incorrect # arguments passed");
1054 std::vector<Value*> ArgsV;
1055 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1056 ArgsV.push_back(Args[i]->Codegen());
1057 if (ArgsV.back() == 0) return 0;
1060 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
1063 Function *PrototypeAST::Codegen() {
1064 // Make the function type: double(double,double) etc.
1065 std::vector<const Type*> Doubles(Args.size(), Type::DoubleTy);
1066 FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
1068 Function *F = new Function(FT, Function::ExternalLinkage, Name, TheModule);
1070 // If F conflicted, there was already something named 'Name'. If it has a
1071 // body, don't allow redefinition or reextern.
1072 if (F->getName() != Name) {
1073 // Delete the one we just made and get the existing one.
1074 F->eraseFromParent();
1075 F = TheModule->getFunction(Name);
1077 // If F already has a body, reject this.
1078 if (!F->empty()) {
1079 ErrorF("redefinition of function");
1083 // If F took a different number of args, reject.
1084 if (F->arg_size() != Args.size()) {
1085 ErrorF("redefinition of function with different # args");
1090 // Set names for all arguments.
1092 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1094 AI->setName(Args[Idx]);
1096 // Add arguments to variable symbol table.
1097 NamedValues[Args[Idx]] = AI;
1103 Function *FunctionAST::Codegen() {
1104 NamedValues.clear();
1106 Function *TheFunction = Proto->Codegen();
1107 if (TheFunction == 0)
1110 // Create a new basic block to start insertion into.
1111 BasicBlock *BB = new BasicBlock("entry", TheFunction);
1112 Builder.SetInsertPoint(BB);
1114 if (Value *RetVal = Body->Codegen()) {
1115 // Finish off the function.
1116 Builder.CreateRet(RetVal);
1118 // Validate the generated code, checking for consistency.
1119 verifyFunction(*TheFunction);
1123 // Error reading body, remove function.
1124 TheFunction->eraseFromParent();
1128 //===----------------------------------------------------------------------===//
1129 // Top-Level parsing and JIT Driver
1130 //===----------------------------------------------------------------------===//
1132 static void HandleDefinition() {
1133 if (FunctionAST *F = ParseDefinition()) {
1134 if (Function *LF = F->Codegen()) {
1135 fprintf(stderr, "Read function definition:");
1139 // Skip token for error recovery.
1144 static void HandleExtern() {
1145 if (PrototypeAST *P = ParseExtern()) {
1146 if (Function *F = P->Codegen()) {
1147 fprintf(stderr, "Read extern: ");
1151 // Skip token for error recovery.
1156 static void HandleTopLevelExpression() {
1157 // Evaluate a top level expression into an anonymous function.
1158 if (FunctionAST *F = ParseTopLevelExpr()) {
1159 if (Function *LF = F->Codegen()) {
1160 fprintf(stderr, "Read top-level expression:");
1164 // Skip token for error recovery.
1169 /// top ::= definition | external | expression | ';'
1170 static void MainLoop() {
1172 fprintf(stderr, "ready> ");
1174 case tok_eof: return;
1175 case ';': getNextToken(); break; // ignore top level semicolons.
1176 case tok_def: HandleDefinition(); break;
1177 case tok_extern: HandleExtern(); break;
1178 default: HandleTopLevelExpression(); break;
1185 //===----------------------------------------------------------------------===//
1186 // "Library" functions that can be "extern'd" from user code.
1187 //===----------------------------------------------------------------------===//
1189 /// putchard - putchar that takes a double and returns 0.
1191 double putchard(double X) {
1196 //===----------------------------------------------------------------------===//
1197 // Main driver code.
1198 //===----------------------------------------------------------------------===//
1201 TheModule = new Module("my cool jit");
1203 // Install standard binary operators.
1204 // 1 is lowest precedence.
1205 BinopPrecedence['<'] = 10;
1206 BinopPrecedence['+'] = 20;
1207 BinopPrecedence['-'] = 20;
1208 BinopPrecedence['*'] = 40; // highest.
1210 // Prime the first token.
1211 fprintf(stderr, "ready> ");
1215 TheModule->dump();
1222 <!-- *********************************************************************** -->
1225 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1226 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1227 <a href="http://validator.w3.org/check/referer"><img
1228 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
1230 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1231 <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
1232 Last modified: $Date: 2007-10-17 11:05:13 -0700 (Wed, 17 Oct 2007) $