• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1<!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: 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  <meta name="author" content="Erick Tryzelaar">
10  <link rel="stylesheet" href="../llvm.css" type="text/css">
11</head>
12
13<body>
14
15<h1>Kaleidoscope: Code generation to LLVM IR</h1>
16
17<ul>
18<li><a href="index.html">Up to Tutorial Index</a></li>
19<li>Chapter 3
20  <ol>
21    <li><a href="#intro">Chapter 3 Introduction</a></li>
22    <li><a href="#basics">Code Generation Setup</a></li>
23    <li><a href="#exprs">Expression Code Generation</a></li>
24    <li><a href="#funcs">Function Code Generation</a></li>
25    <li><a href="#driver">Driver Changes and Closing Thoughts</a></li>
26    <li><a href="#code">Full Code Listing</a></li>
27  </ol>
28</li>
29<li><a href="OCamlLangImpl4.html">Chapter 4</a>: Adding JIT and Optimizer
30Support</li>
31</ul>
32
33<div class="doc_author">
34	<p>
35		Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
36		and <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a>
37	</p>
38</div>
39
40<!-- *********************************************************************** -->
41<h2><a name="intro">Chapter 3 Introduction</a></h2>
42<!-- *********************************************************************** -->
43
44<div>
45
46<p>Welcome to Chapter 3 of the "<a href="index.html">Implementing a language
47with LLVM</a>" tutorial.  This chapter shows you how to transform the <a
48href="OCamlLangImpl2.html">Abstract Syntax Tree</a>, built in Chapter 2, into
49LLVM IR.  This will teach you a little bit about how LLVM does things, as well
50as demonstrate how easy it is to use.  It's much more work to build a lexer and
51parser than it is to generate LLVM IR code. :)
52</p>
53
54<p><b>Please note</b>: the code in this chapter and later require LLVM 2.3 or
55LLVM SVN to work.  LLVM 2.2 and before will not work with it.</p>
56
57</div>
58
59<!-- *********************************************************************** -->
60<h2><a name="basics">Code Generation Setup</a></h2>
61<!-- *********************************************************************** -->
62
63<div>
64
65<p>
66In order to generate LLVM IR, we want some simple setup to get started.  First
67we define virtual code generation (codegen) methods in each AST class:</p>
68
69<div class="doc_code">
70<pre>
71let rec codegen_expr = function
72  | Ast.Number n -&gt; ...
73  | Ast.Variable name -&gt; ...
74</pre>
75</div>
76
77<p>The <tt>Codegen.codegen_expr</tt> function says to emit IR for that AST node
78along with all the things it depends on, and they all return an LLVM Value
79object.  "Value" is the class used to represent a "<a
80href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
81Assignment (SSA)</a> register" or "SSA value" in LLVM.  The most distinct aspect
82of SSA values is that their value is computed as the related instruction
83executes, and it does not get a new value until (and if) the instruction
84re-executes.  In other words, there is no way to "change" an SSA value.  For
85more information, please read up on <a
86href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
87Assignment</a> - the concepts are really quite natural once you grok them.</p>
88
89<p>The
90second thing we want is an "Error" exception like we used for the parser, which
91will be used to report errors found during code generation (for example, use of
92an undeclared parameter):</p>
93
94<div class="doc_code">
95<pre>
96exception Error of string
97
98let context = global_context ()
99let the_module = create_module context "my cool jit"
100let builder = builder context
101let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
102let double_type = double_type context
103</pre>
104</div>
105
106<p>The static variables will be used during code generation.
107<tt>Codgen.the_module</tt> is the LLVM construct that contains all of the
108functions and global variables in a chunk of code.  In many ways, it is the
109top-level structure that the LLVM IR uses to contain code.</p>
110
111<p>The <tt>Codegen.builder</tt> object is a helper object that makes it easy to
112generate LLVM instructions.  Instances of the <a
113href="http://llvm.org/doxygen/IRBuilder_8h-source.html"><tt>IRBuilder</tt></a>
114class keep track of the current place to insert instructions and has methods to
115create new instructions.</p>
116
117<p>The <tt>Codegen.named_values</tt> map keeps track of which values are defined
118in the current scope and what their LLVM representation is.  (In other words, it
119is a symbol table for the code).  In this form of Kaleidoscope, the only things
120that can be referenced are function parameters.  As such, function parameters
121will be in this map when generating code for their function body.</p>
122
123<p>
124With these basics in place, we can start talking about how to generate code for
125each expression.  Note that this assumes that the <tt>Codgen.builder</tt> has
126been set up to generate code <em>into</em> something.  For now, we'll assume
127that this has already been done, and we'll just use it to emit code.</p>
128
129</div>
130
131<!-- *********************************************************************** -->
132<h2><a name="exprs">Expression Code Generation</a></h2>
133<!-- *********************************************************************** -->
134
135<div>
136
137<p>Generating LLVM code for expression nodes is very straightforward: less
138than 30 lines of commented code for all four of our expression nodes.  First
139we'll do numeric literals:</p>
140
141<div class="doc_code">
142<pre>
143  | Ast.Number n -&gt; const_float double_type n
144</pre>
145</div>
146
147<p>In the LLVM IR, numeric constants are represented with the
148<tt>ConstantFP</tt> class, which holds the numeric value in an <tt>APFloat</tt>
149internally (<tt>APFloat</tt> has the capability of holding floating point
150constants of <em>A</em>rbitrary <em>P</em>recision).  This code basically just
151creates and returns a <tt>ConstantFP</tt>.  Note that in the LLVM IR
152that constants are all uniqued together and shared.  For this reason, the API
153uses "the foo::get(..)" idiom instead of "new foo(..)" or "foo::Create(..)".</p>
154
155<div class="doc_code">
156<pre>
157  | Ast.Variable name -&gt;
158      (try Hashtbl.find named_values name with
159        | Not_found -&gt; raise (Error "unknown variable name"))
160</pre>
161</div>
162
163<p>References to variables are also quite simple using LLVM.  In the simple
164version of Kaleidoscope, we assume that the variable has already been emitted
165somewhere and its value is available.  In practice, the only values that can be
166in the <tt>Codegen.named_values</tt> map are function arguments.  This code
167simply checks to see that the specified name is in the map (if not, an unknown
168variable is being referenced) and returns the value for it.  In future chapters,
169we'll add support for <a href="LangImpl5.html#for">loop induction variables</a>
170in the symbol table, and for <a href="LangImpl7.html#localvars">local
171variables</a>.</p>
172
173<div class="doc_code">
174<pre>
175  | Ast.Binary (op, lhs, rhs) -&gt;
176      let lhs_val = codegen_expr lhs in
177      let rhs_val = codegen_expr rhs in
178      begin
179        match op with
180        | '+' -&gt; build_fadd lhs_val rhs_val "addtmp" builder
181        | '-' -&gt; build_fsub lhs_val rhs_val "subtmp" builder
182        | '*' -&gt; build_fmul lhs_val rhs_val "multmp" builder
183        | '&lt;' -&gt;
184            (* Convert bool 0/1 to double 0.0 or 1.0 *)
185            let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
186            build_uitofp i double_type "booltmp" builder
187        | _ -&gt; raise (Error "invalid binary operator")
188      end
189</pre>
190</div>
191
192<p>Binary operators start to get more interesting.  The basic idea here is that
193we recursively emit code for the left-hand side of the expression, then the
194right-hand side, then we compute the result of the binary expression.  In this
195code, we do a simple switch on the opcode to create the right LLVM instruction.
196</p>
197
198<p>In the example above, the LLVM builder class is starting to show its value.
199IRBuilder knows where to insert the newly created instruction, all you have to
200do is specify what instruction to create (e.g. with <tt>Llvm.create_add</tt>),
201which operands to use (<tt>lhs</tt> and <tt>rhs</tt> here) and optionally
202provide a name for the generated instruction.</p>
203
204<p>One nice thing about LLVM is that the name is just a hint.  For instance, if
205the code above emits multiple "addtmp" variables, LLVM will automatically
206provide each one with an increasing, unique numeric suffix.  Local value names
207for instructions are purely optional, but it makes it much easier to read the
208IR dumps.</p>
209
210<p><a href="../LangRef.html#instref">LLVM instructions</a> are constrained by
211strict rules: for example, the Left and Right operators of
212an <a href="../LangRef.html#i_add">add instruction</a> must have the same
213type, and the result type of the add must match the operand types.  Because
214all values in Kaleidoscope are doubles, this makes for very simple code for add,
215sub and mul.</p>
216
217<p>On the other hand, LLVM specifies that the <a
218href="../LangRef.html#i_fcmp">fcmp instruction</a> always returns an 'i1' value
219(a one bit integer).  The problem with this is that Kaleidoscope wants the value to be a 0.0 or 1.0 value.  In order to get these semantics, we combine the fcmp instruction with
220a <a href="../LangRef.html#i_uitofp">uitofp instruction</a>.  This instruction
221converts its input integer into a floating point value by treating the input
222as an unsigned value.  In contrast, if we used the <a
223href="../LangRef.html#i_sitofp">sitofp instruction</a>, the Kaleidoscope '&lt;'
224operator would return 0.0 and -1.0, depending on the input value.</p>
225
226<div class="doc_code">
227<pre>
228  | Ast.Call (callee, args) -&gt;
229      (* Look up the name in the module table. *)
230      let callee =
231        match lookup_function callee the_module with
232        | Some callee -&gt; callee
233        | None -&gt; raise (Error "unknown function referenced")
234      in
235      let params = params callee in
236
237      (* If argument mismatch error. *)
238      if Array.length params == Array.length args then () else
239        raise (Error "incorrect # arguments passed");
240      let args = Array.map codegen_expr args in
241      build_call callee args "calltmp" builder
242</pre>
243</div>
244
245<p>Code generation for function calls is quite straightforward with LLVM.  The
246code above initially does a function name lookup in the LLVM Module's symbol
247table.  Recall that the LLVM Module is the container that holds all of the
248functions we are JIT'ing.  By giving each function the same name as what the
249user specifies, we can use the LLVM symbol table to resolve function names for
250us.</p>
251
252<p>Once we have the function to call, we recursively codegen each argument that
253is to be passed in, and create an LLVM <a href="../LangRef.html#i_call">call
254instruction</a>.  Note that LLVM uses the native C calling conventions by
255default, allowing these calls to also call into standard library functions like
256"sin" and "cos", with no additional effort.</p>
257
258<p>This wraps up our handling of the four basic expressions that we have so far
259in Kaleidoscope.  Feel free to go in and add some more.  For example, by
260browsing the <a href="../LangRef.html">LLVM language reference</a> you'll find
261several other interesting instructions that are really easy to plug into our
262basic framework.</p>
263
264</div>
265
266<!-- *********************************************************************** -->
267<h2><a name="funcs">Function Code Generation</a></h2>
268<!-- *********************************************************************** -->
269
270<div>
271
272<p>Code generation for prototypes and functions must handle a number of
273details, which make their code less beautiful than expression code
274generation, but allows us to illustrate some important points.  First, lets
275talk about code generation for prototypes: they are used both for function
276bodies and external function declarations.  The code starts with:</p>
277
278<div class="doc_code">
279<pre>
280let codegen_proto = function
281  | Ast.Prototype (name, args) -&gt;
282      (* Make the function type: double(double,double) etc. *)
283      let doubles = Array.make (Array.length args) double_type in
284      let ft = function_type double_type doubles in
285      let f =
286        match lookup_function name the_module with
287</pre>
288</div>
289
290<p>This code packs a lot of power into a few lines.  Note first that this
291function returns a "Function*" instead of a "Value*" (although at the moment
292they both are modeled by <tt>llvalue</tt> in ocaml).  Because a "prototype"
293really talks about the external interface for a function (not the value computed
294by an expression), it makes sense for it to return the LLVM Function it
295corresponds to when codegen'd.</p>
296
297<p>The call to <tt>Llvm.function_type</tt> creates the <tt>Llvm.llvalue</tt>
298that should be used for a given Prototype.  Since all function arguments in
299Kaleidoscope are of type double, the first line creates a vector of "N" LLVM
300double types.  It then uses the <tt>Llvm.function_type</tt> method to create a
301function type that takes "N" doubles as arguments, returns one double as a
302result, and that is not vararg (that uses the function
303<tt>Llvm.var_arg_function_type</tt>).  Note that Types in LLVM are uniqued just
304like <tt>Constant</tt>s are, so you don't "new" a type, you "get" it.</p>
305
306<p>The final line above checks if the function has already been defined in
307<tt>Codegen.the_module</tt>. If not, we will create it.</p>
308
309<div class="doc_code">
310<pre>
311        | None -&gt; declare_function name ft the_module
312</pre>
313</div>
314
315<p>This indicates the type and name to use, as well as which module to insert
316into.  By default we assume a function has
317<tt>Llvm.Linkage.ExternalLinkage</tt>.  "<a href="LangRef.html#linkage">external
318linkage</a>" means that the function may be defined outside the current module
319and/or that it is callable by functions outside the module.  The "<tt>name</tt>"
320passed in is the name the user specified: this name is registered in
321"<tt>Codegen.the_module</tt>"s symbol table, which is used by the function call
322code above.</p>
323
324<p>In Kaleidoscope, I choose to allow redefinitions of functions in two cases:
325first, we want to allow 'extern'ing a function more than once, as long as the
326prototypes for the externs match (since all arguments have the same type, we
327just have to check that the number of arguments match).  Second, we want to
328allow 'extern'ing a function and then defining a body for it.  This is useful
329when defining mutually recursive functions.</p>
330
331<div class="doc_code">
332<pre>
333        (* If 'f' conflicted, there was already something named 'name'. If it
334         * has a body, don't allow redefinition or reextern. *)
335        | Some f -&gt;
336            (* If 'f' already has a body, reject this. *)
337            if Array.length (basic_blocks f) == 0 then () else
338              raise (Error "redefinition of function");
339
340            (* If 'f' took a different number of arguments, reject. *)
341            if Array.length (params f) == Array.length args then () else
342              raise (Error "redefinition of function with different # args");
343            f
344      in
345</pre>
346</div>
347
348<p>In order to verify the logic above, we first check to see if the pre-existing
349function is "empty".  In this case, empty means that it has no basic blocks in
350it, which means it has no body.  If it has no body, it is a forward
351declaration.  Since we don't allow anything after a full definition of the
352function, the code rejects this case.  If the previous reference to a function
353was an 'extern', we simply verify that the number of arguments for that
354definition and this one match up.  If not, we emit an error.</p>
355
356<div class="doc_code">
357<pre>
358      (* Set names for all arguments. *)
359      Array.iteri (fun i a -&gt;
360        let n = args.(i) in
361        set_value_name n a;
362        Hashtbl.add named_values n a;
363      ) (params f);
364      f
365</pre>
366</div>
367
368<p>The last bit of code for prototypes loops over all of the arguments in the
369function, setting the name of the LLVM Argument objects to match, and registering
370the arguments in the <tt>Codegen.named_values</tt> map for future use by the
371<tt>Ast.Variable</tt> variant.  Once this is set up, it returns the Function
372object to the caller.  Note that we don't check for conflicting
373argument names here (e.g. "extern foo(a b a)").  Doing so would be very
374straight-forward with the mechanics we have already used above.</p>
375
376<div class="doc_code">
377<pre>
378let codegen_func = function
379  | Ast.Function (proto, body) -&gt;
380      Hashtbl.clear named_values;
381      let the_function = codegen_proto proto in
382</pre>
383</div>
384
385<p>Code generation for function definitions starts out simply enough: we just
386codegen the prototype (Proto) and verify that it is ok.  We then clear out the
387<tt>Codegen.named_values</tt> map to make sure that there isn't anything in it
388from the last function we compiled.  Code generation of the prototype ensures
389that there is an LLVM Function object that is ready to go for us.</p>
390
391<div class="doc_code">
392<pre>
393      (* Create a new basic block to start insertion into. *)
394      let bb = append_block context "entry" the_function in
395      position_at_end bb builder;
396
397      try
398        let ret_val = codegen_expr body in
399</pre>
400</div>
401
402<p>Now we get to the point where the <tt>Codegen.builder</tt> is set up.  The
403first line creates a new
404<a href="http://en.wikipedia.org/wiki/Basic_block">basic block</a> (named
405"entry"), which is inserted into <tt>the_function</tt>.  The second line then
406tells the builder that new instructions should be inserted into the end of the
407new basic block.  Basic blocks in LLVM are an important part of functions that
408define the <a
409href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow Graph</a>.
410Since we don't have any control flow, our functions will only contain one
411block at this point.  We'll fix this in <a href="OCamlLangImpl5.html">Chapter
4125</a> :).</p>
413
414<div class="doc_code">
415<pre>
416        let ret_val = codegen_expr body in
417
418        (* Finish off the function. *)
419        let _ = build_ret ret_val builder in
420
421        (* Validate the generated code, checking for consistency. *)
422        Llvm_analysis.assert_valid_function the_function;
423
424        the_function
425</pre>
426</div>
427
428<p>Once the insertion point is set up, we call the <tt>Codegen.codegen_func</tt>
429method for the root expression of the function.  If no error happens, this emits
430code to compute the expression into the entry block and returns the value that
431was computed.  Assuming no error, we then create an LLVM <a
432href="../LangRef.html#i_ret">ret instruction</a>, which completes the function.
433Once the function is built, we call
434<tt>Llvm_analysis.assert_valid_function</tt>, which is provided by LLVM.  This
435function does a variety of consistency checks on the generated code, to
436determine if our compiler is doing everything right.  Using this is important:
437it can catch a lot of bugs.  Once the function is finished and validated, we
438return it.</p>
439
440<div class="doc_code">
441<pre>
442      with e -&gt;
443        delete_function the_function;
444        raise e
445</pre>
446</div>
447
448<p>The only piece left here is handling of the error case.  For simplicity, we
449handle this by merely deleting the function we produced with the
450<tt>Llvm.delete_function</tt> method.  This allows the user to redefine a
451function that they incorrectly typed in before: if we didn't delete it, it
452would live in the symbol table, with a body, preventing future redefinition.</p>
453
454<p>This code does have a bug, though.  Since the <tt>Codegen.codegen_proto</tt>
455can return a previously defined forward declaration, our code can actually delete
456a forward declaration.  There are a number of ways to fix this bug, see what you
457can come up with!  Here is a testcase:</p>
458
459<div class="doc_code">
460<pre>
461extern foo(a b);     # ok, defines foo.
462def foo(a b) c;      # error, 'c' is invalid.
463def bar() foo(1, 2); # error, unknown function "foo"
464</pre>
465</div>
466
467</div>
468
469<!-- *********************************************************************** -->
470<h2><a name="driver">Driver Changes and Closing Thoughts</a></h2>
471<!-- *********************************************************************** -->
472
473<div>
474
475<p>
476For now, code generation to LLVM doesn't really get us much, except that we can
477look at the pretty IR calls.  The sample code inserts calls to Codegen into the
478"<tt>Toplevel.main_loop</tt>", and then dumps out the LLVM IR.  This gives a
479nice way to look at the LLVM IR for simple functions.  For example:
480</p>
481
482<div class="doc_code">
483<pre>
484ready&gt; <b>4+5</b>;
485Read top-level expression:
486define double @""() {
487entry:
488        %addtmp = fadd double 4.000000e+00, 5.000000e+00
489        ret double %addtmp
490}
491</pre>
492</div>
493
494<p>Note how the parser turns the top-level expression into anonymous functions
495for us.  This will be handy when we add <a href="OCamlLangImpl4.html#jit">JIT
496support</a> in the next chapter.  Also note that the code is very literally
497transcribed, no optimizations are being performed.  We will
498<a href="OCamlLangImpl4.html#trivialconstfold">add optimizations</a> explicitly
499in the next chapter.</p>
500
501<div class="doc_code">
502<pre>
503ready&gt; <b>def foo(a b) a*a + 2*a*b + b*b;</b>
504Read function definition:
505define double @foo(double %a, double %b) {
506entry:
507        %multmp = fmul double %a, %a
508        %multmp1 = fmul double 2.000000e+00, %a
509        %multmp2 = fmul double %multmp1, %b
510        %addtmp = fadd double %multmp, %multmp2
511        %multmp3 = fmul double %b, %b
512        %addtmp4 = fadd double %addtmp, %multmp3
513        ret double %addtmp4
514}
515</pre>
516</div>
517
518<p>This shows some simple arithmetic. Notice the striking similarity to the
519LLVM builder calls that we use to create the instructions.</p>
520
521<div class="doc_code">
522<pre>
523ready&gt; <b>def bar(a) foo(a, 4.0) + bar(31337);</b>
524Read function definition:
525define double @bar(double %a) {
526entry:
527        %calltmp = call double @foo(double %a, double 4.000000e+00)
528        %calltmp1 = call double @bar(double 3.133700e+04)
529        %addtmp = fadd double %calltmp, %calltmp1
530        ret double %addtmp
531}
532</pre>
533</div>
534
535<p>This shows some function calls.  Note that this function will take a long
536time to execute if you call it.  In the future we'll add conditional control
537flow to actually make recursion useful :).</p>
538
539<div class="doc_code">
540<pre>
541ready&gt; <b>extern cos(x);</b>
542Read extern:
543declare double @cos(double)
544
545ready&gt; <b>cos(1.234);</b>
546Read top-level expression:
547define double @""() {
548entry:
549        %calltmp = call double @cos(double 1.234000e+00)
550        ret double %calltmp
551}
552</pre>
553</div>
554
555<p>This shows an extern for the libm "cos" function, and a call to it.</p>
556
557
558<div class="doc_code">
559<pre>
560ready&gt; <b>^D</b>
561; ModuleID = 'my cool jit'
562
563define double @""() {
564entry:
565        %addtmp = fadd double 4.000000e+00, 5.000000e+00
566        ret double %addtmp
567}
568
569define double @foo(double %a, double %b) {
570entry:
571        %multmp = fmul double %a, %a
572        %multmp1 = fmul double 2.000000e+00, %a
573        %multmp2 = fmul double %multmp1, %b
574        %addtmp = fadd double %multmp, %multmp2
575        %multmp3 = fmul double %b, %b
576        %addtmp4 = fadd double %addtmp, %multmp3
577        ret double %addtmp4
578}
579
580define double @bar(double %a) {
581entry:
582        %calltmp = call double @foo(double %a, double 4.000000e+00)
583        %calltmp1 = call double @bar(double 3.133700e+04)
584        %addtmp = fadd double %calltmp, %calltmp1
585        ret double %addtmp
586}
587
588declare double @cos(double)
589
590define double @""() {
591entry:
592        %calltmp = call double @cos(double 1.234000e+00)
593        ret double %calltmp
594}
595</pre>
596</div>
597
598<p>When you quit the current demo, it dumps out the IR for the entire module
599generated.  Here you can see the big picture with all the functions referencing
600each other.</p>
601
602<p>This wraps up the third chapter of the Kaleidoscope tutorial.  Up next, we'll
603describe how to <a href="OCamlLangImpl4.html">add JIT codegen and optimizer
604support</a> to this so we can actually start running code!</p>
605
606</div>
607
608
609<!-- *********************************************************************** -->
610<h2><a name="code">Full Code Listing</a></h2>
611<!-- *********************************************************************** -->
612
613<div>
614
615<p>
616Here is the complete code listing for our running example, enhanced with the
617LLVM code generator.    Because this uses the LLVM libraries, we need to link
618them in.  To do this, we use the <a
619href="http://llvm.org/cmds/llvm-config.html">llvm-config</a> tool to inform
620our makefile/command line about which options to use:</p>
621
622<div class="doc_code">
623<pre>
624# Compile
625ocamlbuild toy.byte
626# Run
627./toy.byte
628</pre>
629</div>
630
631<p>Here is the code:</p>
632
633<dl>
634<dt>_tags:</dt>
635<dd class="doc_code">
636<pre>
637&lt;{lexer,parser}.ml&gt;: use_camlp4, pp(camlp4of)
638&lt;*.{byte,native}&gt;: g++, use_llvm, use_llvm_analysis
639</pre>
640</dd>
641
642<dt>myocamlbuild.ml:</dt>
643<dd class="doc_code">
644<pre>
645open Ocamlbuild_plugin;;
646
647ocaml_lib ~extern:true "llvm";;
648ocaml_lib ~extern:true "llvm_analysis";;
649
650flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
651</pre>
652</dd>
653
654<dt>token.ml:</dt>
655<dd class="doc_code">
656<pre>
657(*===----------------------------------------------------------------------===
658 * Lexer Tokens
659 *===----------------------------------------------------------------------===*)
660
661(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
662 * these others for known things. *)
663type token =
664  (* commands *)
665  | Def | Extern
666
667  (* primary *)
668  | Ident of string | Number of float
669
670  (* unknown *)
671  | Kwd of char
672</pre>
673</dd>
674
675<dt>lexer.ml:</dt>
676<dd class="doc_code">
677<pre>
678(*===----------------------------------------------------------------------===
679 * Lexer
680 *===----------------------------------------------------------------------===*)
681
682let rec lex = parser
683  (* Skip any whitespace. *)
684  | [&lt; ' (' ' | '\n' | '\r' | '\t'); stream &gt;] -&gt; lex stream
685
686  (* identifier: [a-zA-Z][a-zA-Z0-9] *)
687  | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' as c); stream &gt;] -&gt;
688      let buffer = Buffer.create 1 in
689      Buffer.add_char buffer c;
690      lex_ident buffer stream
691
692  (* number: [0-9.]+ *)
693  | [&lt; ' ('0' .. '9' as c); stream &gt;] -&gt;
694      let buffer = Buffer.create 1 in
695      Buffer.add_char buffer c;
696      lex_number buffer stream
697
698  (* Comment until end of line. *)
699  | [&lt; ' ('#'); stream &gt;] -&gt;
700      lex_comment stream
701
702  (* Otherwise, just return the character as its ascii value. *)
703  | [&lt; 'c; stream &gt;] -&gt;
704      [&lt; 'Token.Kwd c; lex stream &gt;]
705
706  (* end of stream. *)
707  | [&lt; &gt;] -&gt; [&lt; &gt;]
708
709and lex_number buffer = parser
710  | [&lt; ' ('0' .. '9' | '.' as c); stream &gt;] -&gt;
711      Buffer.add_char buffer c;
712      lex_number buffer stream
713  | [&lt; stream=lex &gt;] -&gt;
714      [&lt; 'Token.Number (float_of_string (Buffer.contents buffer)); stream &gt;]
715
716and lex_ident buffer = parser
717  | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream &gt;] -&gt;
718      Buffer.add_char buffer c;
719      lex_ident buffer stream
720  | [&lt; stream=lex &gt;] -&gt;
721      match Buffer.contents buffer with
722      | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
723      | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
724      | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
725
726and lex_comment = parser
727  | [&lt; ' ('\n'); stream=lex &gt;] -&gt; stream
728  | [&lt; 'c; e=lex_comment &gt;] -&gt; e
729  | [&lt; &gt;] -&gt; [&lt; &gt;]
730</pre>
731</dd>
732
733<dt>ast.ml:</dt>
734<dd class="doc_code">
735<pre>
736(*===----------------------------------------------------------------------===
737 * Abstract Syntax Tree (aka Parse Tree)
738 *===----------------------------------------------------------------------===*)
739
740(* expr - Base type for all expression nodes. *)
741type expr =
742  (* variant for numeric literals like "1.0". *)
743  | Number of float
744
745  (* variant for referencing a variable, like "a". *)
746  | Variable of string
747
748  (* variant for a binary operator. *)
749  | Binary of char * expr * expr
750
751  (* variant for function calls. *)
752  | Call of string * expr array
753
754(* proto - This type represents the "prototype" for a function, which captures
755 * its name, and its argument names (thus implicitly the number of arguments the
756 * function takes). *)
757type proto = Prototype of string * string array
758
759(* func - This type represents a function definition itself. *)
760type func = Function of proto * expr
761</pre>
762</dd>
763
764<dt>parser.ml:</dt>
765<dd class="doc_code">
766<pre>
767(*===---------------------------------------------------------------------===
768 * Parser
769 *===---------------------------------------------------------------------===*)
770
771(* binop_precedence - This holds the precedence for each binary operator that is
772 * defined *)
773let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
774
775(* precedence - Get the precedence of the pending binary operator token. *)
776let precedence c = try Hashtbl.find binop_precedence c with Not_found -&gt; -1
777
778(* primary
779 *   ::= identifier
780 *   ::= numberexpr
781 *   ::= parenexpr *)
782let rec parse_primary = parser
783  (* numberexpr ::= number *)
784  | [&lt; 'Token.Number n &gt;] -&gt; Ast.Number n
785
786  (* parenexpr ::= '(' expression ')' *)
787  | [&lt; 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" &gt;] -&gt; e
788
789  (* identifierexpr
790   *   ::= identifier
791   *   ::= identifier '(' argumentexpr ')' *)
792  | [&lt; 'Token.Ident id; stream &gt;] -&gt;
793      let rec parse_args accumulator = parser
794        | [&lt; e=parse_expr; stream &gt;] -&gt;
795            begin parser
796              | [&lt; 'Token.Kwd ','; e=parse_args (e :: accumulator) &gt;] -&gt; e
797              | [&lt; &gt;] -&gt; e :: accumulator
798            end stream
799        | [&lt; &gt;] -&gt; accumulator
800      in
801      let rec parse_ident id = parser
802        (* Call. *)
803        | [&lt; 'Token.Kwd '(';
804             args=parse_args [];
805             'Token.Kwd ')' ?? "expected ')'"&gt;] -&gt;
806            Ast.Call (id, Array.of_list (List.rev args))
807
808        (* Simple variable ref. *)
809        | [&lt; &gt;] -&gt; Ast.Variable id
810      in
811      parse_ident id stream
812
813  | [&lt; &gt;] -&gt; raise (Stream.Error "unknown token when expecting an expression.")
814
815(* binoprhs
816 *   ::= ('+' primary)* *)
817and parse_bin_rhs expr_prec lhs stream =
818  match Stream.peek stream with
819  (* If this is a binop, find its precedence. *)
820  | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c -&gt;
821      let token_prec = precedence c in
822
823      (* If this is a binop that binds at least as tightly as the current binop,
824       * consume it, otherwise we are done. *)
825      if token_prec &lt; expr_prec then lhs else begin
826        (* Eat the binop. *)
827        Stream.junk stream;
828
829        (* Parse the primary expression after the binary operator. *)
830        let rhs = parse_primary stream in
831
832        (* Okay, we know this is a binop. *)
833        let rhs =
834          match Stream.peek stream with
835          | Some (Token.Kwd c2) -&gt;
836              (* If BinOp binds less tightly with rhs than the operator after
837               * rhs, let the pending operator take rhs as its lhs. *)
838              let next_prec = precedence c2 in
839              if token_prec &lt; next_prec
840              then parse_bin_rhs (token_prec + 1) rhs stream
841              else rhs
842          | _ -&gt; rhs
843        in
844
845        (* Merge lhs/rhs. *)
846        let lhs = Ast.Binary (c, lhs, rhs) in
847        parse_bin_rhs expr_prec lhs stream
848      end
849  | _ -&gt; lhs
850
851(* expression
852 *   ::= primary binoprhs *)
853and parse_expr = parser
854  | [&lt; lhs=parse_primary; stream &gt;] -&gt; parse_bin_rhs 0 lhs stream
855
856(* prototype
857 *   ::= id '(' id* ')' *)
858let parse_prototype =
859  let rec parse_args accumulator = parser
860    | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
861    | [&lt; &gt;] -&gt; accumulator
862  in
863
864  parser
865  | [&lt; 'Token.Ident id;
866       'Token.Kwd '(' ?? "expected '(' in prototype";
867       args=parse_args [];
868       'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
869      (* success. *)
870      Ast.Prototype (id, Array.of_list (List.rev args))
871
872  | [&lt; &gt;] -&gt;
873      raise (Stream.Error "expected function name in prototype")
874
875(* definition ::= 'def' prototype expression *)
876let parse_definition = parser
877  | [&lt; 'Token.Def; p=parse_prototype; e=parse_expr &gt;] -&gt;
878      Ast.Function (p, e)
879
880(* toplevelexpr ::= expression *)
881let parse_toplevel = parser
882  | [&lt; e=parse_expr &gt;] -&gt;
883      (* Make an anonymous proto. *)
884      Ast.Function (Ast.Prototype ("", [||]), e)
885
886(*  external ::= 'extern' prototype *)
887let parse_extern = parser
888  | [&lt; 'Token.Extern; e=parse_prototype &gt;] -&gt; e
889</pre>
890</dd>
891
892<dt>codegen.ml:</dt>
893<dd class="doc_code">
894<pre>
895(*===----------------------------------------------------------------------===
896 * Code Generation
897 *===----------------------------------------------------------------------===*)
898
899open Llvm
900
901exception Error of string
902
903let context = global_context ()
904let the_module = create_module context "my cool jit"
905let builder = builder context
906let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
907let double_type = double_type context
908
909let rec codegen_expr = function
910  | Ast.Number n -&gt; const_float double_type n
911  | Ast.Variable name -&gt;
912      (try Hashtbl.find named_values name with
913        | Not_found -&gt; raise (Error "unknown variable name"))
914  | Ast.Binary (op, lhs, rhs) -&gt;
915      let lhs_val = codegen_expr lhs in
916      let rhs_val = codegen_expr rhs in
917      begin
918        match op with
919        | '+' -&gt; build_add lhs_val rhs_val "addtmp" builder
920        | '-' -&gt; build_sub lhs_val rhs_val "subtmp" builder
921        | '*' -&gt; build_mul lhs_val rhs_val "multmp" builder
922        | '&lt;' -&gt;
923            (* Convert bool 0/1 to double 0.0 or 1.0 *)
924            let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
925            build_uitofp i double_type "booltmp" builder
926        | _ -&gt; raise (Error "invalid binary operator")
927      end
928  | Ast.Call (callee, args) -&gt;
929      (* Look up the name in the module table. *)
930      let callee =
931        match lookup_function callee the_module with
932        | Some callee -&gt; callee
933        | None -&gt; raise (Error "unknown function referenced")
934      in
935      let params = params callee in
936
937      (* If argument mismatch error. *)
938      if Array.length params == Array.length args then () else
939        raise (Error "incorrect # arguments passed");
940      let args = Array.map codegen_expr args in
941      build_call callee args "calltmp" builder
942
943let codegen_proto = function
944  | Ast.Prototype (name, args) -&gt;
945      (* Make the function type: double(double,double) etc. *)
946      let doubles = Array.make (Array.length args) double_type in
947      let ft = function_type double_type doubles in
948      let f =
949        match lookup_function name the_module with
950        | None -&gt; declare_function name ft the_module
951
952        (* If 'f' conflicted, there was already something named 'name'. If it
953         * has a body, don't allow redefinition or reextern. *)
954        | Some f -&gt;
955            (* If 'f' already has a body, reject this. *)
956            if block_begin f &lt;&gt; At_end f then
957              raise (Error "redefinition of function");
958
959            (* If 'f' took a different number of arguments, reject. *)
960            if element_type (type_of f) &lt;&gt; ft then
961              raise (Error "redefinition of function with different # args");
962            f
963      in
964
965      (* Set names for all arguments. *)
966      Array.iteri (fun i a -&gt;
967        let n = args.(i) in
968        set_value_name n a;
969        Hashtbl.add named_values n a;
970      ) (params f);
971      f
972
973let codegen_func = function
974  | Ast.Function (proto, body) -&gt;
975      Hashtbl.clear named_values;
976      let the_function = codegen_proto proto in
977
978      (* Create a new basic block to start insertion into. *)
979      let bb = append_block context "entry" the_function in
980      position_at_end bb builder;
981
982      try
983        let ret_val = codegen_expr body in
984
985        (* Finish off the function. *)
986        let _ = build_ret ret_val builder in
987
988        (* Validate the generated code, checking for consistency. *)
989        Llvm_analysis.assert_valid_function the_function;
990
991        the_function
992      with e -&gt;
993        delete_function the_function;
994        raise e
995</pre>
996</dd>
997
998<dt>toplevel.ml:</dt>
999<dd class="doc_code">
1000<pre>
1001(*===----------------------------------------------------------------------===
1002 * Top-Level parsing and JIT Driver
1003 *===----------------------------------------------------------------------===*)
1004
1005open Llvm
1006
1007(* top ::= definition | external | expression | ';' *)
1008let rec main_loop stream =
1009  match Stream.peek stream with
1010  | None -&gt; ()
1011
1012  (* ignore top-level semicolons. *)
1013  | Some (Token.Kwd ';') -&gt;
1014      Stream.junk stream;
1015      main_loop stream
1016
1017  | Some token -&gt;
1018      begin
1019        try match token with
1020        | Token.Def -&gt;
1021            let e = Parser.parse_definition stream in
1022            print_endline "parsed a function definition.";
1023            dump_value (Codegen.codegen_func e);
1024        | Token.Extern -&gt;
1025            let e = Parser.parse_extern stream in
1026            print_endline "parsed an extern.";
1027            dump_value (Codegen.codegen_proto e);
1028        | _ -&gt;
1029            (* Evaluate a top-level expression into an anonymous function. *)
1030            let e = Parser.parse_toplevel stream in
1031            print_endline "parsed a top-level expr";
1032            dump_value (Codegen.codegen_func e);
1033        with Stream.Error s | Codegen.Error s -&gt;
1034          (* Skip token for error recovery. *)
1035          Stream.junk stream;
1036          print_endline s;
1037      end;
1038      print_string "ready&gt; "; flush stdout;
1039      main_loop stream
1040</pre>
1041</dd>
1042
1043<dt>toy.ml:</dt>
1044<dd class="doc_code">
1045<pre>
1046(*===----------------------------------------------------------------------===
1047 * Main driver code.
1048 *===----------------------------------------------------------------------===*)
1049
1050open Llvm
1051
1052let main () =
1053  (* Install standard binary operators.
1054   * 1 is the lowest precedence. *)
1055  Hashtbl.add Parser.binop_precedence '&lt;' 10;
1056  Hashtbl.add Parser.binop_precedence '+' 20;
1057  Hashtbl.add Parser.binop_precedence '-' 20;
1058  Hashtbl.add Parser.binop_precedence '*' 40;    (* highest. *)
1059
1060  (* Prime the first token. *)
1061  print_string "ready&gt; "; flush stdout;
1062  let stream = Lexer.lex (Stream.of_channel stdin) in
1063
1064  (* Run the main "interpreter loop" now. *)
1065  Toplevel.main_loop stream;
1066
1067  (* Print out all the generated code. *)
1068  dump_module Codegen.the_module
1069;;
1070
1071main ()
1072</pre>
1073</dd>
1074</dl>
1075
1076<a href="OCamlLangImpl4.html">Next: Adding JIT and Optimizer Support</a>
1077</div>
1078
1079<!-- *********************************************************************** -->
1080<hr>
1081<address>
1082  <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1083  src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1084  <a href="http://validator.w3.org/check/referer"><img
1085  src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
1086
1087  <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1088  <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a><br>
1089  <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
1090  Last modified: $Date: 2011-07-15 16:03:30 -0400 (Fri, 15 Jul 2011) $
1091</address>
1092</body>
1093</html>
1094