1 <!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
6 <title>LLVM Tutorial
2: A More Complicated Function
</title>
7 <meta http-equiv=
"Content-Type" content=
"text/html; charset=utf-8">
8 <meta name=
"author" content=
"Owen Anderson">
9 <meta name=
"description"
10 content=
"LLVM Tutorial 2: A More Complicated Function.">
11 <link rel=
"stylesheet" href=
"../llvm.css" type=
"text/css">
16 <div class=
"doc_title"> LLVM Tutorial
2: A More Complicated Function
</div>
18 <div class=
"doc_author">
19 <p>Written by
<a href=
"mailto:owen@apple.com">Owen Anderson
</a></p>
22 <!-- *********************************************************************** -->
23 <div class=
"doc_section"><a name=
"intro">A First Function
</a></div>
24 <!-- *********************************************************************** -->
26 <div class=
"doc_text">
28 <p>Now that we understand the basics of creating functions in LLVM, let's move on to a more complicated example: something with control flow. As an example, let's consider Euclid's Greatest Common Denominator (GCD) algorithm:
</p>
30 <div class=
"doc_code">
32 unsigned gcd(unsigned x, unsigned y) {
44 <p>With this example, we'll learn how to create functions with multiple blocks and control flow, and how to make function calls within your LLVM code. For starters, consider the diagram below.
</p>
46 <div style=
"text-align: center;"><img src=
"JITTutorial2-1.png" alt=
"GCD CFG" width=
"60%"></div>
48 <p>This is a graphical representation of a program in LLVM IR. It places each basic block on a node of a graph and uses directed edges to indicate flow control. These blocks will be serialized when written to a text or bitcode file, but it is often useful conceptually to think of them as a graph. Again, if you are unsure about the code in the diagram, you should skim through the
<a href=
"../LangRef.html">LLVM Language Reference Manual
</a> and convince yourself that it is, in fact, the GCD algorithm.
</p>
50 <p>The first part of our code is practically the same as from the first tutorial. The same basic setup is required: creating a module, verifying it, and running the
<code>PrintModulePass
</code> on it. Even the first segment of
<code>makeLLVMModule()
</code> looks essentially the same, except that
<code>gcd
</code> takes one fewer parameter than
<code>mul_add
</code>.
</p>
52 <div class=
"doc_code">
54 #include
"llvm/Module.h"
55 #include
"llvm/Function.h"
56 #include
"llvm/PassManager.h"
57 #include
"llvm/Analysis/Verifier.h"
58 #include
"llvm/Assembly/PrintModulePass.h"
59 #include
"llvm/Support/IRBuilder.h"
63 Module* makeLLVMModule();
65 int main(int argc, char**argv) {
66 Module* Mod = makeLLVMModule();
68 verifyModule(*Mod, PrintMessageAction);
71 PM.add(createPrintModulePass(
&llvm::cout));
78 Module* makeLLVMModule() {
79 Module* mod = new Module(
"tut2
");
81 Constant* c = mod-
>getOrInsertFunction(
"gcd
",
86 Function* gcd = cast
<Function
>(c);
88 Function::arg_iterator args = gcd-
>arg_begin();
90 x-
>setName(
"x
");
92 y-
>setName(
"y
");
96 <p>Here, however, is where our code begins to diverge from the first tutorial. Because
<code>gcd
</code> has control flow, it is composed of multiple blocks interconnected by branching (
<code>br
</code>) instructions. For those familiar with assembly language, a block is similar to a labeled set of instructions. For those not familiar with assembly language, a block is basically a set of instructions that can be branched to and is executed linearly until the block is terminated by one of a small number of control flow instructions, such as
<code>br
</code> or
<code>ret
</code>.
</p>
98 <p>Blocks correspond to the nodes in the diagram we looked at in the beginning of this tutorial. From the diagram, we can see that this function contains five blocks, so we'll go ahead and create them. Note that we're making use of LLVM's automatic name uniquing in this code sample, since we're giving two blocks the same name.
</p>
100 <div class=
"doc_code">
102 BasicBlock* entry = BasicBlock::Create(
"entry
", gcd);
103 BasicBlock* ret = BasicBlock::Create(
"return
", gcd);
104 BasicBlock* cond_false = BasicBlock::Create(
"cond_false
", gcd);
105 BasicBlock* cond_true = BasicBlock::Create(
"cond_true
", gcd);
106 BasicBlock* cond_false_2 = BasicBlock::Create(
"cond_false
", gcd);
110 <p>Now we're ready to begin generating code! We'll start with the
<code>entry
</code> block. This block corresponds to the top-level if-statement in the original C code, so we need to compare
<code>x
</code> and
<code>y
</code>. To achieve this, we perform an explicit comparison using
<code>ICmpEQ
</code>.
<code>ICmpEQ
</code> stands for an
<em>integer comparison for equality
</em> and returns a
1-bit integer result. This
1-bit result is then used as the input to a conditional branch, with
<code>ret
</code> as the
<code>true
</code> and
<code>cond_false
</code> as the
<code>false
</code> case.
</p>
112 <div class=
"doc_code">
114 IRBuilder
<> builder(entry);
115 Value* xEqualsY = builder.CreateICmpEQ(x, y,
"tmp
");
116 builder.CreateCondBr(xEqualsY, ret, cond_false);
120 <p>Our next block,
<code>ret
</code>, is pretty simple: it just returns the value of
<code>x
</code>. Recall that this block is only reached if
<code>x == y
</code>, so this is the correct behavior. Notice that instead of creating a new
<code>IRBuilder
</code> for each block, we can use
<code>SetInsertPoint
</code> to retarget our existing one. This saves on construction and memory allocation costs.
</p>
122 <div class=
"doc_code">
124 builder.SetInsertPoint(ret);
125 builder.CreateRet(x);
129 <p><code>cond_false
</code> is a more interesting block: we now know that
<code>x
130 != y
</code>, so we must branch again to determine which of
<code>x
</code>
131 and
<code>y
</code> is larger. This is achieved using the
<code>ICmpULT
</code>
132 instruction, which stands for
<em>integer comparison for unsigned
133 less-than
</em>. In LLVM, integer types do not carry sign; a
32-bit integer
134 pseudo-register can be interpreted as signed or unsigned without casting.
135 Whether a signed or unsigned interpretation is desired is specified in the
136 instruction. This is why several instructions in the LLVM IR, such as integer
137 less-than, include a specifier for signed or unsigned.
</p>
139 <p>Also note that we're again making use of LLVM's automatic name uniquing, this time at a register level. We've deliberately chosen to name every instruction
"tmp" to illustrate that LLVM will give them all unique names without getting confused.
</p>
141 <div class=
"doc_code">
143 builder.SetInsertPoint(cond_false);
144 Value* xLessThanY = builder.CreateICmpULT(x, y,
"tmp
");
145 builder.CreateCondBr(xLessThanY, cond_true, cond_false_2);
149 <p>Our last two blocks are quite similar; they're both recursive calls to
<code>gcd
</code> with different parameters. To create a call instruction, we have to create a
<code>vector
</code> (or any other container with
<code>InputInterator
</code>s) to hold the arguments. We then pass in the beginning and ending iterators for this vector.
</p>
151 <div class=
"doc_code">
153 builder.SetInsertPoint(cond_true);
154 Value* yMinusX = builder.CreateSub(y, x,
"tmp
");
155 std::vector
<Value*
> args1;
157 args1.push_back(yMinusX);
158 Value* recur_1 = builder.CreateCall(gcd, args1.begin(), args1.end(),
"tmp
");
159 builder.CreateRet(recur_1);
161 builder.SetInsertPoint(cond_false_2);
162 Value* xMinusY = builder.CreateSub(x, y,
"tmp
");
163 std::vector
<Value*
> args2;
164 args2.push_back(xMinusY);
166 Value* recur_2 = builder.CreateCall(gcd, args2.begin(), args2.end(),
"tmp
");
167 builder.CreateRet(recur_2);
174 <p>And that's it! You can compile and execute your code in the same way as before, by doing:
</p>
176 <div class=
"doc_code">
178 # c++ -g tut2.cpp `llvm-config --cxxflags --ldflags --libs core` -o tut2
185 <!-- *********************************************************************** -->
188 <a href=
"http://jigsaw.w3.org/css-validator/check/referer"><img
189 src=
"http://jigsaw.w3.org/css-validator/images/vcss" alt=
"Valid CSS!"></a>
190 <a href=
"http://validator.w3.org/check/referer"><img
191 src=
"http://www.w3.org/Icons/valid-html401" alt=
"Valid HTML 4.01!"></a>
193 <a href=
"mailto:owen@apple.com">Owen Anderson
</a><br>
194 <a href=
"http://llvm.org">The LLVM Compiler Infrastructure
</a><br>
195 Last modified: $Date:
2007-
10-
17 11:
05:
13 -
0700 (Wed,
17 Oct
2007) $