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 and <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> class & <tt>-stats</tt>
41 <li>The <tt>InstVisitor</tt> template
42 <li>The general graph API
44 <li><a href="#ViewGraph">Viewing graphs while debugging code</a></li>
47 <li><a href="#datastructure">Picking the Right Data Structure for a Task</a>
49 <li><a href="#ds_sequential">Sequential Containers (std::vector, std::list, etc)</a><ul>
50 <li><a href="#dss_fixedarrays">Fixed Size Arrays</a></li>
51 <li><a href="#dss_heaparrays">Heap Allocated Arrays</a></li>
52 <li><a href="#dss_smallvector">"llvm/ADT/SmallVector.h"</a></li>
53 <li><a href="#dss_vector"><vector></a></li>
54 <li><a href="#dss_ilist">llvm/ADT/ilist</a></li>
55 <li><a href="#dss_list"><list></a></li>
57 <li><a href="#ds_set">Set-Like Containers (std::set, SmallSet, SetVector, etc)</a></li>
58 <li><a href="#ds_map">Map-Like Containers (std::map, DenseMap, etc)</a></li>
61 <li><a href="#common">Helpful Hints for Common Operations</a>
63 <li><a href="#inspection">Basic Inspection and Traversal Routines</a>
65 <li><a href="#iterate_function">Iterating over the <tt>BasicBlock</tt>s
66 in a <tt>Function</tt></a> </li>
67 <li><a href="#iterate_basicblock">Iterating over the <tt>Instruction</tt>s
68 in a <tt>BasicBlock</tt></a> </li>
69 <li><a href="#iterate_institer">Iterating over the <tt>Instruction</tt>s
70 in a <tt>Function</tt></a> </li>
71 <li><a href="#iterate_convert">Turning an iterator into a
72 class pointer</a> </li>
73 <li><a href="#iterate_complex">Finding call sites: a more
74 complex example</a> </li>
75 <li><a href="#calls_and_invokes">Treating calls and invokes
76 the same way</a> </li>
77 <li><a href="#iterate_chains">Iterating over def-use &
78 use-def chains</a> </li>
81 <li><a href="#simplechanges">Making simple changes</a>
83 <li><a href="#schanges_creating">Creating and inserting new
84 <tt>Instruction</tt>s</a> </li>
85 <li><a href="#schanges_deleting">Deleting <tt>Instruction</tt>s</a> </li>
86 <li><a href="#schanges_replacing">Replacing an <tt>Instruction</tt>
87 with another <tt>Value</tt></a> </li>
91 <li>Working with the Control Flow Graph
93 <li>Accessing predecessors and successors of a <tt>BasicBlock</tt>
101 <li><a href="#advanced">Advanced Topics</a>
103 <li><a href="#TypeResolve">LLVM Type Resolution</a>
105 <li><a href="#BuildRecType">Basic Recursive Type Construction</a></li>
106 <li><a href="#refineAbstractTypeTo">The <tt>refineAbstractTypeTo</tt> method</a></li>
107 <li><a href="#PATypeHolder">The PATypeHolder Class</a></li>
108 <li><a href="#AbstractTypeUser">The AbstractTypeUser Class</a></li>
111 <li><a href="#SymbolTable">The <tt>SymbolTable</tt> class </a></li>
114 <li><a href="#coreclasses">The Core LLVM Class Hierarchy Reference</a>
116 <li><a href="#Type">The <tt>Type</tt> class</a> </li>
117 <li><a href="#Value">The <tt>Value</tt> class</a>
119 <li><a href="#User">The <tt>User</tt> class</a>
121 <li><a href="#Instruction">The <tt>Instruction</tt> class</a>
123 <li><a href="#GetElementPtrInst">The <tt>GetElementPtrInst</tt> class</a></li>
126 <li><a href="#Module">The <tt>Module</tt> class</a></li>
127 <li><a href="#Constant">The <tt>Constant</tt> class</a>
129 <li><a href="#GlobalValue">The <tt>GlobalValue</tt> class</a>
131 <li><a href="#BasicBlock">The <tt>BasicBlock</tt>class</a></li>
132 <li><a href="#Function">The <tt>Function</tt> class</a></li>
133 <li><a href="#GlobalVariable">The <tt>GlobalVariable</tt> class</a></li>
140 <li><a href="#Argument">The <tt>Argument</tt> class</a></li>
147 <div class="doc_author">
148 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>,
149 <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a>,
150 <a href="mailto:jstanley@cs.uiuc.edu">Joel Stanley</a>, and
151 <a href="mailto:rspencer@x10sys.com">Reid Spencer</a></p>
154 <!-- *********************************************************************** -->
155 <div class="doc_section">
156 <a name="introduction">Introduction </a>
158 <!-- *********************************************************************** -->
160 <div class="doc_text">
162 <p>This document is meant to highlight some of the important classes and
163 interfaces available in the LLVM source-base. This manual is not
164 intended to explain what LLVM is, how it works, and what LLVM code looks
165 like. It assumes that you know the basics of LLVM and are interested
166 in writing transformations or otherwise analyzing or manipulating the
169 <p>This document should get you oriented so that you can find your
170 way in the continuously growing source code that makes up the LLVM
171 infrastructure. Note that this manual is not intended to serve as a
172 replacement for reading the source code, so if you think there should be
173 a method in one of these classes to do something, but it's not listed,
174 check the source. Links to the <a href="/doxygen/">doxygen</a> sources
175 are provided to make this as easy as possible.</p>
177 <p>The first section of this document describes general information that is
178 useful to know when working in the LLVM infrastructure, and the second describes
179 the Core LLVM classes. In the future this manual will be extended with
180 information describing how to use extension libraries, such as dominator
181 information, CFG traversal routines, and useful utilities like the <tt><a
182 href="/doxygen/InstVisitor_8h-source.html">InstVisitor</a></tt> template.</p>
186 <!-- *********************************************************************** -->
187 <div class="doc_section">
188 <a name="general">General Information</a>
190 <!-- *********************************************************************** -->
192 <div class="doc_text">
194 <p>This section contains general information that is useful if you are working
195 in the LLVM source-base, but that isn't specific to any particular API.</p>
199 <!-- ======================================================================= -->
200 <div class="doc_subsection">
201 <a name="stl">The C++ Standard Template Library</a>
204 <div class="doc_text">
206 <p>LLVM makes heavy use of the C++ Standard Template Library (STL),
207 perhaps much more than you are used to, or have seen before. Because of
208 this, you might want to do a little background reading in the
209 techniques used and capabilities of the library. There are many good
210 pages that discuss the STL, and several books on the subject that you
211 can get, so it will not be discussed in this document.</p>
213 <p>Here are some useful links:</p>
217 <li><a href="http://www.dinkumware.com/refxcpp.html">Dinkumware C++ Library
218 reference</a> - an excellent reference for the STL and other parts of the
219 standard C++ library.</li>
221 <li><a href="http://www.tempest-sw.com/cpp/">C++ In a Nutshell</a> - This is an
222 O'Reilly book in the making. It has a decent
224 Reference that rivals Dinkumware's, and is unfortunately no longer free since the book has been
227 <li><a href="http://www.parashift.com/c++-faq-lite/">C++ Frequently Asked
230 <li><a href="http://www.sgi.com/tech/stl/">SGI's STL Programmer's Guide</a> -
232 href="http://www.sgi.com/tech/stl/stl_introduction.html">Introduction to the
235 <li><a href="http://www.research.att.com/%7Ebs/C++.html">Bjarne Stroustrup's C++
238 <li><a href="http://64.78.49.204/">
239 Bruce Eckel's Thinking in C++, 2nd ed. Volume 2 Revision 4.0 (even better, get
244 <p>You are also encouraged to take a look at the <a
245 href="CodingStandards.html">LLVM Coding Standards</a> guide which focuses on how
246 to write maintainable code more than where to put your curly braces.</p>
250 <!-- ======================================================================= -->
251 <div class="doc_subsection">
252 <a name="stl">Other useful references</a>
255 <div class="doc_text">
258 <li><a href="http://www.psc.edu/%7Esemke/cvs_branches.html">CVS
259 Branch and Tag Primer</a></li>
260 <li><a href="http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html">Using
261 static and shared libraries across platforms</a></li>
266 <!-- *********************************************************************** -->
267 <div class="doc_section">
268 <a name="apis">Important and useful LLVM APIs</a>
270 <!-- *********************************************************************** -->
272 <div class="doc_text">
274 <p>Here we highlight some LLVM APIs that are generally useful and good to
275 know about when writing transformations.</p>
279 <!-- ======================================================================= -->
280 <div class="doc_subsection">
281 <a name="isa">The <tt>isa<></tt>, <tt>cast<></tt> and
282 <tt>dyn_cast<></tt> templates</a>
285 <div class="doc_text">
287 <p>The LLVM source-base makes extensive use of a custom form of RTTI.
288 These templates have many similarities to the C++ <tt>dynamic_cast<></tt>
289 operator, but they don't have some drawbacks (primarily stemming from
290 the fact that <tt>dynamic_cast<></tt> only works on classes that
291 have a v-table). Because they are used so often, you must know what they
292 do and how they work. All of these templates are defined in the <a
293 href="/doxygen/Casting_8h-source.html"><tt>llvm/Support/Casting.h</tt></a>
294 file (note that you very rarely have to include this file directly).</p>
297 <dt><tt>isa<></tt>: </dt>
299 <dd><p>The <tt>isa<></tt> operator works exactly like the Java
300 "<tt>instanceof</tt>" operator. It returns true or false depending on whether
301 a reference or pointer points to an instance of the specified class. This can
302 be very useful for constraint checking of various sorts (example below).</p>
305 <dt><tt>cast<></tt>: </dt>
307 <dd><p>The <tt>cast<></tt> operator is a "checked cast" operation. It
308 converts a pointer or reference from a base class to a derived cast, causing
309 an assertion failure if it is not really an instance of the right type. This
310 should be used in cases where you have some information that makes you believe
311 that something is of the right type. An example of the <tt>isa<></tt>
312 and <tt>cast<></tt> template is:</p>
314 <div class="doc_code">
316 static bool isLoopInvariant(const <a href="#Value">Value</a> *V, const Loop *L) {
317 if (isa<<a href="#Constant">Constant</a>>(V) || isa<<a href="#Argument">Argument</a>>(V) || isa<<a href="#GlobalValue">GlobalValue</a>>(V))
320 // <i>Otherwise, it must be an instruction...</i>
321 return !L->contains(cast<<a href="#Instruction">Instruction</a>>(V)->getParent());
326 <p>Note that you should <b>not</b> use an <tt>isa<></tt> test followed
327 by a <tt>cast<></tt>, for that use the <tt>dyn_cast<></tt>
332 <dt><tt>dyn_cast<></tt>:</dt>
334 <dd><p>The <tt>dyn_cast<></tt> operator is a "checking cast" operation.
335 It checks to see if the operand is of the specified type, and if so, returns a
336 pointer to it (this operator does not work with references). If the operand is
337 not of the correct type, a null pointer is returned. Thus, this works very
338 much like the <tt>dynamic_cast<></tt> operator in C++, and should be
339 used in the same circumstances. Typically, the <tt>dyn_cast<></tt>
340 operator is used in an <tt>if</tt> statement or some other flow control
341 statement like this:</p>
343 <div class="doc_code">
345 if (<a href="#AllocationInst">AllocationInst</a> *AI = dyn_cast<<a href="#AllocationInst">AllocationInst</a>>(Val)) {
351 <p>This form of the <tt>if</tt> statement effectively combines together a call
352 to <tt>isa<></tt> and a call to <tt>cast<></tt> into one
353 statement, which is very convenient.</p>
355 <p>Note that the <tt>dyn_cast<></tt> operator, like C++'s
356 <tt>dynamic_cast<></tt> or Java's <tt>instanceof</tt> operator, can be
357 abused. In particular, you should not use big chained <tt>if/then/else</tt>
358 blocks to check for lots of different variants of classes. If you find
359 yourself wanting to do this, it is much cleaner and more efficient to use the
360 <tt>InstVisitor</tt> class to dispatch over the instruction type directly.</p>
364 <dt><tt>cast_or_null<></tt>: </dt>
366 <dd><p>The <tt>cast_or_null<></tt> operator works just like the
367 <tt>cast<></tt> operator, except that it allows for a null pointer as an
368 argument (which it then propagates). This can sometimes be useful, allowing
369 you to combine several null checks into one.</p></dd>
371 <dt><tt>dyn_cast_or_null<></tt>: </dt>
373 <dd><p>The <tt>dyn_cast_or_null<></tt> operator works just like the
374 <tt>dyn_cast<></tt> operator, except that it allows for a null pointer
375 as an argument (which it then propagates). This can sometimes be useful,
376 allowing you to combine several null checks into one.</p></dd>
380 <p>These five templates can be used with any classes, whether they have a
381 v-table or not. To add support for these templates, you simply need to add
382 <tt>classof</tt> static methods to the class you are interested casting
383 to. Describing this is currently outside the scope of this document, but there
384 are lots of examples in the LLVM source base.</p>
388 <!-- ======================================================================= -->
389 <div class="doc_subsection">
390 <a name="DEBUG">The <tt>DEBUG()</tt> macro and <tt>-debug</tt> option</a>
393 <div class="doc_text">
395 <p>Often when working on your pass you will put a bunch of debugging printouts
396 and other code into your pass. After you get it working, you want to remove
397 it, but you may need it again in the future (to work out new bugs that you run
400 <p> Naturally, because of this, you don't want to delete the debug printouts,
401 but you don't want them to always be noisy. A standard compromise is to comment
402 them out, allowing you to enable them if you need them in the future.</p>
404 <p>The "<tt><a href="/doxygen/Debug_8h-source.html">llvm/Support/Debug.h</a></tt>"
405 file provides a macro named <tt>DEBUG()</tt> that is a much nicer solution to
406 this problem. Basically, you can put arbitrary code into the argument of the
407 <tt>DEBUG</tt> macro, and it is only executed if '<tt>opt</tt>' (or any other
408 tool) is run with the '<tt>-debug</tt>' command line argument:</p>
410 <div class="doc_code">
412 DOUT << "I am here!\n";
416 <p>Then you can run your pass like this:</p>
418 <div class="doc_code">
420 $ opt < a.bc > /dev/null -mypass
421 <i><no output></i>
422 $ opt < a.bc > /dev/null -mypass -debug
427 <p>Using the <tt>DEBUG()</tt> macro instead of a home-brewed solution allows you
428 to not have to create "yet another" command line option for the debug output for
429 your pass. Note that <tt>DEBUG()</tt> macros are disabled for optimized builds,
430 so they do not cause a performance impact at all (for the same reason, they
431 should also not contain side-effects!).</p>
433 <p>One additional nice thing about the <tt>DEBUG()</tt> macro is that you can
434 enable or disable it directly in gdb. Just use "<tt>set DebugFlag=0</tt>" or
435 "<tt>set DebugFlag=1</tt>" from the gdb if the program is running. If the
436 program hasn't been started yet, you can always just run it with
441 <!-- _______________________________________________________________________ -->
442 <div class="doc_subsubsection">
443 <a name="DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt> and
444 the <tt>-debug-only</tt> option</a>
447 <div class="doc_text">
449 <p>Sometimes you may find yourself in a situation where enabling <tt>-debug</tt>
450 just turns on <b>too much</b> information (such as when working on the code
451 generator). If you want to enable debug information with more fine-grained
452 control, you define the <tt>DEBUG_TYPE</tt> macro and the <tt>-debug</tt> only
453 option as follows:</p>
455 <div class="doc_code">
457 DOUT << "No debug type\n";
459 #define DEBUG_TYPE "foo"
460 DOUT << "'foo' debug type\n";
462 #define DEBUG_TYPE "bar"
463 DOUT << "'bar' debug type\n";
465 #define DEBUG_TYPE ""
466 DOUT << "No debug type (2)\n";
470 <p>Then you can run your pass like this:</p>
472 <div class="doc_code">
474 $ opt < a.bc > /dev/null -mypass
475 <i><no output></i>
476 $ opt < a.bc > /dev/null -mypass -debug
481 $ opt < a.bc > /dev/null -mypass -debug-only=foo
483 $ opt < a.bc > /dev/null -mypass -debug-only=bar
488 <p>Of course, in practice, you should only set <tt>DEBUG_TYPE</tt> at the top of
489 a file, to specify the debug type for the entire module (if you do this before
490 you <tt>#include "llvm/Support/Debug.h"</tt>, you don't have to insert the ugly
491 <tt>#undef</tt>'s). Also, you should use names more meaningful than "foo" and
492 "bar", because there is no system in place to ensure that names do not
493 conflict. If two different modules use the same string, they will all be turned
494 on when the name is specified. This allows, for example, all debug information
495 for instruction scheduling to be enabled with <tt>-debug-type=InstrSched</tt>,
496 even if the source lives in multiple files.</p>
500 <!-- ======================================================================= -->
501 <div class="doc_subsection">
502 <a name="Statistic">The <tt>Statistic</tt> class & <tt>-stats</tt>
506 <div class="doc_text">
509 href="/doxygen/Statistic_8h-source.html">llvm/ADT/Statistic.h</a></tt>" file
510 provides a class named <tt>Statistic</tt> that is used as a unified way to
511 keep track of what the LLVM compiler is doing and how effective various
512 optimizations are. It is useful to see what optimizations are contributing to
513 making a particular program run faster.</p>
515 <p>Often you may run your pass on some big program, and you're interested to see
516 how many times it makes a certain transformation. Although you can do this with
517 hand inspection, or some ad-hoc method, this is a real pain and not very useful
518 for big programs. Using the <tt>Statistic</tt> class makes it very easy to
519 keep track of this information, and the calculated information is presented in a
520 uniform manner with the rest of the passes being executed.</p>
522 <p>There are many examples of <tt>Statistic</tt> uses, but the basics of using
523 it are as follows:</p>
526 <li><p>Define your statistic like this:</p>
528 <div class="doc_code">
530 #define <a href="#DEBUG_TYPE">DEBUG_TYPE</a> "mypassname" <i>// This goes before any #includes.</i>
531 STATISTIC(NumXForms, "The # of times I did stuff");
535 <p>The <tt>STATISTIC</tt> macro defines a static variable, whose name is
536 specified by the first argument. The pass name is taken from the DEBUG_TYPE
537 macro, and the description is taken from the second argument. The variable
538 defined ("NumXForms" in this case) acts like an unsigned integer.</p></li>
540 <li><p>Whenever you make a transformation, bump the counter:</p>
542 <div class="doc_code">
544 ++NumXForms; // <i>I did stuff!</i>
551 <p>That's all you have to do. To get '<tt>opt</tt>' to print out the
552 statistics gathered, use the '<tt>-stats</tt>' option:</p>
554 <div class="doc_code">
556 $ opt -stats -mypassname < program.bc > /dev/null
557 <i>... statistics output ...</i>
561 <p> When running <tt>gccas</tt> on a C file from the SPEC benchmark
562 suite, it gives a report that looks like this:</p>
564 <div class="doc_code">
566 7646 bytecodewriter - Number of normal instructions
567 725 bytecodewriter - Number of oversized instructions
568 129996 bytecodewriter - Number of bytecode bytes written
569 2817 raise - Number of insts DCEd or constprop'd
570 3213 raise - Number of cast-of-self removed
571 5046 raise - Number of expression trees converted
572 75 raise - Number of other getelementptr's formed
573 138 raise - Number of load/store peepholes
574 42 deadtypeelim - Number of unused typenames removed from symtab
575 392 funcresolve - Number of varargs functions resolved
576 27 globaldce - Number of global variables removed
577 2 adce - Number of basic blocks removed
578 134 cee - Number of branches revectored
579 49 cee - Number of setcc instruction eliminated
580 532 gcse - Number of loads removed
581 2919 gcse - Number of instructions removed
582 86 indvars - Number of canonical indvars added
583 87 indvars - Number of aux indvars removed
584 25 instcombine - Number of dead inst eliminate
585 434 instcombine - Number of insts combined
586 248 licm - Number of load insts hoisted
587 1298 licm - Number of insts hoisted to a loop pre-header
588 3 licm - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)
589 75 mem2reg - Number of alloca's promoted
590 1444 cfgsimplify - Number of blocks simplified
594 <p>Obviously, with so many optimizations, having a unified framework for this
595 stuff is very nice. Making your pass fit well into the framework makes it more
596 maintainable and useful.</p>
600 <!-- ======================================================================= -->
601 <div class="doc_subsection">
602 <a name="ViewGraph">Viewing graphs while debugging code</a>
605 <div class="doc_text">
607 <p>Several of the important data structures in LLVM are graphs: for example
608 CFGs made out of LLVM <a href="#BasicBlock">BasicBlock</a>s, CFGs made out of
609 LLVM <a href="CodeGenerator.html#machinebasicblock">MachineBasicBlock</a>s, and
610 <a href="CodeGenerator.html#selectiondag_intro">Instruction Selection
611 DAGs</a>. In many cases, while debugging various parts of the compiler, it is
612 nice to instantly visualize these graphs.</p>
614 <p>LLVM provides several callbacks that are available in a debug build to do
615 exactly that. If you call the <tt>Function::viewCFG()</tt> method, for example,
616 the current LLVM tool will pop up a window containing the CFG for the function
617 where each basic block is a node in the graph, and each node contains the
618 instructions in the block. Similarly, there also exists
619 <tt>Function::viewCFGOnly()</tt> (does not include the instructions), the
620 <tt>MachineFunction::viewCFG()</tt> and <tt>MachineFunction::viewCFGOnly()</tt>,
621 and the <tt>SelectionDAG::viewGraph()</tt> methods. Within GDB, for example,
622 you can usually use something like <tt>call DAG.viewGraph()</tt> to pop
623 up a window. Alternatively, you can sprinkle calls to these functions in your
624 code in places you want to debug.</p>
626 <p>Getting this to work requires a small amount of configuration. On Unix
627 systems with X11, install the <a href="http://www.graphviz.org">graphviz</a>
628 toolkit, and make sure 'dot' and 'gv' are in your path. If you are running on
629 Mac OS/X, download and install the Mac OS/X <a
630 href="http://www.pixelglow.com/graphviz/">Graphviz program</a>, and add
631 <tt>/Applications/Graphviz.app/Contents/MacOS/</tt> (or whereever you install
632 it) to your path. Once in your system and path are set up, rerun the LLVM
633 configure script and rebuild LLVM to enable this functionality.</p>
635 <p><tt>SelectionDAG</tt> has been extended to make it easier to locate
636 <i>interesting</i> nodes in large complex graphs. From gdb, if you
637 <tt>call DAG.setGraphColor(<i>node</i>, "<i>color</i>")</tt>, then the
638 next <tt>call DAG.viewGraph()</tt> would hilight the node in the
639 specified color (choices of colors can be found at <a
640 href="http://www.graphviz.org/doc/info/colors.html">Colors<a>.) More
641 complex node attributes can be provided with <tt>call
642 DAG.setGraphAttrs(<i>node</i>, "<i>attributes</i>")</tt> (choices can be
643 found at <a href="http://www.graphviz.org/doc/info/attrs.html">Graph
644 Attributes</a>.) If you want to restart and clear all the current graph
645 attributes, then you can <tt>call DAG.clearGraphAttrs()</tt>. </p>
649 <!-- *********************************************************************** -->
650 <div class="doc_section">
651 <a name="datastructure">Picking the Right Data Structure for a Task</a>
653 <!-- *********************************************************************** -->
655 <div class="doc_text">
657 <p>LLVM has a plethora of datastructures in the <tt>llvm/ADT/</tt> directory,
658 and we commonly use STL datastructures. This section describes the tradeoffs
659 you should consider when you pick one.</p>
662 The first step is a choose your own adventure: do you want a sequential
663 container, a set-like container, or a map-like container? The most important
664 thing when choosing a container is the algorithmic properties of how you plan to
665 access the container. Based on that, you should use:</p>
668 <li>a <a href="#ds_map">map-like</a> container if you need efficient lookup
669 of an value based on another value. Map-like containers also support
670 efficient queries for containment (whether a key is in the map). Map-like
671 containers generally do not support efficient reverse mapping (values to
672 keys). If you need that, use two maps. Some map-like containers also
673 support efficient iteration through the keys in sorted order. Map-like
674 containers are the most expensive sort, only use them if you need one of
675 these capabilities.</li>
677 <li>a <a href="#ds_set">set-like</a> container if you need to put a bunch of
678 stuff into a container that automatically eliminates duplicates. Some
679 set-like containers support efficient iteration through the elements in
680 sorted order. Set-like containers are more expensive than sequential
684 <li>a <a href="#ds_sequential">sequential</a> container provides
685 the most efficient way to add elements and keeps track of the order they are
686 added to the collection. They permit duplicates and support efficient
687 iteration, but do not support efficient lookup based on a key.
693 Once the proper catagory of container is determined, you can fine tune the
694 memory use, constant factors, and cache behaviors of access by intelligently
695 picking a member of the catagory. Note that constant factors and cache behavior
696 can be a big deal. If you have a vector that usually only contains a few
697 elements (but could contain many), for example, it's much better to use
698 <a href="#dss_smallvector">SmallVector</a> than <a href="#dss_vector">vector</a>
699 . Doing so avoids (relatively) expensive malloc/free calls, which dwarf the
700 cost of adding the elements to the container. </p>
704 <!-- ======================================================================= -->
705 <div class="doc_subsection">
706 <a name="ds_sequential">Sequential Containers (std::vector, std::list, etc)</a>
709 <div class="doc_text">
710 There are a variety of sequential containers available for you, based on your
711 needs. Pick the first in this section that will do what you want.
714 <!-- _______________________________________________________________________ -->
715 <div class="doc_subsubsection">
716 <a name="dss_fixedarrays">Fixed Size Arrays</a>
719 <div class="doc_text">
720 <p>Fixed size arrays are very simple and very fast. They are good if you know
721 exactly how many elements you have, or you have a (low) upper bound on how many
725 <!-- _______________________________________________________________________ -->
726 <div class="doc_subsubsection">
727 <a name="dss_heaparrays">Heap Allocated Arrays</a>
730 <div class="doc_text">
731 <p>Heap allocated arrays (new[] + delete[]) are also simple. They are good if
732 the number of elements is variable, if you know how many elements you will need
733 before the array is allocated, and if the array is usually large (if not,
734 consider a <a href="#dss_smallvector">SmallVector</a>). The cost of a heap
735 allocated array is the cost of the new/delete (aka malloc/free). Also note that
736 if you are allocating an array of a type with a constructor, the constructor and
737 destructors will be run for every element in the array (resizable vectors only
738 construct those elements actually used).</p>
741 <!-- _______________________________________________________________________ -->
742 <div class="doc_subsubsection">
743 <a name="dss_smallvector">"llvm/ADT/SmallVector.h"</a>
746 <div class="doc_text">
747 <p><tt>SmallVector<Type, N></tt> is a simple class that looks and smells
748 just like <tt>vector<Type></tt>:
749 it supports efficient iteration, lays out elements in memory order (so you can
750 do pointer arithmetic between elements), supports efficient push_back/pop_back
751 operations, supports efficient random access to its elements, etc.</p>
753 <p>The advantage of SmallVector is that it allocates space for
754 some number of elements (N) <b>in the object itself</b>. Because of this, if
755 the SmallVector is dynamically smaller than N, no malloc is performed. This can
756 be a big win in cases where the malloc/free call is far more expensive than the
757 code that fiddles around with the elements.</p>
759 <p>This is good for vectors that are "usually small" (e.g. the number of
760 predecessors/successors of a block is usually less than 8). On the other hand,
761 this makes the size of the SmallVector itself large, so you don't want to
762 allocate lots of them (doing so will waste a lot of space). As such,
763 SmallVectors are most useful when on the stack.</p>
765 <p>SmallVector also provides a nice portable and efficient replacement for
770 <!-- _______________________________________________________________________ -->
771 <div class="doc_subsubsection">
772 <a name="dss_vector"><vector></a>
775 <div class="doc_text">
777 std::vector is well loved and respected. It is useful when SmallVector isn't:
778 when the size of the vector is often large (thus the small optimization will
779 rarely be a benefit) or if you will be allocating many instances of the vector
780 itself (which would waste space for elements that aren't in the container).
781 vector is also useful when interfacing with code that expects vectors :).
785 <!-- _______________________________________________________________________ -->
786 <div class="doc_subsubsection">
787 <a name="dss_list"><list></a>
790 <div class="doc_text">
791 <p>std::list is an extremely inefficient class that is rarely useful.
792 It performs a heap allocation for every element inserted into it, thus having an
793 extremely high constant factor, particularly for small data types. std::list
794 also only supports bidirectional iteration, not random access iteration.</p>
796 <p>In exchange for this high cost, std::list supports efficient access to both
797 ends of the list (like std::deque, but unlike std::vector or SmallVector). In
798 addition, the iterator invalidation characteristics of std::list are stronger
799 than that of a vector class: inserting or removing an element into the list does
800 not invalidate iterator or pointers to other elements in the list.</p>
803 <!-- _______________________________________________________________________ -->
804 <div class="doc_subsubsection">
805 <a name="dss_ilist">llvm/ADT/ilist</a>
808 <div class="doc_text">
809 <p><tt>ilist<T></tt> implements an 'intrusive' doubly-linked list. It is
810 intrusive, because it requires the element to store and provide access to the
811 prev/next pointers for the list.</p>
813 <p>ilist has the same drawbacks as std::list, and additionally requires an
814 ilist_traits implementation for the element type, but it provides some novel
815 characteristics. In particular, it can efficiently store polymorphic objects,
816 the traits class is informed when an element is inserted or removed from the
817 list, and ilists are guaranteed to support a constant-time splice operation.
820 <p>These properties are exactly what we want for things like Instructions and
821 basic blocks, which is why these are implemented with ilists.</p>
824 <!-- _______________________________________________________________________ -->
825 <div class="doc_subsubsection">
826 <a name="dss_other">Other options</a>
829 <div class="doc_text">
830 <p>Other STL containers are available, such as std::deque (which has similar
831 characteristics to std::vector, but has higher constant factors and provides
832 efficient push_front/pop_front methods) and std::string.</p>
834 <p>There are also various STL adapter classes such as std::queue,
835 std::priority_queue, std::stack, etc. These provide simplified access to an
836 underlying container but don't affect the cost of the container itself.</p>
841 <!-- ======================================================================= -->
842 <div class="doc_subsection">
843 <a name="ds_set">Set-Like Containers (std::set, SmallSet, SetVector, etc)</a>
846 <div class="doc_text">
860 <!-- ======================================================================= -->
861 <div class="doc_subsection">
862 <a name="ds_map">Map-Like Containers (std::map, DenseMap, etc)</a>
865 <div class="doc_text">
875 <!-- *********************************************************************** -->
876 <div class="doc_section">
877 <a name="common">Helpful Hints for Common Operations</a>
879 <!-- *********************************************************************** -->
881 <div class="doc_text">
883 <p>This section describes how to perform some very simple transformations of
884 LLVM code. This is meant to give examples of common idioms used, showing the
885 practical side of LLVM transformations. <p> Because this is a "how-to" section,
886 you should also read about the main classes that you will be working with. The
887 <a href="#coreclasses">Core LLVM Class Hierarchy Reference</a> contains details
888 and descriptions of the main classes that you should know about.</p>
892 <!-- NOTE: this section should be heavy on example code -->
893 <!-- ======================================================================= -->
894 <div class="doc_subsection">
895 <a name="inspection">Basic Inspection and Traversal Routines</a>
898 <div class="doc_text">
900 <p>The LLVM compiler infrastructure have many different data structures that may
901 be traversed. Following the example of the C++ standard template library, the
902 techniques used to traverse these various data structures are all basically the
903 same. For a enumerable sequence of values, the <tt>XXXbegin()</tt> function (or
904 method) returns an iterator to the start of the sequence, the <tt>XXXend()</tt>
905 function returns an iterator pointing to one past the last valid element of the
906 sequence, and there is some <tt>XXXiterator</tt> data type that is common
907 between the two operations.</p>
909 <p>Because the pattern for iteration is common across many different aspects of
910 the program representation, the standard template library algorithms may be used
911 on them, and it is easier to remember how to iterate. First we show a few common
912 examples of the data structures that need to be traversed. Other data
913 structures are traversed in very similar ways.</p>
917 <!-- _______________________________________________________________________ -->
918 <div class="doc_subsubsection">
919 <a name="iterate_function">Iterating over the </a><a
920 href="#BasicBlock"><tt>BasicBlock</tt></a>s in a <a
921 href="#Function"><tt>Function</tt></a>
924 <div class="doc_text">
926 <p>It's quite common to have a <tt>Function</tt> instance that you'd like to
927 transform in some way; in particular, you'd like to manipulate its
928 <tt>BasicBlock</tt>s. To facilitate this, you'll need to iterate over all of
929 the <tt>BasicBlock</tt>s that constitute the <tt>Function</tt>. The following is
930 an example that prints the name of a <tt>BasicBlock</tt> and the number of
931 <tt>Instruction</tt>s it contains:</p>
933 <div class="doc_code">
935 // <i>func is a pointer to a Function instance</i>
936 for (Function::iterator i = func->begin(), e = func->end(); i != e; ++i)
937 // <i>Print out the name of the basic block if it has one, and then the</i>
938 // <i>number of instructions that it contains</i>
939 llvm::cerr << "Basic block (name=" << i->getName() << ") has "
940 << i->size() << " instructions.\n";
944 <p>Note that i can be used as if it were a pointer for the purposes of
945 invoking member functions of the <tt>Instruction</tt> class. This is
946 because the indirection operator is overloaded for the iterator
947 classes. In the above code, the expression <tt>i->size()</tt> is
948 exactly equivalent to <tt>(*i).size()</tt> just like you'd expect.</p>
952 <!-- _______________________________________________________________________ -->
953 <div class="doc_subsubsection">
954 <a name="iterate_basicblock">Iterating over the </a><a
955 href="#Instruction"><tt>Instruction</tt></a>s in a <a
956 href="#BasicBlock"><tt>BasicBlock</tt></a>
959 <div class="doc_text">
961 <p>Just like when dealing with <tt>BasicBlock</tt>s in <tt>Function</tt>s, it's
962 easy to iterate over the individual instructions that make up
963 <tt>BasicBlock</tt>s. Here's a code snippet that prints out each instruction in
964 a <tt>BasicBlock</tt>:</p>
966 <div class="doc_code">
968 // <i>blk is a pointer to a BasicBlock instance</i>
969 for (BasicBlock::iterator i = blk->begin(), e = blk->end(); i != e; ++i)
970 // <i>The next statement works since operator<<(ostream&,...)</i>
971 // <i>is overloaded for Instruction&</i>
972 llvm::cerr << *i << "\n";
976 <p>However, this isn't really the best way to print out the contents of a
977 <tt>BasicBlock</tt>! Since the ostream operators are overloaded for virtually
978 anything you'll care about, you could have just invoked the print routine on the
979 basic block itself: <tt>llvm::cerr << *blk << "\n";</tt>.</p>
983 <!-- _______________________________________________________________________ -->
984 <div class="doc_subsubsection">
985 <a name="iterate_institer">Iterating over the </a><a
986 href="#Instruction"><tt>Instruction</tt></a>s in a <a
987 href="#Function"><tt>Function</tt></a>
990 <div class="doc_text">
992 <p>If you're finding that you commonly iterate over a <tt>Function</tt>'s
993 <tt>BasicBlock</tt>s and then that <tt>BasicBlock</tt>'s <tt>Instruction</tt>s,
994 <tt>InstIterator</tt> should be used instead. You'll need to include <a
995 href="/doxygen/InstIterator_8h-source.html"><tt>llvm/Support/InstIterator.h</tt></a>,
996 and then instantiate <tt>InstIterator</tt>s explicitly in your code. Here's a
997 small example that shows how to dump all instructions in a function to the standard error stream:<p>
999 <div class="doc_code">
1001 #include "<a href="/doxygen/InstIterator_8h-source.html">llvm/Support/InstIterator.h</a>"
1003 // <i>F is a ptr to a Function instance</i>
1004 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
1005 llvm::cerr << *i << "\n";
1009 <p>Easy, isn't it? You can also use <tt>InstIterator</tt>s to fill a
1010 worklist with its initial contents. For example, if you wanted to
1011 initialize a worklist to contain all instructions in a <tt>Function</tt>
1012 F, all you would need to do is something like:</p>
1014 <div class="doc_code">
1016 std::set<Instruction*> worklist;
1017 worklist.insert(inst_begin(F), inst_end(F));
1021 <p>The STL set <tt>worklist</tt> would now contain all instructions in the
1022 <tt>Function</tt> pointed to by F.</p>
1026 <!-- _______________________________________________________________________ -->
1027 <div class="doc_subsubsection">
1028 <a name="iterate_convert">Turning an iterator into a class pointer (and
1032 <div class="doc_text">
1034 <p>Sometimes, it'll be useful to grab a reference (or pointer) to a class
1035 instance when all you've got at hand is an iterator. Well, extracting
1036 a reference or a pointer from an iterator is very straight-forward.
1037 Assuming that <tt>i</tt> is a <tt>BasicBlock::iterator</tt> and <tt>j</tt>
1038 is a <tt>BasicBlock::const_iterator</tt>:</p>
1040 <div class="doc_code">
1042 Instruction& inst = *i; // <i>Grab reference to instruction reference</i>
1043 Instruction* pinst = &*i; // <i>Grab pointer to instruction reference</i>
1044 const Instruction& inst = *j;
1048 <p>However, the iterators you'll be working with in the LLVM framework are
1049 special: they will automatically convert to a ptr-to-instance type whenever they
1050 need to. Instead of dereferencing the iterator and then taking the address of
1051 the result, you can simply assign the iterator to the proper pointer type and
1052 you get the dereference and address-of operation as a result of the assignment
1053 (behind the scenes, this is a result of overloading casting mechanisms). Thus
1054 the last line of the last example,</p>
1056 <div class="doc_code">
1058 Instruction* pinst = &*i;
1062 <p>is semantically equivalent to</p>
1064 <div class="doc_code">
1066 Instruction* pinst = i;
1070 <p>It's also possible to turn a class pointer into the corresponding iterator,
1071 and this is a constant time operation (very efficient). The following code
1072 snippet illustrates use of the conversion constructors provided by LLVM
1073 iterators. By using these, you can explicitly grab the iterator of something
1074 without actually obtaining it via iteration over some structure:</p>
1076 <div class="doc_code">
1078 void printNextInstruction(Instruction* inst) {
1079 BasicBlock::iterator it(inst);
1080 ++it; // <i>After this line, it refers to the instruction after *inst</i>
1081 if (it != inst->getParent()->end()) llvm::cerr << *it << "\n";
1088 <!--_______________________________________________________________________-->
1089 <div class="doc_subsubsection">
1090 <a name="iterate_complex">Finding call sites: a slightly more complex
1094 <div class="doc_text">
1096 <p>Say that you're writing a FunctionPass and would like to count all the
1097 locations in the entire module (that is, across every <tt>Function</tt>) where a
1098 certain function (i.e., some <tt>Function</tt>*) is already in scope. As you'll
1099 learn later, you may want to use an <tt>InstVisitor</tt> to accomplish this in a
1100 much more straight-forward manner, but this example will allow us to explore how
1101 you'd do it if you didn't have <tt>InstVisitor</tt> around. In pseudocode, this
1102 is what we want to do:</p>
1104 <div class="doc_code">
1106 initialize callCounter to zero
1107 for each Function f in the Module
1108 for each BasicBlock b in f
1109 for each Instruction i in b
1110 if (i is a CallInst and calls the given function)
1111 increment callCounter
1115 <p>And the actual code is (remember, because we're writing a
1116 <tt>FunctionPass</tt>, our <tt>FunctionPass</tt>-derived class simply has to
1117 override the <tt>runOnFunction</tt> method):</p>
1119 <div class="doc_code">
1121 Function* targetFunc = ...;
1123 class OurFunctionPass : public FunctionPass {
1125 OurFunctionPass(): callCounter(0) { }
1127 virtual runOnFunction(Function& F) {
1128 for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) {
1129 for (BasicBlock::iterator i = b->begin(); ie = b->end(); i != ie; ++i) {
1130 if (<a href="#CallInst">CallInst</a>* callInst = <a href="#isa">dyn_cast</a><<a
1131 href="#CallInst">CallInst</a>>(&*i)) {
1132 // <i>We know we've encountered a call instruction, so we</i>
1133 // <i>need to determine if it's a call to the</i>
1134 // <i>function pointed to by m_func or not</i>
1136 if (callInst->getCalledFunction() == targetFunc)
1144 unsigned callCounter;
1151 <!--_______________________________________________________________________-->
1152 <div class="doc_subsubsection">
1153 <a name="calls_and_invokes">Treating calls and invokes the same way</a>
1156 <div class="doc_text">
1158 <p>You may have noticed that the previous example was a bit oversimplified in
1159 that it did not deal with call sites generated by 'invoke' instructions. In
1160 this, and in other situations, you may find that you want to treat
1161 <tt>CallInst</tt>s and <tt>InvokeInst</tt>s the same way, even though their
1162 most-specific common base class is <tt>Instruction</tt>, which includes lots of
1163 less closely-related things. For these cases, LLVM provides a handy wrapper
1165 href="http://llvm.org/doxygen/classllvm_1_1CallSite.html"><tt>CallSite</tt></a>.
1166 It is essentially a wrapper around an <tt>Instruction</tt> pointer, with some
1167 methods that provide functionality common to <tt>CallInst</tt>s and
1168 <tt>InvokeInst</tt>s.</p>
1170 <p>This class has "value semantics": it should be passed by value, not by
1171 reference and it should not be dynamically allocated or deallocated using
1172 <tt>operator new</tt> or <tt>operator delete</tt>. It is efficiently copyable,
1173 assignable and constructable, with costs equivalents to that of a bare pointer.
1174 If you look at its definition, it has only a single pointer member.</p>
1178 <!--_______________________________________________________________________-->
1179 <div class="doc_subsubsection">
1180 <a name="iterate_chains">Iterating over def-use & use-def chains</a>
1183 <div class="doc_text">
1185 <p>Frequently, we might have an instance of the <a
1186 href="/doxygen/classllvm_1_1Value.html">Value Class</a> and we want to
1187 determine which <tt>User</tt>s use the <tt>Value</tt>. The list of all
1188 <tt>User</tt>s of a particular <tt>Value</tt> is called a <i>def-use</i> chain.
1189 For example, let's say we have a <tt>Function*</tt> named <tt>F</tt> to a
1190 particular function <tt>foo</tt>. Finding all of the instructions that
1191 <i>use</i> <tt>foo</tt> is as simple as iterating over the <i>def-use</i> chain
1194 <div class="doc_code">
1198 for (Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i)
1199 if (Instruction *Inst = dyn_cast<Instruction>(*i)) {
1200 llvm::cerr << "F is used in instruction:\n";
1201 llvm::cerr << *Inst << "\n";
1206 <p>Alternately, it's common to have an instance of the <a
1207 href="/doxygen/classllvm_1_1User.html">User Class</a> and need to know what
1208 <tt>Value</tt>s are used by it. The list of all <tt>Value</tt>s used by a
1209 <tt>User</tt> is known as a <i>use-def</i> chain. Instances of class
1210 <tt>Instruction</tt> are common <tt>User</tt>s, so we might want to iterate over
1211 all of the values that a particular instruction uses (that is, the operands of
1212 the particular <tt>Instruction</tt>):</p>
1214 <div class="doc_code">
1216 Instruction* pi = ...;
1218 for (User::op_iterator i = pi->op_begin(), e = pi->op_end(); i != e; ++i) {
1226 def-use chains ("finding all users of"): Value::use_begin/use_end
1227 use-def chains ("finding all values used"): User::op_begin/op_end [op=operand]
1232 <!-- ======================================================================= -->
1233 <div class="doc_subsection">
1234 <a name="simplechanges">Making simple changes</a>
1237 <div class="doc_text">
1239 <p>There are some primitive transformation operations present in the LLVM
1240 infrastructure that are worth knowing about. When performing
1241 transformations, it's fairly common to manipulate the contents of basic
1242 blocks. This section describes some of the common methods for doing so
1243 and gives example code.</p>
1247 <!--_______________________________________________________________________-->
1248 <div class="doc_subsubsection">
1249 <a name="schanges_creating">Creating and inserting new
1250 <tt>Instruction</tt>s</a>
1253 <div class="doc_text">
1255 <p><i>Instantiating Instructions</i></p>
1257 <p>Creation of <tt>Instruction</tt>s is straight-forward: simply call the
1258 constructor for the kind of instruction to instantiate and provide the necessary
1259 parameters. For example, an <tt>AllocaInst</tt> only <i>requires</i> a
1260 (const-ptr-to) <tt>Type</tt>. Thus:</p>
1262 <div class="doc_code">
1264 AllocaInst* ai = new AllocaInst(Type::IntTy);
1268 <p>will create an <tt>AllocaInst</tt> instance that represents the allocation of
1269 one integer in the current stack frame, at runtime. Each <tt>Instruction</tt>
1270 subclass is likely to have varying default parameters which change the semantics
1271 of the instruction, so refer to the <a
1272 href="/doxygen/classllvm_1_1Instruction.html">doxygen documentation for the subclass of
1273 Instruction</a> that you're interested in instantiating.</p>
1275 <p><i>Naming values</i></p>
1277 <p>It is very useful to name the values of instructions when you're able to, as
1278 this facilitates the debugging of your transformations. If you end up looking
1279 at generated LLVM machine code, you definitely want to have logical names
1280 associated with the results of instructions! By supplying a value for the
1281 <tt>Name</tt> (default) parameter of the <tt>Instruction</tt> constructor, you
1282 associate a logical name with the result of the instruction's execution at
1283 runtime. For example, say that I'm writing a transformation that dynamically
1284 allocates space for an integer on the stack, and that integer is going to be
1285 used as some kind of index by some other code. To accomplish this, I place an
1286 <tt>AllocaInst</tt> at the first point in the first <tt>BasicBlock</tt> of some
1287 <tt>Function</tt>, and I'm intending to use it within the same
1288 <tt>Function</tt>. I might do:</p>
1290 <div class="doc_code">
1292 AllocaInst* pa = new AllocaInst(Type::IntTy, 0, "indexLoc");
1296 <p>where <tt>indexLoc</tt> is now the logical name of the instruction's
1297 execution value, which is a pointer to an integer on the runtime stack.</p>
1299 <p><i>Inserting instructions</i></p>
1301 <p>There are essentially two ways to insert an <tt>Instruction</tt>
1302 into an existing sequence of instructions that form a <tt>BasicBlock</tt>:</p>
1305 <li>Insertion into an explicit instruction list
1307 <p>Given a <tt>BasicBlock* pb</tt>, an <tt>Instruction* pi</tt> within that
1308 <tt>BasicBlock</tt>, and a newly-created instruction we wish to insert
1309 before <tt>*pi</tt>, we do the following: </p>
1311 <div class="doc_code">
1313 BasicBlock *pb = ...;
1314 Instruction *pi = ...;
1315 Instruction *newInst = new Instruction(...);
1317 pb->getInstList().insert(pi, newInst); // <i>Inserts newInst before pi in pb</i>
1321 <p>Appending to the end of a <tt>BasicBlock</tt> is so common that
1322 the <tt>Instruction</tt> class and <tt>Instruction</tt>-derived
1323 classes provide constructors which take a pointer to a
1324 <tt>BasicBlock</tt> to be appended to. For example code that
1327 <div class="doc_code">
1329 BasicBlock *pb = ...;
1330 Instruction *newInst = new Instruction(...);
1332 pb->getInstList().push_back(newInst); // <i>Appends newInst to pb</i>
1338 <div class="doc_code">
1340 BasicBlock *pb = ...;
1341 Instruction *newInst = new Instruction(..., pb);
1345 <p>which is much cleaner, especially if you are creating
1346 long instruction streams.</p></li>
1348 <li>Insertion into an implicit instruction list
1350 <p><tt>Instruction</tt> instances that are already in <tt>BasicBlock</tt>s
1351 are implicitly associated with an existing instruction list: the instruction
1352 list of the enclosing basic block. Thus, we could have accomplished the same
1353 thing as the above code without being given a <tt>BasicBlock</tt> by doing:
1356 <div class="doc_code">
1358 Instruction *pi = ...;
1359 Instruction *newInst = new Instruction(...);
1361 pi->getParent()->getInstList().insert(pi, newInst);
1365 <p>In fact, this sequence of steps occurs so frequently that the
1366 <tt>Instruction</tt> class and <tt>Instruction</tt>-derived classes provide
1367 constructors which take (as a default parameter) a pointer to an
1368 <tt>Instruction</tt> which the newly-created <tt>Instruction</tt> should
1369 precede. That is, <tt>Instruction</tt> constructors are capable of
1370 inserting the newly-created instance into the <tt>BasicBlock</tt> of a
1371 provided instruction, immediately before that instruction. Using an
1372 <tt>Instruction</tt> constructor with a <tt>insertBefore</tt> (default)
1373 parameter, the above code becomes:</p>
1375 <div class="doc_code">
1377 Instruction* pi = ...;
1378 Instruction* newInst = new Instruction(..., pi);
1382 <p>which is much cleaner, especially if you're creating a lot of
1383 instructions and adding them to <tt>BasicBlock</tt>s.</p></li>
1388 <!--_______________________________________________________________________-->
1389 <div class="doc_subsubsection">
1390 <a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a>
1393 <div class="doc_text">
1395 <p>Deleting an instruction from an existing sequence of instructions that form a
1396 <a href="#BasicBlock"><tt>BasicBlock</tt></a> is very straight-forward. First,
1397 you must have a pointer to the instruction that you wish to delete. Second, you
1398 need to obtain the pointer to that instruction's basic block. You use the
1399 pointer to the basic block to get its list of instructions and then use the
1400 erase function to remove your instruction. For example:</p>
1402 <div class="doc_code">
1404 <a href="#Instruction">Instruction</a> *I = .. ;
1405 <a href="#BasicBlock">BasicBlock</a> *BB = I->getParent();
1407 BB->getInstList().erase(I);
1413 <!--_______________________________________________________________________-->
1414 <div class="doc_subsubsection">
1415 <a name="schanges_replacing">Replacing an <tt>Instruction</tt> with another
1419 <div class="doc_text">
1421 <p><i>Replacing individual instructions</i></p>
1423 <p>Including "<a href="/doxygen/BasicBlockUtils_8h-source.html">llvm/Transforms/Utils/BasicBlockUtils.h</a>"
1424 permits use of two very useful replace functions: <tt>ReplaceInstWithValue</tt>
1425 and <tt>ReplaceInstWithInst</tt>.</p>
1427 <h4><a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a></h4>
1430 <li><tt>ReplaceInstWithValue</tt>
1432 <p>This function replaces all uses (within a basic block) of a given
1433 instruction with a value, and then removes the original instruction. The
1434 following example illustrates the replacement of the result of a particular
1435 <tt>AllocaInst</tt> that allocates memory for a single integer with a null
1436 pointer to an integer.</p>
1438 <div class="doc_code">
1440 AllocaInst* instToReplace = ...;
1441 BasicBlock::iterator ii(instToReplace);
1443 ReplaceInstWithValue(instToReplace->getParent()->getInstList(), ii,
1444 Constant::getNullValue(PointerType::get(Type::IntTy)));
1447 <li><tt>ReplaceInstWithInst</tt>
1449 <p>This function replaces a particular instruction with another
1450 instruction. The following example illustrates the replacement of one
1451 <tt>AllocaInst</tt> with another.</p>
1453 <div class="doc_code">
1455 AllocaInst* instToReplace = ...;
1456 BasicBlock::iterator ii(instToReplace);
1458 ReplaceInstWithInst(instToReplace->getParent()->getInstList(), ii,
1459 new AllocaInst(Type::IntTy, 0, "ptrToReplacedInt"));
1463 <p><i>Replacing multiple uses of <tt>User</tt>s and <tt>Value</tt>s</i></p>
1465 <p>You can use <tt>Value::replaceAllUsesWith</tt> and
1466 <tt>User::replaceUsesOfWith</tt> to change more than one use at a time. See the
1467 doxygen documentation for the <a href="/doxygen/classllvm_1_1Value.html">Value Class</a>
1468 and <a href="/doxygen/classllvm_1_1User.html">User Class</a>, respectively, for more
1471 <!-- Value::replaceAllUsesWith User::replaceUsesOfWith Point out:
1472 include/llvm/Transforms/Utils/ especially BasicBlockUtils.h with:
1473 ReplaceInstWithValue, ReplaceInstWithInst -->
1477 <!-- *********************************************************************** -->
1478 <div class="doc_section">
1479 <a name="advanced">Advanced Topics</a>
1481 <!-- *********************************************************************** -->
1483 <div class="doc_text">
1485 This section describes some of the advanced or obscure API's that most clients
1486 do not need to be aware of. These API's tend manage the inner workings of the
1487 LLVM system, and only need to be accessed in unusual circumstances.
1491 <!-- ======================================================================= -->
1492 <div class="doc_subsection">
1493 <a name="TypeResolve">LLVM Type Resolution</a>
1496 <div class="doc_text">
1499 The LLVM type system has a very simple goal: allow clients to compare types for
1500 structural equality with a simple pointer comparison (aka a shallow compare).
1501 This goal makes clients much simpler and faster, and is used throughout the LLVM
1506 Unfortunately achieving this goal is not a simple matter. In particular,
1507 recursive types and late resolution of opaque types makes the situation very
1508 difficult to handle. Fortunately, for the most part, our implementation makes
1509 most clients able to be completely unaware of the nasty internal details. The
1510 primary case where clients are exposed to the inner workings of it are when
1511 building a recursive type. In addition to this case, the LLVM bytecode reader,
1512 assembly parser, and linker also have to be aware of the inner workings of this
1517 For our purposes below, we need three concepts. First, an "Opaque Type" is
1518 exactly as defined in the <a href="LangRef.html#t_opaque">language
1519 reference</a>. Second an "Abstract Type" is any type which includes an
1520 opaque type as part of its type graph (for example "<tt>{ opaque, i32 }</tt>").
1521 Third, a concrete type is a type that is not an abstract type (e.g. "<tt>{ i32,
1527 <!-- ______________________________________________________________________ -->
1528 <div class="doc_subsubsection">
1529 <a name="BuildRecType">Basic Recursive Type Construction</a>
1532 <div class="doc_text">
1535 Because the most common question is "how do I build a recursive type with LLVM",
1536 we answer it now and explain it as we go. Here we include enough to cause this
1537 to be emitted to an output .ll file:
1540 <div class="doc_code">
1542 %mylist = type { %mylist*, i32 }
1547 To build this, use the following LLVM APIs:
1550 <div class="doc_code">
1552 // <i>Create the initial outer struct</i>
1553 <a href="#PATypeHolder">PATypeHolder</a> StructTy = OpaqueType::get();
1554 std::vector<const Type*> Elts;
1555 Elts.push_back(PointerType::get(StructTy));
1556 Elts.push_back(Type::IntTy);
1557 StructType *NewSTy = StructType::get(Elts);
1559 // <i>At this point, NewSTy = "{ opaque*, i32 }". Tell VMCore that</i>
1560 // <i>the struct and the opaque type are actually the same.</i>
1561 cast<OpaqueType>(StructTy.get())-><a href="#refineAbstractTypeTo">refineAbstractTypeTo</a>(NewSTy);
1563 // <i>NewSTy is potentially invalidated, but StructTy (a <a href="#PATypeHolder">PATypeHolder</a>) is</i>
1564 // <i>kept up-to-date</i>
1565 NewSTy = cast<StructType>(StructTy.get());
1567 // <i>Add a name for the type to the module symbol table (optional)</i>
1568 MyModule->addTypeName("mylist", NewSTy);
1573 This code shows the basic approach used to build recursive types: build a
1574 non-recursive type using 'opaque', then use type unification to close the cycle.
1575 The type unification step is performed by the <tt><a
1576 ref="#refineAbstractTypeTo">refineAbstractTypeTo</a></tt> method, which is
1577 described next. After that, we describe the <a
1578 href="#PATypeHolder">PATypeHolder class</a>.
1583 <!-- ______________________________________________________________________ -->
1584 <div class="doc_subsubsection">
1585 <a name="refineAbstractTypeTo">The <tt>refineAbstractTypeTo</tt> method</a>
1588 <div class="doc_text">
1590 The <tt>refineAbstractTypeTo</tt> method starts the type unification process.
1591 While this method is actually a member of the DerivedType class, it is most
1592 often used on OpaqueType instances. Type unification is actually a recursive
1593 process. After unification, types can become structurally isomorphic to
1594 existing types, and all duplicates are deleted (to preserve pointer equality).
1598 In the example above, the OpaqueType object is definitely deleted.
1599 Additionally, if there is an "{ \2*, i32}" type already created in the system,
1600 the pointer and struct type created are <b>also</b> deleted. Obviously whenever
1601 a type is deleted, any "Type*" pointers in the program are invalidated. As
1602 such, it is safest to avoid having <i>any</i> "Type*" pointers to abstract types
1603 live across a call to <tt>refineAbstractTypeTo</tt> (note that non-abstract
1604 types can never move or be deleted). To deal with this, the <a
1605 href="#PATypeHolder">PATypeHolder</a> class is used to maintain a stable
1606 reference to a possibly refined type, and the <a
1607 href="#AbstractTypeUser">AbstractTypeUser</a> class is used to update more
1608 complex datastructures.
1613 <!-- ______________________________________________________________________ -->
1614 <div class="doc_subsubsection">
1615 <a name="PATypeHolder">The PATypeHolder Class</a>
1618 <div class="doc_text">
1620 PATypeHolder is a form of a "smart pointer" for Type objects. When VMCore
1621 happily goes about nuking types that become isomorphic to existing types, it
1622 automatically updates all PATypeHolder objects to point to the new type. In the
1623 example above, this allows the code to maintain a pointer to the resultant
1624 resolved recursive type, even though the Type*'s are potentially invalidated.
1628 PATypeHolder is an extremely light-weight object that uses a lazy union-find
1629 implementation to update pointers. For example the pointer from a Value to its
1630 Type is maintained by PATypeHolder objects.
1635 <!-- ______________________________________________________________________ -->
1636 <div class="doc_subsubsection">
1637 <a name="AbstractTypeUser">The AbstractTypeUser Class</a>
1640 <div class="doc_text">
1643 Some data structures need more to perform more complex updates when types get
1644 resolved. The <a href="#SymbolTable">SymbolTable</a> class, for example, needs
1645 move and potentially merge type planes in its representation when a pointer
1649 To support this, a class can derive from the AbstractTypeUser class. This class
1650 allows it to get callbacks when certain types are resolved. To register to get
1651 callbacks for a particular type, the DerivedType::{add/remove}AbstractTypeUser
1652 methods can be called on a type. Note that these methods only work for <i>
1653 abstract</i> types. Concrete types (those that do not include any opaque
1654 objects) can never be refined.
1659 <!-- ======================================================================= -->
1660 <div class="doc_subsection">
1661 <a name="SymbolTable">The <tt>SymbolTable</tt> class</a>
1664 <div class="doc_text">
1665 <p>This class provides a symbol table that the <a
1666 href="#Function"><tt>Function</tt></a> and <a href="#Module">
1667 <tt>Module</tt></a> classes use for naming definitions. The symbol table can
1668 provide a name for any <a href="#Value"><tt>Value</tt></a>.
1669 <tt>SymbolTable</tt> is an abstract data type. It hides the data it contains
1670 and provides access to it through a controlled interface.</p>
1672 <p>Note that the <tt>SymbolTable</tt> class should not be directly accessed
1673 by most clients. It should only be used when iteration over the symbol table
1674 names themselves are required, which is very special purpose. Note that not
1676 <a href="#Value">Value</a>s have names, and those without names (i.e. they have
1677 an empty name) do not exist in the symbol table.
1680 <p>To use the <tt>SymbolTable</tt> well, you need to understand the
1681 structure of the information it holds. The class contains two
1682 <tt>std::map</tt> objects. The first, <tt>pmap</tt>, is a map of
1683 <tt>Type*</tt> to maps of name (<tt>std::string</tt>) to <tt>Value*</tt>.
1684 Thus, Values are stored in two-dimensions and accessed by <tt>Type</tt> and
1687 <p>The interface of this class provides three basic types of operations:
1689 <li><em>Accessors</em>. Accessors provide read-only access to information
1690 such as finding a value for a name with the
1691 <a href="#SymbolTable_lookup">lookup</a> method.</li>
1692 <li><em>Mutators</em>. Mutators allow the user to add information to the
1693 <tt>SymbolTable</tt> with methods like
1694 <a href="#SymbolTable_insert"><tt>insert</tt></a>.</li>
1695 <li><em>Iterators</em>. Iterators allow the user to traverse the content
1696 of the symbol table in well defined ways, such as the method
1697 <a href="#SymbolTable_plane_begin"><tt>plane_begin</tt></a>.</li>
1702 <dt><tt>Value* lookup(const Type* Ty, const std::string& name) const</tt>:
1704 <dd>The <tt>lookup</tt> method searches the type plane given by the
1705 <tt>Ty</tt> parameter for a <tt>Value</tt> with the provided <tt>name</tt>.
1706 If a suitable <tt>Value</tt> is not found, null is returned.</dd>
1708 <dt><tt>bool isEmpty() const</tt>:</dt>
1709 <dd>This function returns true if both the value and types maps are
1715 <dt><tt>void insert(Value *Val)</tt>:</dt>
1716 <dd>This method adds the provided value to the symbol table. The Value must
1717 have both a name and a type which are extracted and used to place the value
1718 in the correct type plane under the value's name.</dd>
1720 <dt><tt>void insert(const std::string& Name, Value *Val)</tt>:</dt>
1721 <dd> Inserts a constant or type into the symbol table with the specified
1722 name. There can be a many to one mapping between names and constants
1725 <dt><tt>void remove(Value* Val)</tt>:</dt>
1726 <dd> This method removes a named value from the symbol table. The
1727 type and name of the Value are extracted from \p N and used to
1728 lookup the Value in the correct type plane. If the Value is
1729 not in the symbol table, this method silently ignores the
1732 <dt><tt>Value* remove(const std::string& Name, Value *Val)</tt>:</dt>
1733 <dd> Remove a constant or type with the specified name from the
1736 <dt><tt>Value *remove(const value_iterator& It)</tt>:</dt>
1737 <dd> Removes a specific value from the symbol table.
1738 Returns the removed value.</dd>
1740 <dt><tt>bool strip()</tt>:</dt>
1741 <dd> This method will strip the symbol table of its names leaving
1742 the type and values. </dd>
1744 <dt><tt>void clear()</tt>:</dt>
1745 <dd>Empty the symbol table completely.</dd>
1749 <p>The following functions describe three types of iterators you can obtain
1750 the beginning or end of the sequence for both const and non-const. It is
1751 important to keep track of the different kinds of iterators. There are
1752 three idioms worth pointing out:</p>
1755 <tr><th>Units</th><th>Iterator</th><th>Idiom</th></tr>
1757 <td align="left">Planes Of name/Value maps</td><td>PI</td>
1758 <td align="left"><pre><tt>
1759 for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
1760 PE = ST.plane_end(); PI != PE; ++PI ) {
1761 PI->first // <i>This is the Type* of the plane</i>
1762 PI->second // <i>This is the SymbolTable::ValueMap of name/Value pairs</i>
1767 <td align="left">name/Value pairs in a plane</td><td>VI</td>
1768 <td align="left"><pre><tt>
1769 for (SymbolTable::value_const_iterator VI = ST.value_begin(SomeType),
1770 VE = ST.value_end(SomeType); VI != VE; ++VI ) {
1771 VI->first // <i>This is the name of the Value</i>
1772 VI->second // <i>This is the Value* value associated with the name</i>
1778 <p>Using the recommended iterator names and idioms will help you avoid
1779 making mistakes. Of particular note, make sure that whenever you use
1780 value_begin(SomeType) that you always compare the resulting iterator
1781 with value_end(SomeType) not value_end(SomeOtherType) or else you
1782 will loop infinitely.</p>
1786 <dt><tt>plane_iterator plane_begin()</tt>:</dt>
1787 <dd>Get an iterator that starts at the beginning of the type planes.
1788 The iterator will iterate over the Type/ValueMap pairs in the
1791 <dt><tt>plane_const_iterator plane_begin() const</tt>:</dt>
1792 <dd>Get a const_iterator that starts at the beginning of the type
1793 planes. The iterator will iterate over the Type/ValueMap pairs
1794 in the type planes. </dd>
1796 <dt><tt>plane_iterator plane_end()</tt>:</dt>
1797 <dd>Get an iterator at the end of the type planes. This serves as
1798 the marker for end of iteration over the type planes.</dd>
1800 <dt><tt>plane_const_iterator plane_end() const</tt>:</dt>
1801 <dd>Get a const_iterator at the end of the type planes. This serves as
1802 the marker for end of iteration over the type planes.</dd>
1804 <dt><tt>value_iterator value_begin(const Type *Typ)</tt>:</dt>
1805 <dd>Get an iterator that starts at the beginning of a type plane.
1806 The iterator will iterate over the name/value pairs in the type plane.
1807 Note: The type plane must already exist before using this.</dd>
1809 <dt><tt>value_const_iterator value_begin(const Type *Typ) const</tt>:</dt>
1810 <dd>Get a const_iterator that starts at the beginning of a type plane.
1811 The iterator will iterate over the name/value pairs in the type plane.
1812 Note: The type plane must already exist before using this.</dd>
1814 <dt><tt>value_iterator value_end(const Type *Typ)</tt>:</dt>
1815 <dd>Get an iterator to the end of a type plane. This serves as the marker
1816 for end of iteration of the type plane.
1817 Note: The type plane must already exist before using this.</dd>
1819 <dt><tt>value_const_iterator value_end(const Type *Typ) const</tt>:</dt>
1820 <dd>Get a const_iterator to the end of a type plane. This serves as the
1821 marker for end of iteration of the type plane.
1822 Note: the type plane must already exist before using this.</dd>
1824 <dt><tt>plane_const_iterator find(const Type* Typ ) const</tt>:</dt>
1825 <dd>This method returns a plane_const_iterator for iteration over
1826 the type planes starting at a specific plane, given by \p Ty.</dd>
1828 <dt><tt>plane_iterator find( const Type* Typ </tt>:</dt>
1829 <dd>This method returns a plane_iterator for iteration over the
1830 type planes starting at a specific plane, given by \p Ty.</dd>
1837 <!-- *********************************************************************** -->
1838 <div class="doc_section">
1839 <a name="coreclasses">The Core LLVM Class Hierarchy Reference </a>
1841 <!-- *********************************************************************** -->
1843 <div class="doc_text">
1844 <p><tt>#include "<a href="/doxygen/Type_8h-source.html">llvm/Type.h</a>"</tt>
1845 <br>doxygen info: <a href="/doxygen/classllvm_1_1Type.html">Type Class</a></p>
1847 <p>The Core LLVM classes are the primary means of representing the program
1848 being inspected or transformed. The core LLVM classes are defined in
1849 header files in the <tt>include/llvm/</tt> directory, and implemented in
1850 the <tt>lib/VMCore</tt> directory.</p>
1854 <!-- ======================================================================= -->
1855 <div class="doc_subsection">
1856 <a name="Type">The <tt>Type</tt> class and Derived Types</a>
1859 <div class="doc_text">
1861 <p><tt>Type</tt> is a superclass of all type classes. Every <tt>Value</tt> has
1862 a <tt>Type</tt>. <tt>Type</tt> cannot be instantiated directly but only
1863 through its subclasses. Certain primitive types (<tt>VoidType</tt>,
1864 <tt>LabelType</tt>, <tt>FloatType</tt> and <tt>DoubleType</tt>) have hidden
1865 subclasses. They are hidden because they offer no useful functionality beyond
1866 what the <tt>Type</tt> class offers except to distinguish themselves from
1867 other subclasses of <tt>Type</tt>.</p>
1868 <p>All other types are subclasses of <tt>DerivedType</tt>. Types can be
1869 named, but this is not a requirement. There exists exactly
1870 one instance of a given shape at any one time. This allows type equality to
1871 be performed with address equality of the Type Instance. That is, given two
1872 <tt>Type*</tt> values, the types are identical if the pointers are identical.
1876 <!-- _______________________________________________________________________ -->
1877 <div class="doc_subsubsection">
1878 <a name="m_Value">Important Public Methods</a>
1881 <div class="doc_text">
1884 <li><tt>bool isInteger() const</tt>: Returns true for any integer type.</li>
1886 <li><tt>bool isFloatingPoint()</tt>: Return true if this is one of the two
1887 floating point types.</li>
1889 <li><tt>bool isAbstract()</tt>: Return true if the type is abstract (contains
1890 an OpaqueType anywhere in its definition).</li>
1892 <li><tt>bool isSized()</tt>: Return true if the type has known size. Things
1893 that don't have a size are abstract types, labels and void.</li>
1898 <!-- _______________________________________________________________________ -->
1899 <div class="doc_subsubsection">
1900 <a name="m_Value">Important Derived Types</a>
1902 <div class="doc_text">
1904 <dt><tt>IntegerType</tt></dt>
1905 <dd>Subclass of DerivedType that represents integer types of any bit width.
1906 Any bit width between <tt>IntegerType::MIN_INT_BITS</tt> (1) and
1907 <tt>IntegerType::MAX_INT_BITS</tt> (~8 million) can be represented.
1909 <li><tt>static const IntegerType* get(unsigned NumBits)</tt>: get an integer
1910 type of a specific bit width.</li>
1911 <li><tt>unsigned getBitWidth() const</tt>: Get the bit width of an integer
1915 <dt><tt>SequentialType</tt></dt>
1916 <dd>This is subclassed by ArrayType and PointerType
1918 <li><tt>const Type * getElementType() const</tt>: Returns the type of each
1919 of the elements in the sequential type. </li>
1922 <dt><tt>ArrayType</tt></dt>
1923 <dd>This is a subclass of SequentialType and defines the interface for array
1926 <li><tt>unsigned getNumElements() const</tt>: Returns the number of
1927 elements in the array. </li>
1930 <dt><tt>PointerType</tt></dt>
1931 <dd>Subclass of SequentialType for pointer types.</li>
1932 <dt><tt>PackedType</tt></dt>
1933 <dd>Subclass of SequentialType for packed (vector) types. A
1934 packed type is similar to an ArrayType but is distinguished because it is
1935 a first class type wherease ArrayType is not. Packed types are used for
1936 vector operations and are usually small vectors of of an integer or floating
1938 <dt><tt>StructType</tt></dt>
1939 <dd>Subclass of DerivedTypes for struct types.</dd>
1940 <dt><tt>FunctionType</tt></dt>
1941 <dd>Subclass of DerivedTypes for function types.
1943 <li><tt>bool isVarArg() const</tt>: Returns true if its a vararg
1945 <li><tt> const Type * getReturnType() const</tt>: Returns the
1946 return type of the function.</li>
1947 <li><tt>const Type * getParamType (unsigned i)</tt>: Returns
1948 the type of the ith parameter.</li>
1949 <li><tt> const unsigned getNumParams() const</tt>: Returns the
1950 number of formal parameters.</li>
1953 <dt><tt>OpaqueType</tt></dt>
1954 <dd>Sublcass of DerivedType for abstract types. This class
1955 defines no content and is used as a placeholder for some other type. Note
1956 that OpaqueType is used (temporarily) during type resolution for forward
1957 references of types. Once the referenced type is resolved, the OpaqueType
1958 is replaced with the actual type. OpaqueType can also be used for data
1959 abstraction. At link time opaque types can be resolved to actual types
1960 of the same name.</dd>
1964 <!-- ======================================================================= -->
1965 <div class="doc_subsection">
1966 <a name="Value">The <tt>Value</tt> class</a>
1971 <p><tt>#include "<a href="/doxygen/Value_8h-source.html">llvm/Value.h</a>"</tt>
1973 doxygen info: <a href="/doxygen/classllvm_1_1Value.html">Value Class</a></p>
1975 <p>The <tt>Value</tt> class is the most important class in the LLVM Source
1976 base. It represents a typed value that may be used (among other things) as an
1977 operand to an instruction. There are many different types of <tt>Value</tt>s,
1978 such as <a href="#Constant"><tt>Constant</tt></a>s,<a
1979 href="#Argument"><tt>Argument</tt></a>s. Even <a
1980 href="#Instruction"><tt>Instruction</tt></a>s and <a
1981 href="#Function"><tt>Function</tt></a>s are <tt>Value</tt>s.</p>
1983 <p>A particular <tt>Value</tt> may be used many times in the LLVM representation
1984 for a program. For example, an incoming argument to a function (represented
1985 with an instance of the <a href="#Argument">Argument</a> class) is "used" by
1986 every instruction in the function that references the argument. To keep track
1987 of this relationship, the <tt>Value</tt> class keeps a list of all of the <a
1988 href="#User"><tt>User</tt></a>s that is using it (the <a
1989 href="#User"><tt>User</tt></a> class is a base class for all nodes in the LLVM
1990 graph that can refer to <tt>Value</tt>s). This use list is how LLVM represents
1991 def-use information in the program, and is accessible through the <tt>use_</tt>*
1992 methods, shown below.</p>
1994 <p>Because LLVM is a typed representation, every LLVM <tt>Value</tt> is typed,
1995 and this <a href="#Type">Type</a> is available through the <tt>getType()</tt>
1996 method. In addition, all LLVM values can be named. The "name" of the
1997 <tt>Value</tt> is a symbolic string printed in the LLVM code:</p>
1999 <div class="doc_code">
2001 %<b>foo</b> = add i32 1, 2
2005 <p><a name="#nameWarning">The name of this instruction is "foo".</a> <b>NOTE</b>
2006 that the name of any value may be missing (an empty string), so names should
2007 <b>ONLY</b> be used for debugging (making the source code easier to read,
2008 debugging printouts), they should not be used to keep track of values or map
2009 between them. For this purpose, use a <tt>std::map</tt> of pointers to the
2010 <tt>Value</tt> itself instead.</p>
2012 <p>One important aspect of LLVM is that there is no distinction between an SSA
2013 variable and the operation that produces it. Because of this, any reference to
2014 the value produced by an instruction (or the value available as an incoming
2015 argument, for example) is represented as a direct pointer to the instance of
2017 represents this value. Although this may take some getting used to, it
2018 simplifies the representation and makes it easier to manipulate.</p>
2022 <!-- _______________________________________________________________________ -->
2023 <div class="doc_subsubsection">
2024 <a name="m_Value">Important Public Members of the <tt>Value</tt> class</a>
2027 <div class="doc_text">
2030 <li><tt>Value::use_iterator</tt> - Typedef for iterator over the
2032 <tt>Value::use_const_iterator</tt> - Typedef for const_iterator over
2034 <tt>unsigned use_size()</tt> - Returns the number of users of the
2036 <tt>bool use_empty()</tt> - Returns true if there are no users.<br>
2037 <tt>use_iterator use_begin()</tt> - Get an iterator to the start of
2039 <tt>use_iterator use_end()</tt> - Get an iterator to the end of the
2041 <tt><a href="#User">User</a> *use_back()</tt> - Returns the last
2042 element in the list.
2043 <p> These methods are the interface to access the def-use
2044 information in LLVM. As with all other iterators in LLVM, the naming
2045 conventions follow the conventions defined by the <a href="#stl">STL</a>.</p>
2047 <li><tt><a href="#Type">Type</a> *getType() const</tt>
2048 <p>This method returns the Type of the Value.</p>
2050 <li><tt>bool hasName() const</tt><br>
2051 <tt>std::string getName() const</tt><br>
2052 <tt>void setName(const std::string &Name)</tt>
2053 <p> This family of methods is used to access and assign a name to a <tt>Value</tt>,
2054 be aware of the <a href="#nameWarning">precaution above</a>.</p>
2056 <li><tt>void replaceAllUsesWith(Value *V)</tt>
2058 <p>This method traverses the use list of a <tt>Value</tt> changing all <a
2059 href="#User"><tt>User</tt>s</a> of the current value to refer to
2060 "<tt>V</tt>" instead. For example, if you detect that an instruction always
2061 produces a constant value (for example through constant folding), you can
2062 replace all uses of the instruction with the constant like this:</p>
2064 <div class="doc_code">
2066 Inst->replaceAllUsesWith(ConstVal);
2074 <!-- ======================================================================= -->
2075 <div class="doc_subsection">
2076 <a name="User">The <tt>User</tt> class</a>
2079 <div class="doc_text">
2082 <tt>#include "<a href="/doxygen/User_8h-source.html">llvm/User.h</a>"</tt><br>
2083 doxygen info: <a href="/doxygen/classllvm_1_1User.html">User Class</a><br>
2084 Superclass: <a href="#Value"><tt>Value</tt></a></p>
2086 <p>The <tt>User</tt> class is the common base class of all LLVM nodes that may
2087 refer to <a href="#Value"><tt>Value</tt></a>s. It exposes a list of "Operands"
2088 that are all of the <a href="#Value"><tt>Value</tt></a>s that the User is
2089 referring to. The <tt>User</tt> class itself is a subclass of
2092 <p>The operands of a <tt>User</tt> point directly to the LLVM <a
2093 href="#Value"><tt>Value</tt></a> that it refers to. Because LLVM uses Static
2094 Single Assignment (SSA) form, there can only be one definition referred to,
2095 allowing this direct connection. This connection provides the use-def
2096 information in LLVM.</p>
2100 <!-- _______________________________________________________________________ -->
2101 <div class="doc_subsubsection">
2102 <a name="m_User">Important Public Members of the <tt>User</tt> class</a>
2105 <div class="doc_text">
2107 <p>The <tt>User</tt> class exposes the operand list in two ways: through
2108 an index access interface and through an iterator based interface.</p>
2111 <li><tt>Value *getOperand(unsigned i)</tt><br>
2112 <tt>unsigned getNumOperands()</tt>
2113 <p> These two methods expose the operands of the <tt>User</tt> in a
2114 convenient form for direct access.</p></li>
2116 <li><tt>User::op_iterator</tt> - Typedef for iterator over the operand
2118 <tt>op_iterator op_begin()</tt> - Get an iterator to the start of
2119 the operand list.<br>
2120 <tt>op_iterator op_end()</tt> - Get an iterator to the end of the
2122 <p> Together, these methods make up the iterator based interface to
2123 the operands of a <tt>User</tt>.</p></li>
2128 <!-- ======================================================================= -->
2129 <div class="doc_subsection">
2130 <a name="Instruction">The <tt>Instruction</tt> class</a>
2133 <div class="doc_text">
2135 <p><tt>#include "</tt><tt><a
2136 href="/doxygen/Instruction_8h-source.html">llvm/Instruction.h</a>"</tt><br>
2137 doxygen info: <a href="/doxygen/classllvm_1_1Instruction.html">Instruction Class</a><br>
2138 Superclasses: <a href="#User"><tt>User</tt></a>, <a
2139 href="#Value"><tt>Value</tt></a></p>
2141 <p>The <tt>Instruction</tt> class is the common base class for all LLVM
2142 instructions. It provides only a few methods, but is a very commonly used
2143 class. The primary data tracked by the <tt>Instruction</tt> class itself is the
2144 opcode (instruction type) and the parent <a
2145 href="#BasicBlock"><tt>BasicBlock</tt></a> the <tt>Instruction</tt> is embedded
2146 into. To represent a specific type of instruction, one of many subclasses of
2147 <tt>Instruction</tt> are used.</p>
2149 <p> Because the <tt>Instruction</tt> class subclasses the <a
2150 href="#User"><tt>User</tt></a> class, its operands can be accessed in the same
2151 way as for other <a href="#User"><tt>User</tt></a>s (with the
2152 <tt>getOperand()</tt>/<tt>getNumOperands()</tt> and
2153 <tt>op_begin()</tt>/<tt>op_end()</tt> methods).</p> <p> An important file for
2154 the <tt>Instruction</tt> class is the <tt>llvm/Instruction.def</tt> file. This
2155 file contains some meta-data about the various different types of instructions
2156 in LLVM. It describes the enum values that are used as opcodes (for example
2157 <tt>Instruction::Add</tt> and <tt>Instruction::ICmp</tt>), as well as the
2158 concrete sub-classes of <tt>Instruction</tt> that implement the instruction (for
2159 example <tt><a href="#BinaryOperator">BinaryOperator</a></tt> and <tt><a
2160 href="#CmpInst">CmpInst</a></tt>). Unfortunately, the use of macros in
2161 this file confuses doxygen, so these enum values don't show up correctly in the
2162 <a href="/doxygen/classllvm_1_1Instruction.html">doxygen output</a>.</p>
2166 <!-- _______________________________________________________________________ -->
2167 <div class="doc_subsubsection">
2168 <a name="s_Instruction">Important Subclasses of the <tt>Instruction</tt>
2171 <div class="doc_text">
2173 <li><tt><a name="BinaryOperator">BinaryOperator</a></tt>
2174 <p>This subclasses represents all two operand instructions whose operands
2175 must be the same type, except for the comparison instructions.</p></li>
2176 <li><tt><a name="CastInst">CastInst</a></tt>
2177 <p>This subclass is the parent of the 12 casting instructions. It provides
2178 common operations on cast instructions.</p>
2179 <li><tt><a name="CmpInst">CmpInst</a></tt>
2180 <p>This subclass respresents the two comparison instructions,
2181 <a href="LangRef.html#i_icmp">ICmpInst</a> (integer opreands), and
2182 <a href="LangRef.html#i_fcmp">FCmpInst</a> (floating point operands).</p>
2183 <li><tt><a name="TerminatorInst">TerminatorInst</a></tt>
2184 <p>This subclass is the parent of all terminator instructions (those which
2185 can terminate a block).</p>
2189 <!-- _______________________________________________________________________ -->
2190 <div class="doc_subsubsection">
2191 <a name="m_Instruction">Important Public Members of the <tt>Instruction</tt>
2195 <div class="doc_text">
2198 <li><tt><a href="#BasicBlock">BasicBlock</a> *getParent()</tt>
2199 <p>Returns the <a href="#BasicBlock"><tt>BasicBlock</tt></a> that
2200 this <tt>Instruction</tt> is embedded into.</p></li>
2201 <li><tt>bool mayWriteToMemory()</tt>
2202 <p>Returns true if the instruction writes to memory, i.e. it is a
2203 <tt>call</tt>,<tt>free</tt>,<tt>invoke</tt>, or <tt>store</tt>.</p></li>
2204 <li><tt>unsigned getOpcode()</tt>
2205 <p>Returns the opcode for the <tt>Instruction</tt>.</p></li>
2206 <li><tt><a href="#Instruction">Instruction</a> *clone() const</tt>
2207 <p>Returns another instance of the specified instruction, identical
2208 in all ways to the original except that the instruction has no parent
2209 (ie it's not embedded into a <a href="#BasicBlock"><tt>BasicBlock</tt></a>),
2210 and it has no name</p></li>
2215 <!-- ======================================================================= -->
2216 <div class="doc_subsection">
2217 <a name="BasicBlock">The <tt>BasicBlock</tt> class</a>
2220 <div class="doc_text">
2223 href="/doxygen/BasicBlock_8h-source.html">llvm/BasicBlock.h</a>"</tt><br>
2224 doxygen info: <a href="/doxygen/structllvm_1_1BasicBlock.html">BasicBlock
2226 Superclass: <a href="#Value"><tt>Value</tt></a></p>
2228 <p>This class represents a single entry multiple exit section of the code,
2229 commonly known as a basic block by the compiler community. The
2230 <tt>BasicBlock</tt> class maintains a list of <a
2231 href="#Instruction"><tt>Instruction</tt></a>s, which form the body of the block.
2232 Matching the language definition, the last element of this list of instructions
2233 is always a terminator instruction (a subclass of the <a
2234 href="#TerminatorInst"><tt>TerminatorInst</tt></a> class).</p>
2236 <p>In addition to tracking the list of instructions that make up the block, the
2237 <tt>BasicBlock</tt> class also keeps track of the <a
2238 href="#Function"><tt>Function</tt></a> that it is embedded into.</p>
2240 <p>Note that <tt>BasicBlock</tt>s themselves are <a
2241 href="#Value"><tt>Value</tt></a>s, because they are referenced by instructions
2242 like branches and can go in the switch tables. <tt>BasicBlock</tt>s have type
2247 <!-- _______________________________________________________________________ -->
2248 <div class="doc_subsubsection">
2249 <a name="m_BasicBlock">Important Public Members of the <tt>BasicBlock</tt>
2253 <div class="doc_text">
2257 <li><tt>BasicBlock(const std::string &Name = "", </tt><tt><a
2258 href="#Function">Function</a> *Parent = 0)</tt>
2260 <p>The <tt>BasicBlock</tt> constructor is used to create new basic blocks for
2261 insertion into a function. The constructor optionally takes a name for the new
2262 block, and a <a href="#Function"><tt>Function</tt></a> to insert it into. If
2263 the <tt>Parent</tt> parameter is specified, the new <tt>BasicBlock</tt> is
2264 automatically inserted at the end of the specified <a
2265 href="#Function"><tt>Function</tt></a>, if not specified, the BasicBlock must be
2266 manually inserted into the <a href="#Function"><tt>Function</tt></a>.</p></li>
2268 <li><tt>BasicBlock::iterator</tt> - Typedef for instruction list iterator<br>
2269 <tt>BasicBlock::const_iterator</tt> - Typedef for const_iterator.<br>
2270 <tt>begin()</tt>, <tt>end()</tt>, <tt>front()</tt>, <tt>back()</tt>,
2271 <tt>size()</tt>, <tt>empty()</tt>
2272 STL-style functions for accessing the instruction list.
2274 <p>These methods and typedefs are forwarding functions that have the same
2275 semantics as the standard library methods of the same names. These methods
2276 expose the underlying instruction list of a basic block in a way that is easy to
2277 manipulate. To get the full complement of container operations (including
2278 operations to update the list), you must use the <tt>getInstList()</tt>
2281 <li><tt>BasicBlock::InstListType &getInstList()</tt>
2283 <p>This method is used to get access to the underlying container that actually
2284 holds the Instructions. This method must be used when there isn't a forwarding
2285 function in the <tt>BasicBlock</tt> class for the operation that you would like
2286 to perform. Because there are no forwarding functions for "updating"
2287 operations, you need to use this if you want to update the contents of a
2288 <tt>BasicBlock</tt>.</p></li>
2290 <li><tt><a href="#Function">Function</a> *getParent()</tt>
2292 <p> Returns a pointer to <a href="#Function"><tt>Function</tt></a> the block is
2293 embedded into, or a null pointer if it is homeless.</p></li>
2295 <li><tt><a href="#TerminatorInst">TerminatorInst</a> *getTerminator()</tt>
2297 <p> Returns a pointer to the terminator instruction that appears at the end of
2298 the <tt>BasicBlock</tt>. If there is no terminator instruction, or if the last
2299 instruction in the block is not a terminator, then a null pointer is
2306 <!-- ======================================================================= -->
2307 <div class="doc_subsection">
2308 <a name="GlobalValue">The <tt>GlobalValue</tt> class</a>
2311 <div class="doc_text">
2314 href="/doxygen/GlobalValue_8h-source.html">llvm/GlobalValue.h</a>"</tt><br>
2315 doxygen info: <a href="/doxygen/classllvm_1_1GlobalValue.html">GlobalValue
2317 Superclasses: <a href="#Constant"><tt>Constant</tt></a>,
2318 <a href="#User"><tt>User</tt></a>, <a href="#Value"><tt>Value</tt></a></p>
2320 <p>Global values (<a href="#GlobalVariable"><tt>GlobalVariable</tt></a>s or <a
2321 href="#Function"><tt>Function</tt></a>s) are the only LLVM values that are
2322 visible in the bodies of all <a href="#Function"><tt>Function</tt></a>s.
2323 Because they are visible at global scope, they are also subject to linking with
2324 other globals defined in different translation units. To control the linking
2325 process, <tt>GlobalValue</tt>s know their linkage rules. Specifically,
2326 <tt>GlobalValue</tt>s know whether they have internal or external linkage, as
2327 defined by the <tt>LinkageTypes</tt> enumeration.</p>
2329 <p>If a <tt>GlobalValue</tt> has internal linkage (equivalent to being
2330 <tt>static</tt> in C), it is not visible to code outside the current translation
2331 unit, and does not participate in linking. If it has external linkage, it is
2332 visible to external code, and does participate in linking. In addition to
2333 linkage information, <tt>GlobalValue</tt>s keep track of which <a
2334 href="#Module"><tt>Module</tt></a> they are currently part of.</p>
2336 <p>Because <tt>GlobalValue</tt>s are memory objects, they are always referred to
2337 by their <b>address</b>. As such, the <a href="#Type"><tt>Type</tt></a> of a
2338 global is always a pointer to its contents. It is important to remember this
2339 when using the <tt>GetElementPtrInst</tt> instruction because this pointer must
2340 be dereferenced first. For example, if you have a <tt>GlobalVariable</tt> (a
2341 subclass of <tt>GlobalValue)</tt> that is an array of 24 ints, type <tt>[24 x
2342 i32]</tt>, then the <tt>GlobalVariable</tt> is a pointer to that array. Although
2343 the address of the first element of this array and the value of the
2344 <tt>GlobalVariable</tt> are the same, they have different types. The
2345 <tt>GlobalVariable</tt>'s type is <tt>[24 x i32]</tt>. The first element's type
2346 is <tt>i32.</tt> Because of this, accessing a global value requires you to
2347 dereference the pointer with <tt>GetElementPtrInst</tt> first, then its elements
2348 can be accessed. This is explained in the <a href="LangRef.html#globalvars">LLVM
2349 Language Reference Manual</a>.</p>
2353 <!-- _______________________________________________________________________ -->
2354 <div class="doc_subsubsection">
2355 <a name="m_GlobalValue">Important Public Members of the <tt>GlobalValue</tt>
2359 <div class="doc_text">
2362 <li><tt>bool hasInternalLinkage() const</tt><br>
2363 <tt>bool hasExternalLinkage() const</tt><br>
2364 <tt>void setInternalLinkage(bool HasInternalLinkage)</tt>
2365 <p> These methods manipulate the linkage characteristics of the <tt>GlobalValue</tt>.</p>
2368 <li><tt><a href="#Module">Module</a> *getParent()</tt>
2369 <p> This returns the <a href="#Module"><tt>Module</tt></a> that the
2370 GlobalValue is currently embedded into.</p></li>
2375 <!-- ======================================================================= -->
2376 <div class="doc_subsection">
2377 <a name="Function">The <tt>Function</tt> class</a>
2380 <div class="doc_text">
2383 href="/doxygen/Function_8h-source.html">llvm/Function.h</a>"</tt><br> doxygen
2384 info: <a href="/doxygen/classllvm_1_1Function.html">Function Class</a><br>
2385 Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>,
2386 <a href="#Constant"><tt>Constant</tt></a>,
2387 <a href="#User"><tt>User</tt></a>,
2388 <a href="#Value"><tt>Value</tt></a></p>
2390 <p>The <tt>Function</tt> class represents a single procedure in LLVM. It is
2391 actually one of the more complex classes in the LLVM heirarchy because it must
2392 keep track of a large amount of data. The <tt>Function</tt> class keeps track
2393 of a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, a list of formal
2394 <a href="#Argument"><tt>Argument</tt></a>s, and a
2395 <a href="#SymbolTable"><tt>SymbolTable</tt></a>.</p>
2397 <p>The list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s is the most
2398 commonly used part of <tt>Function</tt> objects. The list imposes an implicit
2399 ordering of the blocks in the function, which indicate how the code will be
2400 layed out by the backend. Additionally, the first <a
2401 href="#BasicBlock"><tt>BasicBlock</tt></a> is the implicit entry node for the
2402 <tt>Function</tt>. It is not legal in LLVM to explicitly branch to this initial
2403 block. There are no implicit exit nodes, and in fact there may be multiple exit
2404 nodes from a single <tt>Function</tt>. If the <a
2405 href="#BasicBlock"><tt>BasicBlock</tt></a> list is empty, this indicates that
2406 the <tt>Function</tt> is actually a function declaration: the actual body of the
2407 function hasn't been linked in yet.</p>
2409 <p>In addition to a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, the
2410 <tt>Function</tt> class also keeps track of the list of formal <a
2411 href="#Argument"><tt>Argument</tt></a>s that the function receives. This
2412 container manages the lifetime of the <a href="#Argument"><tt>Argument</tt></a>
2413 nodes, just like the <a href="#BasicBlock"><tt>BasicBlock</tt></a> list does for
2414 the <a href="#BasicBlock"><tt>BasicBlock</tt></a>s.</p>
2416 <p>The <a href="#SymbolTable"><tt>SymbolTable</tt></a> is a very rarely used
2417 LLVM feature that is only used when you have to look up a value by name. Aside
2418 from that, the <a href="#SymbolTable"><tt>SymbolTable</tt></a> is used
2419 internally to make sure that there are not conflicts between the names of <a
2420 href="#Instruction"><tt>Instruction</tt></a>s, <a
2421 href="#BasicBlock"><tt>BasicBlock</tt></a>s, or <a
2422 href="#Argument"><tt>Argument</tt></a>s in the function body.</p>
2424 <p>Note that <tt>Function</tt> is a <a href="#GlobalValue">GlobalValue</a>
2425 and therefore also a <a href="#Constant">Constant</a>. The value of the function
2426 is its address (after linking) which is guaranteed to be constant.</p>
2429 <!-- _______________________________________________________________________ -->
2430 <div class="doc_subsubsection">
2431 <a name="m_Function">Important Public Members of the <tt>Function</tt>
2435 <div class="doc_text">
2438 <li><tt>Function(const </tt><tt><a href="#FunctionType">FunctionType</a>
2439 *Ty, LinkageTypes Linkage, const std::string &N = "", Module* Parent = 0)</tt>
2441 <p>Constructor used when you need to create new <tt>Function</tt>s to add
2442 the the program. The constructor must specify the type of the function to
2443 create and what type of linkage the function should have. The <a
2444 href="#FunctionType"><tt>FunctionType</tt></a> argument
2445 specifies the formal arguments and return value for the function. The same
2446 <a href="#FunctionTypel"><tt>FunctionType</tt></a> value can be used to
2447 create multiple functions. The <tt>Parent</tt> argument specifies the Module
2448 in which the function is defined. If this argument is provided, the function
2449 will automatically be inserted into that module's list of
2452 <li><tt>bool isExternal()</tt>
2454 <p>Return whether or not the <tt>Function</tt> has a body defined. If the
2455 function is "external", it does not have a body, and thus must be resolved
2456 by linking with a function defined in a different translation unit.</p></li>
2458 <li><tt>Function::iterator</tt> - Typedef for basic block list iterator<br>
2459 <tt>Function::const_iterator</tt> - Typedef for const_iterator.<br>
2461 <tt>begin()</tt>, <tt>end()</tt>
2462 <tt>size()</tt>, <tt>empty()</tt>
2464 <p>These are forwarding methods that make it easy to access the contents of
2465 a <tt>Function</tt> object's <a href="#BasicBlock"><tt>BasicBlock</tt></a>
2468 <li><tt>Function::BasicBlockListType &getBasicBlockList()</tt>
2470 <p>Returns the list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s. This
2471 is necessary to use when you need to update the list or perform a complex
2472 action that doesn't have a forwarding method.</p></li>
2474 <li><tt>Function::arg_iterator</tt> - Typedef for the argument list
2476 <tt>Function::const_arg_iterator</tt> - Typedef for const_iterator.<br>
2478 <tt>arg_begin()</tt>, <tt>arg_end()</tt>
2479 <tt>arg_size()</tt>, <tt>arg_empty()</tt>
2481 <p>These are forwarding methods that make it easy to access the contents of
2482 a <tt>Function</tt> object's <a href="#Argument"><tt>Argument</tt></a>
2485 <li><tt>Function::ArgumentListType &getArgumentList()</tt>
2487 <p>Returns the list of <a href="#Argument"><tt>Argument</tt></a>s. This is
2488 necessary to use when you need to update the list or perform a complex
2489 action that doesn't have a forwarding method.</p></li>
2491 <li><tt><a href="#BasicBlock">BasicBlock</a> &getEntryBlock()</tt>
2493 <p>Returns the entry <a href="#BasicBlock"><tt>BasicBlock</tt></a> for the
2494 function. Because the entry block for the function is always the first
2495 block, this returns the first block of the <tt>Function</tt>.</p></li>
2497 <li><tt><a href="#Type">Type</a> *getReturnType()</tt><br>
2498 <tt><a href="#FunctionType">FunctionType</a> *getFunctionType()</tt>
2500 <p>This traverses the <a href="#Type"><tt>Type</tt></a> of the
2501 <tt>Function</tt> and returns the return type of the function, or the <a
2502 href="#FunctionType"><tt>FunctionType</tt></a> of the actual
2505 <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
2507 <p> Return a pointer to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
2508 for this <tt>Function</tt>.</p></li>
2513 <!-- ======================================================================= -->
2514 <div class="doc_subsection">
2515 <a name="GlobalVariable">The <tt>GlobalVariable</tt> class</a>
2518 <div class="doc_text">
2521 href="/doxygen/GlobalVariable_8h-source.html">llvm/GlobalVariable.h</a>"</tt>
2523 doxygen info: <a href="/doxygen/classllvm_1_1GlobalVariable.html">GlobalVariable
2525 Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>,
2526 <a href="#Constant"><tt>Constant</tt></a>,
2527 <a href="#User"><tt>User</tt></a>,
2528 <a href="#Value"><tt>Value</tt></a></p>
2530 <p>Global variables are represented with the (suprise suprise)
2531 <tt>GlobalVariable</tt> class. Like functions, <tt>GlobalVariable</tt>s are also
2532 subclasses of <a href="#GlobalValue"><tt>GlobalValue</tt></a>, and as such are
2533 always referenced by their address (global values must live in memory, so their
2534 "name" refers to their constant address). See
2535 <a href="#GlobalValue"><tt>GlobalValue</tt></a> for more on this. Global
2536 variables may have an initial value (which must be a
2537 <a href="#Constant"><tt>Constant</tt></a>), and if they have an initializer,
2538 they may be marked as "constant" themselves (indicating that their contents
2539 never change at runtime).</p>
2542 <!-- _______________________________________________________________________ -->
2543 <div class="doc_subsubsection">
2544 <a name="m_GlobalVariable">Important Public Members of the
2545 <tt>GlobalVariable</tt> class</a>
2548 <div class="doc_text">
2551 <li><tt>GlobalVariable(const </tt><tt><a href="#Type">Type</a> *Ty, bool
2552 isConstant, LinkageTypes& Linkage, <a href="#Constant">Constant</a>
2553 *Initializer = 0, const std::string &Name = "", Module* Parent = 0)</tt>
2555 <p>Create a new global variable of the specified type. If
2556 <tt>isConstant</tt> is true then the global variable will be marked as
2557 unchanging for the program. The Linkage parameter specifies the type of
2558 linkage (internal, external, weak, linkonce, appending) for the variable. If
2559 the linkage is InternalLinkage, WeakLinkage, or LinkOnceLinkage, then
2560 the resultant global variable will have internal linkage. AppendingLinkage
2561 concatenates together all instances (in different translation units) of the
2562 variable into a single variable but is only applicable to arrays. See
2563 the <a href="LangRef.html#modulestructure">LLVM Language Reference</a> for
2564 further details on linkage types. Optionally an initializer, a name, and the
2565 module to put the variable into may be specified for the global variable as
2568 <li><tt>bool isConstant() const</tt>
2570 <p>Returns true if this is a global variable that is known not to
2571 be modified at runtime.</p></li>
2573 <li><tt>bool hasInitializer()</tt>
2575 <p>Returns true if this <tt>GlobalVariable</tt> has an intializer.</p></li>
2577 <li><tt><a href="#Constant">Constant</a> *getInitializer()</tt>
2579 <p>Returns the intial value for a <tt>GlobalVariable</tt>. It is not legal
2580 to call this method if there is no initializer.</p></li>
2585 <!-- ======================================================================= -->
2586 <div class="doc_subsection">
2587 <a name="Module">The <tt>Module</tt> class</a>
2590 <div class="doc_text">
2593 href="/doxygen/Module_8h-source.html">llvm/Module.h</a>"</tt><br> doxygen info:
2594 <a href="/doxygen/classllvm_1_1Module.html">Module Class</a></p>
2596 <p>The <tt>Module</tt> class represents the top level structure present in LLVM
2597 programs. An LLVM module is effectively either a translation unit of the
2598 original program or a combination of several translation units merged by the
2599 linker. The <tt>Module</tt> class keeps track of a list of <a
2600 href="#Function"><tt>Function</tt></a>s, a list of <a
2601 href="#GlobalVariable"><tt>GlobalVariable</tt></a>s, and a <a
2602 href="#SymbolTable"><tt>SymbolTable</tt></a>. Additionally, it contains a few
2603 helpful member functions that try to make common operations easy.</p>
2607 <!-- _______________________________________________________________________ -->
2608 <div class="doc_subsubsection">
2609 <a name="m_Module">Important Public Members of the <tt>Module</tt> class</a>
2612 <div class="doc_text">
2615 <li><tt>Module::Module(std::string name = "")</tt></li>
2618 <p>Constructing a <a href="#Module">Module</a> is easy. You can optionally
2619 provide a name for it (probably based on the name of the translation unit).</p>
2622 <li><tt>Module::iterator</tt> - Typedef for function list iterator<br>
2623 <tt>Module::const_iterator</tt> - Typedef for const_iterator.<br>
2625 <tt>begin()</tt>, <tt>end()</tt>
2626 <tt>size()</tt>, <tt>empty()</tt>
2628 <p>These are forwarding methods that make it easy to access the contents of
2629 a <tt>Module</tt> object's <a href="#Function"><tt>Function</tt></a>
2632 <li><tt>Module::FunctionListType &getFunctionList()</tt>
2634 <p> Returns the list of <a href="#Function"><tt>Function</tt></a>s. This is
2635 necessary to use when you need to update the list or perform a complex
2636 action that doesn't have a forwarding method.</p>
2638 <p><!-- Global Variable --></p></li>
2644 <li><tt>Module::global_iterator</tt> - Typedef for global variable list iterator<br>
2646 <tt>Module::const_global_iterator</tt> - Typedef for const_iterator.<br>
2648 <tt>global_begin()</tt>, <tt>global_end()</tt>
2649 <tt>global_size()</tt>, <tt>global_empty()</tt>
2651 <p> These are forwarding methods that make it easy to access the contents of
2652 a <tt>Module</tt> object's <a
2653 href="#GlobalVariable"><tt>GlobalVariable</tt></a> list.</p></li>
2655 <li><tt>Module::GlobalListType &getGlobalList()</tt>
2657 <p>Returns the list of <a
2658 href="#GlobalVariable"><tt>GlobalVariable</tt></a>s. This is necessary to
2659 use when you need to update the list or perform a complex action that
2660 doesn't have a forwarding method.</p>
2662 <p><!-- Symbol table stuff --> </p></li>
2668 <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
2670 <p>Return a reference to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
2671 for this <tt>Module</tt>.</p>
2673 <p><!-- Convenience methods --></p></li>
2679 <li><tt><a href="#Function">Function</a> *getFunction(const std::string
2680 &Name, const <a href="#FunctionType">FunctionType</a> *Ty)</tt>
2682 <p>Look up the specified function in the <tt>Module</tt> <a
2683 href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, return
2684 <tt>null</tt>.</p></li>
2686 <li><tt><a href="#Function">Function</a> *getOrInsertFunction(const
2687 std::string &Name, const <a href="#FunctionType">FunctionType</a> *T)</tt>
2689 <p>Look up the specified function in the <tt>Module</tt> <a
2690 href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, add an
2691 external declaration for the function and return it.</p></li>
2693 <li><tt>std::string getTypeName(const <a href="#Type">Type</a> *Ty)</tt>
2695 <p>If there is at least one entry in the <a
2696 href="#SymbolTable"><tt>SymbolTable</tt></a> for the specified <a
2697 href="#Type"><tt>Type</tt></a>, return it. Otherwise return the empty
2700 <li><tt>bool addTypeName(const std::string &Name, const <a
2701 href="#Type">Type</a> *Ty)</tt>
2703 <p>Insert an entry in the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
2704 mapping <tt>Name</tt> to <tt>Ty</tt>. If there is already an entry for this
2705 name, true is returned and the <a
2706 href="#SymbolTable"><tt>SymbolTable</tt></a> is not modified.</p></li>
2711 <!-- ======================================================================= -->
2712 <div class="doc_subsection">
2713 <a name="Constant">The <tt>Constant</tt> class and subclasses</a>
2716 <div class="doc_text">
2718 <p>Constant represents a base class for different types of constants. It
2719 is subclassed by ConstantInt, ConstantArray, etc. for representing
2720 the various types of Constants.</p>
2724 <!-- _______________________________________________________________________ -->
2725 <div class="doc_subsubsection">
2726 <a name="m_Constant">Important Public Methods</a>
2728 <div class="doc_text">
2731 <!-- _______________________________________________________________________ -->
2732 <div class="doc_subsubsection">Important Subclasses of Constant </div>
2733 <div class="doc_text">
2735 <li>ConstantInt : This subclass of Constant represents an integer constant of
2736 any width, including boolean (1 bit integer).
2738 <li><tt>int64_t getSExtValue() const</tt>: Returns the underlying value of
2739 this constant as a sign extended signed integer value.</li>
2740 <li><tt>uint64_t getZExtValue() const</tt>: Returns the underlying value
2741 of this constant as a zero extended unsigned integer value.</li>
2742 <li><tt>static ConstantInt* get(const Type *Ty, uint64_t Val)</tt>:
2743 Returns the ConstantInt object that represents the value provided by
2744 <tt>Val</tt> for integer type <tt>Ty</tt>.</li>
2747 <li>ConstantFP : This class represents a floating point constant.
2749 <li><tt>double getValue() const</tt>: Returns the underlying value of
2750 this constant. </li>
2754 <li><tt>bool getValue() const</tt>: Returns the underlying value of this
2758 <li>ConstantArray : This represents a constant array.
2760 <li><tt>const std::vector<Use> &getValues() const</tt>: Returns
2761 a vector of component constants that makeup this array. </li>
2764 <li>ConstantStruct : This represents a constant struct.
2766 <li><tt>const std::vector<Use> &getValues() const</tt>: Returns
2767 a vector of component constants that makeup this array. </li>
2770 <li>GlobalValue : This represents either a global variable or a function. In
2771 either case, the value is a constant fixed address (after linking).
2775 <!-- ======================================================================= -->
2776 <div class="doc_subsection">
2777 <a name="Argument">The <tt>Argument</tt> class</a>
2780 <div class="doc_text">
2782 <p>This subclass of Value defines the interface for incoming formal
2783 arguments to a function. A Function maintains a list of its formal
2784 arguments. An argument has a pointer to the parent Function.</p>
2788 <!-- *********************************************************************** -->
2791 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
2792 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
2793 <a href="http://validator.w3.org/check/referer"><img
2794 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /></a>
2796 <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a> and
2797 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
2798 <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
2799 Last modified: $Date$