1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
5 <title>LLVM Programmer's Manual</title>
6 <link rel="stylesheet" href="llvm.css" type="text/css">
10 <div class="doc_title">
11 LLVM Programmer's Manual
15 <li><a href="#introduction">Introduction</a></li>
16 <li><a href="#general">General Information</a>
18 <li><a href="#stl">The C++ Standard Template Library</a></li>
20 <li>The <tt>-time-passes</tt> option</li>
21 <li>How to use the LLVM Makefile system</li>
22 <li>How to write a regression test</li>
27 <li><a href="#apis">Important and useful LLVM APIs</a>
29 <li><a href="#isa">The <tt>isa<></tt>, <tt>cast<></tt>
30 and <tt>dyn_cast<></tt> templates</a> </li>
31 <li><a href="#DEBUG">The <tt>DEBUG()</tt> macro & <tt>-debug</tt>
34 <li><a href="#DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt>
35 and the <tt>-debug-only</tt> option</a> </li>
38 <li><a href="#Statistic">The <tt>Statistic</tt> template & <tt>-stats</tt>
41 <li>The <tt>InstVisitor</tt> template
42 <li>The general graph API
46 <li><a href="#common">Helpful Hints for Common Operations</a>
48 <li><a href="#inspection">Basic Inspection and Traversal Routines</a>
50 <li><a href="#iterate_function">Iterating over the <tt>BasicBlock</tt>s
51 in a <tt>Function</tt></a> </li>
52 <li><a href="#iterate_basicblock">Iterating over the <tt>Instruction</tt>s
53 in a <tt>BasicBlock</tt></a> </li>
54 <li><a href="#iterate_institer">Iterating over the <tt>Instruction</tt>s
55 in a <tt>Function</tt></a> </li>
56 <li><a href="#iterate_convert">Turning an iterator into a
57 class pointer</a> </li>
58 <li><a href="#iterate_complex">Finding call sites: a more
59 complex example</a> </li>
60 <li><a href="#calls_and_invokes">Treating calls and invokes
61 the same way</a> </li>
62 <li><a href="#iterate_chains">Iterating over def-use &
63 use-def chains</a> </li>
66 <li><a href="#simplechanges">Making simple changes</a>
68 <li><a href="#schanges_creating">Creating and inserting new
69 <tt>Instruction</tt>s</a> </li>
70 <li><a href="#schanges_deleting">Deleting <tt>Instruction</tt>s</a> </li>
71 <li><a href="#schanges_replacing">Replacing an <tt>Instruction</tt>
72 with another <tt>Value</tt></a> </li>
76 <li>Working with the Control Flow Graph
78 <li>Accessing predecessors and successors of a <tt>BasicBlock</tt>
86 <li><a href="#advanced">Advanced Topics</a>
88 <li><a href="#TypeResolve">LLVM Type Resolution</a>
90 <li><a href="#BuildRecType">Basic Recursive Type Construction</a></li>
91 <li><a href="#refineAbstractTypeTo">The <tt>refineAbstractTypeTo</tt> method</a></li>
92 <li><a href="#PATypeHolder">The PATypeHolder Class</a></li>
93 <li><a href="#AbstractTypeUser">The AbstractTypeUser Class</a></li>
96 <li><a href="#SymbolTable">The <tt>SymbolTable</tt> class </a></li>
99 <li><a href="#coreclasses">The Core LLVM Class Hierarchy Reference</a>
101 <li><a href="#Value">The <tt>Value</tt> class</a>
103 <li><a href="#User">The <tt>User</tt> class</a>
105 <li><a href="#Instruction">The <tt>Instruction</tt> class</a>
107 <li><a href="#GetElementPtrInst">The <tt>GetElementPtrInst</tt> class</a></li>
110 <li><a href="#Module">The <tt>Module</tt> class</a></li>
111 <li><a href="#Constant">The <tt>Constant</tt> class</a>
113 <li><a href="#GlobalValue">The <tt>GlobalValue</tt> class</a>
115 <li><a href="#BasicBlock">The <tt>BasicBlock</tt>class</a></li>
116 <li><a href="#Function">The <tt>Function</tt> class</a></li>
117 <li><a href="#GlobalVariable">The <tt>GlobalVariable</tt> class</a></li>
124 <li><a href="#Type">The <tt>Type</tt> class</a> </li>
125 <li><a href="#Argument">The <tt>Argument</tt> class</a></li>
132 <div class="doc_author">
133 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>,
134 <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a>,
135 <a href="mailto:jstanley@cs.uiuc.edu">Joel Stanley</a>, and
136 <a href="mailto:rspencer@x10sys.com">Reid Spencer</a></p>
139 <!-- *********************************************************************** -->
140 <div class="doc_section">
141 <a name="introduction">Introduction </a>
143 <!-- *********************************************************************** -->
145 <div class="doc_text">
147 <p>This document is meant to highlight some of the important classes and
148 interfaces available in the LLVM source-base. This manual is not
149 intended to explain what LLVM is, how it works, and what LLVM code looks
150 like. It assumes that you know the basics of LLVM and are interested
151 in writing transformations or otherwise analyzing or manipulating the
154 <p>This document should get you oriented so that you can find your
155 way in the continuously growing source code that makes up the LLVM
156 infrastructure. Note that this manual is not intended to serve as a
157 replacement for reading the source code, so if you think there should be
158 a method in one of these classes to do something, but it's not listed,
159 check the source. Links to the <a href="/doxygen/">doxygen</a> sources
160 are provided to make this as easy as possible.</p>
162 <p>The first section of this document describes general information that is
163 useful to know when working in the LLVM infrastructure, and the second describes
164 the Core LLVM classes. In the future this manual will be extended with
165 information describing how to use extension libraries, such as dominator
166 information, CFG traversal routines, and useful utilities like the <tt><a
167 href="/doxygen/InstVisitor_8h-source.html">InstVisitor</a></tt> template.</p>
171 <!-- *********************************************************************** -->
172 <div class="doc_section">
173 <a name="general">General Information</a>
175 <!-- *********************************************************************** -->
177 <div class="doc_text">
179 <p>This section contains general information that is useful if you are working
180 in the LLVM source-base, but that isn't specific to any particular API.</p>
184 <!-- ======================================================================= -->
185 <div class="doc_subsection">
186 <a name="stl">The C++ Standard Template Library</a>
189 <div class="doc_text">
191 <p>LLVM makes heavy use of the C++ Standard Template Library (STL),
192 perhaps much more than you are used to, or have seen before. Because of
193 this, you might want to do a little background reading in the
194 techniques used and capabilities of the library. There are many good
195 pages that discuss the STL, and several books on the subject that you
196 can get, so it will not be discussed in this document.</p>
198 <p>Here are some useful links:</p>
202 <li><a href="http://www.dinkumware.com/refxcpp.html">Dinkumware C++ Library
203 reference</a> - an excellent reference for the STL and other parts of the
204 standard C++ library.</li>
206 <li><a href="http://www.tempest-sw.com/cpp/">C++ In a Nutshell</a> - This is an
207 O'Reilly book in the making. It has a decent
209 Reference that rivals Dinkumware's, and is unfortunately no longer free since the book has been
212 <li><a href="http://www.parashift.com/c++-faq-lite/">C++ Frequently Asked
215 <li><a href="http://www.sgi.com/tech/stl/">SGI's STL Programmer's Guide</a> -
217 href="http://www.sgi.com/tech/stl/stl_introduction.html">Introduction to the
220 <li><a href="http://www.research.att.com/%7Ebs/C++.html">Bjarne Stroustrup's C++
223 <li><a href="http://64.78.49.204/">
224 Bruce Eckel's Thinking in C++, 2nd ed. Volume 2 Revision 4.0 (even better, get
229 <p>You are also encouraged to take a look at the <a
230 href="CodingStandards.html">LLVM Coding Standards</a> guide which focuses on how
231 to write maintainable code more than where to put your curly braces.</p>
235 <!-- ======================================================================= -->
236 <div class="doc_subsection">
237 <a name="stl">Other useful references</a>
240 <div class="doc_text">
243 <li><a href="http://www.psc.edu/%7Esemke/cvs_branches.html">CVS
244 Branch and Tag Primer</a></li>
245 <li><a href="http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html">Using
246 static and shared libraries across platforms</a></li>
251 <!-- *********************************************************************** -->
252 <div class="doc_section">
253 <a name="apis">Important and useful LLVM APIs</a>
255 <!-- *********************************************************************** -->
257 <div class="doc_text">
259 <p>Here we highlight some LLVM APIs that are generally useful and good to
260 know about when writing transformations.</p>
264 <!-- ======================================================================= -->
265 <div class="doc_subsection">
266 <a name="isa">The isa<>, cast<> and dyn_cast<> templates</a>
269 <div class="doc_text">
271 <p>The LLVM source-base makes extensive use of a custom form of RTTI.
272 These templates have many similarities to the C++ <tt>dynamic_cast<></tt>
273 operator, but they don't have some drawbacks (primarily stemming from
274 the fact that <tt>dynamic_cast<></tt> only works on classes that
275 have a v-table). Because they are used so often, you must know what they
276 do and how they work. All of these templates are defined in the <a
277 href="/doxygen/Casting_8h-source.html"><tt>llvm/Support/Casting.h</tt></a>
278 file (note that you very rarely have to include this file directly).</p>
281 <dt><tt>isa<></tt>: </dt>
283 <dd>The <tt>isa<></tt> operator works exactly like the Java
284 "<tt>instanceof</tt>" operator. It returns true or false depending on whether
285 a reference or pointer points to an instance of the specified class. This can
286 be very useful for constraint checking of various sorts (example below).</dd>
288 <dt><tt>cast<></tt>: </dt>
290 <dd>The <tt>cast<></tt> operator is a "checked cast" operation. It
291 converts a pointer or reference from a base class to a derived cast, causing
292 an assertion failure if it is not really an instance of the right type. This
293 should be used in cases where you have some information that makes you believe
294 that something is of the right type. An example of the <tt>isa<></tt>
295 and <tt>cast<></tt> template is:
298 static bool isLoopInvariant(const <a href="#Value">Value</a> *V, const Loop *L) {
299 if (isa<<a href="#Constant">Constant</a>>(V) || isa<<a href="#Argument">Argument</a>>(V) || isa<<a href="#GlobalValue">GlobalValue</a>>(V))
302 <i>// Otherwise, it must be an instruction...</i>
303 return !L->contains(cast<<a href="#Instruction">Instruction</a>>(V)->getParent());
307 <p>Note that you should <b>not</b> use an <tt>isa<></tt> test followed
308 by a <tt>cast<></tt>, for that use the <tt>dyn_cast<></tt>
313 <dt><tt>dyn_cast<></tt>:</dt>
315 <dd>The <tt>dyn_cast<></tt> operator is a "checking cast" operation. It
316 checks to see if the operand is of the specified type, and if so, returns a
317 pointer to it (this operator does not work with references). If the operand is
318 not of the correct type, a null pointer is returned. Thus, this works very
319 much like the <tt>dynamic_cast</tt> operator in C++, and should be used in the
320 same circumstances. Typically, the <tt>dyn_cast<></tt> operator is used
321 in an <tt>if</tt> statement or some other flow control statement like this:
324 if (<a href="#AllocationInst">AllocationInst</a> *AI = dyn_cast<<a href="#AllocationInst">AllocationInst</a>>(Val)) {
329 <p> This form of the <tt>if</tt> statement effectively combines together a
330 call to <tt>isa<></tt> and a call to <tt>cast<></tt> into one
331 statement, which is very convenient.</p>
333 <p>Note that the <tt>dyn_cast<></tt> operator, like C++'s
334 <tt>dynamic_cast</tt> or Java's <tt>instanceof</tt> operator, can be abused.
335 In particular you should not use big chained <tt>if/then/else</tt> blocks to
336 check for lots of different variants of classes. If you find yourself
337 wanting to do this, it is much cleaner and more efficient to use the
338 <tt>InstVisitor</tt> class to dispatch over the instruction type directly.</p>
342 <dt><tt>cast_or_null<></tt>: </dt>
344 <dd>The <tt>cast_or_null<></tt> operator works just like the
345 <tt>cast<></tt> operator, except that it allows for a null pointer as
346 an argument (which it then propagates). This can sometimes be useful,
347 allowing you to combine several null checks into one.</dd>
349 <dt><tt>dyn_cast_or_null<></tt>: </dt>
351 <dd>The <tt>dyn_cast_or_null<></tt> operator works just like the
352 <tt>dyn_cast<></tt> operator, except that it allows for a null pointer
353 as an argument (which it then propagates). This can sometimes be useful,
354 allowing you to combine several null checks into one.</dd>
358 <p>These five templates can be used with any classes, whether they have a
359 v-table or not. To add support for these templates, you simply need to add
360 <tt>classof</tt> static methods to the class you are interested casting
361 to. Describing this is currently outside the scope of this document, but there
362 are lots of examples in the LLVM source base.</p>
366 <!-- ======================================================================= -->
367 <div class="doc_subsection">
368 <a name="DEBUG">The <tt>DEBUG()</tt> macro & <tt>-debug</tt> option</a>
371 <div class="doc_text">
373 <p>Often when working on your pass you will put a bunch of debugging printouts
374 and other code into your pass. After you get it working, you want to remove
375 it... but you may need it again in the future (to work out new bugs that you run
378 <p> Naturally, because of this, you don't want to delete the debug printouts,
379 but you don't want them to always be noisy. A standard compromise is to comment
380 them out, allowing you to enable them if you need them in the future.</p>
382 <p>The "<tt><a href="/doxygen/Debug_8h-source.html">llvm/Support/Debug.h</a></tt>"
383 file provides a macro named <tt>DEBUG()</tt> that is a much nicer solution to
384 this problem. Basically, you can put arbitrary code into the argument of the
385 <tt>DEBUG</tt> macro, and it is only executed if '<tt>opt</tt>' (or any other
386 tool) is run with the '<tt>-debug</tt>' command line argument:</p>
388 <pre> ... <br> DEBUG(std::cerr << "I am here!\n");<br> ...<br></pre>
390 <p>Then you can run your pass like this:</p>
392 <pre> $ opt < a.bc > /dev/null -mypass<br> <no output><br> $ opt < a.bc > /dev/null -mypass -debug<br> I am here!<br> $<br></pre>
394 <p>Using the <tt>DEBUG()</tt> macro instead of a home-brewed solution allows you
395 to not have to create "yet another" command line option for the debug output for
396 your pass. Note that <tt>DEBUG()</tt> macros are disabled for optimized builds,
397 so they do not cause a performance impact at all (for the same reason, they
398 should also not contain side-effects!).</p>
400 <p>One additional nice thing about the <tt>DEBUG()</tt> macro is that you can
401 enable or disable it directly in gdb. Just use "<tt>set DebugFlag=0</tt>" or
402 "<tt>set DebugFlag=1</tt>" from the gdb if the program is running. If the
403 program hasn't been started yet, you can always just run it with
408 <!-- _______________________________________________________________________ -->
409 <div class="doc_subsubsection">
410 <a name="DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt> and
411 the <tt>-debug-only</tt> option</a>
414 <div class="doc_text">
416 <p>Sometimes you may find yourself in a situation where enabling <tt>-debug</tt>
417 just turns on <b>too much</b> information (such as when working on the code
418 generator). If you want to enable debug information with more fine-grained
419 control, you define the <tt>DEBUG_TYPE</tt> macro and the <tt>-debug</tt> only
420 option as follows:</p>
422 <pre> ...<br> DEBUG(std::cerr << "No debug type\n");<br> #undef DEBUG_TYPE<br> #define DEBUG_TYPE "foo"<br> DEBUG(std::cerr << "'foo' debug type\n");<br> #undef DEBUG_TYPE<br> #define DEBUG_TYPE "bar"<br> DEBUG(std::cerr << "'bar' debug type\n");<br> #undef DEBUG_TYPE<br> #define DEBUG_TYPE ""<br> DEBUG(std::cerr << "No debug type (2)\n");<br> ...<br></pre>
424 <p>Then you can run your pass like this:</p>
426 <pre> $ opt < a.bc > /dev/null -mypass<br> <no output><br> $ opt < a.bc > /dev/null -mypass -debug<br> No debug type<br> 'foo' debug type<br> 'bar' debug type<br> No debug type (2)<br> $ opt < a.bc > /dev/null -mypass -debug-only=foo<br> 'foo' debug type<br> $ opt < a.bc > /dev/null -mypass -debug-only=bar<br> 'bar' debug type<br> $<br></pre>
428 <p>Of course, in practice, you should only set <tt>DEBUG_TYPE</tt> at the top of
429 a file, to specify the debug type for the entire module (if you do this before
430 you <tt>#include "llvm/Support/Debug.h"</tt>, you don't have to insert the ugly
431 <tt>#undef</tt>'s). Also, you should use names more meaningful than "foo" and
432 "bar", because there is no system in place to ensure that names do not
433 conflict. If two different modules use the same string, they will all be turned
434 on when the name is specified. This allows, for example, all debug information
435 for instruction scheduling to be enabled with <tt>-debug-type=InstrSched</tt>,
436 even if the source lives in multiple files.</p>
440 <!-- ======================================================================= -->
441 <div class="doc_subsection">
442 <a name="Statistic">The <tt>Statistic</tt> template & <tt>-stats</tt>
446 <div class="doc_text">
449 href="/doxygen/Statistic_8h-source.html">llvm/ADT/Statistic.h</a></tt>" file
450 provides a template named <tt>Statistic</tt> that is used as a unified way to
451 keep track of what the LLVM compiler is doing and how effective various
452 optimizations are. It is useful to see what optimizations are contributing to
453 making a particular program run faster.</p>
455 <p>Often you may run your pass on some big program, and you're interested to see
456 how many times it makes a certain transformation. Although you can do this with
457 hand inspection, or some ad-hoc method, this is a real pain and not very useful
458 for big programs. Using the <tt>Statistic</tt> template makes it very easy to
459 keep track of this information, and the calculated information is presented in a
460 uniform manner with the rest of the passes being executed.</p>
462 <p>There are many examples of <tt>Statistic</tt> uses, but the basics of using
463 it are as follows:</p>
466 <li>Define your statistic like this:
467 <pre>static Statistic<> NumXForms("mypassname", "The # of times I did stuff");<br></pre>
469 <p>The <tt>Statistic</tt> template can emulate just about any data-type,
470 but if you do not specify a template argument, it defaults to acting like
471 an unsigned int counter (this is usually what you want).</p></li>
473 <li>Whenever you make a transformation, bump the counter:
474 <pre> ++NumXForms; // I did stuff<br></pre>
478 <p>That's all you have to do. To get '<tt>opt</tt>' to print out the
479 statistics gathered, use the '<tt>-stats</tt>' option:</p>
481 <pre> $ opt -stats -mypassname < program.bc > /dev/null<br> ... statistic output ...<br></pre>
483 <p> When running <tt>gccas</tt> on a C file from the SPEC benchmark
484 suite, it gives a report that looks like this:</p>
486 <pre> 7646 bytecodewriter - Number of normal instructions<br> 725 bytecodewriter - Number of oversized instructions<br> 129996 bytecodewriter - Number of bytecode bytes written<br> 2817 raise - Number of insts DCEd or constprop'd<br> 3213 raise - Number of cast-of-self removed<br> 5046 raise - Number of expression trees converted<br> 75 raise - Number of other getelementptr's formed<br> 138 raise - Number of load/store peepholes<br> 42 deadtypeelim - Number of unused typenames removed from symtab<br> 392 funcresolve - Number of varargs functions resolved<br> 27 globaldce - Number of global variables removed<br> 2 adce - Number of basic blocks removed<br> 134 cee - Number of branches revectored<br> 49 cee - Number of setcc instruction eliminated<br> 532 gcse - Number of loads removed<br> 2919 gcse - Number of instructions removed<br> 86 indvars - Number of canonical indvars added<br> 87 indvars - Number of aux indvars removed<br> 25 instcombine - Number of dead inst eliminate<br> 434 instcombine - Number of insts combined<br> 248 licm - Number of load insts hoisted<br> 1298 licm - Number of insts hoisted to a loop pre-header<br> 3 licm - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)<br> 75 mem2reg - Number of alloca's promoted<br> 1444 cfgsimplify - Number of blocks simplified<br></pre>
488 <p>Obviously, with so many optimizations, having a unified framework for this
489 stuff is very nice. Making your pass fit well into the framework makes it more
490 maintainable and useful.</p>
494 <!-- *********************************************************************** -->
495 <div class="doc_section">
496 <a name="common">Helpful Hints for Common Operations</a>
498 <!-- *********************************************************************** -->
500 <div class="doc_text">
502 <p>This section describes how to perform some very simple transformations of
503 LLVM code. This is meant to give examples of common idioms used, showing the
504 practical side of LLVM transformations. <p> Because this is a "how-to" section,
505 you should also read about the main classes that you will be working with. The
506 <a href="#coreclasses">Core LLVM Class Hierarchy Reference</a> contains details
507 and descriptions of the main classes that you should know about.</p>
511 <!-- NOTE: this section should be heavy on example code -->
512 <!-- ======================================================================= -->
513 <div class="doc_subsection">
514 <a name="inspection">Basic Inspection and Traversal Routines</a>
517 <div class="doc_text">
519 <p>The LLVM compiler infrastructure have many different data structures that may
520 be traversed. Following the example of the C++ standard template library, the
521 techniques used to traverse these various data structures are all basically the
522 same. For a enumerable sequence of values, the <tt>XXXbegin()</tt> function (or
523 method) returns an iterator to the start of the sequence, the <tt>XXXend()</tt>
524 function returns an iterator pointing to one past the last valid element of the
525 sequence, and there is some <tt>XXXiterator</tt> data type that is common
526 between the two operations.</p>
528 <p>Because the pattern for iteration is common across many different aspects of
529 the program representation, the standard template library algorithms may be used
530 on them, and it is easier to remember how to iterate. First we show a few common
531 examples of the data structures that need to be traversed. Other data
532 structures are traversed in very similar ways.</p>
536 <!-- _______________________________________________________________________ -->
537 <div class="doc_subsubsection">
538 <a name="iterate_function">Iterating over the </a><a
539 href="#BasicBlock"><tt>BasicBlock</tt></a>s in a <a
540 href="#Function"><tt>Function</tt></a>
543 <div class="doc_text">
545 <p>It's quite common to have a <tt>Function</tt> instance that you'd like to
546 transform in some way; in particular, you'd like to manipulate its
547 <tt>BasicBlock</tt>s. To facilitate this, you'll need to iterate over all of
548 the <tt>BasicBlock</tt>s that constitute the <tt>Function</tt>. The following is
549 an example that prints the name of a <tt>BasicBlock</tt> and the number of
550 <tt>Instruction</tt>s it contains:</p>
552 <pre> // func is a pointer to a Function instance<br> for (Function::iterator i = func->begin(), e = func->end(); i != e; ++i) {<br><br> // print out the name of the basic block if it has one, and then the<br> // number of instructions that it contains<br><br> cerr << "Basic block (name=" << i->getName() << ") has " <br> << i->size() << " instructions.\n";<br> }<br></pre>
554 <p>Note that i can be used as if it were a pointer for the purposes of
555 invoking member functions of the <tt>Instruction</tt> class. This is
556 because the indirection operator is overloaded for the iterator
557 classes. In the above code, the expression <tt>i->size()</tt> is
558 exactly equivalent to <tt>(*i).size()</tt> just like you'd expect.</p>
562 <!-- _______________________________________________________________________ -->
563 <div class="doc_subsubsection">
564 <a name="iterate_basicblock">Iterating over the </a><a
565 href="#Instruction"><tt>Instruction</tt></a>s in a <a
566 href="#BasicBlock"><tt>BasicBlock</tt></a>
569 <div class="doc_text">
571 <p>Just like when dealing with <tt>BasicBlock</tt>s in <tt>Function</tt>s, it's
572 easy to iterate over the individual instructions that make up
573 <tt>BasicBlock</tt>s. Here's a code snippet that prints out each instruction in
574 a <tt>BasicBlock</tt>:</p>
577 // blk is a pointer to a BasicBlock instance
578 for (BasicBlock::iterator i = blk->begin(), e = blk->end(); i != e; ++i)
579 // the next statement works since operator<<(ostream&,...)
580 // is overloaded for Instruction&
581 std::cerr << *i << "\n";
584 <p>However, this isn't really the best way to print out the contents of a
585 <tt>BasicBlock</tt>! Since the ostream operators are overloaded for virtually
586 anything you'll care about, you could have just invoked the print routine on the
587 basic block itself: <tt>std::cerr << *blk << "\n";</tt>.</p>
591 <!-- _______________________________________________________________________ -->
592 <div class="doc_subsubsection">
593 <a name="iterate_institer">Iterating over the </a><a
594 href="#Instruction"><tt>Instruction</tt></a>s in a <a
595 href="#Function"><tt>Function</tt></a>
598 <div class="doc_text">
600 <p>If you're finding that you commonly iterate over a <tt>Function</tt>'s
601 <tt>BasicBlock</tt>s and then that <tt>BasicBlock</tt>'s <tt>Instruction</tt>s,
602 <tt>InstIterator</tt> should be used instead. You'll need to include <a
603 href="/doxygen/InstIterator_8h-source.html"><tt>llvm/Support/InstIterator.h</tt></a>,
604 and then instantiate <tt>InstIterator</tt>s explicitly in your code. Here's a
605 small example that shows how to dump all instructions in a function to the standard error stream:<p>
607 <pre>#include "<a href="/doxygen/InstIterator_8h-source.html">llvm/Support/InstIterator.h</a>"<br>...<br>// Suppose F is a ptr to a function<br>for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)<br> cerr << *i << "\n";<br></pre>
608 Easy, isn't it? You can also use <tt>InstIterator</tt>s to fill a
609 worklist with its initial contents. For example, if you wanted to
610 initialize a worklist to contain all instructions in a <tt>Function</tt>
611 F, all you would need to do is something like:
612 <pre>std::set<Instruction*> worklist;<br>worklist.insert(inst_begin(F), inst_end(F));<br></pre>
614 <p>The STL set <tt>worklist</tt> would now contain all instructions in the
615 <tt>Function</tt> pointed to by F.</p>
619 <!-- _______________________________________________________________________ -->
620 <div class="doc_subsubsection">
621 <a name="iterate_convert">Turning an iterator into a class pointer (and
625 <div class="doc_text">
627 <p>Sometimes, it'll be useful to grab a reference (or pointer) to a class
628 instance when all you've got at hand is an iterator. Well, extracting
629 a reference or a pointer from an iterator is very straight-forward.
630 Assuming that <tt>i</tt> is a <tt>BasicBlock::iterator</tt> and <tt>j</tt>
631 is a <tt>BasicBlock::const_iterator</tt>:</p>
633 <pre> Instruction& inst = *i; // grab reference to instruction reference<br> Instruction* pinst = &*i; // grab pointer to instruction reference<br> const Instruction& inst = *j;<br></pre>
635 <p>However, the iterators you'll be working with in the LLVM framework are
636 special: they will automatically convert to a ptr-to-instance type whenever they
637 need to. Instead of dereferencing the iterator and then taking the address of
638 the result, you can simply assign the iterator to the proper pointer type and
639 you get the dereference and address-of operation as a result of the assignment
640 (behind the scenes, this is a result of overloading casting mechanisms). Thus
641 the last line of the last example,</p>
643 <pre>Instruction* pinst = &*i;</pre>
645 <p>is semantically equivalent to</p>
647 <pre>Instruction* pinst = i;</pre>
649 <p>It's also possible to turn a class pointer into the corresponding iterator,
650 and this is a constant time operation (very efficient). The following code
651 snippet illustrates use of the conversion constructors provided by LLVM
652 iterators. By using these, you can explicitly grab the iterator of something
653 without actually obtaining it via iteration over some structure:</p>
655 <pre>void printNextInstruction(Instruction* inst) {<br> BasicBlock::iterator it(inst);<br> ++it; // after this line, it refers to the instruction after *inst.<br> if (it != inst->getParent()->end()) cerr << *it << "\n";<br>}<br></pre>
659 <!--_______________________________________________________________________-->
660 <div class="doc_subsubsection">
661 <a name="iterate_complex">Finding call sites: a slightly more complex
665 <div class="doc_text">
667 <p>Say that you're writing a FunctionPass and would like to count all the
668 locations in the entire module (that is, across every <tt>Function</tt>) where a
669 certain function (i.e., some <tt>Function</tt>*) is already in scope. As you'll
670 learn later, you may want to use an <tt>InstVisitor</tt> to accomplish this in a
671 much more straight-forward manner, but this example will allow us to explore how
672 you'd do it if you didn't have <tt>InstVisitor</tt> around. In pseudocode, this
673 is what we want to do:</p>
675 <pre>initialize callCounter to zero<br>for each Function f in the Module<br> for each BasicBlock b in f<br> for each Instruction i in b<br> if (i is a CallInst and calls the given function)<br> increment callCounter<br></pre>
677 <p>And the actual code is (remember, since we're writing a
678 <tt>FunctionPass</tt>, our <tt>FunctionPass</tt>-derived class simply has to
679 override the <tt>runOnFunction</tt> method...):</p>
681 <pre>Function* targetFunc = ...;<br><br>class OurFunctionPass : public FunctionPass {<br> public:<br> OurFunctionPass(): callCounter(0) { }<br><br> virtual runOnFunction(Function& F) {<br> for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) {<br> for (BasicBlock::iterator i = b->begin(); ie = b->end(); i != ie; ++i) {<br> if (<a
682 href="#CallInst">CallInst</a>* callInst = <a href="#isa">dyn_cast</a><<a
683 href="#CallInst">CallInst</a>>(&*i)) {<br> // we know we've encountered a call instruction, so we<br> // need to determine if it's a call to the<br> // function pointed to by m_func or not.<br> <br> if (callInst->getCalledFunction() == targetFunc)<br> ++callCounter;<br> }<br> }<br> }<br> <br> private:<br> unsigned callCounter;<br>};<br></pre>
687 <!--_______________________________________________________________________-->
688 <div class="doc_subsubsection">
689 <a name="calls_and_invokes">Treating calls and invokes the same way</a>
692 <div class="doc_text">
694 <p>You may have noticed that the previous example was a bit oversimplified in
695 that it did not deal with call sites generated by 'invoke' instructions. In
696 this, and in other situations, you may find that you want to treat
697 <tt>CallInst</tt>s and <tt>InvokeInst</tt>s the same way, even though their
698 most-specific common base class is <tt>Instruction</tt>, which includes lots of
699 less closely-related things. For these cases, LLVM provides a handy wrapper
701 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1CallSite.html"><tt>CallSite</tt></a>.
702 It is essentially a wrapper around an <tt>Instruction</tt> pointer, with some
703 methods that provide functionality common to <tt>CallInst</tt>s and
704 <tt>InvokeInst</tt>s.</p>
706 <p>This class has "value semantics": it should be passed by value, not by
707 reference and it should not be dynamically allocated or deallocated using
708 <tt>operator new</tt> or <tt>operator delete</tt>. It is efficiently copyable,
709 assignable and constructable, with costs equivalents to that of a bare pointer.
710 If you look at its definition, it has only a single pointer member.</p>
714 <!--_______________________________________________________________________-->
715 <div class="doc_subsubsection">
716 <a name="iterate_chains">Iterating over def-use & use-def chains</a>
719 <div class="doc_text">
721 <p>Frequently, we might have an instance of the <a
722 href="/doxygen/structllvm_1_1Value.html">Value Class</a> and we want to
723 determine which <tt>User</tt>s use the <tt>Value</tt>. The list of all
724 <tt>User</tt>s of a particular <tt>Value</tt> is called a <i>def-use</i> chain.
725 For example, let's say we have a <tt>Function*</tt> named <tt>F</tt> to a
726 particular function <tt>foo</tt>. Finding all of the instructions that
727 <i>use</i> <tt>foo</tt> is as simple as iterating over the <i>def-use</i> chain
730 <pre>Function* F = ...;<br><br>for (Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i) {<br> if (Instruction *Inst = dyn_cast<Instruction>(*i)) {<br> cerr << "F is used in instruction:\n";<br> cerr << *Inst << "\n";<br> }<br>}<br></pre>
732 <p>Alternately, it's common to have an instance of the <a
733 href="/doxygen/classllvm_1_1User.html">User Class</a> and need to know what
734 <tt>Value</tt>s are used by it. The list of all <tt>Value</tt>s used by a
735 <tt>User</tt> is known as a <i>use-def</i> chain. Instances of class
736 <tt>Instruction</tt> are common <tt>User</tt>s, so we might want to iterate over
737 all of the values that a particular instruction uses (that is, the operands of
738 the particular <tt>Instruction</tt>):</p>
740 <pre>Instruction* pi = ...;<br><br>for (User::op_iterator i = pi->op_begin(), e = pi->op_end(); i != e; ++i) {<br> Value* v = *i;<br> ...<br>}<br></pre>
743 def-use chains ("finding all users of"): Value::use_begin/use_end
744 use-def chains ("finding all values used"): User::op_begin/op_end [op=operand]
749 <!-- ======================================================================= -->
750 <div class="doc_subsection">
751 <a name="simplechanges">Making simple changes</a>
754 <div class="doc_text">
756 <p>There are some primitive transformation operations present in the LLVM
757 infrastructure that are worth knowing about. When performing
758 transformations, it's fairly common to manipulate the contents of basic
759 blocks. This section describes some of the common methods for doing so
760 and gives example code.</p>
764 <!--_______________________________________________________________________-->
765 <div class="doc_subsubsection">
766 <a name="schanges_creating">Creating and inserting new
767 <tt>Instruction</tt>s</a>
770 <div class="doc_text">
772 <p><i>Instantiating Instructions</i></p>
774 <p>Creation of <tt>Instruction</tt>s is straight-forward: simply call the
775 constructor for the kind of instruction to instantiate and provide the necessary
776 parameters. For example, an <tt>AllocaInst</tt> only <i>requires</i> a
777 (const-ptr-to) <tt>Type</tt>. Thus:</p>
779 <pre>AllocaInst* ai = new AllocaInst(Type::IntTy);</pre>
781 <p>will create an <tt>AllocaInst</tt> instance that represents the allocation of
782 one integer in the current stack frame, at runtime. Each <tt>Instruction</tt>
783 subclass is likely to have varying default parameters which change the semantics
784 of the instruction, so refer to the <a
785 href="/doxygen/classllvm_1_1Instruction.html">doxygen documentation for the subclass of
786 Instruction</a> that you're interested in instantiating.</p>
788 <p><i>Naming values</i></p>
790 <p>It is very useful to name the values of instructions when you're able to, as
791 this facilitates the debugging of your transformations. If you end up looking
792 at generated LLVM machine code, you definitely want to have logical names
793 associated with the results of instructions! By supplying a value for the
794 <tt>Name</tt> (default) parameter of the <tt>Instruction</tt> constructor, you
795 associate a logical name with the result of the instruction's execution at
796 runtime. For example, say that I'm writing a transformation that dynamically
797 allocates space for an integer on the stack, and that integer is going to be
798 used as some kind of index by some other code. To accomplish this, I place an
799 <tt>AllocaInst</tt> at the first point in the first <tt>BasicBlock</tt> of some
800 <tt>Function</tt>, and I'm intending to use it within the same
801 <tt>Function</tt>. I might do:</p>
803 <pre>AllocaInst* pa = new AllocaInst(Type::IntTy, 0, "indexLoc");</pre>
805 <p>where <tt>indexLoc</tt> is now the logical name of the instruction's
806 execution value, which is a pointer to an integer on the runtime stack.</p>
808 <p><i>Inserting instructions</i></p>
810 <p>There are essentially two ways to insert an <tt>Instruction</tt>
811 into an existing sequence of instructions that form a <tt>BasicBlock</tt>:</p>
814 <li>Insertion into an explicit instruction list
816 <p>Given a <tt>BasicBlock* pb</tt>, an <tt>Instruction* pi</tt> within that
817 <tt>BasicBlock</tt>, and a newly-created instruction we wish to insert
818 before <tt>*pi</tt>, we do the following: </p>
820 <pre> BasicBlock *pb = ...;<br> Instruction *pi = ...;<br> Instruction *newInst = new Instruction(...);<br> pb->getInstList().insert(pi, newInst); // inserts newInst before pi in pb<br></pre>
822 <p>Appending to the end of a <tt>BasicBlock</tt> is so common that
823 the <tt>Instruction</tt> class and <tt>Instruction</tt>-derived
824 classes provide constructors which take a pointer to a
825 <tt>BasicBlock</tt> to be appended to. For example code that
828 <pre> BasicBlock *pb = ...;<br> Instruction *newInst = new Instruction(...);<br> pb->getInstList().push_back(newInst); // appends newInst to pb<br></pre>
832 <pre> BasicBlock *pb = ...;<br> Instruction *newInst = new Instruction(..., pb);<br></pre>
834 <p>which is much cleaner, especially if you are creating
835 long instruction streams.</p></li>
837 <li>Insertion into an implicit instruction list
839 <p><tt>Instruction</tt> instances that are already in <tt>BasicBlock</tt>s
840 are implicitly associated with an existing instruction list: the instruction
841 list of the enclosing basic block. Thus, we could have accomplished the same
842 thing as the above code without being given a <tt>BasicBlock</tt> by doing:
845 <pre> Instruction *pi = ...;<br> Instruction *newInst = new Instruction(...);<br> pi->getParent()->getInstList().insert(pi, newInst);<br></pre>
847 <p>In fact, this sequence of steps occurs so frequently that the
848 <tt>Instruction</tt> class and <tt>Instruction</tt>-derived classes provide
849 constructors which take (as a default parameter) a pointer to an
850 <tt>Instruction</tt> which the newly-created <tt>Instruction</tt> should
851 precede. That is, <tt>Instruction</tt> constructors are capable of
852 inserting the newly-created instance into the <tt>BasicBlock</tt> of a
853 provided instruction, immediately before that instruction. Using an
854 <tt>Instruction</tt> constructor with a <tt>insertBefore</tt> (default)
855 parameter, the above code becomes:</p>
857 <pre>Instruction* pi = ...;<br>Instruction* newInst = new Instruction(..., pi);<br></pre>
859 <p>which is much cleaner, especially if you're creating a lot of
860 instructions and adding them to <tt>BasicBlock</tt>s.</p></li>
865 <!--_______________________________________________________________________-->
866 <div class="doc_subsubsection">
867 <a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a>
870 <div class="doc_text">
872 <p>Deleting an instruction from an existing sequence of instructions that form a
873 <a href="#BasicBlock"><tt>BasicBlock</tt></a> is very straight-forward. First,
874 you must have a pointer to the instruction that you wish to delete. Second, you
875 need to obtain the pointer to that instruction's basic block. You use the
876 pointer to the basic block to get its list of instructions and then use the
877 erase function to remove your instruction. For example:</p>
879 <pre> <a href="#Instruction">Instruction</a> *I = .. ;<br> <a
880 href="#BasicBlock">BasicBlock</a> *BB = I->getParent();<br> BB->getInstList().erase(I);<br></pre>
884 <!--_______________________________________________________________________-->
885 <div class="doc_subsubsection">
886 <a name="schanges_replacing">Replacing an <tt>Instruction</tt> with another
890 <div class="doc_text">
892 <p><i>Replacing individual instructions</i></p>
894 <p>Including "<a href="/doxygen/BasicBlockUtils_8h-source.html">llvm/Transforms/Utils/BasicBlockUtils.h</a>"
895 permits use of two very useful replace functions: <tt>ReplaceInstWithValue</tt>
896 and <tt>ReplaceInstWithInst</tt>.</p>
898 <h4><a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a></h4>
901 <li><tt>ReplaceInstWithValue</tt>
903 <p>This function replaces all uses (within a basic block) of a given
904 instruction with a value, and then removes the original instruction. The
905 following example illustrates the replacement of the result of a particular
906 <tt>AllocaInst</tt> that allocates memory for a single integer with a null
907 pointer to an integer.</p>
909 <pre>AllocaInst* instToReplace = ...;<br>BasicBlock::iterator ii(instToReplace);<br>ReplaceInstWithValue(instToReplace->getParent()->getInstList(), ii,<br> Constant::getNullValue(PointerType::get(Type::IntTy)));<br></pre></li>
911 <li><tt>ReplaceInstWithInst</tt>
913 <p>This function replaces a particular instruction with another
914 instruction. The following example illustrates the replacement of one
915 <tt>AllocaInst</tt> with another.</p>
917 <pre>AllocaInst* instToReplace = ...;<br>BasicBlock::iterator ii(instToReplace);<br>ReplaceInstWithInst(instToReplace->getParent()->getInstList(), ii,<br> new AllocaInst(Type::IntTy, 0, "ptrToReplacedInt"));<br></pre></li>
920 <p><i>Replacing multiple uses of <tt>User</tt>s and <tt>Value</tt>s</i></p>
922 <p>You can use <tt>Value::replaceAllUsesWith</tt> and
923 <tt>User::replaceUsesOfWith</tt> to change more than one use at a time. See the
924 doxygen documentation for the <a href="/doxygen/structllvm_1_1Value.html">Value Class</a>
925 and <a href="/doxygen/classllvm_1_1User.html">User Class</a>, respectively, for more
928 <!-- Value::replaceAllUsesWith User::replaceUsesOfWith Point out:
929 include/llvm/Transforms/Utils/ especially BasicBlockUtils.h with:
930 ReplaceInstWithValue, ReplaceInstWithInst -->
934 <!-- *********************************************************************** -->
935 <div class="doc_section">
936 <a name="advanced">Advanced Topics</a>
938 <!-- *********************************************************************** -->
940 <div class="doc_text">
942 This section describes some of the advanced or obscure API's that most clients
943 do not need to be aware of. These API's tend manage the inner workings of the
944 LLVM system, and only need to be accessed in unusual circumstances.
948 <!-- ======================================================================= -->
949 <div class="doc_subsection">
950 <a name="TypeResolve">LLVM Type Resolution</a>
953 <div class="doc_text">
956 The LLVM type system has a very simple goal: allow clients to compare types for
957 structural equality with a simple pointer comparison (aka a shallow compare).
958 This goal makes clients much simpler and faster, and is used throughout the LLVM
963 Unfortunately achieving this goal is not a simple matter. In particular,
964 recursive types and late resolution of opaque types makes the situation very
965 difficult to handle. Fortunately, for the most part, our implementation makes
966 most clients able to be completely unaware of the nasty internal details. The
967 primary case where clients are exposed to the inner workings of it are when
968 building a recursive type. In addition to this case, the LLVM bytecode reader,
969 assembly parser, and linker also have to be aware of the inner workings of this
974 For our purposes below, we need three concepts. First, an "Opaque Type" is
975 exactly as defined in the <a href="LangRef.html#t_opaque">language
976 reference</a>. Second an "Abstract Type" is any type which includes an
977 opaque type as part of its type graph (for example "<tt>{ opaque, int }</tt>").
978 Third, a concrete type is a type that is not an abstract type (e.g. "<tt>[ int,
984 <!-- ______________________________________________________________________ -->
985 <div class="doc_subsubsection">
986 <a name="BuildRecType">Basic Recursive Type Construction</a>
989 <div class="doc_text">
992 Because the most common question is "how do I build a recursive type with LLVM",
993 we answer it now and explain it as we go. Here we include enough to cause this
994 to be emitted to an output .ll file:
998 %mylist = type { %mylist*, int }
1002 To build this, use the following LLVM APIs:
1006 //<i> Create the initial outer struct.</i>
1007 <a href="#PATypeHolder">PATypeHolder</a> StructTy = OpaqueType::get();
1008 std::vector<const Type*> Elts;
1009 Elts.push_back(PointerType::get(StructTy));
1010 Elts.push_back(Type::IntTy);
1011 StructType *NewSTy = StructType::get(Elts);
1013 //<i> At this point, NewSTy = "{ opaque*, int }". Tell VMCore that</i>
1014 //<i> the struct and the opaque type are actually the same.</i>
1015 cast<OpaqueType>(StructTy.get())-><a href="#refineAbstractTypeTo">refineAbstractTypeTo</a>(NewSTy);
1017 // <i>NewSTy is potentially invalidated, but StructTy (a <a href="#PATypeHolder">PATypeHolder</a>) is</i>
1018 // <i>kept up-to-date.</i>
1019 NewSTy = cast<StructType>(StructTy.get());
1021 // <i>Add a name for the type to the module symbol table (optional).</i>
1022 MyModule->addTypeName("mylist", NewSTy);
1026 This code shows the basic approach used to build recursive types: build a
1027 non-recursive type using 'opaque', then use type unification to close the cycle.
1028 The type unification step is performed by the <tt><a
1029 ref="#refineAbstractTypeTo">refineAbstractTypeTo</a></tt> method, which is
1030 described next. After that, we describe the <a
1031 href="#PATypeHolder">PATypeHolder class</a>.
1036 <!-- ______________________________________________________________________ -->
1037 <div class="doc_subsubsection">
1038 <a name="refineAbstractTypeTo">The <tt>refineAbstractTypeTo</tt> method</a>
1041 <div class="doc_text">
1043 The <tt>refineAbstractTypeTo</tt> method starts the type unification process.
1044 While this method is actually a member of the DerivedType class, it is most
1045 often used on OpaqueType instances. Type unification is actually a recursive
1046 process. After unification, types can become structurally isomorphic to
1047 existing types, and all duplicates are deleted (to preserve pointer equality).
1051 In the example above, the OpaqueType object is definitely deleted.
1052 Additionally, if there is an "{ \2*, int}" type already created in the system,
1053 the pointer and struct type created are <b>also</b> deleted. Obviously whenever
1054 a type is deleted, any "Type*" pointers in the program are invalidated. As
1055 such, it is safest to avoid having <i>any</i> "Type*" pointers to abstract types
1056 live across a call to <tt>refineAbstractTypeTo</tt> (note that non-abstract
1057 types can never move or be deleted). To deal with this, the <a
1058 href="#PATypeHolder">PATypeHolder</a> class is used to maintain a stable
1059 reference to a possibly refined type, and the <a
1060 href="#AbstractTypeUser">AbstractTypeUser</a> class is used to update more
1061 complex datastructures.
1066 <!-- ______________________________________________________________________ -->
1067 <div class="doc_subsubsection">
1068 <a name="PATypeHolder">The PATypeHolder Class</a>
1071 <div class="doc_text">
1073 PATypeHolder is a form of a "smart pointer" for Type objects. When VMCore
1074 happily goes about nuking types that become isomorphic to existing types, it
1075 automatically updates all PATypeHolder objects to point to the new type. In the
1076 example above, this allows the code to maintain a pointer to the resultant
1077 resolved recursive type, even though the Type*'s are potentially invalidated.
1081 PATypeHolder is an extremely light-weight object that uses a lazy union-find
1082 implementation to update pointers. For example the pointer from a Value to its
1083 Type is maintained by PATypeHolder objects.
1088 <!-- ______________________________________________________________________ -->
1089 <div class="doc_subsubsection">
1090 <a name="AbstractTypeUser">The AbstractTypeUser Class</a>
1093 <div class="doc_text">
1096 Some data structures need more to perform more complex updates when types get
1097 resolved. The <a href="#SymbolTable">SymbolTable</a> class, for example, needs
1098 move and potentially merge type planes in its representation when a pointer
1102 To support this, a class can derive from the AbstractTypeUser class. This class
1103 allows it to get callbacks when certain types are resolved. To register to get
1104 callbacks for a particular type, the DerivedType::{add/remove}AbstractTypeUser
1105 methods can be called on a type. Note that these methods only work for <i>
1106 abstract</i> types. Concrete types (those that do not include an opaque objects
1107 somewhere) can never be refined.
1112 <!-- ======================================================================= -->
1113 <div class="doc_subsection">
1114 <a name="SymbolTable">The <tt>SymbolTable</tt> class</a>
1117 <div class="doc_text">
1118 <p>This class provides a symbol table that the <a
1119 href="#Function"><tt>Function</tt></a> and <a href="#Module">
1120 <tt>Module</tt></a> classes use for naming definitions. The symbol table can
1121 provide a name for any <a href="#Value"><tt>Value</tt></a> or <a
1122 href="#Type"><tt>Type</tt></a>. <tt>SymbolTable</tt> is an abstract data
1123 type. It hides the data it contains and provides access to it through a
1124 controlled interface.</p>
1126 <p>Note that the symbol table class is should not be directly accessed by most
1127 clients. It should only be used when iteration over the symbol table names
1128 themselves are required, which is very special purpose. Note that not all LLVM
1129 <a href="#Value">Value</a>s have names, and those without names (i.e. they have
1130 an empty name) do not exist in the symbol table.
1133 <p>To use the <tt>SymbolTable</tt> well, you need to understand the
1134 structure of the information it holds. The class contains two
1135 <tt>std::map</tt> objects. The first, <tt>pmap</tt>, is a map of
1136 <tt>Type*</tt> to maps of name (<tt>std::string</tt>) to <tt>Value*</tt>.
1137 The second, <tt>tmap</tt>, is a map of names to <tt>Type*</tt>. Thus, Values
1138 are stored in two-dimensions and accessed by <tt>Type</tt> and name. Types,
1139 however, are stored in a single dimension and accessed only by name.</p>
1141 <p>The interface of this class provides three basic types of operations:
1143 <li><em>Accessors</em>. Accessors provide read-only access to information
1144 such as finding a value for a name with the
1145 <a href="#SymbolTable_lookup">lookup</a> method.</li>
1146 <li><em>Mutators</em>. Mutators allow the user to add information to the
1147 <tt>SymbolTable</tt> with methods like
1148 <a href="#SymbolTable_insert"><tt>insert</tt></a>.</li>
1149 <li><em>Iterators</em>. Iterators allow the user to traverse the content
1150 of the symbol table in well defined ways, such as the method
1151 <a href="#SymbolTable_type_begin"><tt>type_begin</tt></a>.</li>
1156 <dt><tt>Value* lookup(const Type* Ty, const std::string& name) const</tt>:
1158 <dd>The <tt>lookup</tt> method searches the type plane given by the
1159 <tt>Ty</tt> parameter for a <tt>Value</tt> with the provided <tt>name</tt>.
1160 If a suitable <tt>Value</tt> is not found, null is returned.</dd>
1162 <dt><tt>Type* lookupType( const std::string& name) const</tt>:</dt>
1163 <dd>The <tt>lookupType</tt> method searches through the types for a
1164 <tt>Type</tt> with the provided <tt>name</tt>. If a suitable <tt>Type</tt>
1165 is not found, null is returned.</dd>
1167 <dt><tt>bool hasTypes() const</tt>:</dt>
1168 <dd>This function returns true if an entry has been made into the type
1171 <dt><tt>bool isEmpty() const</tt>:</dt>
1172 <dd>This function returns true if both the value and types maps are
1178 <dt><tt>void insert(Value *Val)</tt>:</dt>
1179 <dd>This method adds the provided value to the symbol table. The Value must
1180 have both a name and a type which are extracted and used to place the value
1181 in the correct type plane under the value's name.</dd>
1183 <dt><tt>void insert(const std::string& Name, Value *Val)</tt>:</dt>
1184 <dd> Inserts a constant or type into the symbol table with the specified
1185 name. There can be a many to one mapping between names and constants
1188 <dt><tt>void insert(const std::string& Name, Type *Typ)</tt>:</dt>
1189 <dd> Inserts a type into the symbol table with the specified name. There
1190 can be a many-to-one mapping between names and types. This method
1191 allows a type with an existing entry in the symbol table to get
1194 <dt><tt>void remove(Value* Val)</tt>:</dt>
1195 <dd> This method removes a named value from the symbol table. The
1196 type and name of the Value are extracted from \p N and used to
1197 lookup the Value in the correct type plane. If the Value is
1198 not in the symbol table, this method silently ignores the
1201 <dt><tt>void remove(Type* Typ)</tt>:</dt>
1202 <dd> This method removes a named type from the symbol table. The
1203 name of the type is extracted from \P T and used to look up
1204 the Type in the type map. If the Type is not in the symbol
1205 table, this method silently ignores the request.</dd>
1207 <dt><tt>Value* remove(const std::string& Name, Value *Val)</tt>:</dt>
1208 <dd> Remove a constant or type with the specified name from the
1211 <dt><tt>Type* remove(const std::string& Name, Type* T)</tt>:</dt>
1212 <dd> Remove a type with the specified name from the symbol table.
1213 Returns the removed Type.</dd>
1215 <dt><tt>Value *value_remove(const value_iterator& It)</tt>:</dt>
1216 <dd> Removes a specific value from the symbol table.
1217 Returns the removed value.</dd>
1219 <dt><tt>bool strip()</tt>:</dt>
1220 <dd> This method will strip the symbol table of its names leaving
1221 the type and values. </dd>
1223 <dt><tt>void clear()</tt>:</dt>
1224 <dd>Empty the symbol table completely.</dd>
1228 <p>The following functions describe three types of iterators you can obtain
1229 the beginning or end of the sequence for both const and non-const. It is
1230 important to keep track of the different kinds of iterators. There are
1231 three idioms worth pointing out:</p>
1233 <tr><th>Units</th><th>Iterator</th><th>Idiom</th></tr>
1235 <td align="left">Planes Of name/Value maps</td><td>PI</td>
1236 <td align="left"><pre><tt>
1237 for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
1238 PE = ST.plane_end(); PI != PE; ++PI ) {
1239 PI->first // This is the Type* of the plane
1240 PI->second // This is the SymbolTable::ValueMap of name/Value pairs
1244 <td align="left">All name/Type Pairs</td><td>TI</td>
1245 <td align="left"><pre><tt>
1246 for (SymbolTable::type_const_iterator TI = ST.type_begin(),
1247 TE = ST.type_end(); TI != TE; ++TI )
1248 TI->first // This is the name of the type
1249 TI->second // This is the Type* value associated with the name
1253 <td align="left">name/Value pairs in a plane</td><td>VI</td>
1254 <td align="left"><pre><tt>
1255 for (SymbolTable::value_const_iterator VI = ST.value_begin(SomeType),
1256 VE = ST.value_end(SomeType); VI != VE; ++VI )
1257 VI->first // This is the name of the Value
1258 VI->second // This is the Value* value associated with the name
1263 <p>Using the recommended iterator names and idioms will help you avoid
1264 making mistakes. Of particular note, make sure that whenever you use
1265 value_begin(SomeType) that you always compare the resulting iterator
1266 with value_end(SomeType) not value_end(SomeOtherType) or else you
1267 will loop infinitely.</p>
1271 <dt><tt>plane_iterator plane_begin()</tt>:</dt>
1272 <dd>Get an iterator that starts at the beginning of the type planes.
1273 The iterator will iterate over the Type/ValueMap pairs in the
1276 <dt><tt>plane_const_iterator plane_begin() const</tt>:</dt>
1277 <dd>Get a const_iterator that starts at the beginning of the type
1278 planes. The iterator will iterate over the Type/ValueMap pairs
1279 in the type planes. </dd>
1281 <dt><tt>plane_iterator plane_end()</tt>:</dt>
1282 <dd>Get an iterator at the end of the type planes. This serves as
1283 the marker for end of iteration over the type planes.</dd>
1285 <dt><tt>plane_const_iterator plane_end() const</tt>:</dt>
1286 <dd>Get a const_iterator at the end of the type planes. This serves as
1287 the marker for end of iteration over the type planes.</dd>
1289 <dt><tt>value_iterator value_begin(const Type *Typ)</tt>:</dt>
1290 <dd>Get an iterator that starts at the beginning of a type plane.
1291 The iterator will iterate over the name/value pairs in the type plane.
1292 Note: The type plane must already exist before using this.</dd>
1294 <dt><tt>value_const_iterator value_begin(const Type *Typ) const</tt>:</dt>
1295 <dd>Get a const_iterator that starts at the beginning of a type plane.
1296 The iterator will iterate over the name/value pairs in the type plane.
1297 Note: The type plane must already exist before using this.</dd>
1299 <dt><tt>value_iterator value_end(const Type *Typ)</tt>:</dt>
1300 <dd>Get an iterator to the end of a type plane. This serves as the marker
1301 for end of iteration of the type plane.
1302 Note: The type plane must already exist before using this.</dd>
1304 <dt><tt>value_const_iterator value_end(const Type *Typ) const</tt>:</dt>
1305 <dd>Get a const_iterator to the end of a type plane. This serves as the
1306 marker for end of iteration of the type plane.
1307 Note: the type plane must already exist before using this.</dd>
1309 <dt><tt>type_iterator type_begin()</tt>:</dt>
1310 <dd>Get an iterator to the start of the name/Type map.</dd>
1312 <dt><tt>type_const_iterator type_begin() cons</tt>:</dt>
1313 <dd> Get a const_iterator to the start of the name/Type map.</dd>
1315 <dt><tt>type_iterator type_end()</tt>:</dt>
1316 <dd>Get an iterator to the end of the name/Type map. This serves as the
1317 marker for end of iteration of the types.</dd>
1319 <dt><tt>type_const_iterator type_end() const</tt>:</dt>
1320 <dd>Get a const-iterator to the end of the name/Type map. This serves
1321 as the marker for end of iteration of the types.</dd>
1323 <dt><tt>plane_const_iterator find(const Type* Typ ) const</tt>:</dt>
1324 <dd>This method returns a plane_const_iterator for iteration over
1325 the type planes starting at a specific plane, given by \p Ty.</dd>
1327 <dt><tt>plane_iterator find( const Type* Typ </tt>:</dt>
1328 <dd>This method returns a plane_iterator for iteration over the
1329 type planes starting at a specific plane, given by \p Ty.</dd>
1336 <!-- *********************************************************************** -->
1337 <div class="doc_section">
1338 <a name="coreclasses">The Core LLVM Class Hierarchy Reference </a>
1340 <!-- *********************************************************************** -->
1342 <div class="doc_text">
1344 <p>The Core LLVM classes are the primary means of representing the program
1345 being inspected or transformed. The core LLVM classes are defined in
1346 header files in the <tt>include/llvm/</tt> directory, and implemented in
1347 the <tt>lib/VMCore</tt> directory.</p>
1351 <!-- ======================================================================= -->
1352 <div class="doc_subsection">
1353 <a name="Value">The <tt>Value</tt> class</a>
1358 <p><tt>#include "<a href="/doxygen/Value_8h-source.html">llvm/Value.h</a>"</tt>
1360 doxygen info: <a href="/doxygen/structllvm_1_1Value.html">Value Class</a></p>
1362 <p>The <tt>Value</tt> class is the most important class in the LLVM Source
1363 base. It represents a typed value that may be used (among other things) as an
1364 operand to an instruction. There are many different types of <tt>Value</tt>s,
1365 such as <a href="#Constant"><tt>Constant</tt></a>s,<a
1366 href="#Argument"><tt>Argument</tt></a>s. Even <a
1367 href="#Instruction"><tt>Instruction</tt></a>s and <a
1368 href="#Function"><tt>Function</tt></a>s are <tt>Value</tt>s.</p>
1370 <p>A particular <tt>Value</tt> may be used many times in the LLVM representation
1371 for a program. For example, an incoming argument to a function (represented
1372 with an instance of the <a href="#Argument">Argument</a> class) is "used" by
1373 every instruction in the function that references the argument. To keep track
1374 of this relationship, the <tt>Value</tt> class keeps a list of all of the <a
1375 href="#User"><tt>User</tt></a>s that is using it (the <a
1376 href="#User"><tt>User</tt></a> class is a base class for all nodes in the LLVM
1377 graph that can refer to <tt>Value</tt>s). This use list is how LLVM represents
1378 def-use information in the program, and is accessible through the <tt>use_</tt>*
1379 methods, shown below.</p>
1381 <p>Because LLVM is a typed representation, every LLVM <tt>Value</tt> is typed,
1382 and this <a href="#Type">Type</a> is available through the <tt>getType()</tt>
1383 method. In addition, all LLVM values can be named. The "name" of the
1384 <tt>Value</tt> is a symbolic string printed in the LLVM code:</p>
1386 <pre> %<b>foo</b> = add int 1, 2<br></pre>
1388 <p><a name="#nameWarning">The name of this instruction is "foo".</a> <b>NOTE</b>
1389 that the name of any value may be missing (an empty string), so names should
1390 <b>ONLY</b> be used for debugging (making the source code easier to read,
1391 debugging printouts), they should not be used to keep track of values or map
1392 between them. For this purpose, use a <tt>std::map</tt> of pointers to the
1393 <tt>Value</tt> itself instead.</p>
1395 <p>One important aspect of LLVM is that there is no distinction between an SSA
1396 variable and the operation that produces it. Because of this, any reference to
1397 the value produced by an instruction (or the value available as an incoming
1398 argument, for example) is represented as a direct pointer to the instance of
1400 represents this value. Although this may take some getting used to, it
1401 simplifies the representation and makes it easier to manipulate.</p>
1405 <!-- _______________________________________________________________________ -->
1406 <div class="doc_subsubsection">
1407 <a name="m_Value">Important Public Members of the <tt>Value</tt> class</a>
1410 <div class="doc_text">
1413 <li><tt>Value::use_iterator</tt> - Typedef for iterator over the
1415 <tt>Value::use_const_iterator</tt> - Typedef for const_iterator over
1417 <tt>unsigned use_size()</tt> - Returns the number of users of the
1419 <tt>bool use_empty()</tt> - Returns true if there are no users.<br>
1420 <tt>use_iterator use_begin()</tt> - Get an iterator to the start of
1422 <tt>use_iterator use_end()</tt> - Get an iterator to the end of the
1424 <tt><a href="#User">User</a> *use_back()</tt> - Returns the last
1425 element in the list.
1426 <p> These methods are the interface to access the def-use
1427 information in LLVM. As with all other iterators in LLVM, the naming
1428 conventions follow the conventions defined by the <a href="#stl">STL</a>.</p>
1430 <li><tt><a href="#Type">Type</a> *getType() const</tt>
1431 <p>This method returns the Type of the Value.</p>
1433 <li><tt>bool hasName() const</tt><br>
1434 <tt>std::string getName() const</tt><br>
1435 <tt>void setName(const std::string &Name)</tt>
1436 <p> This family of methods is used to access and assign a name to a <tt>Value</tt>,
1437 be aware of the <a href="#nameWarning">precaution above</a>.</p>
1439 <li><tt>void replaceAllUsesWith(Value *V)</tt>
1441 <p>This method traverses the use list of a <tt>Value</tt> changing all <a
1442 href="#User"><tt>User</tt>s</a> of the current value to refer to
1443 "<tt>V</tt>" instead. For example, if you detect that an instruction always
1444 produces a constant value (for example through constant folding), you can
1445 replace all uses of the instruction with the constant like this:</p>
1447 <pre> Inst->replaceAllUsesWith(ConstVal);<br></pre>
1452 <!-- ======================================================================= -->
1453 <div class="doc_subsection">
1454 <a name="User">The <tt>User</tt> class</a>
1457 <div class="doc_text">
1460 <tt>#include "<a href="/doxygen/User_8h-source.html">llvm/User.h</a>"</tt><br>
1461 doxygen info: <a href="/doxygen/classllvm_1_1User.html">User Class</a><br>
1462 Superclass: <a href="#Value"><tt>Value</tt></a></p>
1464 <p>The <tt>User</tt> class is the common base class of all LLVM nodes that may
1465 refer to <a href="#Value"><tt>Value</tt></a>s. It exposes a list of "Operands"
1466 that are all of the <a href="#Value"><tt>Value</tt></a>s that the User is
1467 referring to. The <tt>User</tt> class itself is a subclass of
1470 <p>The operands of a <tt>User</tt> point directly to the LLVM <a
1471 href="#Value"><tt>Value</tt></a> that it refers to. Because LLVM uses Static
1472 Single Assignment (SSA) form, there can only be one definition referred to,
1473 allowing this direct connection. This connection provides the use-def
1474 information in LLVM.</p>
1478 <!-- _______________________________________________________________________ -->
1479 <div class="doc_subsubsection">
1480 <a name="m_User">Important Public Members of the <tt>User</tt> class</a>
1483 <div class="doc_text">
1485 <p>The <tt>User</tt> class exposes the operand list in two ways: through
1486 an index access interface and through an iterator based interface.</p>
1489 <li><tt>Value *getOperand(unsigned i)</tt><br>
1490 <tt>unsigned getNumOperands()</tt>
1491 <p> These two methods expose the operands of the <tt>User</tt> in a
1492 convenient form for direct access.</p></li>
1494 <li><tt>User::op_iterator</tt> - Typedef for iterator over the operand
1496 <tt>op_iterator op_begin()</tt> - Get an iterator to the start of
1497 the operand list.<br>
1498 <tt>op_iterator op_end()</tt> - Get an iterator to the end of the
1500 <p> Together, these methods make up the iterator based interface to
1501 the operands of a <tt>User</tt>.</p></li>
1506 <!-- ======================================================================= -->
1507 <div class="doc_subsection">
1508 <a name="Instruction">The <tt>Instruction</tt> class</a>
1511 <div class="doc_text">
1513 <p><tt>#include "</tt><tt><a
1514 href="/doxygen/Instruction_8h-source.html">llvm/Instruction.h</a>"</tt><br>
1515 doxygen info: <a href="/doxygen/classllvm_1_1Instruction.html">Instruction Class</a><br>
1516 Superclasses: <a href="#User"><tt>User</tt></a>, <a
1517 href="#Value"><tt>Value</tt></a></p>
1519 <p>The <tt>Instruction</tt> class is the common base class for all LLVM
1520 instructions. It provides only a few methods, but is a very commonly used
1521 class. The primary data tracked by the <tt>Instruction</tt> class itself is the
1522 opcode (instruction type) and the parent <a
1523 href="#BasicBlock"><tt>BasicBlock</tt></a> the <tt>Instruction</tt> is embedded
1524 into. To represent a specific type of instruction, one of many subclasses of
1525 <tt>Instruction</tt> are used.</p>
1527 <p> Because the <tt>Instruction</tt> class subclasses the <a
1528 href="#User"><tt>User</tt></a> class, its operands can be accessed in the same
1529 way as for other <a href="#User"><tt>User</tt></a>s (with the
1530 <tt>getOperand()</tt>/<tt>getNumOperands()</tt> and
1531 <tt>op_begin()</tt>/<tt>op_end()</tt> methods).</p> <p> An important file for
1532 the <tt>Instruction</tt> class is the <tt>llvm/Instruction.def</tt> file. This
1533 file contains some meta-data about the various different types of instructions
1534 in LLVM. It describes the enum values that are used as opcodes (for example
1535 <tt>Instruction::Add</tt> and <tt>Instruction::SetLE</tt>), as well as the
1536 concrete sub-classes of <tt>Instruction</tt> that implement the instruction (for
1537 example <tt><a href="#BinaryOperator">BinaryOperator</a></tt> and <tt><a
1538 href="#SetCondInst">SetCondInst</a></tt>). Unfortunately, the use of macros in
1539 this file confuses doxygen, so these enum values don't show up correctly in the
1540 <a href="/doxygen/classllvm_1_1Instruction.html">doxygen output</a>.</p>
1544 <!-- _______________________________________________________________________ -->
1545 <div class="doc_subsubsection">
1546 <a name="m_Instruction">Important Public Members of the <tt>Instruction</tt>
1550 <div class="doc_text">
1553 <li><tt><a href="#BasicBlock">BasicBlock</a> *getParent()</tt>
1554 <p>Returns the <a href="#BasicBlock"><tt>BasicBlock</tt></a> that
1555 this <tt>Instruction</tt> is embedded into.</p></li>
1556 <li><tt>bool mayWriteToMemory()</tt>
1557 <p>Returns true if the instruction writes to memory, i.e. it is a
1558 <tt>call</tt>,<tt>free</tt>,<tt>invoke</tt>, or <tt>store</tt>.</p></li>
1559 <li><tt>unsigned getOpcode()</tt>
1560 <p>Returns the opcode for the <tt>Instruction</tt>.</p></li>
1561 <li><tt><a href="#Instruction">Instruction</a> *clone() const</tt>
1562 <p>Returns another instance of the specified instruction, identical
1563 in all ways to the original except that the instruction has no parent
1564 (ie it's not embedded into a <a href="#BasicBlock"><tt>BasicBlock</tt></a>),
1565 and it has no name</p></li>
1570 <!-- ======================================================================= -->
1571 <div class="doc_subsection">
1572 <a name="BasicBlock">The <tt>BasicBlock</tt> class</a>
1575 <div class="doc_text">
1578 href="/doxygen/BasicBlock_8h-source.html">llvm/BasicBlock.h</a>"</tt><br>
1579 doxygen info: <a href="/doxygen/structllvm_1_1BasicBlock.html">BasicBlock
1581 Superclass: <a href="#Value"><tt>Value</tt></a></p>
1583 <p>This class represents a single entry multiple exit section of the code,
1584 commonly known as a basic block by the compiler community. The
1585 <tt>BasicBlock</tt> class maintains a list of <a
1586 href="#Instruction"><tt>Instruction</tt></a>s, which form the body of the block.
1587 Matching the language definition, the last element of this list of instructions
1588 is always a terminator instruction (a subclass of the <a
1589 href="#TerminatorInst"><tt>TerminatorInst</tt></a> class).</p>
1591 <p>In addition to tracking the list of instructions that make up the block, the
1592 <tt>BasicBlock</tt> class also keeps track of the <a
1593 href="#Function"><tt>Function</tt></a> that it is embedded into.</p>
1595 <p>Note that <tt>BasicBlock</tt>s themselves are <a
1596 href="#Value"><tt>Value</tt></a>s, because they are referenced by instructions
1597 like branches and can go in the switch tables. <tt>BasicBlock</tt>s have type
1602 <!-- _______________________________________________________________________ -->
1603 <div class="doc_subsubsection">
1604 <a name="m_BasicBlock">Important Public Members of the <tt>BasicBlock</tt>
1608 <div class="doc_text">
1612 <li><tt>BasicBlock(const std::string &Name = "", </tt><tt><a
1613 href="#Function">Function</a> *Parent = 0)</tt>
1615 <p>The <tt>BasicBlock</tt> constructor is used to create new basic blocks for
1616 insertion into a function. The constructor optionally takes a name for the new
1617 block, and a <a href="#Function"><tt>Function</tt></a> to insert it into. If
1618 the <tt>Parent</tt> parameter is specified, the new <tt>BasicBlock</tt> is
1619 automatically inserted at the end of the specified <a
1620 href="#Function"><tt>Function</tt></a>, if not specified, the BasicBlock must be
1621 manually inserted into the <a href="#Function"><tt>Function</tt></a>.</p></li>
1623 <li><tt>BasicBlock::iterator</tt> - Typedef for instruction list iterator<br>
1624 <tt>BasicBlock::const_iterator</tt> - Typedef for const_iterator.<br>
1625 <tt>begin()</tt>, <tt>end()</tt>, <tt>front()</tt>, <tt>back()</tt>,
1626 <tt>size()</tt>, <tt>empty()</tt>
1627 STL-style functions for accessing the instruction list.
1629 <p>These methods and typedefs are forwarding functions that have the same
1630 semantics as the standard library methods of the same names. These methods
1631 expose the underlying instruction list of a basic block in a way that is easy to
1632 manipulate. To get the full complement of container operations (including
1633 operations to update the list), you must use the <tt>getInstList()</tt>
1636 <li><tt>BasicBlock::InstListType &getInstList()</tt>
1638 <p>This method is used to get access to the underlying container that actually
1639 holds the Instructions. This method must be used when there isn't a forwarding
1640 function in the <tt>BasicBlock</tt> class for the operation that you would like
1641 to perform. Because there are no forwarding functions for "updating"
1642 operations, you need to use this if you want to update the contents of a
1643 <tt>BasicBlock</tt>.</p></li>
1645 <li><tt><a href="#Function">Function</a> *getParent()</tt>
1647 <p> Returns a pointer to <a href="#Function"><tt>Function</tt></a> the block is
1648 embedded into, or a null pointer if it is homeless.</p></li>
1650 <li><tt><a href="#TerminatorInst">TerminatorInst</a> *getTerminator()</tt>
1652 <p> Returns a pointer to the terminator instruction that appears at the end of
1653 the <tt>BasicBlock</tt>. If there is no terminator instruction, or if the last
1654 instruction in the block is not a terminator, then a null pointer is
1661 <!-- ======================================================================= -->
1662 <div class="doc_subsection">
1663 <a name="GlobalValue">The <tt>GlobalValue</tt> class</a>
1666 <div class="doc_text">
1669 href="/doxygen/GlobalValue_8h-source.html">llvm/GlobalValue.h</a>"</tt><br>
1670 doxygen info: <a href="/doxygen/classllvm_1_1GlobalValue.html">GlobalValue
1672 Superclasses: <a href="#User"><tt>User</tt></a>, <a
1673 href="#Value"><tt>Value</tt></a></p>
1675 <p>Global values (<a href="#GlobalVariable"><tt>GlobalVariable</tt></a>s or <a
1676 href="#Function"><tt>Function</tt></a>s) are the only LLVM values that are
1677 visible in the bodies of all <a href="#Function"><tt>Function</tt></a>s.
1678 Because they are visible at global scope, they are also subject to linking with
1679 other globals defined in different translation units. To control the linking
1680 process, <tt>GlobalValue</tt>s know their linkage rules. Specifically,
1681 <tt>GlobalValue</tt>s know whether they have internal or external linkage, as
1682 defined by the <tt>LinkageTypes</tt> enumeration.</p>
1684 <p>If a <tt>GlobalValue</tt> has internal linkage (equivalent to being
1685 <tt>static</tt> in C), it is not visible to code outside the current translation
1686 unit, and does not participate in linking. If it has external linkage, it is
1687 visible to external code, and does participate in linking. In addition to
1688 linkage information, <tt>GlobalValue</tt>s keep track of which <a
1689 href="#Module"><tt>Module</tt></a> they are currently part of.</p>
1691 <p>Because <tt>GlobalValue</tt>s are memory objects, they are always referred to
1692 by their <b>address</b>. As such, the <a href="#Type"><tt>Type</tt></a> of a
1693 global is always a pointer to its contents. It is important to remember this
1694 when using the <tt>GetElementPtrInst</tt> instruction because this pointer must
1695 be dereferenced first. For example, if you have a <tt>GlobalVariable</tt> (a
1696 subclass of <tt>GlobalValue)</tt> that is an array of 24 ints, type <tt>[24 x
1697 int]</tt>, then the <tt>GlobalVariable</tt> is a pointer to that array. Although
1698 the address of the first element of this array and the value of the
1699 <tt>GlobalVariable</tt> are the same, they have different types. The
1700 <tt>GlobalVariable</tt>'s type is <tt>[24 x int]</tt>. The first element's type
1701 is <tt>int.</tt> Because of this, accessing a global value requires you to
1702 dereference the pointer with <tt>GetElementPtrInst</tt> first, then its elements
1703 can be accessed. This is explained in the <a href="LangRef.html#globalvars">LLVM
1704 Language Reference Manual</a>.</p>
1708 <!-- _______________________________________________________________________ -->
1709 <div class="doc_subsubsection">
1710 <a name="m_GlobalValue">Important Public Members of the <tt>GlobalValue</tt>
1714 <div class="doc_text">
1717 <li><tt>bool hasInternalLinkage() const</tt><br>
1718 <tt>bool hasExternalLinkage() const</tt><br>
1719 <tt>void setInternalLinkage(bool HasInternalLinkage)</tt>
1720 <p> These methods manipulate the linkage characteristics of the <tt>GlobalValue</tt>.</p>
1723 <li><tt><a href="#Module">Module</a> *getParent()</tt>
1724 <p> This returns the <a href="#Module"><tt>Module</tt></a> that the
1725 GlobalValue is currently embedded into.</p></li>
1730 <!-- ======================================================================= -->
1731 <div class="doc_subsection">
1732 <a name="Function">The <tt>Function</tt> class</a>
1735 <div class="doc_text">
1738 href="/doxygen/Function_8h-source.html">llvm/Function.h</a>"</tt><br> doxygen
1739 info: <a href="/doxygen/classllvm_1_1Function.html">Function Class</a><br>
1740 Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>, <a
1741 href="#User"><tt>User</tt></a>, <a href="#Value"><tt>Value</tt></a></p>
1743 <p>The <tt>Function</tt> class represents a single procedure in LLVM. It is
1744 actually one of the more complex classes in the LLVM heirarchy because it must
1745 keep track of a large amount of data. The <tt>Function</tt> class keeps track
1746 of a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, a list of formal <a
1747 href="#Argument"><tt>Argument</tt></a>s, and a <a
1748 href="#SymbolTable"><tt>SymbolTable</tt></a>.</p>
1750 <p>The list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s is the most
1751 commonly used part of <tt>Function</tt> objects. The list imposes an implicit
1752 ordering of the blocks in the function, which indicate how the code will be
1753 layed out by the backend. Additionally, the first <a
1754 href="#BasicBlock"><tt>BasicBlock</tt></a> is the implicit entry node for the
1755 <tt>Function</tt>. It is not legal in LLVM to explicitly branch to this initial
1756 block. There are no implicit exit nodes, and in fact there may be multiple exit
1757 nodes from a single <tt>Function</tt>. If the <a
1758 href="#BasicBlock"><tt>BasicBlock</tt></a> list is empty, this indicates that
1759 the <tt>Function</tt> is actually a function declaration: the actual body of the
1760 function hasn't been linked in yet.</p>
1762 <p>In addition to a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, the
1763 <tt>Function</tt> class also keeps track of the list of formal <a
1764 href="#Argument"><tt>Argument</tt></a>s that the function receives. This
1765 container manages the lifetime of the <a href="#Argument"><tt>Argument</tt></a>
1766 nodes, just like the <a href="#BasicBlock"><tt>BasicBlock</tt></a> list does for
1767 the <a href="#BasicBlock"><tt>BasicBlock</tt></a>s.</p>
1769 <p>The <a href="#SymbolTable"><tt>SymbolTable</tt></a> is a very rarely used
1770 LLVM feature that is only used when you have to look up a value by name. Aside
1771 from that, the <a href="#SymbolTable"><tt>SymbolTable</tt></a> is used
1772 internally to make sure that there are not conflicts between the names of <a
1773 href="#Instruction"><tt>Instruction</tt></a>s, <a
1774 href="#BasicBlock"><tt>BasicBlock</tt></a>s, or <a
1775 href="#Argument"><tt>Argument</tt></a>s in the function body.</p>
1777 <p>Note that <tt>Function</tt> is a <a href="#GlobalValue">GlobalValue</a>
1778 and therefore also a <a href="#Constant">Constant</a>. The value of the function
1779 is its address (after linking) which is guaranteed to be constant.</p>
1782 <!-- _______________________________________________________________________ -->
1783 <div class="doc_subsubsection">
1784 <a name="m_Function">Important Public Members of the <tt>Function</tt>
1788 <div class="doc_text">
1791 <li><tt>Function(const </tt><tt><a href="#FunctionType">FunctionType</a>
1792 *Ty, LinkageTypes Linkage, const std::string &N = "", Module* Parent = 0)</tt>
1794 <p>Constructor used when you need to create new <tt>Function</tt>s to add
1795 the the program. The constructor must specify the type of the function to
1796 create and what type of linkage the function should have. The <a
1797 href="#FunctionType"><tt>FunctionType</tt></a> argument
1798 specifies the formal arguments and return value for the function. The same
1799 <a href="#FunctionTypel"><tt>FunctionType</tt></a> value can be used to
1800 create multiple functions. The <tt>Parent</tt> argument specifies the Module
1801 in which the function is defined. If this argument is provided, the function
1802 will automatically be inserted into that module's list of
1805 <li><tt>bool isExternal()</tt>
1807 <p>Return whether or not the <tt>Function</tt> has a body defined. If the
1808 function is "external", it does not have a body, and thus must be resolved
1809 by linking with a function defined in a different translation unit.</p></li>
1811 <li><tt>Function::iterator</tt> - Typedef for basic block list iterator<br>
1812 <tt>Function::const_iterator</tt> - Typedef for const_iterator.<br>
1814 <tt>begin()</tt>, <tt>end()</tt>
1815 <tt>size()</tt>, <tt>empty()</tt>
1817 <p>These are forwarding methods that make it easy to access the contents of
1818 a <tt>Function</tt> object's <a href="#BasicBlock"><tt>BasicBlock</tt></a>
1821 <li><tt>Function::BasicBlockListType &getBasicBlockList()</tt>
1823 <p>Returns the list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s. This
1824 is necessary to use when you need to update the list or perform a complex
1825 action that doesn't have a forwarding method.</p></li>
1827 <li><tt>Function::arg_iterator</tt> - Typedef for the argument list
1829 <tt>Function::const_arg_iterator</tt> - Typedef for const_iterator.<br>
1831 <tt>arg_begin()</tt>, <tt>arg_end()</tt>
1832 <tt>arg_size()</tt>, <tt>arg_empty()</tt>
1834 <p>These are forwarding methods that make it easy to access the contents of
1835 a <tt>Function</tt> object's <a href="#Argument"><tt>Argument</tt></a>
1838 <li><tt>Function::ArgumentListType &getArgumentList()</tt>
1840 <p>Returns the list of <a href="#Argument"><tt>Argument</tt></a>s. This is
1841 necessary to use when you need to update the list or perform a complex
1842 action that doesn't have a forwarding method.</p></li>
1844 <li><tt><a href="#BasicBlock">BasicBlock</a> &getEntryBlock()</tt>
1846 <p>Returns the entry <a href="#BasicBlock"><tt>BasicBlock</tt></a> for the
1847 function. Because the entry block for the function is always the first
1848 block, this returns the first block of the <tt>Function</tt>.</p></li>
1850 <li><tt><a href="#Type">Type</a> *getReturnType()</tt><br>
1851 <tt><a href="#FunctionType">FunctionType</a> *getFunctionType()</tt>
1853 <p>This traverses the <a href="#Type"><tt>Type</tt></a> of the
1854 <tt>Function</tt> and returns the return type of the function, or the <a
1855 href="#FunctionType"><tt>FunctionType</tt></a> of the actual
1858 <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
1860 <p> Return a pointer to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
1861 for this <tt>Function</tt>.</p></li>
1866 <!-- ======================================================================= -->
1867 <div class="doc_subsection">
1868 <a name="GlobalVariable">The <tt>GlobalVariable</tt> class</a>
1871 <div class="doc_text">
1874 href="/doxygen/GlobalVariable_8h-source.html">llvm/GlobalVariable.h</a>"</tt>
1876 doxygen info: <a href="/doxygen/classllvm_1_1GlobalVariable.html">GlobalVariable
1877 Class</a><br> Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>, <a
1878 href="#User"><tt>User</tt></a>, <a href="#Value"><tt>Value</tt></a></p>
1880 <p>Global variables are represented with the (suprise suprise)
1881 <tt>GlobalVariable</tt> class. Like functions, <tt>GlobalVariable</tt>s are also
1882 subclasses of <a href="#GlobalValue"><tt>GlobalValue</tt></a>, and as such are
1883 always referenced by their address (global values must live in memory, so their
1884 "name" refers to their address). See <a
1885 href="#GlobalValue"><tt>GlobalValue</tt></a> for more on this. Global variables
1886 may have an initial value (which must be a <a
1887 href="#Constant"><tt>Constant</tt></a>), and if they have an initializer, they
1888 may be marked as "constant" themselves (indicating that their contents never
1889 change at runtime).</p>
1893 <!-- _______________________________________________________________________ -->
1894 <div class="doc_subsubsection">
1895 <a name="m_GlobalVariable">Important Public Members of the
1896 <tt>GlobalVariable</tt> class</a>
1899 <div class="doc_text">
1902 <li><tt>GlobalVariable(const </tt><tt><a href="#Type">Type</a> *Ty, bool
1903 isConstant, LinkageTypes& Linkage, <a href="#Constant">Constant</a>
1904 *Initializer = 0, const std::string &Name = "", Module* Parent = 0)</tt>
1906 <p>Create a new global variable of the specified type. If
1907 <tt>isConstant</tt> is true then the global variable will be marked as
1908 unchanging for the program. The Linkage parameter specifies the type of
1909 linkage (internal, external, weak, linkonce, appending) for the variable. If
1910 the linkage is InternalLinkage, WeakLinkage, or LinkOnceLinkage, then
1911 the resultant global variable will have internal linkage. AppendingLinkage
1912 concatenates together all instances (in different translation units) of the
1913 variable into a single variable but is only applicable to arrays. See
1914 the <a href="LangRef.html#modulestructure">LLVM Language Reference</a> for
1915 further details on linkage types. Optionally an initializer, a name, and the
1916 module to put the variable into may be specified for the global variable as
1919 <li><tt>bool isConstant() const</tt>
1921 <p>Returns true if this is a global variable that is known not to
1922 be modified at runtime.</p></li>
1924 <li><tt>bool hasInitializer()</tt>
1926 <p>Returns true if this <tt>GlobalVariable</tt> has an intializer.</p></li>
1928 <li><tt><a href="#Constant">Constant</a> *getInitializer()</tt>
1930 <p>Returns the intial value for a <tt>GlobalVariable</tt>. It is not legal
1931 to call this method if there is no initializer.</p></li>
1936 <!-- ======================================================================= -->
1937 <div class="doc_subsection">
1938 <a name="Module">The <tt>Module</tt> class</a>
1941 <div class="doc_text">
1944 href="/doxygen/Module_8h-source.html">llvm/Module.h</a>"</tt><br> doxygen info:
1945 <a href="/doxygen/classllvm_1_1Module.html">Module Class</a></p>
1947 <p>The <tt>Module</tt> class represents the top level structure present in LLVM
1948 programs. An LLVM module is effectively either a translation unit of the
1949 original program or a combination of several translation units merged by the
1950 linker. The <tt>Module</tt> class keeps track of a list of <a
1951 href="#Function"><tt>Function</tt></a>s, a list of <a
1952 href="#GlobalVariable"><tt>GlobalVariable</tt></a>s, and a <a
1953 href="#SymbolTable"><tt>SymbolTable</tt></a>. Additionally, it contains a few
1954 helpful member functions that try to make common operations easy.</p>
1958 <!-- _______________________________________________________________________ -->
1959 <div class="doc_subsubsection">
1960 <a name="m_Module">Important Public Members of the <tt>Module</tt> class</a>
1963 <div class="doc_text">
1966 <li><tt>Module::Module(std::string name = "")</tt></li>
1969 <p>Constructing a <a href="#Module">Module</a> is easy. You can optionally
1970 provide a name for it (probably based on the name of the translation unit).</p>
1973 <li><tt>Module::iterator</tt> - Typedef for function list iterator<br>
1974 <tt>Module::const_iterator</tt> - Typedef for const_iterator.<br>
1976 <tt>begin()</tt>, <tt>end()</tt>
1977 <tt>size()</tt>, <tt>empty()</tt>
1979 <p>These are forwarding methods that make it easy to access the contents of
1980 a <tt>Module</tt> object's <a href="#Function"><tt>Function</tt></a>
1983 <li><tt>Module::FunctionListType &getFunctionList()</tt>
1985 <p> Returns the list of <a href="#Function"><tt>Function</tt></a>s. This is
1986 necessary to use when you need to update the list or perform a complex
1987 action that doesn't have a forwarding method.</p>
1989 <p><!-- Global Variable --></p></li>
1995 <li><tt>Module::global_iterator</tt> - Typedef for global variable list iterator<br>
1997 <tt>Module::const_global_iterator</tt> - Typedef for const_iterator.<br>
1999 <tt>global_begin()</tt>, <tt>global_end()</tt>
2000 <tt>global_size()</tt>, <tt>global_empty()</tt>
2002 <p> These are forwarding methods that make it easy to access the contents of
2003 a <tt>Module</tt> object's <a
2004 href="#GlobalVariable"><tt>GlobalVariable</tt></a> list.</p></li>
2006 <li><tt>Module::GlobalListType &getGlobalList()</tt>
2008 <p>Returns the list of <a
2009 href="#GlobalVariable"><tt>GlobalVariable</tt></a>s. This is necessary to
2010 use when you need to update the list or perform a complex action that
2011 doesn't have a forwarding method.</p>
2013 <p><!-- Symbol table stuff --> </p></li>
2019 <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
2021 <p>Return a reference to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
2022 for this <tt>Module</tt>.</p>
2024 <p><!-- Convenience methods --></p></li>
2030 <li><tt><a href="#Function">Function</a> *getFunction(const std::string
2031 &Name, const <a href="#FunctionType">FunctionType</a> *Ty)</tt>
2033 <p>Look up the specified function in the <tt>Module</tt> <a
2034 href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, return
2035 <tt>null</tt>.</p></li>
2037 <li><tt><a href="#Function">Function</a> *getOrInsertFunction(const
2038 std::string &Name, const <a href="#FunctionType">FunctionType</a> *T)</tt>
2040 <p>Look up the specified function in the <tt>Module</tt> <a
2041 href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, add an
2042 external declaration for the function and return it.</p></li>
2044 <li><tt>std::string getTypeName(const <a href="#Type">Type</a> *Ty)</tt>
2046 <p>If there is at least one entry in the <a
2047 href="#SymbolTable"><tt>SymbolTable</tt></a> for the specified <a
2048 href="#Type"><tt>Type</tt></a>, return it. Otherwise return the empty
2051 <li><tt>bool addTypeName(const std::string &Name, const <a
2052 href="#Type">Type</a> *Ty)</tt>
2054 <p>Insert an entry in the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
2055 mapping <tt>Name</tt> to <tt>Ty</tt>. If there is already an entry for this
2056 name, true is returned and the <a
2057 href="#SymbolTable"><tt>SymbolTable</tt></a> is not modified.</p></li>
2062 <!-- ======================================================================= -->
2063 <div class="doc_subsection">
2064 <a name="Constant">The <tt>Constant</tt> class and subclasses</a>
2067 <div class="doc_text">
2069 <p>Constant represents a base class for different types of constants. It
2070 is subclassed by ConstantBool, ConstantInt, ConstantSInt, ConstantUInt,
2071 ConstantArray etc for representing the various types of Constants.</p>
2075 <!-- _______________________________________________________________________ -->
2076 <div class="doc_subsubsection">
2077 <a name="m_Constant">Important Public Methods</a>
2079 <div class="doc_text">
2082 <!-- _______________________________________________________________________ -->
2083 <div class="doc_subsubsection">Important Subclasses of Constant </div>
2084 <div class="doc_text">
2086 <li>ConstantSInt : This subclass of Constant represents a signed integer
2089 <li><tt>int64_t getValue() const</tt>: Returns the underlying value of
2090 this constant. </li>
2093 <li>ConstantUInt : This class represents an unsigned integer.
2095 <li><tt>uint64_t getValue() const</tt>: Returns the underlying value of
2096 this constant. </li>
2099 <li>ConstantFP : This class represents a floating point constant.
2101 <li><tt>double getValue() const</tt>: Returns the underlying value of
2102 this constant. </li>
2105 <li>ConstantBool : This represents a boolean constant.
2107 <li><tt>bool getValue() const</tt>: Returns the underlying value of this
2111 <li>ConstantArray : This represents a constant array.
2113 <li><tt>const std::vector<Use> &getValues() const</tt>: Returns
2114 a vector of component constants that makeup this array. </li>
2117 <li>ConstantStruct : This represents a constant struct.
2119 <li><tt>const std::vector<Use> &getValues() const</tt>: Returns
2120 a vector of component constants that makeup this array. </li>
2123 <li>GlobalValue : This represents either a global variable or a function. In
2124 either case, the value is a constant fixed address (after linking).
2129 <!-- ======================================================================= -->
2130 <div class="doc_subsection">
2131 <a name="Type">The <tt>Type</tt> class and Derived Types</a>
2134 <div class="doc_text">
2136 <p>Type as noted earlier is also a subclass of a Value class. Any primitive
2137 type (like int, short etc) in LLVM is an instance of Type Class. All other
2138 types are instances of subclasses of type like FunctionType, ArrayType
2139 etc. DerivedType is the interface for all such dervied types including
2140 FunctionType, ArrayType, PointerType, StructType. Types can have names. They can
2141 be recursive (StructType). There exists exactly one instance of any type
2142 structure at a time. This allows using pointer equality of Type *s for comparing
2147 <!-- _______________________________________________________________________ -->
2148 <div class="doc_subsubsection">
2149 <a name="m_Value">Important Public Methods</a>
2152 <div class="doc_text">
2156 <li><tt>bool isSigned() const</tt>: Returns whether an integral numeric type
2157 is signed. This is true for SByteTy, ShortTy, IntTy, LongTy. Note that this is
2158 not true for Float and Double. </li>
2160 <li><tt>bool isUnsigned() const</tt>: Returns whether a numeric type is
2161 unsigned. This is not quite the complement of isSigned... nonnumeric types
2162 return false as they do with isSigned. This returns true for UByteTy,
2163 UShortTy, UIntTy, and ULongTy. </li>
2165 <li><tt>bool isInteger() const</tt>: Equivalent to isSigned() || isUnsigned().</li>
2167 <li><tt>bool isIntegral() const</tt>: Returns true if this is an integral
2168 type, which is either Bool type or one of the Integer types.</li>
2170 <li><tt>bool isFloatingPoint()</tt>: Return true if this is one of the two
2171 floating point types.</li>
2173 <li><tt>isLosslesslyConvertableTo (const Type *Ty) const</tt>: Return true if
2174 this type can be converted to 'Ty' without any reinterpretation of bits. For
2175 example, uint to int or one pointer type to another.</li>
2179 <!-- _______________________________________________________________________ -->
2180 <div class="doc_subsubsection">
2181 <a name="m_Value">Important Derived Types</a>
2183 <div class="doc_text">
2185 <li>SequentialType : This is subclassed by ArrayType and PointerType
2187 <li><tt>const Type * getElementType() const</tt>: Returns the type of each
2188 of the elements in the sequential type. </li>
2191 <li>ArrayType : This is a subclass of SequentialType and defines interface for
2194 <li><tt>unsigned getNumElements() const</tt>: Returns the number of
2195 elements in the array. </li>
2198 <li>PointerType : Subclass of SequentialType for pointer types. </li>
2199 <li>StructType : subclass of DerivedTypes for struct types </li>
2200 <li>FunctionType : subclass of DerivedTypes for function types.
2202 <li><tt>bool isVarArg() const</tt>: Returns true if its a vararg
2204 <li><tt> const Type * getReturnType() const</tt>: Returns the
2205 return type of the function.</li>
2206 <li><tt>const Type * getParamType (unsigned i)</tt>: Returns
2207 the type of the ith parameter.</li>
2208 <li><tt> const unsigned getNumParams() const</tt>: Returns the
2209 number of formal parameters.</li>
2215 <!-- ======================================================================= -->
2216 <div class="doc_subsection">
2217 <a name="Argument">The <tt>Argument</tt> class</a>
2220 <div class="doc_text">
2222 <p>This subclass of Value defines the interface for incoming formal
2223 arguments to a function. A Function maintains a list of its formal
2224 arguments. An argument has a pointer to the parent Function.</p>
2228 <!-- *********************************************************************** -->
2231 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
2232 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
2233 <a href="http://validator.w3.org/check/referer"><img
2234 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /></a>
2236 <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a> and
2237 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
2238 <a href="http://llvm.cs.uiuc.edu">The LLVM Compiler Infrastructure</a><br>
2239 Last modified: $Date$