1 ==================================================
2 Kaleidoscope: Extending the Language: Control Flow
3 ==================================================
11 Welcome to Chapter 5 of the "`Implementing a language with
12 LLVM <index.html>`_" tutorial. Parts 1-4 described the implementation of
13 the simple Kaleidoscope language and included support for generating
14 LLVM IR, followed by optimizations and a JIT compiler. Unfortunately, as
15 presented, Kaleidoscope is mostly useless: it has no control flow other
16 than call and return. This means that you can't have conditional
17 branches in the code, significantly limiting its power. In this episode
18 of "build that compiler", we'll extend Kaleidoscope to have an
19 if/then/else expression plus a simple 'for' loop.
24 Extending Kaleidoscope to support if/then/else is quite straightforward.
25 It basically requires adding lexer support for this "new" concept to the
26 lexer, parser, AST, and LLVM code emitter. This example is nice, because
27 it shows how easy it is to "grow" a language over time, incrementally
28 extending it as new ideas are discovered.
30 Before we get going on "how" we add this extension, lets talk about
31 "what" we want. The basic idea is that we want to be able to write this
42 In Kaleidoscope, every construct is an expression: there are no
43 statements. As such, the if/then/else expression needs to return a value
44 like any other. Since we're using a mostly functional form, we'll have
45 it evaluate its conditional, then return the 'then' or 'else' value
46 based on how the condition was resolved. This is very similar to the C
49 The semantics of the if/then/else expression is that it evaluates the
50 condition to a boolean equality value: 0.0 is considered to be false and
51 everything else is considered to be true. If the condition is true, the
52 first subexpression is evaluated and returned, if the condition is
53 false, the second subexpression is evaluated and returned. Since
54 Kaleidoscope allows side-effects, this behavior is important to nail
57 Now that we know what we "want", lets break this down into its
60 Lexer Extensions for If/Then/Else
61 ---------------------------------
63 The lexer extensions are straightforward. First we add new variants for
69 | If | Then | Else | For | In
71 Once we have that, we recognize the new keywords in the lexer. This is
77 match Buffer.contents buffer with
78 | "def" -> [< 'Token.Def; stream >]
79 | "extern" -> [< 'Token.Extern; stream >]
80 | "if" -> [< 'Token.If; stream >]
81 | "then" -> [< 'Token.Then; stream >]
82 | "else" -> [< 'Token.Else; stream >]
83 | "for" -> [< 'Token.For; stream >]
84 | "in" -> [< 'Token.In; stream >]
85 | id -> [< 'Token.Ident id; stream >]
87 AST Extensions for If/Then/Else
88 -------------------------------
90 To represent the new expression we add a new AST variant for it:
96 (* variant for if/then/else. *)
97 | If of expr * expr * expr
99 The AST variant just has pointers to the various subexpressions.
101 Parser Extensions for If/Then/Else
102 ----------------------------------
104 Now that we have the relevant tokens coming from the lexer and we have
105 the AST node to build, our parsing logic is relatively straightforward.
106 Next we add a new case for parsing a if-expression as a primary expression:
108 .. code-block:: ocaml
110 let rec parse_primary = parser
112 (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
113 | [< 'Token.If; c=parse_expr;
114 'Token.Then ?? "expected 'then'"; t=parse_expr;
115 'Token.Else ?? "expected 'else'"; e=parse_expr >] ->
118 LLVM IR for If/Then/Else
119 ------------------------
121 Now that we have it parsing and building the AST, the final piece is
122 adding LLVM code generation support. This is the most interesting part
123 of the if/then/else example, because this is where it starts to
124 introduce new concepts. All of the code above has been thoroughly
125 described in previous chapters.
127 To motivate the code we want to produce, lets take a look at a simple
134 def baz(x) if x then foo() else bar();
136 If you disable optimizations, the code you'll (soon) get from
137 Kaleidoscope looks like this:
141 declare double @foo()
143 declare double @bar()
145 define double @baz(double %x) {
147 %ifcond = fcmp one double %x, 0.000000e+00
148 br i1 %ifcond, label %then, label %else
150 then: ; preds = %entry
151 %calltmp = call double @foo()
154 else: ; preds = %entry
155 %calltmp1 = call double @bar()
158 ifcont: ; preds = %else, %then
159 %iftmp = phi double [ %calltmp, %then ], [ %calltmp1, %else ]
163 To visualize the control flow graph, you can use a nifty feature of the
164 LLVM '`opt <http://llvm.org/cmds/opt.html>`_' tool. If you put this LLVM
165 IR into "t.ll" and run "``llvm-as < t.ll | opt -analyze -view-cfg``", `a
166 window will pop up <../ProgrammersManual.html#viewing-graphs-while-debugging-code>`_ and you'll
169 .. figure:: MyFirstLanguageFrontend/LangImpl05-cfg.png
175 Another way to get this is to call
176 "``Llvm_analysis.view_function_cfg f``" or
177 "``Llvm_analysis.view_function_cfg_only f``" (where ``f`` is a
178 "``Function``") either by inserting actual calls into the code and
179 recompiling or by calling these in the debugger. LLVM has many nice
180 features for visualizing various graphs.
182 Getting back to the generated code, it is fairly simple: the entry block
183 evaluates the conditional expression ("x" in our case here) and compares
184 the result to 0.0 with the "``fcmp one``" instruction ('one' is "Ordered
185 and Not Equal"). Based on the result of this expression, the code jumps
186 to either the "then" or "else" blocks, which contain the expressions for
187 the true/false cases.
189 Once the then/else blocks are finished executing, they both branch back
190 to the 'ifcont' block to execute the code that happens after the
191 if/then/else. In this case the only thing left to do is to return to the
192 caller of the function. The question then becomes: how does the code
193 know which expression to return?
195 The answer to this question involves an important SSA operation: the
197 operation <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
198 If you're not familiar with SSA, `the wikipedia
199 article <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
200 is a good introduction and there are various other introductions to it
201 available on your favorite search engine. The short version is that
202 "execution" of the Phi operation requires "remembering" which block
203 control came from. The Phi operation takes on the value corresponding to
204 the input control block. In this case, if control comes in from the
205 "then" block, it gets the value of "calltmp". If control comes from the
206 "else" block, it gets the value of "calltmp1".
208 At this point, you are probably starting to think "Oh no! This means my
209 simple and elegant front-end will have to start generating SSA form in
210 order to use LLVM!". Fortunately, this is not the case, and we strongly
211 advise *not* implementing an SSA construction algorithm in your
212 front-end unless there is an amazingly good reason to do so. In
213 practice, there are two sorts of values that float around in code
214 written for your average imperative programming language that might need
217 #. Code that involves user variables: ``x = 1; x = x + 1;``
218 #. Values that are implicit in the structure of your AST, such as the
219 Phi node in this case.
221 In `Chapter 7 <OCamlLangImpl7.html>`_ of this tutorial ("mutable
222 variables"), we'll talk about #1 in depth. For now, just believe me that
223 you don't need SSA construction to handle this case. For #2, you have
224 the choice of using the techniques that we will describe for #1, or you
225 can insert Phi nodes directly, if convenient. In this case, it is really
226 really easy to generate the Phi node, so we choose to do it directly.
228 Okay, enough of the motivation and overview, lets generate code!
230 Code Generation for If/Then/Else
231 --------------------------------
233 In order to generate code for this, we implement the ``Codegen`` method
236 .. code-block:: ocaml
238 let rec codegen_expr = function
240 | Ast.If (cond, then_, else_) ->
241 let cond = codegen_expr cond in
243 (* Convert condition to a bool by comparing equal to 0.0 *)
244 let zero = const_float double_type 0.0 in
245 let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
247 This code is straightforward and similar to what we saw before. We emit
248 the expression for the condition, then compare that value to zero to get
249 a truth value as a 1-bit (bool) value.
251 .. code-block:: ocaml
253 (* Grab the first block so that we might later add the conditional branch
254 * to it at the end of the function. *)
255 let start_bb = insertion_block builder in
256 let the_function = block_parent start_bb in
258 let then_bb = append_block context "then" the_function in
259 position_at_end then_bb builder;
261 As opposed to the `C++ tutorial <LangImpl05.html>`_, we have to build our
262 basic blocks bottom up since we can't have dangling BasicBlocks. We
263 start off by saving a pointer to the first block (which might not be the
264 entry block), which we'll need to build a conditional branch later. We
265 do this by asking the ``builder`` for the current BasicBlock. The fourth
266 line gets the current Function object that is being built. It gets this
267 by the ``start_bb`` for its "parent" (the function it is currently
270 Once it has that, it creates one block. It is automatically appended
271 into the function's list of blocks.
273 .. code-block:: ocaml
275 (* Emit 'then' value. *)
276 position_at_end then_bb builder;
277 let then_val = codegen_expr then_ in
279 (* Codegen of 'then' can change the current block, update then_bb for the
280 * phi. We create a new name because one is used for the phi node, and the
281 * other is used for the conditional branch. *)
282 let new_then_bb = insertion_block builder in
284 We move the builder to start inserting into the "then" block. Strictly
285 speaking, this call moves the insertion point to be at the end of the
286 specified block. However, since the "then" block is empty, it also
287 starts out by inserting at the beginning of the block. :)
289 Once the insertion point is set, we recursively codegen the "then"
290 expression from the AST.
292 The final line here is quite subtle, but is very important. The basic
293 issue is that when we create the Phi node in the merge block, we need to
294 set up the block/value pairs that indicate how the Phi will work.
295 Importantly, the Phi node expects to have an entry for each predecessor
296 of the block in the CFG. Why then, are we getting the current block when
297 we just set it to ThenBB 5 lines above? The problem is that the "Then"
298 expression may actually itself change the block that the Builder is
299 emitting into if, for example, it contains a nested "if/then/else"
300 expression. Because calling Codegen recursively could arbitrarily change
301 the notion of the current block, we are required to get an up-to-date
302 value for code that will set up the Phi node.
304 .. code-block:: ocaml
306 (* Emit 'else' value. *)
307 let else_bb = append_block context "else" the_function in
308 position_at_end else_bb builder;
309 let else_val = codegen_expr else_ in
311 (* Codegen of 'else' can change the current block, update else_bb for the
313 let new_else_bb = insertion_block builder in
315 Code generation for the 'else' block is basically identical to codegen
316 for the 'then' block.
318 .. code-block:: ocaml
320 (* Emit merge block. *)
321 let merge_bb = append_block context "ifcont" the_function in
322 position_at_end merge_bb builder;
323 let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
324 let phi = build_phi incoming "iftmp" builder in
326 The first two lines here are now familiar: the first adds the "merge"
327 block to the Function object. The second changes the insertion
328 point so that newly created code will go into the "merge" block. Once
329 that is done, we need to create the PHI node and set up the block/value
332 .. code-block:: ocaml
334 (* Return to the start block to add the conditional branch. *)
335 position_at_end start_bb builder;
336 ignore (build_cond_br cond_val then_bb else_bb builder);
338 Once the blocks are created, we can emit the conditional branch that
339 chooses between them. Note that creating new blocks does not implicitly
340 affect the IRBuilder, so it is still inserting into the block that the
341 condition went into. This is why we needed to save the "start" block.
343 .. code-block:: ocaml
345 (* Set a unconditional branch at the end of the 'then' block and the
346 * 'else' block to the 'merge' block. *)
347 position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
348 position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
350 (* Finally, set the builder to the end of the merge block. *)
351 position_at_end merge_bb builder;
355 To finish off the blocks, we create an unconditional branch to the merge
356 block. One interesting (and very important) aspect of the LLVM IR is
357 that it `requires all basic blocks to be
358 "terminated" <../LangRef.html#functionstructure>`_ with a `control flow
359 instruction <../LangRef.html#terminators>`_ such as return or branch.
360 This means that all control flow, *including fall throughs* must be made
361 explicit in the LLVM IR. If you violate this rule, the verifier will
364 Finally, the CodeGen function returns the phi node as the value computed
365 by the if/then/else expression. In our example above, this returned
366 value will feed into the code for the top-level function, which will
367 create the return instruction.
369 Overall, we now have the ability to execute conditional code in
370 Kaleidoscope. With this extension, Kaleidoscope is a fairly complete
371 language that can calculate a wide variety of numeric functions. Next up
372 we'll add another useful expression that is familiar from non-functional
375 'for' Loop Expression
376 =====================
378 Now that we know how to add basic control flow constructs to the
379 language, we have the tools to add more powerful things. Lets add
380 something more aggressive, a 'for' expression:
384 extern putchard(char);
386 for i = 1, i < n, 1.0 in
387 putchard(42); # ascii 42 = '*'
389 # print 100 '*' characters
392 This expression defines a new variable ("i" in this case) which iterates
393 from a starting value, while the condition ("i < n" in this case) is
394 true, incrementing by an optional step value ("1.0" in this case). If
395 the step value is omitted, it defaults to 1.0. While the loop is true,
396 it executes its body expression. Because we don't have anything better
397 to return, we'll just define the loop as always returning 0.0. In the
398 future when we have mutable variables, it will get more useful.
400 As before, lets talk about the changes that we need to Kaleidoscope to
403 Lexer Extensions for the 'for' Loop
404 -----------------------------------
406 The lexer extensions are the same sort of thing as for if/then/else:
408 .. code-block:: ocaml
410 ... in Token.token ...
415 ... in Lexer.lex_ident...
416 match Buffer.contents buffer with
417 | "def" -> [< 'Token.Def; stream >]
418 | "extern" -> [< 'Token.Extern; stream >]
419 | "if" -> [< 'Token.If; stream >]
420 | "then" -> [< 'Token.Then; stream >]
421 | "else" -> [< 'Token.Else; stream >]
422 | "for" -> [< 'Token.For; stream >]
423 | "in" -> [< 'Token.In; stream >]
424 | id -> [< 'Token.Ident id; stream >]
426 AST Extensions for the 'for' Loop
427 ---------------------------------
429 The AST variant is just as simple. It basically boils down to capturing
430 the variable name and the constituent expressions in the node.
432 .. code-block:: ocaml
436 (* variant for for/in. *)
437 | For of string * expr * expr * expr option * expr
439 Parser Extensions for the 'for' Loop
440 ------------------------------------
442 The parser code is also fairly standard. The only interesting thing here
443 is handling of the optional step value. The parser code handles it by
444 checking to see if the second comma is present. If not, it sets the step
445 value to null in the AST node:
447 .. code-block:: ocaml
449 let rec parse_primary = parser
452 ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
454 'Token.Ident id ?? "expected identifier after for";
455 'Token.Kwd '=' ?? "expected '=' after for";
460 'Token.Kwd ',' ?? "expected ',' after for";
465 | [< 'Token.Kwd ','; step=parse_expr >] -> Some step
470 | [< 'Token.In; body=parse_expr >] ->
471 Ast.For (id, start, end_, step, body)
473 raise (Stream.Error "expected 'in' after for")
476 raise (Stream.Error "expected '=' after for")
479 LLVM IR for the 'for' Loop
480 --------------------------
482 Now we get to the good part: the LLVM IR we want to generate for this
483 thing. With the simple example above, we get this LLVM IR (note that
484 this dump is generated with optimizations disabled for clarity):
488 declare double @putchard(double)
490 define double @printstar(double %n) {
492 ; initial value = 1.0 (inlined into phi)
495 loop: ; preds = %loop, %entry
496 %i = phi double [ 1.000000e+00, %entry ], [ %nextvar, %loop ]
498 %calltmp = call double @putchard(double 4.200000e+01)
500 %nextvar = fadd double %i, 1.000000e+00
503 %cmptmp = fcmp ult double %i, %n
504 %booltmp = uitofp i1 %cmptmp to double
505 %loopcond = fcmp one double %booltmp, 0.000000e+00
506 br i1 %loopcond, label %loop, label %afterloop
508 afterloop: ; preds = %loop
509 ; loop always returns 0.0
510 ret double 0.000000e+00
513 This loop contains all the same constructs we saw before: a phi node,
514 several expressions, and some basic blocks. Lets see how this fits
517 Code Generation for the 'for' Loop
518 ----------------------------------
520 The first part of Codegen is very simple: we just output the start
521 expression for the loop value:
523 .. code-block:: ocaml
525 let rec codegen_expr = function
527 | Ast.For (var_name, start, end_, step, body) ->
528 (* Emit the start code first, without 'variable' in scope. *)
529 let start_val = codegen_expr start in
531 With this out of the way, the next step is to set up the LLVM basic
532 block for the start of the loop body. In the case above, the whole loop
533 body is one block, but remember that the body code itself could consist
534 of multiple blocks (e.g. if it contains an if/then/else or a for/in
537 .. code-block:: ocaml
539 (* Make the new basic block for the loop header, inserting after current
541 let preheader_bb = insertion_block builder in
542 let the_function = block_parent preheader_bb in
543 let loop_bb = append_block context "loop" the_function in
545 (* Insert an explicit fall through from the current block to the
547 ignore (build_br loop_bb builder);
549 This code is similar to what we saw for if/then/else. Because we will
550 need it to create the Phi node, we remember the block that falls through
551 into the loop. Once we have that, we create the actual block that starts
552 the loop and create an unconditional branch for the fall-through between
555 .. code-block:: ocaml
557 (* Start insertion in loop_bb. *)
558 position_at_end loop_bb builder;
560 (* Start the PHI node with an entry for start. *)
561 let variable = build_phi [(start_val, preheader_bb)] var_name builder in
563 Now that the "preheader" for the loop is set up, we switch to emitting
564 code for the loop body. To begin with, we move the insertion point and
565 create the PHI node for the loop induction variable. Since we already
566 know the incoming value for the starting value, we add it to the Phi
567 node. Note that the Phi will eventually get a second value for the
568 backedge, but we can't set it up yet (because it doesn't exist!).
570 .. code-block:: ocaml
572 (* Within the loop, the variable is defined equal to the PHI node. If it
573 * shadows an existing variable, we have to restore it, so save it
576 try Some (Hashtbl.find named_values var_name) with Not_found -> None
578 Hashtbl.add named_values var_name variable;
580 (* Emit the body of the loop. This, like any other expr, can change the
581 * current BB. Note that we ignore the value computed by the body, but
582 * don't allow an error *)
583 ignore (codegen_expr body);
585 Now the code starts to get more interesting. Our 'for' loop introduces a
586 new variable to the symbol table. This means that our symbol table can
587 now contain either function arguments or loop variables. To handle this,
588 before we codegen the body of the loop, we add the loop variable as the
589 current value for its name. Note that it is possible that there is a
590 variable of the same name in the outer scope. It would be easy to make
591 this an error (emit an error and return null if there is already an
592 entry for VarName) but we choose to allow shadowing of variables. In
593 order to handle this correctly, we remember the Value that we are
594 potentially shadowing in ``old_val`` (which will be None if there is no
597 Once the loop variable is set into the symbol table, the code
598 recursively codegen's the body. This allows the body to use the loop
599 variable: any references to it will naturally find it in the symbol
602 .. code-block:: ocaml
604 (* Emit the step value. *)
607 | Some step -> codegen_expr step
608 (* If not specified, use 1.0. *)
609 | None -> const_float double_type 1.0
612 let next_var = build_add variable step_val "nextvar" builder in
614 Now that the body is emitted, we compute the next value of the iteration
615 variable by adding the step value, or 1.0 if it isn't present.
616 '``next_var``' will be the value of the loop variable on the next
617 iteration of the loop.
619 .. code-block:: ocaml
621 (* Compute the end condition. *)
622 let end_cond = codegen_expr end_ in
624 (* Convert condition to a bool by comparing equal to 0.0. *)
625 let zero = const_float double_type 0.0 in
626 let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
628 Finally, we evaluate the exit value of the loop, to determine whether
629 the loop should exit. This mirrors the condition evaluation for the
630 if/then/else statement.
632 .. code-block:: ocaml
634 (* Create the "after loop" block and insert it. *)
635 let loop_end_bb = insertion_block builder in
636 let after_bb = append_block context "afterloop" the_function in
638 (* Insert the conditional branch into the end of loop_end_bb. *)
639 ignore (build_cond_br end_cond loop_bb after_bb builder);
641 (* Any new code will be inserted in after_bb. *)
642 position_at_end after_bb builder;
644 With the code for the body of the loop complete, we just need to finish
645 up the control flow for it. This code remembers the end block (for the
646 phi node), then creates the block for the loop exit ("afterloop"). Based
647 on the value of the exit condition, it creates a conditional branch that
648 chooses between executing the loop again and exiting the loop. Any
649 future code is emitted in the "afterloop" block, so it sets the
650 insertion position to it.
652 .. code-block:: ocaml
654 (* Add a new entry to the PHI node for the backedge. *)
655 add_incoming (next_var, loop_end_bb) variable;
657 (* Restore the unshadowed variable. *)
658 begin match old_val with
659 | Some old_val -> Hashtbl.add named_values var_name old_val
663 (* for expr always returns 0.0. *)
664 const_null double_type
666 The final code handles various cleanups: now that we have the
667 "``next_var``" value, we can add the incoming value to the loop PHI
668 node. After that, we remove the loop variable from the symbol table, so
669 that it isn't in scope after the for loop. Finally, code generation of
670 the for loop always returns 0.0, so that is what we return from
671 ``Codegen.codegen_expr``.
673 With this, we conclude the "adding control flow to Kaleidoscope" chapter
674 of the tutorial. In this chapter we added two control flow constructs,
675 and used them to motivate a couple of aspects of the LLVM IR that are
676 important for front-end implementors to know. In the next chapter of our
677 saga, we will get a bit crazier and add `user-defined
678 operators <OCamlLangImpl6.html>`_ to our poor innocent language.
683 Here is the complete code listing for our running example, enhanced with
684 the if/then/else and for expressions.. To build this example, use:
698 <{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
699 <*.{byte,native}>: g++, use_llvm, use_llvm_analysis
700 <*.{byte,native}>: use_llvm_executionengine, use_llvm_target
701 <*.{byte,native}>: use_llvm_scalar_opts, use_bindings
704 .. code-block:: ocaml
706 open Ocamlbuild_plugin;;
708 ocaml_lib ~extern:true "llvm";;
709 ocaml_lib ~extern:true "llvm_analysis";;
710 ocaml_lib ~extern:true "llvm_executionengine";;
711 ocaml_lib ~extern:true "llvm_target";;
712 ocaml_lib ~extern:true "llvm_scalar_opts";;
714 flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
715 dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
718 .. code-block:: ocaml
720 (*===----------------------------------------------------------------------===
722 *===----------------------------------------------------------------------===*)
724 (* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
725 * these others for known things. *)
731 | Ident of string | Number of float
741 .. code-block:: ocaml
743 (*===----------------------------------------------------------------------===
745 *===----------------------------------------------------------------------===*)
748 (* Skip any whitespace. *)
749 | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
751 (* identifier: [a-zA-Z][a-zA-Z0-9] *)
752 | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
753 let buffer = Buffer.create 1 in
754 Buffer.add_char buffer c;
755 lex_ident buffer stream
757 (* number: [0-9.]+ *)
758 | [< ' ('0' .. '9' as c); stream >] ->
759 let buffer = Buffer.create 1 in
760 Buffer.add_char buffer c;
761 lex_number buffer stream
763 (* Comment until end of line. *)
764 | [< ' ('#'); stream >] ->
767 (* Otherwise, just return the character as its ascii value. *)
768 | [< 'c; stream >] ->
769 [< 'Token.Kwd c; lex stream >]
774 and lex_number buffer = parser
775 | [< ' ('0' .. '9' | '.' as c); stream >] ->
776 Buffer.add_char buffer c;
777 lex_number buffer stream
778 | [< stream=lex >] ->
779 [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
781 and lex_ident buffer = parser
782 | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
783 Buffer.add_char buffer c;
784 lex_ident buffer stream
785 | [< stream=lex >] ->
786 match Buffer.contents buffer with
787 | "def" -> [< 'Token.Def; stream >]
788 | "extern" -> [< 'Token.Extern; stream >]
789 | "if" -> [< 'Token.If; stream >]
790 | "then" -> [< 'Token.Then; stream >]
791 | "else" -> [< 'Token.Else; stream >]
792 | "for" -> [< 'Token.For; stream >]
793 | "in" -> [< 'Token.In; stream >]
794 | id -> [< 'Token.Ident id; stream >]
796 and lex_comment = parser
797 | [< ' ('\n'); stream=lex >] -> stream
798 | [< 'c; e=lex_comment >] -> e
802 .. code-block:: ocaml
804 (*===----------------------------------------------------------------------===
805 * Abstract Syntax Tree (aka Parse Tree)
806 *===----------------------------------------------------------------------===*)
808 (* expr - Base type for all expression nodes. *)
810 (* variant for numeric literals like "1.0". *)
813 (* variant for referencing a variable, like "a". *)
816 (* variant for a binary operator. *)
817 | Binary of char * expr * expr
819 (* variant for function calls. *)
820 | Call of string * expr array
822 (* variant for if/then/else. *)
823 | If of expr * expr * expr
825 (* variant for for/in. *)
826 | For of string * expr * expr * expr option * expr
828 (* proto - This type represents the "prototype" for a function, which captures
829 * its name, and its argument names (thus implicitly the number of arguments the
830 * function takes). *)
831 type proto = Prototype of string * string array
833 (* func - This type represents a function definition itself. *)
834 type func = Function of proto * expr
837 .. code-block:: ocaml
839 (*===---------------------------------------------------------------------===
841 *===---------------------------------------------------------------------===*)
843 (* binop_precedence - This holds the precedence for each binary operator that is
845 let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
847 (* precedence - Get the precedence of the pending binary operator token. *)
848 let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
856 let rec parse_primary = parser
857 (* numberexpr ::= number *)
858 | [< 'Token.Number n >] -> Ast.Number n
860 (* parenexpr ::= '(' expression ')' *)
861 | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
865 * ::= identifier '(' argumentexpr ')' *)
866 | [< 'Token.Ident id; stream >] ->
867 let rec parse_args accumulator = parser
868 | [< e=parse_expr; stream >] ->
870 | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
871 | [< >] -> e :: accumulator
873 | [< >] -> accumulator
875 let rec parse_ident id = parser
879 'Token.Kwd ')' ?? "expected ')'">] ->
880 Ast.Call (id, Array.of_list (List.rev args))
882 (* Simple variable ref. *)
883 | [< >] -> Ast.Variable id
885 parse_ident id stream
887 (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
888 | [< 'Token.If; c=parse_expr;
889 'Token.Then ?? "expected 'then'"; t=parse_expr;
890 'Token.Else ?? "expected 'else'"; e=parse_expr >] ->
894 ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
896 'Token.Ident id ?? "expected identifier after for";
897 'Token.Kwd '=' ?? "expected '=' after for";
902 'Token.Kwd ',' ?? "expected ',' after for";
907 | [< 'Token.Kwd ','; step=parse_expr >] -> Some step
912 | [< 'Token.In; body=parse_expr >] ->
913 Ast.For (id, start, end_, step, body)
915 raise (Stream.Error "expected 'in' after for")
918 raise (Stream.Error "expected '=' after for")
921 | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
924 * ::= ('+' primary)* *)
925 and parse_bin_rhs expr_prec lhs stream =
926 match Stream.peek stream with
927 (* If this is a binop, find its precedence. *)
928 | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
929 let token_prec = precedence c in
931 (* If this is a binop that binds at least as tightly as the current binop,
932 * consume it, otherwise we are done. *)
933 if token_prec < expr_prec then lhs else begin
937 (* Parse the primary expression after the binary operator. *)
938 let rhs = parse_primary stream in
940 (* Okay, we know this is a binop. *)
942 match Stream.peek stream with
943 | Some (Token.Kwd c2) ->
944 (* If BinOp binds less tightly with rhs than the operator after
945 * rhs, let the pending operator take rhs as its lhs. *)
946 let next_prec = precedence c2 in
947 if token_prec < next_prec
948 then parse_bin_rhs (token_prec + 1) rhs stream
954 let lhs = Ast.Binary (c, lhs, rhs) in
955 parse_bin_rhs expr_prec lhs stream
960 * ::= primary binoprhs *)
961 and parse_expr = parser
962 | [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
965 * ::= id '(' id* ')' *)
966 let parse_prototype =
967 let rec parse_args accumulator = parser
968 | [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
969 | [< >] -> accumulator
973 | [< 'Token.Ident id;
974 'Token.Kwd '(' ?? "expected '(' in prototype";
976 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
978 Ast.Prototype (id, Array.of_list (List.rev args))
981 raise (Stream.Error "expected function name in prototype")
983 (* definition ::= 'def' prototype expression *)
984 let parse_definition = parser
985 | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
988 (* toplevelexpr ::= expression *)
989 let parse_toplevel = parser
990 | [< e=parse_expr >] ->
991 (* Make an anonymous proto. *)
992 Ast.Function (Ast.Prototype ("", [||]), e)
994 (* external ::= 'extern' prototype *)
995 let parse_extern = parser
996 | [< 'Token.Extern; e=parse_prototype >] -> e
999 .. code-block:: ocaml
1001 (*===----------------------------------------------------------------------===
1003 *===----------------------------------------------------------------------===*)
1007 exception Error of string
1009 let context = global_context ()
1010 let the_module = create_module context "my cool jit"
1011 let builder = builder context
1012 let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
1013 let double_type = double_type context
1015 let rec codegen_expr = function
1016 | Ast.Number n -> const_float double_type n
1017 | Ast.Variable name ->
1018 (try Hashtbl.find named_values name with
1019 | Not_found -> raise (Error "unknown variable name"))
1020 | Ast.Binary (op, lhs, rhs) ->
1021 let lhs_val = codegen_expr lhs in
1022 let rhs_val = codegen_expr rhs in
1025 | '+' -> build_add lhs_val rhs_val "addtmp" builder
1026 | '-' -> build_sub lhs_val rhs_val "subtmp" builder
1027 | '*' -> build_mul lhs_val rhs_val "multmp" builder
1029 (* Convert bool 0/1 to double 0.0 or 1.0 *)
1030 let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
1031 build_uitofp i double_type "booltmp" builder
1032 | _ -> raise (Error "invalid binary operator")
1034 | Ast.Call (callee, args) ->
1035 (* Look up the name in the module table. *)
1037 match lookup_function callee the_module with
1038 | Some callee -> callee
1039 | None -> raise (Error "unknown function referenced")
1041 let params = params callee in
1043 (* If argument mismatch error. *)
1044 if Array.length params == Array.length args then () else
1045 raise (Error "incorrect # arguments passed");
1046 let args = Array.map codegen_expr args in
1047 build_call callee args "calltmp" builder
1048 | Ast.If (cond, then_, else_) ->
1049 let cond = codegen_expr cond in
1051 (* Convert condition to a bool by comparing equal to 0.0 *)
1052 let zero = const_float double_type 0.0 in
1053 let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
1055 (* Grab the first block so that we might later add the conditional branch
1056 * to it at the end of the function. *)
1057 let start_bb = insertion_block builder in
1058 let the_function = block_parent start_bb in
1060 let then_bb = append_block context "then" the_function in
1062 (* Emit 'then' value. *)
1063 position_at_end then_bb builder;
1064 let then_val = codegen_expr then_ in
1066 (* Codegen of 'then' can change the current block, update then_bb for the
1067 * phi. We create a new name because one is used for the phi node, and the
1068 * other is used for the conditional branch. *)
1069 let new_then_bb = insertion_block builder in
1071 (* Emit 'else' value. *)
1072 let else_bb = append_block context "else" the_function in
1073 position_at_end else_bb builder;
1074 let else_val = codegen_expr else_ in
1076 (* Codegen of 'else' can change the current block, update else_bb for the
1078 let new_else_bb = insertion_block builder in
1080 (* Emit merge block. *)
1081 let merge_bb = append_block context "ifcont" the_function in
1082 position_at_end merge_bb builder;
1083 let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
1084 let phi = build_phi incoming "iftmp" builder in
1086 (* Return to the start block to add the conditional branch. *)
1087 position_at_end start_bb builder;
1088 ignore (build_cond_br cond_val then_bb else_bb builder);
1090 (* Set a unconditional branch at the end of the 'then' block and the
1091 * 'else' block to the 'merge' block. *)
1092 position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
1093 position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
1095 (* Finally, set the builder to the end of the merge block. *)
1096 position_at_end merge_bb builder;
1099 | Ast.For (var_name, start, end_, step, body) ->
1100 (* Emit the start code first, without 'variable' in scope. *)
1101 let start_val = codegen_expr start in
1103 (* Make the new basic block for the loop header, inserting after current
1105 let preheader_bb = insertion_block builder in
1106 let the_function = block_parent preheader_bb in
1107 let loop_bb = append_block context "loop" the_function in
1109 (* Insert an explicit fall through from the current block to the
1111 ignore (build_br loop_bb builder);
1113 (* Start insertion in loop_bb. *)
1114 position_at_end loop_bb builder;
1116 (* Start the PHI node with an entry for start. *)
1117 let variable = build_phi [(start_val, preheader_bb)] var_name builder in
1119 (* Within the loop, the variable is defined equal to the PHI node. If it
1120 * shadows an existing variable, we have to restore it, so save it
1123 try Some (Hashtbl.find named_values var_name) with Not_found -> None
1125 Hashtbl.add named_values var_name variable;
1127 (* Emit the body of the loop. This, like any other expr, can change the
1128 * current BB. Note that we ignore the value computed by the body, but
1129 * don't allow an error *)
1130 ignore (codegen_expr body);
1132 (* Emit the step value. *)
1135 | Some step -> codegen_expr step
1136 (* If not specified, use 1.0. *)
1137 | None -> const_float double_type 1.0
1140 let next_var = build_add variable step_val "nextvar" builder in
1142 (* Compute the end condition. *)
1143 let end_cond = codegen_expr end_ in
1145 (* Convert condition to a bool by comparing equal to 0.0. *)
1146 let zero = const_float double_type 0.0 in
1147 let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
1149 (* Create the "after loop" block and insert it. *)
1150 let loop_end_bb = insertion_block builder in
1151 let after_bb = append_block context "afterloop" the_function in
1153 (* Insert the conditional branch into the end of loop_end_bb. *)
1154 ignore (build_cond_br end_cond loop_bb after_bb builder);
1156 (* Any new code will be inserted in after_bb. *)
1157 position_at_end after_bb builder;
1159 (* Add a new entry to the PHI node for the backedge. *)
1160 add_incoming (next_var, loop_end_bb) variable;
1162 (* Restore the unshadowed variable. *)
1163 begin match old_val with
1164 | Some old_val -> Hashtbl.add named_values var_name old_val
1168 (* for expr always returns 0.0. *)
1169 const_null double_type
1171 let codegen_proto = function
1172 | Ast.Prototype (name, args) ->
1173 (* Make the function type: double(double,double) etc. *)
1174 let doubles = Array.make (Array.length args) double_type in
1175 let ft = function_type double_type doubles in
1177 match lookup_function name the_module with
1178 | None -> declare_function name ft the_module
1180 (* If 'f' conflicted, there was already something named 'name'. If it
1181 * has a body, don't allow redefinition or reextern. *)
1183 (* If 'f' already has a body, reject this. *)
1184 if block_begin f <> At_end f then
1185 raise (Error "redefinition of function");
1187 (* If 'f' took a different number of arguments, reject. *)
1188 if element_type (type_of f) <> ft then
1189 raise (Error "redefinition of function with different # args");
1193 (* Set names for all arguments. *)
1194 Array.iteri (fun i a ->
1197 Hashtbl.add named_values n a;
1201 let codegen_func the_fpm = function
1202 | Ast.Function (proto, body) ->
1203 Hashtbl.clear named_values;
1204 let the_function = codegen_proto proto in
1206 (* Create a new basic block to start insertion into. *)
1207 let bb = append_block context "entry" the_function in
1208 position_at_end bb builder;
1211 let ret_val = codegen_expr body in
1213 (* Finish off the function. *)
1214 let _ = build_ret ret_val builder in
1216 (* Validate the generated code, checking for consistency. *)
1217 Llvm_analysis.assert_valid_function the_function;
1219 (* Optimize the function. *)
1220 let _ = PassManager.run_function the_function the_fpm in
1224 delete_function the_function;
1228 .. code-block:: ocaml
1230 (*===----------------------------------------------------------------------===
1231 * Top-Level parsing and JIT Driver
1232 *===----------------------------------------------------------------------===*)
1235 open Llvm_executionengine
1237 (* top ::= definition | external | expression | ';' *)
1238 let rec main_loop the_fpm the_execution_engine stream =
1239 match Stream.peek stream with
1242 (* ignore top-level semicolons. *)
1243 | Some (Token.Kwd ';') ->
1245 main_loop the_fpm the_execution_engine stream
1249 try match token with
1251 let e = Parser.parse_definition stream in
1252 print_endline "parsed a function definition.";
1253 dump_value (Codegen.codegen_func the_fpm e);
1255 let e = Parser.parse_extern stream in
1256 print_endline "parsed an extern.";
1257 dump_value (Codegen.codegen_proto e);
1259 (* Evaluate a top-level expression into an anonymous function. *)
1260 let e = Parser.parse_toplevel stream in
1261 print_endline "parsed a top-level expr";
1262 let the_function = Codegen.codegen_func the_fpm e in
1263 dump_value the_function;
1265 (* JIT the function, returning a function pointer. *)
1266 let result = ExecutionEngine.run_function the_function [||]
1267 the_execution_engine in
1269 print_string "Evaluated to ";
1270 print_float (GenericValue.as_float Codegen.double_type result);
1272 with Stream.Error s | Codegen.Error s ->
1273 (* Skip token for error recovery. *)
1277 print_string "ready> "; flush stdout;
1278 main_loop the_fpm the_execution_engine stream
1281 .. code-block:: ocaml
1283 (*===----------------------------------------------------------------------===
1285 *===----------------------------------------------------------------------===*)
1288 open Llvm_executionengine
1290 open Llvm_scalar_opts
1293 ignore (initialize_native_target ());
1295 (* Install standard binary operators.
1296 * 1 is the lowest precedence. *)
1297 Hashtbl.add Parser.binop_precedence '<' 10;
1298 Hashtbl.add Parser.binop_precedence '+' 20;
1299 Hashtbl.add Parser.binop_precedence '-' 20;
1300 Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
1302 (* Prime the first token. *)
1303 print_string "ready> "; flush stdout;
1304 let stream = Lexer.lex (Stream.of_channel stdin) in
1306 (* Create the JIT. *)
1307 let the_execution_engine = ExecutionEngine.create Codegen.the_module in
1308 let the_fpm = PassManager.create_function Codegen.the_module in
1310 (* Set up the optimizer pipeline. Start with registering info about how the
1311 * target lays out data structures. *)
1312 DataLayout.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
1314 (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
1315 add_instruction_combination the_fpm;
1317 (* reassociate expressions. *)
1318 add_reassociation the_fpm;
1320 (* Eliminate Common SubExpressions. *)
1323 (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
1324 add_cfg_simplification the_fpm;
1326 ignore (PassManager.initialize the_fpm);
1328 (* Run the main "interpreter loop" now. *)
1329 Toplevel.main_loop the_fpm the_execution_engine stream;
1331 (* Print out all the generated code. *)
1332 dump_module Codegen.the_module
1342 /* putchard - putchar that takes a double and returns 0. */
1343 extern double putchard(double X) {
1348 `Next: Extending the language: user-defined
1349 operators <OCamlLangImpl6.html>`_