blob: add0e188734144cd5eba467ad93b1371aa656829 [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 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 enum values
64for the relevant tokens:
65
66.. code-block:: c++
67
68 // control
69 tok_if = -6, tok_then = -7, tok_else = -8,
70
71Once we have that, we recognize the new keywords in the lexer. This is
72pretty simple stuff:
73
74.. code-block:: c++
75
76 ...
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;
83
84AST Extensions for If/Then/Else
85-------------------------------
86
87To represent the new expression we add a new AST node for it:
88
89.. code-block:: c++
90
91 /// IfExprAST - Expression class for if/then/else.
92 class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +000093 std::unique<ExprAST> Cond, Then, Else;
Sean Silvad7fb3962012-12-05 00:26:32 +000094 public:
Lang Hames09bf4c12015-08-18 18:11:06 +000095 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)) {}
Sean Silvad7fb3962012-12-05 00:26:32 +000098 virtual Value *Codegen();
99 };
100
101The AST node just has pointers to the various subexpressions.
102
103Parser Extensions for If/Then/Else
104----------------------------------
105
106Now that we have the relevant tokens coming from the lexer and we have
107the AST node to build, our parsing logic is relatively straightforward.
108First we define a new parsing function:
109
110.. code-block:: c++
111
112 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000113 static std::unique_ptr<ExprAST> ParseIfExpr() {
Sean Silvad7fb3962012-12-05 00:26:32 +0000114 getNextToken(); // eat the if.
115
116 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000117 auto Cond = ParseExpression();
118 if (!Cond) return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000119
120 if (CurTok != tok_then)
121 return Error("expected then");
122 getNextToken(); // eat the then
123
Lang Hames09bf4c12015-08-18 18:11:06 +0000124 auto Then = ParseExpression();
125 if (Then) return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000126
127 if (CurTok != tok_else)
128 return Error("expected else");
129
130 getNextToken();
131
Lang Hames09bf4c12015-08-18 18:11:06 +0000132 auto Else = ParseExpression();
133 if (!Else) return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000134
Lang Hames09bf4c12015-08-18 18:11:06 +0000135 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
136 std::move(Else));
Sean Silvad7fb3962012-12-05 00:26:32 +0000137 }
138
139Next we hook it up as a primary expression:
140
141.. code-block:: c++
142
Lang Hames09bf4c12015-08-18 18:11:06 +0000143 static std::unique_ptr<ExprAST> ParsePrimary() {
Sean Silvad7fb3962012-12-05 00:26:32 +0000144 switch (CurTok) {
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();
150 }
151 }
152
153LLVM IR for If/Then/Else
154------------------------
155
156Now that we have it parsing and building the AST, the final piece is
157adding LLVM code generation support. This is the most interesting part
158of the if/then/else example, because this is where it starts to
159introduce new concepts. All of the code above has been thoroughly
160described in previous chapters.
161
162To motivate the code we want to produce, lets take a look at a simple
163example. Consider:
164
165::
166
167 extern foo();
168 extern bar();
169 def baz(x) if x then foo() else bar();
170
171If you disable optimizations, the code you'll (soon) get from
172Kaleidoscope looks like this:
173
174.. code-block:: llvm
175
176 declare double @foo()
177
178 declare double @bar()
179
180 define double @baz(double %x) {
181 entry:
182 %ifcond = fcmp one double %x, 0.000000e+00
183 br i1 %ifcond, label %then, label %else
184
185 then: ; preds = %entry
186 %calltmp = call double @foo()
187 br label %ifcont
188
189 else: ; preds = %entry
190 %calltmp1 = call double @bar()
191 br label %ifcont
192
193 ifcont: ; preds = %else, %then
194 %iftmp = phi double [ %calltmp, %then ], [ %calltmp1, %else ]
195 ret double %iftmp
196 }
197
198To visualize the control flow graph, you can use a nifty feature of the
199LLVM '`opt <http://llvm.org/cmds/opt.html>`_' tool. If you put this LLVM
200IR into "t.ll" and run "``llvm-as < t.ll | opt -analyze -view-cfg``", `a
201window will pop up <../ProgrammersManual.html#ViewGraph>`_ and you'll
202see this graph:
203
204.. figure:: LangImpl5-cfg.png
205 :align: center
206 :alt: Example CFG
207
208 Example CFG
209
210Another way to get this is to call "``F->viewCFG()``" or
211"``F->viewCFGOnly()``" (where F is a "``Function*``") either by
212inserting actual calls into the code and recompiling or by calling these
213in the debugger. LLVM has many nice features for visualizing various
214graphs.
215
216Getting back to the generated code, it is fairly simple: the entry block
217evaluates the conditional expression ("x" in our case here) and compares
218the result to 0.0 with the "``fcmp one``" instruction ('one' is "Ordered
219and Not Equal"). Based on the result of this expression, the code jumps
220to either the "then" or "else" blocks, which contain the expressions for
221the true/false cases.
222
223Once the then/else blocks are finished executing, they both branch back
224to the 'ifcont' block to execute the code that happens after the
225if/then/else. In this case the only thing left to do is to return to the
226caller of the function. The question then becomes: how does the code
227know which expression to return?
228
229The answer to this question involves an important SSA operation: the
230`Phi
231operation <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
232If you're not familiar with SSA, `the wikipedia
233article <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
234is a good introduction and there are various other introductions to it
235available on your favorite search engine. The short version is that
236"execution" of the Phi operation requires "remembering" which block
237control came from. The Phi operation takes on the value corresponding to
238the 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".
241
242At this point, you are probably starting to think "Oh no! This means my
243simple and elegant front-end will have to start generating SSA form in
244order to use LLVM!". Fortunately, this is not the case, and we strongly
245advise *not* implementing an SSA construction algorithm in your
246front-end unless there is an amazingly good reason to do so. In
247practice, there are two sorts of values that float around in code
248written for your average imperative programming language that might need
249Phi nodes:
250
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.
254
255In `Chapter 7 <LangImpl7.html>`_ of this tutorial ("mutable variables"),
256we'll talk about #1 in depth. For now, just believe me that you don't
257need SSA construction to handle this case. For #2, you have the choice
258of using the techniques that we will describe for #1, or you can insert
Ed Maste8ed40ce2015-04-14 20:52:58 +0000259Phi nodes directly, if convenient. In this case, it is really
Sean Silvad7fb3962012-12-05 00:26:32 +0000260easy to generate the Phi node, so we choose to do it directly.
261
262Okay, enough of the motivation and overview, lets generate code!
263
264Code Generation for If/Then/Else
265--------------------------------
266
267In order to generate code for this, we implement the ``Codegen`` method
268for ``IfExprAST``:
269
270.. code-block:: c++
271
272 Value *IfExprAST::Codegen() {
273 Value *CondV = Cond->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000274 if (!CondV) return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000275
276 // Convert condition to a bool by comparing equal to 0.0.
277 CondV = Builder.CreateFCmpONE(CondV,
278 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
279 "ifcond");
280
281This code is straightforward and similar to what we saw before. We emit
282the expression for the condition, then compare that value to zero to get
283a truth value as a 1-bit (bool) value.
284
285.. code-block:: c++
286
287 Function *TheFunction = Builder.GetInsertBlock()->getParent();
288
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");
294
295 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
296
297This code creates the basic blocks that are related to the if/then/else
298statement, and correspond directly to the blocks in the example above.
299The first line gets the current Function object that is being built. It
300gets this by asking the builder for the current BasicBlock, and asking
301that block for its "parent" (the function it is currently embedded
302into).
303
304Once it has that, it creates three blocks. Note that it passes
305"TheFunction" into the constructor for the "then" block. This causes the
306constructor to automatically insert the new block into the end of the
307specified function. The other two blocks are created, but aren't yet
308inserted into the function.
309
310Once the blocks are created, we can emit the conditional branch that
311chooses between them. Note that creating new blocks does not implicitly
312affect the IRBuilder, so it is still inserting into the block that the
313condition 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
315inserted into the function yet. This is all ok: it is the standard way
316that LLVM supports forward references.
317
318.. code-block:: c++
319
320 // Emit then value.
321 Builder.SetInsertPoint(ThenBB);
322
323 Value *ThenV = Then->Codegen();
324 if (ThenV == 0) return 0;
325
326 Builder.CreateBr(MergeBB);
327 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
328 ThenBB = Builder.GetInsertBlock();
329
330After the conditional branch is inserted, we move the builder to start
331inserting into the "then" block. Strictly speaking, this call moves the
332insertion point to be at the end of the specified block. However, since
333the "then" block is empty, it also starts out by inserting at the
334beginning of the block. :)
335
336Once the insertion point is set, we recursively codegen the "then"
337expression from the AST. To finish off the "then" block, we create an
338unconditional branch to the merge block. One interesting (and very
339important) aspect of the LLVM IR is that it `requires all basic blocks
340to be "terminated" <../LangRef.html#functionstructure>`_ with a `control
341flow instruction <../LangRef.html#terminators>`_ such as return or
342branch. This means that all control flow, *including fall throughs* must
343be made explicit in the LLVM IR. If you violate this rule, the verifier
344will emit an error.
345
346The final line here is quite subtle, but is very important. The basic
347issue is that when we create the Phi node in the merge block, we need to
348set up the block/value pairs that indicate how the Phi will work.
349Importantly, the Phi node expects to have an entry for each predecessor
350of the block in the CFG. Why then, are we getting the current block when
351we just set it to ThenBB 5 lines above? The problem is that the "Then"
352expression may actually itself change the block that the Builder is
353emitting into if, for example, it contains a nested "if/then/else"
354expression. Because calling Codegen recursively could arbitrarily change
355the notion of the current block, we are required to get an up-to-date
356value for code that will set up the Phi node.
357
358.. code-block:: c++
359
360 // Emit else block.
361 TheFunction->getBasicBlockList().push_back(ElseBB);
362 Builder.SetInsertPoint(ElseBB);
363
364 Value *ElseV = Else->Codegen();
365 if (ElseV == 0) return 0;
366
367 Builder.CreateBr(MergeBB);
368 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
369 ElseBB = Builder.GetInsertBlock();
370
371Code generation for the 'else' block is basically identical to codegen
372for the 'then' block. The only significant difference is the first line,
373which 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
376code:
377
378.. code-block:: c++
379
380 // Emit merge block.
381 TheFunction->getBasicBlockList().push_back(MergeBB);
382 Builder.SetInsertPoint(MergeBB);
383 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
384 "iftmp");
385
386 PN->addIncoming(ThenV, ThenBB);
387 PN->addIncoming(ElseV, ElseBB);
388 return PN;
389 }
390
391The first two lines here are now familiar: the first adds the "merge"
392block to the Function object (it was previously floating, like the else
Sean Silvafb8908c2015-03-31 22:48:45 +0000393block above). The second changes the insertion point so that newly
Sean Silvad7fb3962012-12-05 00:26:32 +0000394created code will go into the "merge" block. Once that is done, we need
395to create the PHI node and set up the block/value pairs for the PHI.
396
397Finally, the CodeGen function returns the phi node as the value computed
398by the if/then/else expression. In our example above, this returned
399value will feed into the code for the top-level function, which will
400create the return instruction.
401
402Overall, we now have the ability to execute conditional code in
403Kaleidoscope. With this extension, Kaleidoscope is a fairly complete
404language that can calculate a wide variety of numeric functions. Next up
405we'll add another useful expression that is familiar from non-functional
406languages...
407
408'for' Loop Expression
409=====================
410
411Now that we know how to add basic control flow constructs to the
412language, we have the tools to add more powerful things. Lets add
413something more aggressive, a 'for' expression:
414
415::
416
417 extern putchard(char)
418 def printstar(n)
419 for i = 1, i < n, 1.0 in
420 putchard(42); # ascii 42 = '*'
421
422 # print 100 '*' characters
423 printstar(100);
424
425This expression defines a new variable ("i" in this case) which iterates
426from a starting value, while the condition ("i < n" in this case) is
427true, incrementing by an optional step value ("1.0" in this case). If
428the step value is omitted, it defaults to 1.0. While the loop is true,
429it executes its body expression. Because we don't have anything better
430to return, we'll just define the loop as always returning 0.0. In the
431future when we have mutable variables, it will get more useful.
432
433As before, lets talk about the changes that we need to Kaleidoscope to
434support this.
435
436Lexer Extensions for the 'for' Loop
437-----------------------------------
438
439The lexer extensions are the same sort of thing as for if/then/else:
440
441.. code-block:: c++
442
443 ... in enum Token ...
444 // control
445 tok_if = -6, tok_then = -7, tok_else = -8,
446 tok_for = -9, tok_in = -10
447
448 ... in gettok ...
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;
457
458AST Extensions for the 'for' Loop
459---------------------------------
460
461The AST node is just as simple. It basically boils down to capturing the
462variable name and the constituent expressions in the node.
463
464.. code-block:: c++
465
466 /// ForExprAST - Expression class for for/in.
467 class ForExprAST : public ExprAST {
468 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000469 std::unique_ptr<ExprAST> Start, End, Step, Body;
Sean Silvad7fb3962012-12-05 00:26:32 +0000470 public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000471 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)) {}
Sean Silvad7fb3962012-12-05 00:26:32 +0000476 virtual Value *Codegen();
477 };
478
479Parser Extensions for the 'for' Loop
480------------------------------------
481
482The parser code is also fairly standard. The only interesting thing here
483is handling of the optional step value. The parser code handles it by
484checking to see if the second comma is present. If not, it sets the step
485value to null in the AST node:
486
487.. code-block:: c++
488
489 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000490 static std::unique_ptr<ExprAST> ParseForExpr() {
Sean Silvad7fb3962012-12-05 00:26:32 +0000491 getNextToken(); // eat the for.
492
493 if (CurTok != tok_identifier)
494 return Error("expected identifier after for");
495
496 std::string IdName = IdentifierStr;
497 getNextToken(); // eat identifier.
498
499 if (CurTok != '=')
500 return Error("expected '=' after for");
501 getNextToken(); // eat '='.
502
503
Lang Hames09bf4c12015-08-18 18:11:06 +0000504 auto Start = ParseExpression();
505 if (!Start) return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000506 if (CurTok != ',')
507 return Error("expected ',' after for start value");
508 getNextToken();
509
Lang Hames09bf4c12015-08-18 18:11:06 +0000510 auto End = ParseExpression();
511 if (!End) return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000512
513 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000514 std::unique_ptr<ExprAST> Step;
Sean Silvad7fb3962012-12-05 00:26:32 +0000515 if (CurTok == ',') {
516 getNextToken();
517 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000518 if (!Step) return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000519 }
520
521 if (CurTok != tok_in)
522 return Error("expected 'in' after for");
523 getNextToken(); // eat 'in'.
524
Lang Hames09bf4c12015-08-18 18:11:06 +0000525 auto Body = ParseExpression();
526 if (!Body) return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000527
Lang Hames09bf4c12015-08-18 18:11:06 +0000528 return llvm::make_unique<ForExprAST>(IdName, std::move(Start),
529 std::move(End), std::move(Step),
530 std::move(Body));
Sean Silvad7fb3962012-12-05 00:26:32 +0000531 }
532
533LLVM IR for the 'for' Loop
534--------------------------
535
536Now we get to the good part: the LLVM IR we want to generate for this
537thing. With the simple example above, we get this LLVM IR (note that
538this dump is generated with optimizations disabled for clarity):
539
540.. code-block:: llvm
541
542 declare double @putchard(double)
543
544 define double @printstar(double %n) {
545 entry:
546 ; initial value = 1.0 (inlined into phi)
547 br label %loop
548
549 loop: ; preds = %loop, %entry
550 %i = phi double [ 1.000000e+00, %entry ], [ %nextvar, %loop ]
551 ; body
552 %calltmp = call double @putchard(double 4.200000e+01)
553 ; increment
554 %nextvar = fadd double %i, 1.000000e+00
555
556 ; termination test
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
561
562 afterloop: ; preds = %loop
563 ; loop always returns 0.0
564 ret double 0.000000e+00
565 }
566
567This loop contains all the same constructs we saw before: a phi node,
568several expressions, and some basic blocks. Lets see how this fits
569together.
570
571Code Generation for the 'for' Loop
572----------------------------------
573
574The first part of Codegen is very simple: we just output the start
575expression for the loop value:
576
577.. code-block:: c++
578
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;
583
584With this out of the way, the next step is to set up the LLVM basic
585block for the start of the loop body. In the case above, the whole loop
586body is one block, but remember that the body code itself could consist
587of multiple blocks (e.g. if it contains an if/then/else or a for/in
588expression).
589
590.. code-block:: c++
591
592 // Make the new basic block for the loop header, inserting after current
593 // block.
594 Function *TheFunction = Builder.GetInsertBlock()->getParent();
595 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
596 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
597
598 // Insert an explicit fall through from the current block to the LoopBB.
599 Builder.CreateBr(LoopBB);
600
601This code is similar to what we saw for if/then/else. Because we will
602need it to create the Phi node, we remember the block that falls through
603into the loop. Once we have that, we create the actual block that starts
604the loop and create an unconditional branch for the fall-through between
605the two blocks.
606
607.. code-block:: c++
608
609 // Start insertion in LoopBB.
610 Builder.SetInsertPoint(LoopBB);
611
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);
615
616Now that the "preheader" for the loop is set up, we switch to emitting
617code for the loop body. To begin with, we move the insertion point and
618create the PHI node for the loop induction variable. Since we already
619know the incoming value for the starting value, we add it to the Phi
620node. Note that the Phi will eventually get a second value for the
621backedge, but we can't set it up yet (because it doesn't exist!).
622
623.. code-block:: c++
624
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;
629
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
632 // allow an error.
633 if (Body->Codegen() == 0)
634 return 0;
635
636Now the code starts to get more interesting. Our 'for' loop introduces a
637new variable to the symbol table. This means that our symbol table can
638now contain either function arguments or loop variables. To handle this,
639before we codegen the body of the loop, we add the loop variable as the
640current value for its name. Note that it is possible that there is a
641variable of the same name in the outer scope. It would be easy to make
642this an error (emit an error and return null if there is already an
643entry for VarName) but we choose to allow shadowing of variables. In
644order to handle this correctly, we remember the Value that we are
645potentially shadowing in ``OldVal`` (which will be null if there is no
646shadowed variable).
647
648Once the loop variable is set into the symbol table, the code
649recursively codegen's the body. This allows the body to use the loop
650variable: any references to it will naturally find it in the symbol
651table.
652
653.. code-block:: c++
654
655 // Emit the step value.
656 Value *StepVal;
657 if (Step) {
658 StepVal = Step->Codegen();
659 if (StepVal == 0) return 0;
660 } else {
661 // If not specified, use 1.0.
662 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
663 }
664
665 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
666
667Now that the body is emitted, we compute the next value of the iteration
668variable 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
670iteration of the loop.
671
672.. code-block:: c++
673
674 // Compute the end condition.
675 Value *EndCond = End->Codegen();
676 if (EndCond == 0) return EndCond;
677
678 // Convert condition to a bool by comparing equal to 0.0.
679 EndCond = Builder.CreateFCmpONE(EndCond,
680 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
681 "loopcond");
682
683Finally, we evaluate the exit value of the loop, to determine whether
684the loop should exit. This mirrors the condition evaluation for the
685if/then/else statement.
686
687.. code-block:: c++
688
689 // Create the "after loop" block and insert it.
690 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
691 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
692
693 // Insert the conditional branch into the end of LoopEndBB.
694 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
695
696 // Any new code will be inserted in AfterBB.
697 Builder.SetInsertPoint(AfterBB);
698
699With the code for the body of the loop complete, we just need to finish
700up the control flow for it. This code remembers the end block (for the
701phi node), then creates the block for the loop exit ("afterloop"). Based
702on the value of the exit condition, it creates a conditional branch that
703chooses between executing the loop again and exiting the loop. Any
704future code is emitted in the "afterloop" block, so it sets the
705insertion position to it.
706
707.. code-block:: c++
708
709 // Add a new entry to the PHI node for the backedge.
710 Variable->addIncoming(NextVar, LoopEndBB);
711
712 // Restore the unshadowed variable.
713 if (OldVal)
714 NamedValues[VarName] = OldVal;
715 else
716 NamedValues.erase(VarName);
717
718 // for expr always returns 0.0.
719 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
720 }
721
722The final code handles various cleanups: now that we have the "NextVar"
723value, we can add the incoming value to the loop PHI node. After that,
724we remove the loop variable from the symbol table, so that it isn't in
725scope after the for loop. Finally, code generation of the for loop
726always returns 0.0, so that is what we return from
727``ForExprAST::Codegen``.
728
729With this, we conclude the "adding control flow to Kaleidoscope" chapter
730of the tutorial. In this chapter we added two control flow constructs,
731and used them to motivate a couple of aspects of the LLVM IR that are
732important for front-end implementors to know. In the next chapter of our
733saga, we will get a bit crazier and add `user-defined
734operators <LangImpl6.html>`_ to our poor innocent language.
735
736Full Code Listing
737=================
738
739Here is the complete code listing for our running example, enhanced with
740the if/then/else and for expressions.. To build this example, use:
741
742.. code-block:: bash
743
744 # Compile
Eric Christophera8c6a0a2015-01-08 19:07:01 +0000745 clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy
Sean Silvad7fb3962012-12-05 00:26:32 +0000746 # Run
747 ./toy
748
749Here is the code:
750
Logan Chien855b17d2013-06-08 09:03:03 +0000751.. literalinclude:: ../../examples/Kaleidoscope/Chapter5/toy.cpp
752 :language: c++
Sean Silvad7fb3962012-12-05 00:26:32 +0000753
754`Next: Extending the language: user-defined operators <LangImpl6.html>`_
755