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 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 enum values
64 for the relevant tokens:
69 tok_if = -6, tok_then = -7, tok_else = -8,
71 Once we have that, we recognize the new keywords in the lexer. This is
77 if (IdentifierStr == "def") return tok_def;
78 if (IdentifierStr == "extern") return tok_extern;
79 if (IdentifierStr == "if") return tok_if;
80 if (IdentifierStr == "then") return tok_then;
81 if (IdentifierStr == "else") return tok_else;
82 return tok_identifier;
84 AST Extensions for If/Then/Else
85 -------------------------------
87 To represent the new expression we add a new AST node for it:
91 /// IfExprAST - Expression class for if/then/else.
92 class IfExprAST : public ExprAST {
93 std::unique<ExprAST> Cond, Then, Else;
95 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
96 std::unique_ptr<ExprAST> Else)
97 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
98 virtual Value *Codegen();
101 The AST node just has pointers to the various subexpressions.
103 Parser Extensions for If/Then/Else
104 ----------------------------------
106 Now that we have the relevant tokens coming from the lexer and we have
107 the AST node to build, our parsing logic is relatively straightforward.
108 First we define a new parsing function:
112 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
113 static std::unique_ptr<ExprAST> ParseIfExpr() {
114 getNextToken(); // eat the if.
117 auto Cond = ParseExpression();
118 if (!Cond) return nullptr;
120 if (CurTok != tok_then)
121 return Error("expected then");
122 getNextToken(); // eat the then
124 auto Then = ParseExpression();
125 if (Then) return nullptr;
127 if (CurTok != tok_else)
128 return Error("expected else");
132 auto Else = ParseExpression();
133 if (!Else) return nullptr;
135 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
139 Next we hook it up as a primary expression:
143 static std::unique_ptr<ExprAST> ParsePrimary() {
145 default: return Error("unknown token when expecting an expression");
146 case tok_identifier: return ParseIdentifierExpr();
147 case tok_number: return ParseNumberExpr();
148 case '(': return ParseParenExpr();
149 case tok_if: return ParseIfExpr();
153 LLVM IR for If/Then/Else
154 ------------------------
156 Now that we have it parsing and building the AST, the final piece is
157 adding LLVM code generation support. This is the most interesting part
158 of the if/then/else example, because this is where it starts to
159 introduce new concepts. All of the code above has been thoroughly
160 described in previous chapters.
162 To motivate the code we want to produce, lets take a look at a simple
169 def baz(x) if x then foo() else bar();
171 If you disable optimizations, the code you'll (soon) get from
172 Kaleidoscope looks like this:
176 declare double @foo()
178 declare double @bar()
180 define double @baz(double %x) {
182 %ifcond = fcmp one double %x, 0.000000e+00
183 br i1 %ifcond, label %then, label %else
185 then: ; preds = %entry
186 %calltmp = call double @foo()
189 else: ; preds = %entry
190 %calltmp1 = call double @bar()
193 ifcont: ; preds = %else, %then
194 %iftmp = phi double [ %calltmp, %then ], [ %calltmp1, %else ]
198 To visualize the control flow graph, you can use a nifty feature of the
199 LLVM '`opt <http://llvm.org/cmds/opt.html>`_' tool. If you put this LLVM
200 IR into "t.ll" and run "``llvm-as < t.ll | opt -analyze -view-cfg``", `a
201 window will pop up <../ProgrammersManual.html#ViewGraph>`_ and you'll
204 .. figure:: LangImpl5-cfg.png
210 Another way to get this is to call "``F->viewCFG()``" or
211 "``F->viewCFGOnly()``" (where F is a "``Function*``") either by
212 inserting actual calls into the code and recompiling or by calling these
213 in the debugger. LLVM has many nice features for visualizing various
216 Getting back to the generated code, it is fairly simple: the entry block
217 evaluates the conditional expression ("x" in our case here) and compares
218 the result to 0.0 with the "``fcmp one``" instruction ('one' is "Ordered
219 and Not Equal"). Based on the result of this expression, the code jumps
220 to either the "then" or "else" blocks, which contain the expressions for
221 the true/false cases.
223 Once the then/else blocks are finished executing, they both branch back
224 to the 'ifcont' block to execute the code that happens after the
225 if/then/else. In this case the only thing left to do is to return to the
226 caller of the function. The question then becomes: how does the code
227 know which expression to return?
229 The answer to this question involves an important SSA operation: the
231 operation <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
232 If you're not familiar with SSA, `the wikipedia
233 article <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
234 is a good introduction and there are various other introductions to it
235 available on your favorite search engine. The short version is that
236 "execution" of the Phi operation requires "remembering" which block
237 control came from. The Phi operation takes on the value corresponding to
238 the input control block. In this case, if control comes in from the
239 "then" block, it gets the value of "calltmp". If control comes from the
240 "else" block, it gets the value of "calltmp1".
242 At this point, you are probably starting to think "Oh no! This means my
243 simple and elegant front-end will have to start generating SSA form in
244 order to use LLVM!". Fortunately, this is not the case, and we strongly
245 advise *not* implementing an SSA construction algorithm in your
246 front-end unless there is an amazingly good reason to do so. In
247 practice, there are two sorts of values that float around in code
248 written for your average imperative programming language that might need
251 #. Code that involves user variables: ``x = 1; x = x + 1;``
252 #. Values that are implicit in the structure of your AST, such as the
253 Phi node in this case.
255 In `Chapter 7 <LangImpl7.html>`_ of this tutorial ("mutable variables"),
256 we'll talk about #1 in depth. For now, just believe me that you don't
257 need SSA construction to handle this case. For #2, you have the choice
258 of using the techniques that we will describe for #1, or you can insert
259 Phi nodes directly, if convenient. In this case, it is really
260 easy to generate the Phi node, so we choose to do it directly.
262 Okay, enough of the motivation and overview, lets generate code!
264 Code Generation for If/Then/Else
265 --------------------------------
267 In order to generate code for this, we implement the ``Codegen`` method
272 Value *IfExprAST::Codegen() {
273 Value *CondV = Cond->Codegen();
274 if (!CondV) return nullptr;
276 // Convert condition to a bool by comparing equal to 0.0.
277 CondV = Builder.CreateFCmpONE(CondV,
278 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
281 This code is straightforward and similar to what we saw before. We emit
282 the expression for the condition, then compare that value to zero to get
283 a truth value as a 1-bit (bool) value.
287 Function *TheFunction = Builder.GetInsertBlock()->getParent();
289 // Create blocks for the then and else cases. Insert the 'then' block at the
290 // end of the function.
291 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
292 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
293 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
295 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
297 This code creates the basic blocks that are related to the if/then/else
298 statement, and correspond directly to the blocks in the example above.
299 The first line gets the current Function object that is being built. It
300 gets this by asking the builder for the current BasicBlock, and asking
301 that block for its "parent" (the function it is currently embedded
304 Once it has that, it creates three blocks. Note that it passes
305 "TheFunction" into the constructor for the "then" block. This causes the
306 constructor to automatically insert the new block into the end of the
307 specified function. The other two blocks are created, but aren't yet
308 inserted into the function.
310 Once the blocks are created, we can emit the conditional branch that
311 chooses between them. Note that creating new blocks does not implicitly
312 affect the IRBuilder, so it is still inserting into the block that the
313 condition went into. Also note that it is creating a branch to the
314 "then" block and the "else" block, even though the "else" block isn't
315 inserted into the function yet. This is all ok: it is the standard way
316 that LLVM supports forward references.
321 Builder.SetInsertPoint(ThenBB);
323 Value *ThenV = Then->Codegen();
324 if (ThenV == 0) return 0;
326 Builder.CreateBr(MergeBB);
327 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
328 ThenBB = Builder.GetInsertBlock();
330 After the conditional branch is inserted, we move the builder to start
331 inserting into the "then" block. Strictly speaking, this call moves the
332 insertion point to be at the end of the specified block. However, since
333 the "then" block is empty, it also starts out by inserting at the
334 beginning of the block. :)
336 Once the insertion point is set, we recursively codegen the "then"
337 expression from the AST. To finish off the "then" block, we create an
338 unconditional branch to the merge block. One interesting (and very
339 important) aspect of the LLVM IR is that it `requires all basic blocks
340 to be "terminated" <../LangRef.html#functionstructure>`_ with a `control
341 flow instruction <../LangRef.html#terminators>`_ such as return or
342 branch. This means that all control flow, *including fall throughs* must
343 be made explicit in the LLVM IR. If you violate this rule, the verifier
346 The final line here is quite subtle, but is very important. The basic
347 issue is that when we create the Phi node in the merge block, we need to
348 set up the block/value pairs that indicate how the Phi will work.
349 Importantly, the Phi node expects to have an entry for each predecessor
350 of the block in the CFG. Why then, are we getting the current block when
351 we just set it to ThenBB 5 lines above? The problem is that the "Then"
352 expression may actually itself change the block that the Builder is
353 emitting into if, for example, it contains a nested "if/then/else"
354 expression. Because calling Codegen recursively could arbitrarily change
355 the notion of the current block, we are required to get an up-to-date
356 value for code that will set up the Phi node.
361 TheFunction->getBasicBlockList().push_back(ElseBB);
362 Builder.SetInsertPoint(ElseBB);
364 Value *ElseV = Else->Codegen();
365 if (ElseV == 0) return 0;
367 Builder.CreateBr(MergeBB);
368 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
369 ElseBB = Builder.GetInsertBlock();
371 Code generation for the 'else' block is basically identical to codegen
372 for the 'then' block. The only significant difference is the first line,
373 which adds the 'else' block to the function. Recall previously that the
374 'else' block was created, but not added to the function. Now that the
375 'then' and 'else' blocks are emitted, we can finish up with the merge
381 TheFunction->getBasicBlockList().push_back(MergeBB);
382 Builder.SetInsertPoint(MergeBB);
383 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
386 PN->addIncoming(ThenV, ThenBB);
387 PN->addIncoming(ElseV, ElseBB);
391 The first two lines here are now familiar: the first adds the "merge"
392 block to the Function object (it was previously floating, like the else
393 block above). The second changes the insertion point so that newly
394 created code will go into the "merge" block. Once that is done, we need
395 to create the PHI node and set up the block/value pairs for the PHI.
397 Finally, the CodeGen function returns the phi node as the value computed
398 by the if/then/else expression. In our example above, this returned
399 value will feed into the code for the top-level function, which will
400 create the return instruction.
402 Overall, we now have the ability to execute conditional code in
403 Kaleidoscope. With this extension, Kaleidoscope is a fairly complete
404 language that can calculate a wide variety of numeric functions. Next up
405 we'll add another useful expression that is familiar from non-functional
408 'for' Loop Expression
409 =====================
411 Now that we know how to add basic control flow constructs to the
412 language, we have the tools to add more powerful things. Lets add
413 something more aggressive, a 'for' expression:
417 extern putchard(char)
419 for i = 1, i < n, 1.0 in
420 putchard(42); # ascii 42 = '*'
422 # print 100 '*' characters
425 This expression defines a new variable ("i" in this case) which iterates
426 from a starting value, while the condition ("i < n" in this case) is
427 true, incrementing by an optional step value ("1.0" in this case). If
428 the step value is omitted, it defaults to 1.0. While the loop is true,
429 it executes its body expression. Because we don't have anything better
430 to return, we'll just define the loop as always returning 0.0. In the
431 future when we have mutable variables, it will get more useful.
433 As before, lets talk about the changes that we need to Kaleidoscope to
436 Lexer Extensions for the 'for' Loop
437 -----------------------------------
439 The lexer extensions are the same sort of thing as for if/then/else:
443 ... in enum Token ...
445 tok_if = -6, tok_then = -7, tok_else = -8,
446 tok_for = -9, tok_in = -10
449 if (IdentifierStr == "def") return tok_def;
450 if (IdentifierStr == "extern") return tok_extern;
451 if (IdentifierStr == "if") return tok_if;
452 if (IdentifierStr == "then") return tok_then;
453 if (IdentifierStr == "else") return tok_else;
454 if (IdentifierStr == "for") return tok_for;
455 if (IdentifierStr == "in") return tok_in;
456 return tok_identifier;
458 AST Extensions for the 'for' Loop
459 ---------------------------------
461 The AST node is just as simple. It basically boils down to capturing the
462 variable name and the constituent expressions in the node.
466 /// ForExprAST - Expression class for for/in.
467 class ForExprAST : public ExprAST {
469 std::unique_ptr<ExprAST> Start, End, Step, Body;
471 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
472 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
473 std::unique_ptr<ExprAST> Body)
474 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
475 Step(std::move(Step)), Body(std::move(Body)) {}
476 virtual Value *Codegen();
479 Parser Extensions for the 'for' Loop
480 ------------------------------------
482 The parser code is also fairly standard. The only interesting thing here
483 is handling of the optional step value. The parser code handles it by
484 checking to see if the second comma is present. If not, it sets the step
485 value to null in the AST node:
489 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
490 static std::unique_ptr<ExprAST> ParseForExpr() {
491 getNextToken(); // eat the for.
493 if (CurTok != tok_identifier)
494 return Error("expected identifier after for");
496 std::string IdName = IdentifierStr;
497 getNextToken(); // eat identifier.
500 return Error("expected '=' after for");
501 getNextToken(); // eat '='.
504 auto Start = ParseExpression();
505 if (!Start) return nullptr;
507 return Error("expected ',' after for start value");
510 auto End = ParseExpression();
511 if (!End) return nullptr;
513 // The step value is optional.
514 std::unique_ptr<ExprAST> Step;
517 Step = ParseExpression();
518 if (!Step) return nullptr;
521 if (CurTok != tok_in)
522 return Error("expected 'in' after for");
523 getNextToken(); // eat 'in'.
525 auto Body = ParseExpression();
526 if (!Body) return nullptr;
528 return llvm::make_unique<ForExprAST>(IdName, std::move(Start),
529 std::move(End), std::move(Step),
533 LLVM IR for the 'for' Loop
534 --------------------------
536 Now we get to the good part: the LLVM IR we want to generate for this
537 thing. With the simple example above, we get this LLVM IR (note that
538 this dump is generated with optimizations disabled for clarity):
542 declare double @putchard(double)
544 define double @printstar(double %n) {
546 ; initial value = 1.0 (inlined into phi)
549 loop: ; preds = %loop, %entry
550 %i = phi double [ 1.000000e+00, %entry ], [ %nextvar, %loop ]
552 %calltmp = call double @putchard(double 4.200000e+01)
554 %nextvar = fadd double %i, 1.000000e+00
557 %cmptmp = fcmp ult double %i, %n
558 %booltmp = uitofp i1 %cmptmp to double
559 %loopcond = fcmp one double %booltmp, 0.000000e+00
560 br i1 %loopcond, label %loop, label %afterloop
562 afterloop: ; preds = %loop
563 ; loop always returns 0.0
564 ret double 0.000000e+00
567 This loop contains all the same constructs we saw before: a phi node,
568 several expressions, and some basic blocks. Lets see how this fits
571 Code Generation for the 'for' Loop
572 ----------------------------------
574 The first part of Codegen is very simple: we just output the start
575 expression for the loop value:
579 Value *ForExprAST::Codegen() {
580 // Emit the start code first, without 'variable' in scope.
581 Value *StartVal = Start->Codegen();
582 if (StartVal == 0) return 0;
584 With this out of the way, the next step is to set up the LLVM basic
585 block for the start of the loop body. In the case above, the whole loop
586 body is one block, but remember that the body code itself could consist
587 of multiple blocks (e.g. if it contains an if/then/else or a for/in
592 // Make the new basic block for the loop header, inserting after current
594 Function *TheFunction = Builder.GetInsertBlock()->getParent();
595 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
596 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
598 // Insert an explicit fall through from the current block to the LoopBB.
599 Builder.CreateBr(LoopBB);
601 This code is similar to what we saw for if/then/else. Because we will
602 need it to create the Phi node, we remember the block that falls through
603 into the loop. Once we have that, we create the actual block that starts
604 the loop and create an unconditional branch for the fall-through between
609 // Start insertion in LoopBB.
610 Builder.SetInsertPoint(LoopBB);
612 // Start the PHI node with an entry for Start.
613 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
614 Variable->addIncoming(StartVal, PreheaderBB);
616 Now that the "preheader" for the loop is set up, we switch to emitting
617 code for the loop body. To begin with, we move the insertion point and
618 create the PHI node for the loop induction variable. Since we already
619 know the incoming value for the starting value, we add it to the Phi
620 node. Note that the Phi will eventually get a second value for the
621 backedge, but we can't set it up yet (because it doesn't exist!).
625 // Within the loop, the variable is defined equal to the PHI node. If it
626 // shadows an existing variable, we have to restore it, so save it now.
627 Value *OldVal = NamedValues[VarName];
628 NamedValues[VarName] = Variable;
630 // Emit the body of the loop. This, like any other expr, can change the
631 // current BB. Note that we ignore the value computed by the body, but don't
633 if (Body->Codegen() == 0)
636 Now the code starts to get more interesting. Our 'for' loop introduces a
637 new variable to the symbol table. This means that our symbol table can
638 now contain either function arguments or loop variables. To handle this,
639 before we codegen the body of the loop, we add the loop variable as the
640 current value for its name. Note that it is possible that there is a
641 variable of the same name in the outer scope. It would be easy to make
642 this an error (emit an error and return null if there is already an
643 entry for VarName) but we choose to allow shadowing of variables. In
644 order to handle this correctly, we remember the Value that we are
645 potentially shadowing in ``OldVal`` (which will be null if there is no
648 Once the loop variable is set into the symbol table, the code
649 recursively codegen's the body. This allows the body to use the loop
650 variable: any references to it will naturally find it in the symbol
655 // Emit the step value.
658 StepVal = Step->Codegen();
659 if (StepVal == 0) return 0;
661 // If not specified, use 1.0.
662 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
665 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
667 Now that the body is emitted, we compute the next value of the iteration
668 variable by adding the step value, or 1.0 if it isn't present.
669 '``NextVar``' will be the value of the loop variable on the next
670 iteration of the loop.
674 // Compute the end condition.
675 Value *EndCond = End->Codegen();
676 if (EndCond == 0) return EndCond;
678 // Convert condition to a bool by comparing equal to 0.0.
679 EndCond = Builder.CreateFCmpONE(EndCond,
680 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
683 Finally, we evaluate the exit value of the loop, to determine whether
684 the loop should exit. This mirrors the condition evaluation for the
685 if/then/else statement.
689 // Create the "after loop" block and insert it.
690 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
691 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
693 // Insert the conditional branch into the end of LoopEndBB.
694 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
696 // Any new code will be inserted in AfterBB.
697 Builder.SetInsertPoint(AfterBB);
699 With the code for the body of the loop complete, we just need to finish
700 up the control flow for it. This code remembers the end block (for the
701 phi node), then creates the block for the loop exit ("afterloop"). Based
702 on the value of the exit condition, it creates a conditional branch that
703 chooses between executing the loop again and exiting the loop. Any
704 future code is emitted in the "afterloop" block, so it sets the
705 insertion position to it.
709 // Add a new entry to the PHI node for the backedge.
710 Variable->addIncoming(NextVar, LoopEndBB);
712 // Restore the unshadowed variable.
714 NamedValues[VarName] = OldVal;
716 NamedValues.erase(VarName);
718 // for expr always returns 0.0.
719 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
722 The final code handles various cleanups: now that we have the "NextVar"
723 value, we can add the incoming value to the loop PHI node. After that,
724 we remove the loop variable from the symbol table, so that it isn't in
725 scope after the for loop. Finally, code generation of the for loop
726 always returns 0.0, so that is what we return from
727 ``ForExprAST::Codegen``.
729 With this, we conclude the "adding control flow to Kaleidoscope" chapter
730 of the tutorial. In this chapter we added two control flow constructs,
731 and used them to motivate a couple of aspects of the LLVM IR that are
732 important for front-end implementors to know. In the next chapter of our
733 saga, we will get a bit crazier and add `user-defined
734 operators <LangImpl6.html>`_ to our poor innocent language.
739 Here is the complete code listing for our running example, enhanced with
740 the if/then/else and for expressions.. To build this example, use:
745 clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy
751 .. literalinclude:: ../../examples/Kaleidoscope/Chapter5/toy.cpp
754 `Next: Extending the language: user-defined operators <LangImpl6.html>`_