blob: 6e17de4b2bde8d6d5fca60bb681ac8fef184e630 [file] [log] [blame]
Sean Silvad7fb3962012-12-05 00:26:32 +00001==================================================
2Kaleidoscope: Extending the Language: Control Flow
3==================================================
4
5.. contents::
6 :local:
7
Sean Silvad7fb3962012-12-05 00:26:32 +00008Chapter 5 Introduction
9======================
10
11Welcome to Chapter 5 of the "`Implementing a language with
12LLVM <index.html>`_" tutorial. Parts 1-4 described the implementation of
13the simple Kaleidoscope language and included support for generating
14LLVM IR, followed by optimizations and a JIT compiler. Unfortunately, as
15presented, Kaleidoscope is mostly useless: it has no control flow other
16than call and return. This means that you can't have conditional
17branches in the code, significantly limiting its power. In this episode
18of "build that compiler", we'll extend Kaleidoscope to have an
19if/then/else expression plus a simple 'for' loop.
20
21If/Then/Else
22============
23
24Extending Kaleidoscope to support if/then/else is quite straightforward.
25It basically requires adding lexer support for this "new" concept to the
26lexer, parser, AST, and LLVM code emitter. This example is nice, because
27it shows how easy it is to "grow" a language over time, incrementally
28extending it as new ideas are discovered.
29
30Before 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
32sort of thing:
33
34::
35
36 def fib(x)
37 if x < 3 then
38 1
39 else
40 fib(x-1)+fib(x-2);
41
42In Kaleidoscope, every construct is an expression: there are no
43statements. As such, the if/then/else expression needs to return a value
44like any other. Since we're using a mostly functional form, we'll have
45it evaluate its conditional, then return the 'then' or 'else' value
46based on how the condition was resolved. This is very similar to the C
47"?:" expression.
48
49The semantics of the if/then/else expression is that it evaluates the
50condition to a boolean equality value: 0.0 is considered to be false and
51everything else is considered to be true. If the condition is true, the
52first subexpression is evaluated and returned, if the condition is
53false, the second subexpression is evaluated and returned. Since
54Kaleidoscope allows side-effects, this behavior is important to nail
55down.
56
57Now that we know what we "want", lets break this down into its
58constituent pieces.
59
60Lexer Extensions for If/Then/Else
61---------------------------------
62
63The lexer extensions are straightforward. First we add new variants for
64the relevant tokens:
65
66.. code-block:: ocaml
67
68 (* control *)
69 | If | Then | Else | For | In
70
71Once we have that, we recognize the new keywords in the lexer. This is
72pretty simple stuff:
73
74.. code-block:: ocaml
75
76 ...
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 >]
86
87AST Extensions for If/Then/Else
88-------------------------------
89
90To represent the new expression we add a new AST variant for it:
91
92.. code-block:: ocaml
93
94 type expr =
95 ...
96 (* variant for if/then/else. *)
97 | If of expr * expr * expr
98
99The AST variant just has pointers to the various subexpressions.
100
101Parser Extensions for If/Then/Else
102----------------------------------
103
104Now that we have the relevant tokens coming from the lexer and we have
105the AST node to build, our parsing logic is relatively straightforward.
Sylvestre Ledru51043682017-03-04 14:00:44 +0000106Next we add a new case for parsing a if-expression as a primary expression:
Sean Silvad7fb3962012-12-05 00:26:32 +0000107
108.. code-block:: ocaml
109
110 let rec parse_primary = parser
111 ...
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 >] ->
116 Ast.If (c, t, e)
117
118LLVM IR for If/Then/Else
119------------------------
120
121Now that we have it parsing and building the AST, the final piece is
122adding LLVM code generation support. This is the most interesting part
123of the if/then/else example, because this is where it starts to
124introduce new concepts. All of the code above has been thoroughly
125described in previous chapters.
126
127To motivate the code we want to produce, lets take a look at a simple
128example. Consider:
129
130::
131
132 extern foo();
133 extern bar();
134 def baz(x) if x then foo() else bar();
135
136If you disable optimizations, the code you'll (soon) get from
137Kaleidoscope looks like this:
138
139.. code-block:: llvm
140
141 declare double @foo()
142
143 declare double @bar()
144
145 define double @baz(double %x) {
146 entry:
147 %ifcond = fcmp one double %x, 0.000000e+00
148 br i1 %ifcond, label %then, label %else
149
150 then: ; preds = %entry
151 %calltmp = call double @foo()
152 br label %ifcont
153
154 else: ; preds = %entry
155 %calltmp1 = call double @bar()
156 br label %ifcont
157
158 ifcont: ; preds = %else, %then
159 %iftmp = phi double [ %calltmp, %then ], [ %calltmp1, %else ]
160 ret double %iftmp
161 }
162
163To visualize the control flow graph, you can use a nifty feature of the
164LLVM '`opt <http://llvm.org/cmds/opt.html>`_' tool. If you put this LLVM
165IR into "t.ll" and run "``llvm-as < t.ll | opt -analyze -view-cfg``", `a
Alex Denisov596e9792015-12-15 20:50:29 +0000166window will pop up <../ProgrammersManual.html#viewing-graphs-while-debugging-code>`_ and you'll
Sean Silvad7fb3962012-12-05 00:26:32 +0000167see this graph:
168
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000169.. figure:: LangImpl05-cfg.png
Sean Silvad7fb3962012-12-05 00:26:32 +0000170 :align: center
171 :alt: Example CFG
172
173 Example CFG
174
175Another 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
179recompiling or by calling these in the debugger. LLVM has many nice
180features for visualizing various graphs.
181
182Getting back to the generated code, it is fairly simple: the entry block
183evaluates the conditional expression ("x" in our case here) and compares
184the result to 0.0 with the "``fcmp one``" instruction ('one' is "Ordered
185and Not Equal"). Based on the result of this expression, the code jumps
186to either the "then" or "else" blocks, which contain the expressions for
187the true/false cases.
188
189Once the then/else blocks are finished executing, they both branch back
190to the 'ifcont' block to execute the code that happens after the
191if/then/else. In this case the only thing left to do is to return to the
192caller of the function. The question then becomes: how does the code
193know which expression to return?
194
195The answer to this question involves an important SSA operation: the
196`Phi
197operation <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
198If you're not familiar with SSA, `the wikipedia
199article <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
200is a good introduction and there are various other introductions to it
201available on your favorite search engine. The short version is that
202"execution" of the Phi operation requires "remembering" which block
203control came from. The Phi operation takes on the value corresponding to
204the 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".
207
208At this point, you are probably starting to think "Oh no! This means my
209simple and elegant front-end will have to start generating SSA form in
210order to use LLVM!". Fortunately, this is not the case, and we strongly
211advise *not* implementing an SSA construction algorithm in your
212front-end unless there is an amazingly good reason to do so. In
213practice, there are two sorts of values that float around in code
214written for your average imperative programming language that might need
215Phi nodes:
216
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.
220
221In `Chapter 7 <OCamlLangImpl7.html>`_ of this tutorial ("mutable
222variables"), we'll talk about #1 in depth. For now, just believe me that
223you don't need SSA construction to handle this case. For #2, you have
224the choice of using the techniques that we will describe for #1, or you
225can insert Phi nodes directly, if convenient. In this case, it is really
226really easy to generate the Phi node, so we choose to do it directly.
227
228Okay, enough of the motivation and overview, lets generate code!
229
230Code Generation for If/Then/Else
231--------------------------------
232
233In order to generate code for this, we implement the ``Codegen`` method
234for ``IfExprAST``:
235
236.. code-block:: ocaml
237
238 let rec codegen_expr = function
239 ...
240 | Ast.If (cond, then_, else_) ->
241 let cond = codegen_expr cond in
242
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
246
247This code is straightforward and similar to what we saw before. We emit
248the expression for the condition, then compare that value to zero to get
249a truth value as a 1-bit (bool) value.
250
251.. code-block:: ocaml
252
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
257
258 let then_bb = append_block context "then" the_function in
259 position_at_end then_bb builder;
260
261As opposed to the `C++ tutorial <LangImpl5.html>`_, we have to build our
262basic blocks bottom up since we can't have dangling BasicBlocks. We
263start off by saving a pointer to the first block (which might not be the
264entry block), which we'll need to build a conditional branch later. We
265do this by asking the ``builder`` for the current BasicBlock. The fourth
266line gets the current Function object that is being built. It gets this
267by the ``start_bb`` for its "parent" (the function it is currently
268embedded into).
269
270Once it has that, it creates one block. It is automatically appended
271into the function's list of blocks.
272
273.. code-block:: ocaml
274
275 (* Emit 'then' value. *)
276 position_at_end then_bb builder;
277 let then_val = codegen_expr then_ in
278
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
283
284We move the builder to start inserting into the "then" block. Strictly
285speaking, this call moves the insertion point to be at the end of the
286specified block. However, since the "then" block is empty, it also
287starts out by inserting at the beginning of the block. :)
288
289Once the insertion point is set, we recursively codegen the "then"
290expression from the AST.
291
292The final line here is quite subtle, but is very important. The basic
293issue is that when we create the Phi node in the merge block, we need to
294set up the block/value pairs that indicate how the Phi will work.
295Importantly, the Phi node expects to have an entry for each predecessor
296of the block in the CFG. Why then, are we getting the current block when
297we just set it to ThenBB 5 lines above? The problem is that the "Then"
298expression may actually itself change the block that the Builder is
299emitting into if, for example, it contains a nested "if/then/else"
300expression. Because calling Codegen recursively could arbitrarily change
301the notion of the current block, we are required to get an up-to-date
302value for code that will set up the Phi node.
303
304.. code-block:: ocaml
305
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
310
311 (* Codegen of 'else' can change the current block, update else_bb for the
312 * phi. *)
313 let new_else_bb = insertion_block builder in
314
315Code generation for the 'else' block is basically identical to codegen
316for the 'then' block.
317
318.. code-block:: ocaml
319
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
325
326The first two lines here are now familiar: the first adds the "merge"
Sean Silvafb8908c2015-03-31 22:48:45 +0000327block to the Function object. The second changes the insertion
Sean Silvad7fb3962012-12-05 00:26:32 +0000328point so that newly created code will go into the "merge" block. Once
329that is done, we need to create the PHI node and set up the block/value
330pairs for the PHI.
331
332.. code-block:: ocaml
333
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);
337
338Once the blocks are created, we can emit the conditional branch that
339chooses between them. Note that creating new blocks does not implicitly
340affect the IRBuilder, so it is still inserting into the block that the
341condition went into. This is why we needed to save the "start" block.
342
343.. code-block:: ocaml
344
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);
349
350 (* Finally, set the builder to the end of the merge block. *)
351 position_at_end merge_bb builder;
352
353 phi
354
355To finish off the blocks, we create an unconditional branch to the merge
356block. One interesting (and very important) aspect of the LLVM IR is
357that it `requires all basic blocks to be
358"terminated" <../LangRef.html#functionstructure>`_ with a `control flow
359instruction <../LangRef.html#terminators>`_ such as return or branch.
360This means that all control flow, *including fall throughs* must be made
361explicit in the LLVM IR. If you violate this rule, the verifier will
362emit an error.
363
364Finally, the CodeGen function returns the phi node as the value computed
365by the if/then/else expression. In our example above, this returned
366value will feed into the code for the top-level function, which will
367create the return instruction.
368
369Overall, we now have the ability to execute conditional code in
370Kaleidoscope. With this extension, Kaleidoscope is a fairly complete
371language that can calculate a wide variety of numeric functions. Next up
372we'll add another useful expression that is familiar from non-functional
373languages...
374
375'for' Loop Expression
376=====================
377
378Now that we know how to add basic control flow constructs to the
379language, we have the tools to add more powerful things. Lets add
380something more aggressive, a 'for' expression:
381
382::
383
384 extern putchard(char);
385 def printstar(n)
386 for i = 1, i < n, 1.0 in
387 putchard(42); # ascii 42 = '*'
388
389 # print 100 '*' characters
390 printstar(100);
391
392This expression defines a new variable ("i" in this case) which iterates
393from a starting value, while the condition ("i < n" in this case) is
394true, incrementing by an optional step value ("1.0" in this case). If
395the step value is omitted, it defaults to 1.0. While the loop is true,
396it executes its body expression. Because we don't have anything better
397to return, we'll just define the loop as always returning 0.0. In the
398future when we have mutable variables, it will get more useful.
399
400As before, lets talk about the changes that we need to Kaleidoscope to
401support this.
402
403Lexer Extensions for the 'for' Loop
404-----------------------------------
405
406The lexer extensions are the same sort of thing as for if/then/else:
407
408.. code-block:: ocaml
409
410 ... in Token.token ...
411 (* control *)
412 | If | Then | Else
413 | For | In
414
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 >]
425
426AST Extensions for the 'for' Loop
427---------------------------------
428
429The AST variant is just as simple. It basically boils down to capturing
430the variable name and the constituent expressions in the node.
431
432.. code-block:: ocaml
433
434 type expr =
435 ...
436 (* variant for for/in. *)
437 | For of string * expr * expr * expr option * expr
438
439Parser Extensions for the 'for' Loop
440------------------------------------
441
442The parser code is also fairly standard. The only interesting thing here
443is handling of the optional step value. The parser code handles it by
444checking to see if the second comma is present. If not, it sets the step
445value to null in the AST node:
446
447.. code-block:: ocaml
448
449 let rec parse_primary = parser
450 ...
451 (* forexpr
452 ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
453 | [< 'Token.For;
454 'Token.Ident id ?? "expected identifier after for";
455 'Token.Kwd '=' ?? "expected '=' after for";
456 stream >] ->
457 begin parser
458 | [<
459 start=parse_expr;
460 'Token.Kwd ',' ?? "expected ',' after for";
461 end_=parse_expr;
462 stream >] ->
463 let step =
464 begin parser
465 | [< 'Token.Kwd ','; step=parse_expr >] -> Some step
466 | [< >] -> None
467 end stream
468 in
469 begin parser
470 | [< 'Token.In; body=parse_expr >] ->
471 Ast.For (id, start, end_, step, body)
472 | [< >] ->
473 raise (Stream.Error "expected 'in' after for")
474 end stream
475 | [< >] ->
476 raise (Stream.Error "expected '=' after for")
477 end stream
478
479LLVM IR for the 'for' Loop
480--------------------------
481
482Now we get to the good part: the LLVM IR we want to generate for this
483thing. With the simple example above, we get this LLVM IR (note that
484this dump is generated with optimizations disabled for clarity):
485
486.. code-block:: llvm
487
488 declare double @putchard(double)
489
490 define double @printstar(double %n) {
491 entry:
492 ; initial value = 1.0 (inlined into phi)
493 br label %loop
494
495 loop: ; preds = %loop, %entry
496 %i = phi double [ 1.000000e+00, %entry ], [ %nextvar, %loop ]
497 ; body
498 %calltmp = call double @putchard(double 4.200000e+01)
499 ; increment
500 %nextvar = fadd double %i, 1.000000e+00
501
502 ; termination test
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
507
508 afterloop: ; preds = %loop
509 ; loop always returns 0.0
510 ret double 0.000000e+00
511 }
512
513This loop contains all the same constructs we saw before: a phi node,
514several expressions, and some basic blocks. Lets see how this fits
515together.
516
517Code Generation for the 'for' Loop
518----------------------------------
519
520The first part of Codegen is very simple: we just output the start
521expression for the loop value:
522
523.. code-block:: ocaml
524
525 let rec codegen_expr = function
526 ...
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
530
531With this out of the way, the next step is to set up the LLVM basic
532block for the start of the loop body. In the case above, the whole loop
533body is one block, but remember that the body code itself could consist
534of multiple blocks (e.g. if it contains an if/then/else or a for/in
535expression).
536
537.. code-block:: ocaml
538
539 (* Make the new basic block for the loop header, inserting after current
540 * block. *)
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
544
545 (* Insert an explicit fall through from the current block to the
546 * loop_bb. *)
547 ignore (build_br loop_bb builder);
548
549This code is similar to what we saw for if/then/else. Because we will
550need it to create the Phi node, we remember the block that falls through
551into the loop. Once we have that, we create the actual block that starts
552the loop and create an unconditional branch for the fall-through between
553the two blocks.
554
555.. code-block:: ocaml
556
557 (* Start insertion in loop_bb. *)
558 position_at_end loop_bb builder;
559
560 (* Start the PHI node with an entry for start. *)
561 let variable = build_phi [(start_val, preheader_bb)] var_name builder in
562
563Now that the "preheader" for the loop is set up, we switch to emitting
564code for the loop body. To begin with, we move the insertion point and
565create the PHI node for the loop induction variable. Since we already
566know the incoming value for the starting value, we add it to the Phi
567node. Note that the Phi will eventually get a second value for the
568backedge, but we can't set it up yet (because it doesn't exist!).
569
570.. code-block:: ocaml
571
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
574 * now. *)
575 let old_val =
576 try Some (Hashtbl.find named_values var_name) with Not_found -> None
577 in
578 Hashtbl.add named_values var_name variable;
579
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);
584
585Now the code starts to get more interesting. Our 'for' loop introduces a
586new variable to the symbol table. This means that our symbol table can
587now contain either function arguments or loop variables. To handle this,
588before we codegen the body of the loop, we add the loop variable as the
589current value for its name. Note that it is possible that there is a
590variable of the same name in the outer scope. It would be easy to make
591this an error (emit an error and return null if there is already an
592entry for VarName) but we choose to allow shadowing of variables. In
593order to handle this correctly, we remember the Value that we are
594potentially shadowing in ``old_val`` (which will be None if there is no
595shadowed variable).
596
597Once the loop variable is set into the symbol table, the code
598recursively codegen's the body. This allows the body to use the loop
599variable: any references to it will naturally find it in the symbol
600table.
601
602.. code-block:: ocaml
603
604 (* Emit the step value. *)
605 let step_val =
606 match step with
607 | Some step -> codegen_expr step
608 (* If not specified, use 1.0. *)
609 | None -> const_float double_type 1.0
610 in
611
612 let next_var = build_add variable step_val "nextvar" builder in
613
614Now that the body is emitted, we compute the next value of the iteration
615variable 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
617iteration of the loop.
618
619.. code-block:: ocaml
620
621 (* Compute the end condition. *)
622 let end_cond = codegen_expr end_ in
623
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
627
628Finally, we evaluate the exit value of the loop, to determine whether
629the loop should exit. This mirrors the condition evaluation for the
630if/then/else statement.
631
632.. code-block:: ocaml
633
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
637
638 (* Insert the conditional branch into the end of loop_end_bb. *)
639 ignore (build_cond_br end_cond loop_bb after_bb builder);
640
641 (* Any new code will be inserted in after_bb. *)
642 position_at_end after_bb builder;
643
644With the code for the body of the loop complete, we just need to finish
645up the control flow for it. This code remembers the end block (for the
646phi node), then creates the block for the loop exit ("afterloop"). Based
647on the value of the exit condition, it creates a conditional branch that
648chooses between executing the loop again and exiting the loop. Any
649future code is emitted in the "afterloop" block, so it sets the
650insertion position to it.
651
652.. code-block:: ocaml
653
654 (* Add a new entry to the PHI node for the backedge. *)
655 add_incoming (next_var, loop_end_bb) variable;
656
657 (* Restore the unshadowed variable. *)
658 begin match old_val with
659 | Some old_val -> Hashtbl.add named_values var_name old_val
660 | None -> ()
661 end;
662
663 (* for expr always returns 0.0. *)
664 const_null double_type
665
666The final code handles various cleanups: now that we have the
667"``next_var``" value, we can add the incoming value to the loop PHI
668node. After that, we remove the loop variable from the symbol table, so
669that it isn't in scope after the for loop. Finally, code generation of
670the for loop always returns 0.0, so that is what we return from
671``Codegen.codegen_expr``.
672
673With this, we conclude the "adding control flow to Kaleidoscope" chapter
674of the tutorial. In this chapter we added two control flow constructs,
675and used them to motivate a couple of aspects of the LLVM IR that are
676important for front-end implementors to know. In the next chapter of our
677saga, we will get a bit crazier and add `user-defined
678operators <OCamlLangImpl6.html>`_ to our poor innocent language.
679
680Full Code Listing
681=================
682
683Here is the complete code listing for our running example, enhanced with
684the if/then/else and for expressions.. To build this example, use:
685
686.. code-block:: bash
687
688 # Compile
689 ocamlbuild toy.byte
690 # Run
691 ./toy.byte
692
693Here is the code:
694
695\_tags:
696 ::
697
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
702
703myocamlbuild.ml:
704 .. code-block:: ocaml
705
706 open Ocamlbuild_plugin;;
707
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";;
713
714 flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
715 dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
716
717token.ml:
718 .. code-block:: ocaml
719
720 (*===----------------------------------------------------------------------===
721 * Lexer Tokens
722 *===----------------------------------------------------------------------===*)
723
724 (* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
725 * these others for known things. *)
726 type token =
727 (* commands *)
728 | Def | Extern
729
730 (* primary *)
731 | Ident of string | Number of float
732
733 (* unknown *)
734 | Kwd of char
735
736 (* control *)
737 | If | Then | Else
738 | For | In
739
740lexer.ml:
741 .. code-block:: ocaml
742
743 (*===----------------------------------------------------------------------===
744 * Lexer
745 *===----------------------------------------------------------------------===*)
746
747 let rec lex = parser
748 (* Skip any whitespace. *)
749 | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
750
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
756
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
762
763 (* Comment until end of line. *)
764 | [< ' ('#'); stream >] ->
765 lex_comment stream
766
767 (* Otherwise, just return the character as its ascii value. *)
768 | [< 'c; stream >] ->
769 [< 'Token.Kwd c; lex stream >]
770
771 (* end of stream. *)
772 | [< >] -> [< >]
773
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 >]
780
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 >]
795
796 and lex_comment = parser
797 | [< ' ('\n'); stream=lex >] -> stream
798 | [< 'c; e=lex_comment >] -> e
799 | [< >] -> [< >]
800
801ast.ml:
802 .. code-block:: ocaml
803
804 (*===----------------------------------------------------------------------===
805 * Abstract Syntax Tree (aka Parse Tree)
806 *===----------------------------------------------------------------------===*)
807
808 (* expr - Base type for all expression nodes. *)
809 type expr =
810 (* variant for numeric literals like "1.0". *)
811 | Number of float
812
813 (* variant for referencing a variable, like "a". *)
814 | Variable of string
815
816 (* variant for a binary operator. *)
817 | Binary of char * expr * expr
818
819 (* variant for function calls. *)
820 | Call of string * expr array
821
822 (* variant for if/then/else. *)
823 | If of expr * expr * expr
824
825 (* variant for for/in. *)
826 | For of string * expr * expr * expr option * expr
827
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
832
833 (* func - This type represents a function definition itself. *)
834 type func = Function of proto * expr
835
836parser.ml:
837 .. code-block:: ocaml
838
839 (*===---------------------------------------------------------------------===
840 * Parser
841 *===---------------------------------------------------------------------===*)
842
843 (* binop_precedence - This holds the precedence for each binary operator that is
844 * defined *)
845 let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
846
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
849
850 (* primary
851 * ::= identifier
852 * ::= numberexpr
853 * ::= parenexpr
854 * ::= ifexpr
855 * ::= forexpr *)
856 let rec parse_primary = parser
857 (* numberexpr ::= number *)
858 | [< 'Token.Number n >] -> Ast.Number n
859
860 (* parenexpr ::= '(' expression ')' *)
861 | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
862
863 (* identifierexpr
864 * ::= identifier
865 * ::= identifier '(' argumentexpr ')' *)
866 | [< 'Token.Ident id; stream >] ->
867 let rec parse_args accumulator = parser
868 | [< e=parse_expr; stream >] ->
869 begin parser
870 | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
871 | [< >] -> e :: accumulator
872 end stream
873 | [< >] -> accumulator
874 in
875 let rec parse_ident id = parser
876 (* Call. *)
877 | [< 'Token.Kwd '(';
878 args=parse_args [];
879 'Token.Kwd ')' ?? "expected ')'">] ->
880 Ast.Call (id, Array.of_list (List.rev args))
881
882 (* Simple variable ref. *)
883 | [< >] -> Ast.Variable id
884 in
885 parse_ident id stream
886
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 >] ->
891 Ast.If (c, t, e)
892
893 (* forexpr
894 ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
895 | [< 'Token.For;
896 'Token.Ident id ?? "expected identifier after for";
897 'Token.Kwd '=' ?? "expected '=' after for";
898 stream >] ->
899 begin parser
900 | [<
901 start=parse_expr;
902 'Token.Kwd ',' ?? "expected ',' after for";
903 end_=parse_expr;
904 stream >] ->
905 let step =
906 begin parser
907 | [< 'Token.Kwd ','; step=parse_expr >] -> Some step
908 | [< >] -> None
909 end stream
910 in
911 begin parser
912 | [< 'Token.In; body=parse_expr >] ->
913 Ast.For (id, start, end_, step, body)
914 | [< >] ->
915 raise (Stream.Error "expected 'in' after for")
916 end stream
917 | [< >] ->
918 raise (Stream.Error "expected '=' after for")
919 end stream
920
921 | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
922
923 (* binoprhs
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
930
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
934 (* Eat the binop. *)
935 Stream.junk stream;
936
937 (* Parse the primary expression after the binary operator. *)
938 let rhs = parse_primary stream in
939
940 (* Okay, we know this is a binop. *)
941 let rhs =
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
949 else rhs
950 | _ -> rhs
951 in
952
953 (* Merge lhs/rhs. *)
954 let lhs = Ast.Binary (c, lhs, rhs) in
955 parse_bin_rhs expr_prec lhs stream
956 end
957 | _ -> lhs
958
959 (* expression
960 * ::= primary binoprhs *)
961 and parse_expr = parser
962 | [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
963
964 (* prototype
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
970 in
971
972 parser
973 | [< 'Token.Ident id;
974 'Token.Kwd '(' ?? "expected '(' in prototype";
975 args=parse_args [];
976 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
977 (* success. *)
978 Ast.Prototype (id, Array.of_list (List.rev args))
979
980 | [< >] ->
981 raise (Stream.Error "expected function name in prototype")
982
983 (* definition ::= 'def' prototype expression *)
984 let parse_definition = parser
985 | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
986 Ast.Function (p, e)
987
988 (* toplevelexpr ::= expression *)
989 let parse_toplevel = parser
990 | [< e=parse_expr >] ->
991 (* Make an anonymous proto. *)
992 Ast.Function (Ast.Prototype ("", [||]), e)
993
994 (* external ::= 'extern' prototype *)
995 let parse_extern = parser
996 | [< 'Token.Extern; e=parse_prototype >] -> e
997
998codegen.ml:
999 .. code-block:: ocaml
1000
1001 (*===----------------------------------------------------------------------===
1002 * Code Generation
1003 *===----------------------------------------------------------------------===*)
1004
1005 open Llvm
1006
1007 exception Error of string
1008
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
1014
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
1023 begin
1024 match op with
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
1028 | '<' ->
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")
1033 end
1034 | Ast.Call (callee, args) ->
1035 (* Look up the name in the module table. *)
1036 let callee =
1037 match lookup_function callee the_module with
1038 | Some callee -> callee
1039 | None -> raise (Error "unknown function referenced")
1040 in
1041 let params = params callee in
1042
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
1050
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
1054
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
1059
1060 let then_bb = append_block context "then" the_function in
1061
1062 (* Emit 'then' value. *)
1063 position_at_end then_bb builder;
1064 let then_val = codegen_expr then_ in
1065
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
1070
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
1075
1076 (* Codegen of 'else' can change the current block, update else_bb for the
1077 * phi. *)
1078 let new_else_bb = insertion_block builder in
1079
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
1085
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);
1089
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);
1094
1095 (* Finally, set the builder to the end of the merge block. *)
1096 position_at_end merge_bb builder;
1097
1098 phi
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
1102
1103 (* Make the new basic block for the loop header, inserting after current
1104 * block. *)
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
1108
1109 (* Insert an explicit fall through from the current block to the
1110 * loop_bb. *)
1111 ignore (build_br loop_bb builder);
1112
1113 (* Start insertion in loop_bb. *)
1114 position_at_end loop_bb builder;
1115
1116 (* Start the PHI node with an entry for start. *)
1117 let variable = build_phi [(start_val, preheader_bb)] var_name builder in
1118
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
1121 * now. *)
1122 let old_val =
1123 try Some (Hashtbl.find named_values var_name) with Not_found -> None
1124 in
1125 Hashtbl.add named_values var_name variable;
1126
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);
1131
1132 (* Emit the step value. *)
1133 let step_val =
1134 match step with
1135 | Some step -> codegen_expr step
1136 (* If not specified, use 1.0. *)
1137 | None -> const_float double_type 1.0
1138 in
1139
1140 let next_var = build_add variable step_val "nextvar" builder in
1141
1142 (* Compute the end condition. *)
1143 let end_cond = codegen_expr end_ in
1144
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
1148
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
1152
1153 (* Insert the conditional branch into the end of loop_end_bb. *)
1154 ignore (build_cond_br end_cond loop_bb after_bb builder);
1155
1156 (* Any new code will be inserted in after_bb. *)
1157 position_at_end after_bb builder;
1158
1159 (* Add a new entry to the PHI node for the backedge. *)
1160 add_incoming (next_var, loop_end_bb) variable;
1161
1162 (* Restore the unshadowed variable. *)
1163 begin match old_val with
1164 | Some old_val -> Hashtbl.add named_values var_name old_val
1165 | None -> ()
1166 end;
1167
1168 (* for expr always returns 0.0. *)
1169 const_null double_type
1170
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
1176 let f =
1177 match lookup_function name the_module with
1178 | None -> declare_function name ft the_module
1179
1180 (* If 'f' conflicted, there was already something named 'name'. If it
1181 * has a body, don't allow redefinition or reextern. *)
1182 | Some f ->
1183 (* If 'f' already has a body, reject this. *)
1184 if block_begin f <> At_end f then
1185 raise (Error "redefinition of function");
1186
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");
1190 f
1191 in
1192
1193 (* Set names for all arguments. *)
1194 Array.iteri (fun i a ->
1195 let n = args.(i) in
1196 set_value_name n a;
1197 Hashtbl.add named_values n a;
1198 ) (params f);
1199 f
1200
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
1205
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;
1209
1210 try
1211 let ret_val = codegen_expr body in
1212
1213 (* Finish off the function. *)
1214 let _ = build_ret ret_val builder in
1215
1216 (* Validate the generated code, checking for consistency. *)
1217 Llvm_analysis.assert_valid_function the_function;
1218
1219 (* Optimize the function. *)
1220 let _ = PassManager.run_function the_function the_fpm in
1221
1222 the_function
1223 with e ->
1224 delete_function the_function;
1225 raise e
1226
1227toplevel.ml:
1228 .. code-block:: ocaml
1229
1230 (*===----------------------------------------------------------------------===
1231 * Top-Level parsing and JIT Driver
1232 *===----------------------------------------------------------------------===*)
1233
1234 open Llvm
1235 open Llvm_executionengine
1236
1237 (* top ::= definition | external | expression | ';' *)
1238 let rec main_loop the_fpm the_execution_engine stream =
1239 match Stream.peek stream with
1240 | None -> ()
1241
1242 (* ignore top-level semicolons. *)
1243 | Some (Token.Kwd ';') ->
1244 Stream.junk stream;
1245 main_loop the_fpm the_execution_engine stream
1246
1247 | Some token ->
1248 begin
1249 try match token with
1250 | Token.Def ->
1251 let e = Parser.parse_definition stream in
1252 print_endline "parsed a function definition.";
1253 dump_value (Codegen.codegen_func the_fpm e);
1254 | Token.Extern ->
1255 let e = Parser.parse_extern stream in
1256 print_endline "parsed an extern.";
1257 dump_value (Codegen.codegen_proto e);
1258 | _ ->
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;
1264
1265 (* JIT the function, returning a function pointer. *)
1266 let result = ExecutionEngine.run_function the_function [||]
1267 the_execution_engine in
1268
1269 print_string "Evaluated to ";
1270 print_float (GenericValue.as_float Codegen.double_type result);
1271 print_newline ();
1272 with Stream.Error s | Codegen.Error s ->
1273 (* Skip token for error recovery. *)
1274 Stream.junk stream;
1275 print_endline s;
1276 end;
1277 print_string "ready> "; flush stdout;
1278 main_loop the_fpm the_execution_engine stream
1279
1280toy.ml:
1281 .. code-block:: ocaml
1282
1283 (*===----------------------------------------------------------------------===
1284 * Main driver code.
1285 *===----------------------------------------------------------------------===*)
1286
1287 open Llvm
1288 open Llvm_executionengine
1289 open Llvm_target
1290 open Llvm_scalar_opts
1291
1292 let main () =
1293 ignore (initialize_native_target ());
1294
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. *)
1301
1302 (* Prime the first token. *)
1303 print_string "ready> "; flush stdout;
1304 let stream = Lexer.lex (Stream.of_channel stdin) in
1305
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
1309
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;
1313
1314 (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
1315 add_instruction_combination the_fpm;
1316
1317 (* reassociate expressions. *)
1318 add_reassociation the_fpm;
1319
1320 (* Eliminate Common SubExpressions. *)
1321 add_gvn the_fpm;
1322
1323 (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
1324 add_cfg_simplification the_fpm;
1325
1326 ignore (PassManager.initialize the_fpm);
1327
1328 (* Run the main "interpreter loop" now. *)
1329 Toplevel.main_loop the_fpm the_execution_engine stream;
1330
1331 (* Print out all the generated code. *)
1332 dump_module Codegen.the_module
1333 ;;
1334
1335 main ()
1336
1337bindings.c
1338 .. code-block:: c
1339
1340 #include <stdio.h>
1341
1342 /* putchard - putchar that takes a double and returns 0. */
1343 extern double putchard(double X) {
1344 putchar((char)X);
1345 return 0;
1346 }
1347
1348`Next: Extending the language: user-defined
1349operators <OCamlLangImpl6.html>`_
1350