blob: 978187f996f094f719475c11cbe8eb1094f79e12 [file] [log] [blame]
Owen Anderson6f1fd942007-10-20 05:23:06 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
3
4<html>
5<head>
6 <title>LLVM Tutorial 1: A First 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 1: A First Function.">
11 <link rel="stylesheet" href="../llvm.css" type="text/css">
12</head>
13
14<body>
15
16<div class="doc_title"> LLVM Tutorial 1: A First Function </div>
17
18<div class="doc_author">
19 <p>Written by <a href="mailto:owen@apple.com">Owen Anderson</a></p>
20</div>
21
Owen Andersonc333e4f2007-10-22 06:35:07 +000022<!-- *********************************************************************** -->
23<div class="doc_section"><a name="intro">Code Samples</a></div>
24<!-- *********************************************************************** -->
25
26<div class="doc_text">
27All the code in this example can be downloaded at <a href="Tutorial1.tar.bz2">Tutorial1.tar.bz2</a> or <a href="Tutorial1.zip">Tutorial1.zip</a>.
28</div>
29
30<!-- *********************************************************************** -->
31<div class="doc_section"><a name="intro">A First Function</a></div>
32<!-- *********************************************************************** -->
33
Owen Anderson6f1fd942007-10-20 05:23:06 +000034<div class="doc_text">
35
36<p>For starters, lets consider a relatively straightforward function that takes three integer parameters and returns an arithmetic combination of them. This is nice and simple, especially since it involves no control flow:</p>
37
38<div class="doc_code">
39<pre>
Owen Anderson7d69c952007-10-20 05:41:39 +000040int mul_add(int x, int y, int z) {
41 return x * y + z;
42}
Owen Anderson6f1fd942007-10-20 05:23:06 +000043</pre>
44</div>
45
46<p>As a preview, the LLVM IR we’re going to end up generating for this function will look like:</p>
47
48<div class="doc_code">
49<pre>
Owen Anderson7d69c952007-10-20 05:41:39 +000050define i32 @mul_add(i32 %x, i32 %y, i32 %z) {
51entry:
52 %tmp = mul i32 %x, %y
53 %tmp2 = add i32 %tmp, %z
54 ret i32 %tmp2
55}
Owen Anderson6f1fd942007-10-20 05:23:06 +000056</pre>
57</div>
58
Owen Anderson0ec16ee2007-10-20 06:12:33 +000059<p>If you're unsure what the above code says, skim through the <a href="../LangRef.html">LLVM Language Reference Manual</a> and convince yourself that the above LLVM IR is actually equivalent to the original function. Once you’re satisfied with that, let’s move on to actually generating it programmatically!</p>
Owen Anderson6f1fd942007-10-20 05:23:06 +000060
61<p>... STUFF ABOUT HEADERS ... </p>
62
63<p>Now, let’s get started on our real program. Here’s what our basic <code>main()</code> will look like:</p>
64
65<div class="doc_code">
66<pre>
67using namespace llvm;
68
69Module* makeLLVMModule();
70
71int main(int argc, char**argv) {
72 Module* Mod = makeLLVMModule();
73
74 verifyModule(*Mod, PrintMessageAction);
75
76 PassManager PM;
77 PM.add(new PrintModulePass(&amp;llvm::cout));
78 PM.run(*Mod);
79
80 return 0;
81}
82</pre>
83</div>
84
85<p>The first segment is pretty simple: it creates an LLVM “module.” In LLVM, a module represents a single unit of code that is to be processed together. A module contains things like global variables and function declarations and implementations. Here, we’ve declared a <code>makeLLVMModule()</code> function to do the real work of creating the module. Don’t worry, we’ll be looking at that one next!</p>
86
87<p>The second segment runs the LLVM module verifier on our newly created module. While this probably isn’t really necessary for a simple module like this one, it’s always a good idea, especially if you’re generating LLVM IR based on some input. The verifier will print an error message if your LLVM module is malformed in any way.</p>
88
89<p>Finally, we instantiate an LLVM <code>PassManager</code> and run the <code>PrintModulePass</code> on our module. LLVM uses an explicit pass infrastructure to manage optimizations and various other things. A <code>PassManager</code>, as should be obvious from its name, manages passes: it is responsible for scheduling them, invoking them, and insuring the proper disposal after we’re done with them. For this example, we’re just using a trivial pass that prints out our module in textual form.</p>
90
Owen Anderson0ec16ee2007-10-20 06:12:33 +000091<p>Now onto the interesting part: creating a populating a module. Here’s the first chunk of our <code>makeLLVMModule()</code>:</p>
Owen Anderson6f1fd942007-10-20 05:23:06 +000092
93<div class="doc_code">
94<pre>
95Module* makeLLVMModule() {
96 // Module Construction
97 Module* mod = new Module("test");
98</pre>
99</div>
100
101<p>Exciting, isn’t it!? All we’re doing here is instantiating a module and giving it a name. The name isn’t particularly important unless you’re going to be dealing with multiple modules at once.</p>
102
103<div class="doc_code">
104<pre>
Owen Andersond2ae9a92007-10-22 06:29:31 +0000105 Constant* c = mod->getOrInsertFunction("mul_add",
106 /*ret type*/ IntegerType::get(32),
107 /*args*/ IntegerType::get(32),
108 IntegerType::get(32),
109 IntegerType::get(32),
110 /*varargs terminated with null*/ NULL);
Owen Anderson6f1fd942007-10-20 05:23:06 +0000111
Owen Anderson2d279f82007-10-20 05:40:47 +0000112 Function* mul_add = cast&lt;Function&gt;(c);
Owen Anderson6f1fd942007-10-20 05:23:06 +0000113 mul_add->setCallingConv(CallingConv::C);
114</pre>
115</div>
116
Owen Anderson2d279f82007-10-20 05:40:47 +0000117<p>We construct our <code>Function</code> by calling <code>getOrInsertFunction()</code> on our module, passing in the name, return type, and argument types of the function. In the case of our <code>mul_add</code> function, that means one 32-bit integer for the return value, and three 32-bit integers for the arguments.</p>
Owen Anderson6f1fd942007-10-20 05:23:06 +0000118
Owen Anderson2d279f82007-10-20 05:40:47 +0000119<p>You'll notice that <code>getOrInsertFunction</code> doesn't actually return a <code>Function*</code>. This is because, if the function already existed, but with a different prototype, <code>getOrInsertFunction</code> will return a cast of the existing function to the desired prototype. Since we know that there's not already a <code>mul_add</code> function, we can safely just cast <code>c</code> to a <code>Function*</code>.
120
121<p>In addition, we set the calling convention for our new function to be the C calling convention. This isn’t strictly necessary, but it insures that our new function will interoperate properly with C code, which is a good thing.</p>
Owen Anderson6f1fd942007-10-20 05:23:06 +0000122
123<div class="doc_code">
124<pre>
125 Function::arg_iterator args = mul_add->arg_begin();
126 Value* x = args++;
127 x->setName("x");
128 Value* y = args++;
129 y->setName("y");
130 Value* z = args++;
131 z->setName("z");
132</pre>
133</div>
134
135<p>While we’re setting up our function, let’s also give names to the parameters. This also isn’t strictly necessary (LLVM will generate names for them if you don’t specify them), but it’ll make looking at our output somewhat more pleasant. To name the parameters, we iterator over the arguments of our function, and call <code>setName()</code> on them. We’ll also keep the pointer to <code>x</code>, <code>y</code>, and <code>z</code> around, since we’ll need them when we get around to creating instructions.</p>
136
137<p>Great! We have a function now. But what good is a function if it has no body? Before we start working on a body for our new function, we need to recall some details of the LLVM IR. The IR, being an abstract assembly language, represents control flow using jumps (we call them branches), both conditional and unconditional. The straight-line sequences of code between branches are called basic blocks, or just blocks. To create a body for our function, we fill it with blocks!</p>
138
139<div class="doc_code">
140<pre>
141 BasicBlock* block = new BasicBlock("entry", mul_add);
142 LLVMBuilder builder(block);
143</pre>
144</div>
145
146<p>We create a new basic block, as you might expect, by calling its constructor. All we need to tell it is its name and the function to which it belongs. In addition, we’re creating an <code>LLVMBuilder</code> object, which is a convenience interface for creating instructions and appending them to the end of a block. Instructions can be created through their constructors as well, but some of their interfaces are quite complicated. Unless you need a lot of control, using <code>LLVMBuilder</code> will make your life simpler.</p>
147
148<div class="doc_code">
149<pre>
150 Value* tmp = builder.CreateBinOp(Instruction::Mul,
151 x, y, "tmp");
152 Value* tmp2 = builder.CreateBinOp(Instruction::Add,
153 tmp, z, "tmp2");
154
155 builder.CreateRet(tmp2);
Owen Andersond2ae9a92007-10-22 06:29:31 +0000156
157 return mod;
Owen Anderson6f1fd942007-10-20 05:23:06 +0000158}
159</pre>
160</div>
161
162<p>The final step in creating our function is to create the instructions that make it up. Our <code>mul_add</code> function is composed of just three instructions: a multiply, an add, and a return. <code>LLVMBuilder</code> gives us a simple interface for constructing these instructions and appending them to the “entry” block. Each of the calls to <code>LLVMBuilder</code> returns a <code>Value*</code> that represents the value yielded by the instruction. You’ll also notice that, above, <code>x</code>, <code>y</code>, and <code>z</code> are also <code>Value*</code>’s, so it’s clear that instructions operate on <code>Value*</code>’s.</p>
163
164<p>And that’s it! Now you can compile and run your code, and get a wonder textual print out of the LLVM IR we saw at the beginning.</p>
165
166<p> ... SECTION ABOUT USING llvm-config TO GET THE NECESSARY COMPILER FLAGS TO COMPILE YOUR CODE ... </p>
167
168</div>
169
170</body>
171</html>