<div class="doc_title">Kaleidoscope: Extending the Language: Mutable Variables</div>
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 7
+ <ol>
+ <li><a href="#intro">Chapter 7 Introduction</a></li>
+ <li><a href="#why">Why is this a hard problem?</a></li>
+ <li><a href="#memory">Memory in LLVM</a></li>
+ <li><a href="#kalvars">Mutable Variables in Kaleidoscope</a></li>
+ <li><a href="#adjustments">Adjusting Existing Variables for
+ Mutation</a></li>
+ <li><a href="#assignment">New Assignment Operator</a></li>
+ <li><a href="#localvars">User-defined Local Variables</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="LangImpl8.html">Chapter 8</a>: Conclusion and other useful LLVM
+ tidbits</li>
+</ul>
+
<div class="doc_author">
<p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
</div>
<!-- *********************************************************************** -->
-<div class="doc_section"><a name="intro">Part 7 Introduction</a></div>
+<div class="doc_section"><a name="intro">Chapter 7 Introduction</a></div>
<!-- *********************************************************************** -->
<div class="doc_text">
-<p>Welcome to Part 7 of the "<a href="index.html">Implementing a language with
-LLVM</a>" tutorial. In parts 1 through 6, we've built a very respectable,
-albeit simple, <a
+<p>Welcome to Chapter 7 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. In chapters 1 through 6, we've built a very
+respectable, albeit simple, <a
href="http://en.wikipedia.org/wiki/Functional_programming">functional
programming language</a>. In our journey, we learned some parsing techniques,
how to build and represent an AST, how to build LLVM IR, and how to optimize
-the resultant code and JIT compile it.</p>
+the resultant code as well as JIT compile it.</p>
-<p>While Kaleidoscope is interesting as a functional language, this makes it
-"too easy" to generate LLVM IR for it. In particular, a functional language
-makes it very easy to build LLVM IR directly in <a
+<p>While Kaleidoscope is interesting as a functional language, the fact that it
+is functional makes it "too easy" to generate LLVM IR for it. In particular, a
+functional language makes it very easy to build LLVM IR directly in <a
href="http://en.wikipedia.org/wiki/Static_single_assignment_form">SSA form</a>.
Since LLVM requires that the input code be in SSA form, this is a very nice
property and it is often unclear to newcomers how to generate code for an
(cond_true/cond_false). In order to merge the incoming values, the X.2 phi node
in the cond_next block selects the right value to use based on where control
flow is coming from: if control flow comes from the cond_false block, X.2 gets
-the value of X.1. Alternatively, if control flow comes from cond_tree, it gets
+the value of X.1. Alternatively, if control flow comes from cond_true, it gets
the value of X.0. The intent of this chapter is not to explain the details of
SSA form. For more information, see one of the many <a
href="http://en.wikipedia.org/wiki/Static_single_assignment_form">online
references</a>.</p>
-<p>The question for this article is "who places phi nodes when lowering
+<p>The question for this article is "who places the phi nodes when lowering
assignments to mutable variables?". The issue here is that LLVM
<em>requires</em> that its IR be in SSA form: there is no "non-ssa" mode for it.
However, SSA construction requires non-trivial algorithms and data structures,
</p>
<p>In LLVM, all memory accesses are explicit with load/store instructions, and
-it is carefully designed to not have (or need) an "address-of" operator. Notice
+it is carefully designed not to have (or need) an "address-of" operator. Notice
how the type of the @G/@H global variables is actually "i32*" even though the
variable is defined as "i32". What this means is that @G defines <em>space</em>
for an i32 in the global data area, but its <em>name</em> actually refers to the
-address for that space. Stack variables work the same way, but instead of being
-declared with global variable definitions, they are declared with the
+address for that space. Stack variables work the same way, except that instead of
+being declared with global variable definitions, they are declared with the
<a href="../LangRef.html#i_alloca">LLVM alloca instruction</a>:</p>
<div class="doc_code">
<pre>
-define i32 @test(i1 %Condition) {
+define i32 @example() {
entry:
%X = alloca i32 ; type of %X is i32*.
...
</pre>
</div>
-<p>The mem2reg pass implements the standard "iterated dominator frontier"
+<p>The mem2reg pass implements the standard "iterated dominance frontier"
algorithm for constructing SSA form and has a number of optimizations that speed
-up very common degenerate cases. mem2reg really is the answer for dealing with
-mutable variables, and we highly recommend that you depend on it. Note that
+up (very common) degenerate cases. The mem2reg optimization pass is the answer to dealing
+with mutable variables, and we highly recommend that you depend on it. Note that
mem2reg only works on variables in certain circumstances:</p>
<ol>
<p>
All of these properties are easy to satisfy for most imperative languages, and
-we'll illustrate this below with Kaleidoscope. The final question you may be
+we'll illustrate it below with Kaleidoscope. The final question you may be
asking is: should I bother with this nonsense for my front-end? Wouldn't it be
better if I just did SSA construction directly, avoiding use of the mem2reg
-optimization pass? In short, we strongly recommend that use you this technique
+optimization pass? In short, we strongly recommend that you use this technique
for building SSA form, unless there is an extremely good reason not to. Using
this technique is:</p>
<li>Needed for debug info generation: <a href="../SourceLevelDebugging.html">
Debug information in LLVM</a> relies on having the address of the variable
-exposed to attach debug info to it. This technique dovetails very naturally
-with this style of debug info.</li>
+exposed so that debug info can be attached to it. This technique dovetails
+very naturally with this style of debug info.</li>
</ul>
<p>If nothing else, this makes it much easier to get your front-end up and
</ol>
<p>While the first item is really what this is about, we only have variables
-for incoming arguments and for induction variables, and redefining them only
+for incoming arguments as well as for induction variables, and redefining those only
goes so far :). Also, the ability to define new variables is a
useful thing regardless of whether you will be mutating them. Here's a
motivating example that shows how we could use these:</p>
# Iterative fib.
def fibi(x)
<b>var a = 1, b = 1, c in</b>
- (for i = 3, i &;t; x in
+ (for i = 3, i < x in
<b>c = a + b</b> :
<b>a = b</b> :
<b>b = c</b>) :
</p>
<p>To start our transformation of Kaleidoscope, we'll change the NamedValues
-map to map to AllocaInst* instead of Value*. Once we do this, the C++ compiler
-will tell use what parts of the code we need to update:</p>
+map so that it maps to AllocaInst* instead of Value*. Once we do this, the C++
+compiler will tell us what parts of the code we need to update:</p>
<div class="doc_code">
<pre>
/// the function. This is used for mutable variables etc.
static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
const std::string &VarName) {
- LLVMBuilder TmpB(&TheFunction->getEntryBlock(),
- TheFunction->getEntryBlock().begin());
+ IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
+ TheFunction->getEntryBlock().begin());
return TmpB.CreateAlloca(Type::DoubleTy, 0, VarName.c_str());
}
</pre>
</div>
-<p>This funny looking code creates an LLVMBuilder object that is pointing at
+<p>This funny looking code creates an IRBuilder object that is pointing at
the first instruction (.begin()) of the entry block. It then creates an alloca
with the expected name and returns it. Because all values in Kaleidoscope are
doubles, there is no need to pass in a type to use.</p>
Value *V = NamedValues[Name];
if (V == 0) return ErrorV("Unknown variable name");
- // Load the value.
- return Builder.CreateLoad(V, Name.c_str());
+ <b>// Load the value.
+ return Builder.CreateLoad(V, Name.c_str());</b>
}
</pre>
</div>
-<p>As you can see, this is pretty straight-forward. Next we need to update the
+<p>As you can see, this is pretty straightforward. Now we need to update the
things that define the variables to set up the alloca. We'll start with
<tt>ForExprAST::Codegen</tt> (see the <a href="#code">full code listing</a> for
the unabridged code):</p>
argument. This method gets invoked by <tt>FunctionAST::Codegen</tt> right after
it sets up the entry block for the function.</p>
-<p>The final missing piece is adding the 'mem2reg' pass, which allows us to get
+<p>The final missing piece is adding the mem2reg pass, which allows us to get
good codegen once again:</p>
<div class="doc_code">
<p>It is interesting to see what the code looks like before and after the
mem2reg optimization runs. For example, this is the before/after code for our
-recursive fib. Before the optimization:</p>
+recursive fib function. Before the optimization:</p>
<div class="doc_code">
<pre>
<b>%x1 = alloca double
store double %x, double* %x1
%x2 = load double* %x1</b>
- %multmp = fcmp ult double %x2, 3.000000e+00
- %booltmp = uitofp i1 %multmp to double
+ %cmptmp = fcmp ult double %x2, 3.000000e+00
+ %booltmp = uitofp i1 %cmptmp to double
%ifcond = fcmp one double %booltmp, 0.000000e+00
br i1 %ifcond, label %then, label %else
<pre>
define double @fib(double %x) {
entry:
- %multmp = fcmp ult double <b>%x</b>, 3.000000e+00
- %booltmp = uitofp i1 %multmp to double
+ %cmptmp = fcmp ult double <b>%x</b>, 3.000000e+00
+ %booltmp = uitofp i1 %cmptmp to double
%ifcond = fcmp one double %booltmp, 0.000000e+00
br i1 %ifcond, label %then, label %else
<pre>
define double @fib(double %x) {
entry:
- %multmp = fcmp ult double %x, 3.000000e+00
- %booltmp = uitofp i1 %multmp to double
+ %cmptmp = fcmp ult double %x, 3.000000e+00
+ %booltmp = uitofp i1 %cmptmp to double
%ifcond = fcmp ueq double %booltmp, 0.000000e+00
br i1 %ifcond, label %else, label %ifcont
<p>Unlike the rest of the binary operators, our assignment operator doesn't
follow the "emit LHS, emit RHS, do computation" model. As such, it is handled
as a special case before the other binary operators are handled. The other
-strange thing about it is that it requires the LHS to be a variable directly.
+strange thing is that it requires the LHS to be a variable. It is invalid to
+have "(x+1) = expr" - only things like "x = expr" are allowed.
</p>
<div class="doc_code">
</pre>
</div>
-<p>Once it has the variable, codegen'ing the assignment is straight-forward:
+<p>Once we have the variable, codegen'ing the assignment is straightforward:
we emit the RHS of the assignment, create a store, and return the computed
value. Returning a value allows for chained assignments like "X = (Y = Z)".</p>
</div>
<p>The next step is to define the AST node that we will construct. For var/in,
-it will look like this:</p>
+it looks like this:</p>
<div class="doc_code">
<pre>
<p>var/in allows a list of names to be defined all at once, and each name can
optionally have an initializer value. As such, we capture this information in
the VarNames vector. Also, var/in has a body, this body is allowed to access
-the variables defined by the let/in.</p>
+the variables defined by the var/in.</p>
-<p>With this ready, we can define the parser pieces. First thing we do is add
+<p>With this in place, we can define the parser pieces. The first thing we do is add
it as a primary expression:</p>
<div class="doc_code">
<div class="doc_code">
<pre>
-/// varexpr ::= 'var' identifer ('=' expression)?
-// (',' identifer ('=' expression)?)* 'in' expression
+/// varexpr ::= 'var' identifier ('=' expression)?
+// (',' identifier ('=' expression)?)* 'in' expression
static ExprAST *ParseVarExpr() {
getNextToken(); // eat the var.
<pre>
while (1) {
std::string Name = IdentifierStr;
- getNextToken(); // eat identifer.
+ getNextToken(); // eat identifier.
// Read the optional initializer.
ExprAST *Init = 0;
InitVal = Init->Codegen();
if (InitVal == 0) return 0;
} else { // If not specified, use 0.0.
- InitVal = ConstantFP::get(Type::DoubleTy, APFloat(0.0));
+ InitVal = ConstantFP::get(APFloat(0.0));
}
AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
<p>With this, we completed what we set out to do. Our nice iterative fib
example from the intro compiles and runs just fine. The mem2reg pass optimizes
all of our stack variables into SSA registers, inserting PHI nodes where needed,
-and our front-end remains simple: no iterated dominator frontier computation
+and our front-end remains simple: no "iterated dominance frontier" computation
anywhere in sight.</p>
</div>
<pre>
#include "llvm/DerivedTypes.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/ModuleProvider.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Scalar.h"
-#include "llvm/Support/LLVMBuilder.h"
+#include "llvm/Support/IRBuilder.h"
#include <cstdio>
#include <string>
#include <map>
if (LastChar == '#') {
// Comment until end of line.
do LastChar = getchar();
- while (LastChar != EOF && LastChar != '\n' & LastChar != '\r');
+ while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF)
return gettok();
static ExprAST *ParseExpression();
/// identifierexpr
-/// ::= identifer
-/// ::= identifer '(' expression* ')'
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
static ExprAST *ParseIdentifierExpr() {
std::string IdName = IdentifierStr;
- getNextToken(); // eat identifer.
+ getNextToken(); // eat identifier.
if (CurTok != '(') // Simple variable ref.
return new VariableExprAST(IdName);
if (CurTok == ')') break;
if (CurTok != ',')
- return Error("Expected ')'");
+ return Error("Expected ')' or ',' in argument list");
getNextToken();
}
}
return new IfExprAST(Cond, Then, Else);
}
-/// forexpr ::= 'for' identifer '=' expr ',' expr (',' expr)? 'in' expression
+/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
static ExprAST *ParseForExpr() {
getNextToken(); // eat the for.
return Error("expected identifier after for");
std::string IdName = IdentifierStr;
- getNextToken(); // eat identifer.
+ getNextToken(); // eat identifier.
if (CurTok != '=')
return Error("expected '=' after for");
return new ForExprAST(IdName, Start, End, Step, Body);
}
-/// varexpr ::= 'var' identifer ('=' expression)?
-// (',' identifer ('=' expression)?)* 'in' expression
+/// varexpr ::= 'var' identifier ('=' expression)?
+// (',' identifier ('=' expression)?)* 'in' expression
static ExprAST *ParseVarExpr() {
getNextToken(); // eat the var.
while (1) {
std::string Name = IdentifierStr;
- getNextToken(); // eat identifer.
+ getNextToken(); // eat identifier.
// Read the optional initializer.
ExprAST *Init = 0;
//===----------------------------------------------------------------------===//
static Module *TheModule;
-static LLVMFoldingBuilder Builder;
+static IRBuilder<> Builder(getGlobalContext());
static std::map<std::string, AllocaInst*> NamedValues;
static FunctionPassManager *TheFPM;
/// the function. This is used for mutable variables etc.
static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
const std::string &VarName) {
- LLVMBuilder TmpB(&TheFunction->getEntryBlock(),
- TheFunction->getEntryBlock().begin());
+ IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
+ TheFunction->getEntryBlock().begin());
return TmpB.CreateAlloca(Type::DoubleTy, 0, VarName.c_str());
}
Value *NumberExprAST::Codegen() {
- return ConstantFP::get(Type::DoubleTy, APFloat(Val));
+ return ConstantFP::get(APFloat(Val));
}
Value *VariableExprAST::Codegen() {
case '-': return Builder.CreateSub(L, R, "subtmp");
case '*': return Builder.CreateMul(L, R, "multmp");
case '<':
- L = Builder.CreateFCmpULT(L, R, "multmp");
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
// Convert bool 0/1 to double 0.0 or 1.0
return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
default: break;
// Convert condition to a bool by comparing equal to 0.0.
CondV = Builder.CreateFCmpONE(CondV,
- ConstantFP::get(Type::DoubleTy, APFloat(0.0)),
+ ConstantFP::get(APFloat(0.0)),
"ifcond");
Function *TheFunction = Builder.GetInsertBlock()->getParent();
// Create blocks for the then and else cases. Insert the 'then' block at the
// end of the function.
- BasicBlock *ThenBB = new BasicBlock("then", TheFunction);
- BasicBlock *ElseBB = new BasicBlock("else");
- BasicBlock *MergeBB = new BasicBlock("ifcont");
+ BasicBlock *ThenBB = BasicBlock::Create("then", TheFunction);
+ BasicBlock *ElseBB = BasicBlock::Create("else");
+ BasicBlock *MergeBB = BasicBlock::Create("ifcont");
Builder.CreateCondBr(CondV, ThenBB, ElseBB);
// Make the new basic block for the loop header, inserting after current
// block.
BasicBlock *PreheaderBB = Builder.GetInsertBlock();
- BasicBlock *LoopBB = new BasicBlock("loop", TheFunction);
+ BasicBlock *LoopBB = BasicBlock::Create("loop", TheFunction);
// Insert an explicit fall through from the current block to the LoopBB.
Builder.CreateBr(LoopBB);
if (StepVal == 0) return 0;
} else {
// If not specified, use 1.0.
- StepVal = ConstantFP::get(Type::DoubleTy, APFloat(1.0));
+ StepVal = ConstantFP::get(APFloat(1.0));
}
// Compute the end condition.
// Convert condition to a bool by comparing equal to 0.0.
EndCond = Builder.CreateFCmpONE(EndCond,
- ConstantFP::get(Type::DoubleTy, APFloat(0.0)),
+ ConstantFP::get(APFloat(0.0)),
"loopcond");
// Create the "after loop" block and insert it.
BasicBlock *LoopEndBB = Builder.GetInsertBlock();
- BasicBlock *AfterBB = new BasicBlock("afterloop", TheFunction);
+ BasicBlock *AfterBB = BasicBlock::Create("afterloop", TheFunction);
// Insert the conditional branch into the end of LoopEndBB.
Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
InitVal = Init->Codegen();
if (InitVal == 0) return 0;
} else { // If not specified, use 0.0.
- InitVal = ConstantFP::get(Type::DoubleTy, APFloat(0.0));
+ InitVal = ConstantFP::get(APFloat(0.0));
}
AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
std::vector<const Type*> Doubles(Args.size(), Type::DoubleTy);
FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
- Function *F = new Function(FT, Function::ExternalLinkage, Name, TheModule);
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
// If F conflicted, there was already something named 'Name'. If it has a
// body, don't allow redefinition or reextern.
BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
// Create a new basic block to start insertion into.
- BasicBlock *BB = new BasicBlock("entry", TheFunction);
+ BasicBlock *BB = BasicBlock::Create("entry", TheFunction);
Builder.SetInsertPoint(BB);
// Add all arguments to the symbol table and create their allocas.
getNextToken();
// Make the module, which holds all the code.
- TheModule = new Module("my cool jit");
+ TheModule = new Module("my cool jit", getGlobalContext());
// Create the JIT.
TheExecutionEngine = ExecutionEngine::create(TheModule);
MainLoop();
TheFPM = 0;
- } // Free module provider and pass manager.
-
-
- // Print out all of the generated code.
- TheModule->dump();
+
+ // Print out all of the generated code.
+ TheModule->dump();
+
+ } // Free module provider (and thus the module) and pass manager.
+
return 0;
}
</pre>
</div>
+<a href="LangImpl8.html">Next: Conclusion and other useful LLVM tidbits</a>
</div>
<!-- *********************************************************************** -->