Add TOC
[oota-llvm.git] / docs / ProgrammersManual.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2                       "http://www.w3.org/TR/html4/strict.dtd">
3 <html>
4 <head>
5   <title>LLVM Programmer's Manual</title>
6   <link rel="stylesheet" href="llvm.css" type="text/css">
7 </head>
8 <body>
9
10 <div class="doc_title">
11   LLVM Programmer's Manual
12 </div>
13
14 <ol>
15   <li><a href="#introduction">Introduction</a></li>
16   <li><a href="#general">General Information</a>
17     <ul>
18       <li><a href="#stl">The C++ Standard Template Library</a></li>
19 <!--
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>
23
24 --> 
25     </ul>
26   </li>
27   <li><a href="#apis">Important and useful LLVM APIs</a>
28     <ul>
29       <li><a href="#isa">The <tt>isa&lt;&gt;</tt>, <tt>cast&lt;&gt;</tt>
30 and <tt>dyn_cast&lt;&gt;</tt> templates</a> </li>
31       <li><a href="#DEBUG">The <tt>DEBUG()</tt> macro and <tt>-debug</tt>
32 option</a>
33         <ul>
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>
36         </ul>
37       </li>
38       <li><a href="#Statistic">The <tt>Statistic</tt> class &amp; <tt>-stats</tt>
39 option</a></li>
40 <!--
41       <li>The <tt>InstVisitor</tt> template
42       <li>The general graph API
43 --> 
44       <li><a href="#ViewGraph">Viewing graphs while debugging code</a></li>
45     </ul>
46   </li>
47   <li><a href="#datastructure">Picking the Right Data Structure for a Task</a>
48     <ul>
49     <li><a href="#ds_sequential">Sequential Containers (std::vector, std::list, etc)</a>
50     <ul>
51       <li><a href="#dss_fixedarrays">Fixed Size Arrays</a></li>
52       <li><a href="#dss_heaparrays">Heap Allocated Arrays</a></li>
53       <li><a href="#dss_smallvector">"llvm/ADT/SmallVector.h"</a></li>
54       <li><a href="#dss_vector">&lt;vector&gt;</a></li>
55       <li><a href="#dss_deque">&lt;deque&gt;</a></li>
56       <li><a href="#dss_list">&lt;list&gt;</a></li>
57       <li><a href="#dss_ilist">llvm/ADT/ilist</a></li>
58       <li><a href="#dss_other">Other Sequential Container Options</a></li>
59     </ul></li>
60     <li><a href="#ds_set">Set-Like Containers (std::set, SmallSet, SetVector, etc)</a>
61     <ul>
62       <li><a href="#dss_sortedvectorset">A sorted 'vector'</a></li>
63       <li><a href="#dss_smallset">"llvm/ADT/SmallSet.h"</a></li>
64       <li><a href="#dss_smallptrset">"llvm/ADT/SmallPtrSet.h"</a></li>
65       <li><a href="#dss_FoldingSet">"llvm/ADT/FoldingSet.h"</a></li>
66       <li><a href="#dss_set">&lt;set&gt;</a></li>
67       <li><a href="#dss_setvector">"llvm/ADT/SetVector.h"</a></li>
68       <li><a href="#dss_uniquevector">"llvm/ADT/UniqueVector.h"</a></li>
69       <li><a href="#dss_otherset">Other Set-Like ContainerOptions</a></li>
70     </ul></li>
71     <li><a href="#ds_map">Map-Like Containers (std::map, DenseMap, etc)</a>
72     <ul>
73       <li><a href="#dss_sortedvectormap">A sorted 'vector'</a></li>
74       <li><a href="#dss_cstringmap">"llvm/ADT/CStringMap.h"</a></li>
75       <li><a href="#dss_indexedmap">"llvm/ADT/IndexedMap.h"</a></li>
76       <li><a href="#dss_densemap">"llvm/ADT/DenseMap.h"</a></li>
77       <li><a href="#dss_map">&lt;map&gt;</a></li>
78       <li><a href="#dss_othermap">Other Map-Like Container Options</a></li>
79     </ul></li>
80   </ul>
81   </li>
82   <li><a href="#common">Helpful Hints for Common Operations</a>
83     <ul>
84       <li><a href="#inspection">Basic Inspection and Traversal Routines</a>
85         <ul>
86           <li><a href="#iterate_function">Iterating over the <tt>BasicBlock</tt>s
87 in a <tt>Function</tt></a> </li>
88           <li><a href="#iterate_basicblock">Iterating over the <tt>Instruction</tt>s
89 in a <tt>BasicBlock</tt></a> </li>
90           <li><a href="#iterate_institer">Iterating over the <tt>Instruction</tt>s
91 in a <tt>Function</tt></a> </li>
92           <li><a href="#iterate_convert">Turning an iterator into a
93 class pointer</a> </li>
94           <li><a href="#iterate_complex">Finding call sites: a more
95 complex example</a> </li>
96           <li><a href="#calls_and_invokes">Treating calls and invokes
97 the same way</a> </li>
98           <li><a href="#iterate_chains">Iterating over def-use &amp;
99 use-def chains</a> </li>
100         </ul>
101       </li>
102       <li><a href="#simplechanges">Making simple changes</a>
103         <ul>
104           <li><a href="#schanges_creating">Creating and inserting new
105                  <tt>Instruction</tt>s</a> </li>
106           <li><a href="#schanges_deleting">Deleting              <tt>Instruction</tt>s</a> </li>
107           <li><a href="#schanges_replacing">Replacing an                 <tt>Instruction</tt>
108 with another <tt>Value</tt></a> </li>
109         </ul>
110       </li>
111 <!--
112     <li>Working with the Control Flow Graph
113     <ul>
114       <li>Accessing predecessors and successors of a <tt>BasicBlock</tt>
115       <li>
116       <li>
117     </ul>
118 --> 
119     </ul>
120   </li>
121
122   <li><a href="#advanced">Advanced Topics</a>
123   <ul>
124   <li><a href="#TypeResolve">LLVM Type Resolution</a>
125   <ul>
126     <li><a href="#BuildRecType">Basic Recursive Type Construction</a></li>
127     <li><a href="#refineAbstractTypeTo">The <tt>refineAbstractTypeTo</tt> method</a></li>
128     <li><a href="#PATypeHolder">The PATypeHolder Class</a></li>
129     <li><a href="#AbstractTypeUser">The AbstractTypeUser Class</a></li>
130   </ul></li>
131
132   <li><a href="#SymbolTable">The <tt>SymbolTable</tt> class </a></li>
133   </ul></li>
134
135   <li><a href="#coreclasses">The Core LLVM Class Hierarchy Reference</a>
136     <ul>
137       <li><a href="#Type">The <tt>Type</tt> class</a> </li>
138       <li><a href="#Value">The <tt>Value</tt> class</a>
139         <ul>
140           <li><a href="#User">The <tt>User</tt> class</a>
141             <ul>
142               <li><a href="#Instruction">The <tt>Instruction</tt> class</a>
143                 <ul>
144                   <li><a href="#GetElementPtrInst">The <tt>GetElementPtrInst</tt> class</a></li>
145                 </ul>
146               </li>
147               <li><a href="#Module">The <tt>Module</tt> class</a></li>
148               <li><a href="#Constant">The <tt>Constant</tt> class</a>
149                 <ul>
150                   <li><a href="#GlobalValue">The <tt>GlobalValue</tt> class</a>
151                     <ul>
152                       <li><a href="#BasicBlock">The <tt>BasicBlock</tt>class</a></li>
153                       <li><a href="#Function">The <tt>Function</tt> class</a></li>
154                       <li><a href="#GlobalVariable">The <tt>GlobalVariable</tt> class</a></li>
155                     </ul>
156                   </li>
157                 </ul>
158               </li>
159             </ul>
160           </li>
161           <li><a href="#Argument">The <tt>Argument</tt> class</a></li>
162         </ul>
163       </li>
164     </ul>
165   </li>
166 </ol>
167
168 <div class="doc_author">    
169   <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>, 
170                 <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a>, 
171                 <a href="mailto:jstanley@cs.uiuc.edu">Joel Stanley</a>, and
172                 <a href="mailto:rspencer@x10sys.com">Reid Spencer</a></p>
173 </div>
174
175 <!-- *********************************************************************** -->
176 <div class="doc_section">
177   <a name="introduction">Introduction </a>
178 </div>
179 <!-- *********************************************************************** -->
180
181 <div class="doc_text">
182
183 <p>This document is meant to highlight some of the important classes and
184 interfaces available in the LLVM source-base.  This manual is not
185 intended to explain what LLVM is, how it works, and what LLVM code looks
186 like.  It assumes that you know the basics of LLVM and are interested
187 in writing transformations or otherwise analyzing or manipulating the
188 code.</p>
189
190 <p>This document should get you oriented so that you can find your
191 way in the continuously growing source code that makes up the LLVM
192 infrastructure. Note that this manual is not intended to serve as a
193 replacement for reading the source code, so if you think there should be
194 a method in one of these classes to do something, but it's not listed,
195 check the source.  Links to the <a href="/doxygen/">doxygen</a> sources
196 are provided to make this as easy as possible.</p>
197
198 <p>The first section of this document describes general information that is
199 useful to know when working in the LLVM infrastructure, and the second describes
200 the Core LLVM classes.  In the future this manual will be extended with
201 information describing how to use extension libraries, such as dominator
202 information, CFG traversal routines, and useful utilities like the <tt><a
203 href="/doxygen/InstVisitor_8h-source.html">InstVisitor</a></tt> template.</p>
204
205 </div>
206
207 <!-- *********************************************************************** -->
208 <div class="doc_section">
209   <a name="general">General Information</a>
210 </div>
211 <!-- *********************************************************************** -->
212
213 <div class="doc_text">
214
215 <p>This section contains general information that is useful if you are working
216 in the LLVM source-base, but that isn't specific to any particular API.</p>
217
218 </div>
219
220 <!-- ======================================================================= -->
221 <div class="doc_subsection">
222   <a name="stl">The C++ Standard Template Library</a>
223 </div>
224
225 <div class="doc_text">
226
227 <p>LLVM makes heavy use of the C++ Standard Template Library (STL),
228 perhaps much more than you are used to, or have seen before.  Because of
229 this, you might want to do a little background reading in the
230 techniques used and capabilities of the library.  There are many good
231 pages that discuss the STL, and several books on the subject that you
232 can get, so it will not be discussed in this document.</p>
233
234 <p>Here are some useful links:</p>
235
236 <ol>
237
238 <li><a href="http://www.dinkumware.com/refxcpp.html">Dinkumware C++ Library
239 reference</a> - an excellent reference for the STL and other parts of the
240 standard C++ library.</li>
241
242 <li><a href="http://www.tempest-sw.com/cpp/">C++ In a Nutshell</a> - This is an
243 O'Reilly book in the making.  It has a decent 
244 Standard Library
245 Reference that rivals Dinkumware's, and is unfortunately no longer free since the book has been 
246 published.</li>
247
248 <li><a href="http://www.parashift.com/c++-faq-lite/">C++ Frequently Asked
249 Questions</a></li>
250
251 <li><a href="http://www.sgi.com/tech/stl/">SGI's STL Programmer's Guide</a> -
252 Contains a useful <a
253 href="http://www.sgi.com/tech/stl/stl_introduction.html">Introduction to the
254 STL</a>.</li>
255
256 <li><a href="http://www.research.att.com/%7Ebs/C++.html">Bjarne Stroustrup's C++
257 Page</a></li>
258
259 <li><a href="http://64.78.49.204/">
260 Bruce Eckel's Thinking in C++, 2nd ed. Volume 2 Revision 4.0 (even better, get
261 the book).</a></li>
262
263 </ol>
264   
265 <p>You are also encouraged to take a look at the <a
266 href="CodingStandards.html">LLVM Coding Standards</a> guide which focuses on how
267 to write maintainable code more than where to put your curly braces.</p>
268
269 </div>
270
271 <!-- ======================================================================= -->
272 <div class="doc_subsection">
273   <a name="stl">Other useful references</a>
274 </div>
275
276 <div class="doc_text">
277
278 <ol>
279 <li><a href="http://www.psc.edu/%7Esemke/cvs_branches.html">CVS
280 Branch and Tag Primer</a></li>
281 <li><a href="http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html">Using
282 static and shared libraries across platforms</a></li>
283 </ol>
284
285 </div>
286
287 <!-- *********************************************************************** -->
288 <div class="doc_section">
289   <a name="apis">Important and useful LLVM APIs</a>
290 </div>
291 <!-- *********************************************************************** -->
292
293 <div class="doc_text">
294
295 <p>Here we highlight some LLVM APIs that are generally useful and good to
296 know about when writing transformations.</p>
297
298 </div>
299
300 <!-- ======================================================================= -->
301 <div class="doc_subsection">
302   <a name="isa">The <tt>isa&lt;&gt;</tt>, <tt>cast&lt;&gt;</tt> and
303   <tt>dyn_cast&lt;&gt;</tt> templates</a>
304 </div>
305
306 <div class="doc_text">
307
308 <p>The LLVM source-base makes extensive use of a custom form of RTTI.
309 These templates have many similarities to the C++ <tt>dynamic_cast&lt;&gt;</tt>
310 operator, but they don't have some drawbacks (primarily stemming from
311 the fact that <tt>dynamic_cast&lt;&gt;</tt> only works on classes that
312 have a v-table). Because they are used so often, you must know what they
313 do and how they work. All of these templates are defined in the <a
314  href="/doxygen/Casting_8h-source.html"><tt>llvm/Support/Casting.h</tt></a>
315 file (note that you very rarely have to include this file directly).</p>
316
317 <dl>
318   <dt><tt>isa&lt;&gt;</tt>: </dt>
319
320   <dd><p>The <tt>isa&lt;&gt;</tt> operator works exactly like the Java
321   "<tt>instanceof</tt>" operator.  It returns true or false depending on whether
322   a reference or pointer points to an instance of the specified class.  This can
323   be very useful for constraint checking of various sorts (example below).</p>
324   </dd>
325
326   <dt><tt>cast&lt;&gt;</tt>: </dt>
327
328   <dd><p>The <tt>cast&lt;&gt;</tt> operator is a "checked cast" operation. It
329   converts a pointer or reference from a base class to a derived cast, causing
330   an assertion failure if it is not really an instance of the right type.  This
331   should be used in cases where you have some information that makes you believe
332   that something is of the right type.  An example of the <tt>isa&lt;&gt;</tt>
333   and <tt>cast&lt;&gt;</tt> template is:</p>
334
335 <div class="doc_code">
336 <pre>
337 static bool isLoopInvariant(const <a href="#Value">Value</a> *V, const Loop *L) {
338   if (isa&lt;<a href="#Constant">Constant</a>&gt;(V) || isa&lt;<a href="#Argument">Argument</a>&gt;(V) || isa&lt;<a href="#GlobalValue">GlobalValue</a>&gt;(V))
339     return true;
340
341   // <i>Otherwise, it must be an instruction...</i>
342   return !L-&gt;contains(cast&lt;<a href="#Instruction">Instruction</a>&gt;(V)-&gt;getParent());
343 }
344 </pre>
345 </div>
346
347   <p>Note that you should <b>not</b> use an <tt>isa&lt;&gt;</tt> test followed
348   by a <tt>cast&lt;&gt;</tt>, for that use the <tt>dyn_cast&lt;&gt;</tt>
349   operator.</p>
350
351   </dd>
352
353   <dt><tt>dyn_cast&lt;&gt;</tt>:</dt>
354
355   <dd><p>The <tt>dyn_cast&lt;&gt;</tt> operator is a "checking cast" operation.
356   It checks to see if the operand is of the specified type, and if so, returns a
357   pointer to it (this operator does not work with references). If the operand is
358   not of the correct type, a null pointer is returned.  Thus, this works very
359   much like the <tt>dynamic_cast&lt;&gt;</tt> operator in C++, and should be
360   used in the same circumstances.  Typically, the <tt>dyn_cast&lt;&gt;</tt>
361   operator is used in an <tt>if</tt> statement or some other flow control
362   statement like this:</p>
363
364 <div class="doc_code">
365 <pre>
366 if (<a href="#AllocationInst">AllocationInst</a> *AI = dyn_cast&lt;<a href="#AllocationInst">AllocationInst</a>&gt;(Val)) {
367   // <i>...</i>
368 }
369 </pre>
370 </div>
371    
372   <p>This form of the <tt>if</tt> statement effectively combines together a call
373   to <tt>isa&lt;&gt;</tt> and a call to <tt>cast&lt;&gt;</tt> into one
374   statement, which is very convenient.</p>
375
376   <p>Note that the <tt>dyn_cast&lt;&gt;</tt> operator, like C++'s
377   <tt>dynamic_cast&lt;&gt;</tt> or Java's <tt>instanceof</tt> operator, can be
378   abused.  In particular, you should not use big chained <tt>if/then/else</tt>
379   blocks to check for lots of different variants of classes.  If you find
380   yourself wanting to do this, it is much cleaner and more efficient to use the
381   <tt>InstVisitor</tt> class to dispatch over the instruction type directly.</p>
382
383   </dd>
384
385   <dt><tt>cast_or_null&lt;&gt;</tt>: </dt>
386   
387   <dd><p>The <tt>cast_or_null&lt;&gt;</tt> operator works just like the
388   <tt>cast&lt;&gt;</tt> operator, except that it allows for a null pointer as an
389   argument (which it then propagates).  This can sometimes be useful, allowing
390   you to combine several null checks into one.</p></dd>
391
392   <dt><tt>dyn_cast_or_null&lt;&gt;</tt>: </dt>
393
394   <dd><p>The <tt>dyn_cast_or_null&lt;&gt;</tt> operator works just like the
395   <tt>dyn_cast&lt;&gt;</tt> operator, except that it allows for a null pointer
396   as an argument (which it then propagates).  This can sometimes be useful,
397   allowing you to combine several null checks into one.</p></dd>
398
399 </dl>
400
401 <p>These five templates can be used with any classes, whether they have a
402 v-table or not.  To add support for these templates, you simply need to add
403 <tt>classof</tt> static methods to the class you are interested casting
404 to. Describing this is currently outside the scope of this document, but there
405 are lots of examples in the LLVM source base.</p>
406
407 </div>
408
409 <!-- ======================================================================= -->
410 <div class="doc_subsection">
411   <a name="DEBUG">The <tt>DEBUG()</tt> macro and <tt>-debug</tt> option</a>
412 </div>
413
414 <div class="doc_text">
415
416 <p>Often when working on your pass you will put a bunch of debugging printouts
417 and other code into your pass.  After you get it working, you want to remove
418 it, but you may need it again in the future (to work out new bugs that you run
419 across).</p>
420
421 <p> Naturally, because of this, you don't want to delete the debug printouts,
422 but you don't want them to always be noisy.  A standard compromise is to comment
423 them out, allowing you to enable them if you need them in the future.</p>
424
425 <p>The "<tt><a href="/doxygen/Debug_8h-source.html">llvm/Support/Debug.h</a></tt>"
426 file provides a macro named <tt>DEBUG()</tt> that is a much nicer solution to
427 this problem.  Basically, you can put arbitrary code into the argument of the
428 <tt>DEBUG</tt> macro, and it is only executed if '<tt>opt</tt>' (or any other
429 tool) is run with the '<tt>-debug</tt>' command line argument:</p>
430
431 <div class="doc_code">
432 <pre>
433 DOUT &lt;&lt; "I am here!\n";
434 </pre>
435 </div>
436
437 <p>Then you can run your pass like this:</p>
438
439 <div class="doc_code">
440 <pre>
441 $ opt &lt; a.bc &gt; /dev/null -mypass
442 <i>&lt;no output&gt;</i>
443 $ opt &lt; a.bc &gt; /dev/null -mypass -debug
444 I am here!
445 </pre>
446 </div>
447
448 <p>Using the <tt>DEBUG()</tt> macro instead of a home-brewed solution allows you
449 to not have to create "yet another" command line option for the debug output for
450 your pass.  Note that <tt>DEBUG()</tt> macros are disabled for optimized builds,
451 so they do not cause a performance impact at all (for the same reason, they
452 should also not contain side-effects!).</p>
453
454 <p>One additional nice thing about the <tt>DEBUG()</tt> macro is that you can
455 enable or disable it directly in gdb.  Just use "<tt>set DebugFlag=0</tt>" or
456 "<tt>set DebugFlag=1</tt>" from the gdb if the program is running.  If the
457 program hasn't been started yet, you can always just run it with
458 <tt>-debug</tt>.</p>
459
460 </div>
461
462 <!-- _______________________________________________________________________ -->
463 <div class="doc_subsubsection">
464   <a name="DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt> and
465   the <tt>-debug-only</tt> option</a>
466 </div>
467
468 <div class="doc_text">
469
470 <p>Sometimes you may find yourself in a situation where enabling <tt>-debug</tt>
471 just turns on <b>too much</b> information (such as when working on the code
472 generator).  If you want to enable debug information with more fine-grained
473 control, you define the <tt>DEBUG_TYPE</tt> macro and the <tt>-debug</tt> only
474 option as follows:</p>
475
476 <div class="doc_code">
477 <pre>
478 DOUT &lt;&lt; "No debug type\n";
479 #undef  DEBUG_TYPE
480 #define DEBUG_TYPE "foo"
481 DOUT &lt;&lt; "'foo' debug type\n";
482 #undef  DEBUG_TYPE
483 #define DEBUG_TYPE "bar"
484 DOUT &lt;&lt; "'bar' debug type\n";
485 #undef  DEBUG_TYPE
486 #define DEBUG_TYPE ""
487 DOUT &lt;&lt; "No debug type (2)\n";
488 </pre>
489 </div>
490
491 <p>Then you can run your pass like this:</p>
492
493 <div class="doc_code">
494 <pre>
495 $ opt &lt; a.bc &gt; /dev/null -mypass
496 <i>&lt;no output&gt;</i>
497 $ opt &lt; a.bc &gt; /dev/null -mypass -debug
498 No debug type
499 'foo' debug type
500 'bar' debug type
501 No debug type (2)
502 $ opt &lt; a.bc &gt; /dev/null -mypass -debug-only=foo
503 'foo' debug type
504 $ opt &lt; a.bc &gt; /dev/null -mypass -debug-only=bar
505 'bar' debug type
506 </pre>
507 </div>
508
509 <p>Of course, in practice, you should only set <tt>DEBUG_TYPE</tt> at the top of
510 a file, to specify the debug type for the entire module (if you do this before
511 you <tt>#include "llvm/Support/Debug.h"</tt>, you don't have to insert the ugly
512 <tt>#undef</tt>'s).  Also, you should use names more meaningful than "foo" and
513 "bar", because there is no system in place to ensure that names do not
514 conflict. If two different modules use the same string, they will all be turned
515 on when the name is specified. This allows, for example, all debug information
516 for instruction scheduling to be enabled with <tt>-debug-type=InstrSched</tt>,
517 even if the source lives in multiple files.</p>
518
519 </div>
520
521 <!-- ======================================================================= -->
522 <div class="doc_subsection">
523   <a name="Statistic">The <tt>Statistic</tt> class &amp; <tt>-stats</tt>
524   option</a>
525 </div>
526
527 <div class="doc_text">
528
529 <p>The "<tt><a
530 href="/doxygen/Statistic_8h-source.html">llvm/ADT/Statistic.h</a></tt>" file
531 provides a class named <tt>Statistic</tt> that is used as a unified way to
532 keep track of what the LLVM compiler is doing and how effective various
533 optimizations are.  It is useful to see what optimizations are contributing to
534 making a particular program run faster.</p>
535
536 <p>Often you may run your pass on some big program, and you're interested to see
537 how many times it makes a certain transformation.  Although you can do this with
538 hand inspection, or some ad-hoc method, this is a real pain and not very useful
539 for big programs.  Using the <tt>Statistic</tt> class makes it very easy to
540 keep track of this information, and the calculated information is presented in a
541 uniform manner with the rest of the passes being executed.</p>
542
543 <p>There are many examples of <tt>Statistic</tt> uses, but the basics of using
544 it are as follows:</p>
545
546 <ol>
547     <li><p>Define your statistic like this:</p>
548
549 <div class="doc_code">
550 <pre>
551 #define <a href="#DEBUG_TYPE">DEBUG_TYPE</a> "mypassname"   <i>// This goes before any #includes.</i>
552 STATISTIC(NumXForms, "The # of times I did stuff");
553 </pre>
554 </div>
555
556   <p>The <tt>STATISTIC</tt> macro defines a static variable, whose name is
557     specified by the first argument.  The pass name is taken from the DEBUG_TYPE
558     macro, and the description is taken from the second argument.  The variable
559     defined ("NumXForms" in this case) acts like an unsigned integer.</p></li>
560
561     <li><p>Whenever you make a transformation, bump the counter:</p>
562
563 <div class="doc_code">
564 <pre>
565 ++NumXForms;   // <i>I did stuff!</i>
566 </pre>
567 </div>
568
569     </li>
570   </ol>
571
572   <p>That's all you have to do.  To get '<tt>opt</tt>' to print out the
573   statistics gathered, use the '<tt>-stats</tt>' option:</p>
574
575 <div class="doc_code">
576 <pre>
577 $ opt -stats -mypassname &lt; program.bc &gt; /dev/null
578 <i>... statistics output ...</i>
579 </pre>
580 </div>
581
582   <p> When running <tt>gccas</tt> on a C file from the SPEC benchmark
583 suite, it gives a report that looks like this:</p>
584
585 <div class="doc_code">
586 <pre>
587    7646 bytecodewriter  - Number of normal instructions
588     725 bytecodewriter  - Number of oversized instructions
589  129996 bytecodewriter  - Number of bytecode bytes written
590    2817 raise           - Number of insts DCEd or constprop'd
591    3213 raise           - Number of cast-of-self removed
592    5046 raise           - Number of expression trees converted
593      75 raise           - Number of other getelementptr's formed
594     138 raise           - Number of load/store peepholes
595      42 deadtypeelim    - Number of unused typenames removed from symtab
596     392 funcresolve     - Number of varargs functions resolved
597      27 globaldce       - Number of global variables removed
598       2 adce            - Number of basic blocks removed
599     134 cee             - Number of branches revectored
600      49 cee             - Number of setcc instruction eliminated
601     532 gcse            - Number of loads removed
602    2919 gcse            - Number of instructions removed
603      86 indvars         - Number of canonical indvars added
604      87 indvars         - Number of aux indvars removed
605      25 instcombine     - Number of dead inst eliminate
606     434 instcombine     - Number of insts combined
607     248 licm            - Number of load insts hoisted
608    1298 licm            - Number of insts hoisted to a loop pre-header
609       3 licm            - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)
610      75 mem2reg         - Number of alloca's promoted
611    1444 cfgsimplify     - Number of blocks simplified
612 </pre>
613 </div>
614
615 <p>Obviously, with so many optimizations, having a unified framework for this
616 stuff is very nice.  Making your pass fit well into the framework makes it more
617 maintainable and useful.</p>
618
619 </div>
620
621 <!-- ======================================================================= -->
622 <div class="doc_subsection">
623   <a name="ViewGraph">Viewing graphs while debugging code</a>
624 </div>
625
626 <div class="doc_text">
627
628 <p>Several of the important data structures in LLVM are graphs: for example
629 CFGs made out of LLVM <a href="#BasicBlock">BasicBlock</a>s, CFGs made out of
630 LLVM <a href="CodeGenerator.html#machinebasicblock">MachineBasicBlock</a>s, and
631 <a href="CodeGenerator.html#selectiondag_intro">Instruction Selection
632 DAGs</a>.  In many cases, while debugging various parts of the compiler, it is
633 nice to instantly visualize these graphs.</p>
634
635 <p>LLVM provides several callbacks that are available in a debug build to do
636 exactly that.  If you call the <tt>Function::viewCFG()</tt> method, for example,
637 the current LLVM tool will pop up a window containing the CFG for the function
638 where each basic block is a node in the graph, and each node contains the
639 instructions in the block.  Similarly, there also exists 
640 <tt>Function::viewCFGOnly()</tt> (does not include the instructions), the
641 <tt>MachineFunction::viewCFG()</tt> and <tt>MachineFunction::viewCFGOnly()</tt>,
642 and the <tt>SelectionDAG::viewGraph()</tt> methods.  Within GDB, for example,
643 you can usually use something like <tt>call DAG.viewGraph()</tt> to pop
644 up a window.  Alternatively, you can sprinkle calls to these functions in your
645 code in places you want to debug.</p>
646
647 <p>Getting this to work requires a small amount of configuration.  On Unix
648 systems with X11, install the <a href="http://www.graphviz.org">graphviz</a>
649 toolkit, and make sure 'dot' and 'gv' are in your path.  If you are running on
650 Mac OS/X, download and install the Mac OS/X <a 
651 href="http://www.pixelglow.com/graphviz/">Graphviz program</a>, and add
652 <tt>/Applications/Graphviz.app/Contents/MacOS/</tt> (or whereever you install
653 it) to your path.  Once in your system and path are set up, rerun the LLVM
654 configure script and rebuild LLVM to enable this functionality.</p>
655
656 <p><tt>SelectionDAG</tt> has been extended to make it easier to locate
657 <i>interesting</i> nodes in large complex graphs.  From gdb, if you
658 <tt>call DAG.setGraphColor(<i>node</i>, "<i>color</i>")</tt>, then the
659 next <tt>call DAG.viewGraph()</tt> would hilight the node in the
660 specified color (choices of colors can be found at <a
661 href="http://www.graphviz.org/doc/info/colors.html">colors</a>.) More
662 complex node attributes can be provided with <tt>call
663 DAG.setGraphAttrs(<i>node</i>, "<i>attributes</i>")</tt> (choices can be
664 found at <a href="http://www.graphviz.org/doc/info/attrs.html">Graph
665 Attributes</a>.)  If you want to restart and clear all the current graph
666 attributes, then you can <tt>call DAG.clearGraphAttrs()</tt>. </p>
667
668 </div>
669
670 <!-- *********************************************************************** -->
671 <div class="doc_section">
672   <a name="datastructure">Picking the Right Data Structure for a Task</a>
673 </div>
674 <!-- *********************************************************************** -->
675
676 <div class="doc_text">
677
678 <p>LLVM has a plethora of datastructures in the <tt>llvm/ADT/</tt> directory,
679  and we commonly use STL datastructures.  This section describes the tradeoffs
680  you should consider when you pick one.</p>
681
682 <p>
683 The first step is a choose your own adventure: do you want a sequential
684 container, a set-like container, or a map-like container?  The most important
685 thing when choosing a container is the algorithmic properties of how you plan to
686 access the container.  Based on that, you should use:</p>
687
688 <ul>
689 <li>a <a href="#ds_map">map-like</a> container if you need efficient lookup
690     of an value based on another value.  Map-like containers also support
691     efficient queries for containment (whether a key is in the map).  Map-like
692     containers generally do not support efficient reverse mapping (values to
693     keys).  If you need that, use two maps.  Some map-like containers also
694     support efficient iteration through the keys in sorted order.  Map-like
695     containers are the most expensive sort, only use them if you need one of
696     these capabilities.</li>
697
698 <li>a <a href="#ds_set">set-like</a> container if you need to put a bunch of
699     stuff into a container that automatically eliminates duplicates.  Some
700     set-like containers support efficient iteration through the elements in
701     sorted order.  Set-like containers are more expensive than sequential
702     containers.
703 </li>
704
705 <li>a <a href="#ds_sequential">sequential</a> container provides
706     the most efficient way to add elements and keeps track of the order they are
707     added to the collection.  They permit duplicates and support efficient
708     iteration, but do not support efficient lookup based on a key.
709 </li>
710
711 </ul>
712
713 <p>
714 Once the proper catagory of container is determined, you can fine tune the
715 memory use, constant factors, and cache behaviors of access by intelligently
716 picking a member of the catagory.  Note that constant factors and cache behavior
717 can be a big deal.  If you have a vector that usually only contains a few
718 elements (but could contain many), for example, it's much better to use
719 <a href="#dss_smallvector">SmallVector</a> than <a href="#dss_vector">vector</a>
720 .  Doing so avoids (relatively) expensive malloc/free calls, which dwarf the
721 cost of adding the elements to the container. </p>
722
723 </div>
724
725 <!-- ======================================================================= -->
726 <div class="doc_subsection">
727   <a name="ds_sequential">Sequential Containers (std::vector, std::list, etc)</a>
728 </div>
729
730 <div class="doc_text">
731 There are a variety of sequential containers available for you, based on your
732 needs.  Pick the first in this section that will do what you want.
733 </div>
734
735 <!-- _______________________________________________________________________ -->
736 <div class="doc_subsubsection">
737   <a name="dss_fixedarrays">Fixed Size Arrays</a>
738 </div>
739
740 <div class="doc_text">
741 <p>Fixed size arrays are very simple and very fast.  They are good if you know
742 exactly how many elements you have, or you have a (low) upper bound on how many
743 you have.</p>
744 </div>
745
746 <!-- _______________________________________________________________________ -->
747 <div class="doc_subsubsection">
748   <a name="dss_heaparrays">Heap Allocated Arrays</a>
749 </div>
750
751 <div class="doc_text">
752 <p>Heap allocated arrays (new[] + delete[]) are also simple.  They are good if
753 the number of elements is variable, if you know how many elements you will need
754 before the array is allocated, and if the array is usually large (if not,
755 consider a <a href="#dss_smallvector">SmallVector</a>).  The cost of a heap
756 allocated array is the cost of the new/delete (aka malloc/free).  Also note that
757 if you are allocating an array of a type with a constructor, the constructor and
758 destructors will be run for every element in the array (resizable vectors only
759 construct those elements actually used).</p>
760 </div>
761
762 <!-- _______________________________________________________________________ -->
763 <div class="doc_subsubsection">
764   <a name="dss_smallvector">"llvm/ADT/SmallVector.h"</a>
765 </div>
766
767 <div class="doc_text">
768 <p><tt>SmallVector&lt;Type, N&gt;</tt> is a simple class that looks and smells
769 just like <tt>vector&lt;Type&gt;</tt>:
770 it supports efficient iteration, lays out elements in memory order (so you can
771 do pointer arithmetic between elements), supports efficient push_back/pop_back
772 operations, supports efficient random access to its elements, etc.</p>
773
774 <p>The advantage of SmallVector is that it allocates space for
775 some number of elements (N) <b>in the object itself</b>.  Because of this, if
776 the SmallVector is dynamically smaller than N, no malloc is performed.  This can
777 be a big win in cases where the malloc/free call is far more expensive than the
778 code that fiddles around with the elements.</p>
779
780 <p>This is good for vectors that are "usually small" (e.g. the number of
781 predecessors/successors of a block is usually less than 8).  On the other hand,
782 this makes the size of the SmallVector itself large, so you don't want to
783 allocate lots of them (doing so will waste a lot of space).  As such,
784 SmallVectors are most useful when on the stack.</p>
785
786 <p>SmallVector also provides a nice portable and efficient replacement for
787 <tt>alloca</tt>.</p>
788
789 </div>
790
791 <!-- _______________________________________________________________________ -->
792 <div class="doc_subsubsection">
793   <a name="dss_vector">&lt;vector&gt;</a>
794 </div>
795
796 <div class="doc_text">
797 <p>
798 std::vector is well loved and respected.  It is useful when SmallVector isn't:
799 when the size of the vector is often large (thus the small optimization will
800 rarely be a benefit) or if you will be allocating many instances of the vector
801 itself (which would waste space for elements that aren't in the container).
802 vector is also useful when interfacing with code that expects vectors :).
803 </p>
804 </div>
805
806 <!-- _______________________________________________________________________ -->
807 <div class="doc_subsubsection">
808   <a name="dss_deque">&lt;deque&gt;</a>
809 </div>
810
811 <div class="doc_text">
812 <p>std::deque is, in some senses, a generalized version of std::vector.  Like
813 std::vector, it provides constant time random access and other similar
814 properties, but it also provides efficient access to the front of the list.  It
815 does not guarantee continuity of elements within memory.</p>
816
817 <p>In exchange for this extra flexibility, std::deque has significantly higher
818 constant factor costs than std::vector.  If possible, use std::vector or
819 something cheaper.</p>
820 </div>
821
822 <!-- _______________________________________________________________________ -->
823 <div class="doc_subsubsection">
824   <a name="dss_list">&lt;list&gt;</a>
825 </div>
826
827 <div class="doc_text">
828 <p>std::list is an extremely inefficient class that is rarely useful.
829 It performs a heap allocation for every element inserted into it, thus having an
830 extremely high constant factor, particularly for small data types.  std::list
831 also only supports bidirectional iteration, not random access iteration.</p>
832
833 <p>In exchange for this high cost, std::list supports efficient access to both
834 ends of the list (like std::deque, but unlike std::vector or SmallVector).  In
835 addition, the iterator invalidation characteristics of std::list are stronger
836 than that of a vector class: inserting or removing an element into the list does
837 not invalidate iterator or pointers to other elements in the list.</p>
838 </div>
839
840 <!-- _______________________________________________________________________ -->
841 <div class="doc_subsubsection">
842   <a name="dss_ilist">llvm/ADT/ilist</a>
843 </div>
844
845 <div class="doc_text">
846 <p><tt>ilist&lt;T&gt;</tt> implements an 'intrusive' doubly-linked list.  It is
847 intrusive, because it requires the element to store and provide access to the
848 prev/next pointers for the list.</p>
849
850 <p>ilist has the same drawbacks as std::list, and additionally requires an
851 ilist_traits implementation for the element type, but it provides some novel
852 characteristics.  In particular, it can efficiently store polymorphic objects,
853 the traits class is informed when an element is inserted or removed from the
854 list, and ilists are guaranteed to support a constant-time splice operation.
855 </p>
856
857 <p>These properties are exactly what we want for things like Instructions and
858 basic blocks, which is why these are implemented with ilists.</p>
859 </div>
860
861 <!-- _______________________________________________________________________ -->
862 <div class="doc_subsubsection">
863   <a name="dss_other">Other Sequential Container options</a>
864 </div>
865
866 <div class="doc_text">
867 <p>Other STL containers are available, such as std::string.</p>
868
869 <p>There are also various STL adapter classes such as std::queue,
870 std::priority_queue, std::stack, etc.  These provide simplified access to an
871 underlying container but don't affect the cost of the container itself.</p>
872
873 </div>
874
875
876 <!-- ======================================================================= -->
877 <div class="doc_subsection">
878   <a name="ds_set">Set-Like Containers (std::set, SmallSet, SetVector, etc)</a>
879 </div>
880
881 <div class="doc_text">
882
883 <p>Set-like containers are useful when you need to canonicalize multiple values
884 into a single representation.  There are several different choices for how to do
885 this, providing various trade-offs.</p>
886
887 </div>
888
889
890 <!-- _______________________________________________________________________ -->
891 <div class="doc_subsubsection">
892   <a name="dss_sortedvectorset">A sorted 'vector'</a>
893 </div>
894
895 <div class="doc_text">
896
897 <p>If you intend to insert a lot of elements, then do a lot of queries, a
898 great approach is to use a vector (or other sequential container) with
899 std::sort+std::unique to remove duplicates.  This approach works really well if
900 your usage pattern has these two distinct phases (insert then query), and can be
901 coupled with a good choice of <a href="#ds_sequential">sequential container</a>.
902 </p>
903
904 <p>
905 This combination provides the several nice properties: the result data is
906 contiguous in memory (good for cache locality), has few allocations, is easy to
907 address (iterators in the final vector are just indices or pointers), and can be
908 efficiently queried with a standard binary or radix search.</p>
909
910 </div>
911
912 <!-- _______________________________________________________________________ -->
913 <div class="doc_subsubsection">
914   <a name="dss_smallset">"llvm/ADT/SmallSet.h"</a>
915 </div>
916
917 <div class="doc_text">
918
919 <p>If you have a set-like datastructure that is usually small and whose elements
920 are reasonably small, a <tt>SmallSet&lt;Type, N&gt;</tt> is a good choice.  This set
921 has space for N elements in place (thus, if the set is dynamically smaller than
922 N, no malloc traffic is required) and accesses them with a simple linear search.
923 When the set grows beyond 'N' elements, it allocates a more expensive representation that
924 guarantees efficient access (for most types, it falls back to std::set, but for
925 pointers it uses something far better, <a
926 href="#dss_smallptrset">SmallPtrSet</a>).</p>
927
928 <p>The magic of this class is that it handles small sets extremely efficiently,
929 but gracefully handles extremely large sets without loss of efficiency.  The
930 drawback is that the interface is quite small: it supports insertion, queries
931 and erasing, but does not support iteration.</p>
932
933 </div>
934
935 <!-- _______________________________________________________________________ -->
936 <div class="doc_subsubsection">
937   <a name="dss_smallptrset">"llvm/ADT/SmallPtrSet.h"</a>
938 </div>
939
940 <div class="doc_text">
941
942 <p>SmallPtrSet has all the advantages of SmallSet (and a SmallSet of pointers is 
943 transparently implemented with a SmallPtrSet), but also suports iterators.  If
944 more than 'N' insertions are performed, a single quadratically
945 probed hash table is allocated and grows as needed, providing extremely
946 efficient access (constant time insertion/deleting/queries with low constant
947 factors) and is very stingy with malloc traffic.</p>
948
949 <p>Note that, unlike std::set, the iterators of SmallPtrSet are invalidated
950 whenever an insertion occurs.  Also, the values visited by the iterators are not
951 visited in sorted order.</p>
952
953 </div>
954
955 <!-- _______________________________________________________________________ -->
956 <div class="doc_subsubsection">
957   <a name="dss_FoldingSet">"llvm/ADT/FoldingSet.h"</a>
958 </div>
959
960 <div class="doc_text">
961
962 <p>
963 FoldingSet is an aggregate class that is really good at uniquing
964 expensive-to-create or polymorphic objects.  It is a combination of a chained
965 hash table with intrusive links (uniqued objects are required to inherit from
966 FoldingSetNode) that uses <a href="#dss_smallvector">SmallVector</a> as part of
967 its ID process.</p>
968
969 <p>Consider a case where you want to implement a "getOrCreateFoo" method for
970 a complex object (for example, a node in the code generator).  The client has a
971 description of *what* it wants to generate (it knows the opcode and all the
972 operands), but we don't want to 'new' a node, then try inserting it into a set
973 only to find out it already exists, at which point we would have to delete it
974 and return the node that already exists.
975 </p>
976
977 <p>To support this style of client, FoldingSet perform a query with a
978 FoldingSetNodeID (which wraps SmallVector) that can be used to describe the
979 element that we want to query for.  The query either returns the element
980 matching the ID or it returns an opaque ID that indicates where insertion should
981 take place.  Construction of the ID usually does not require heap traffic.</p>
982
983 <p>Because FoldingSet uses intrusive links, it can support polymorphic objects
984 in the set (for example, you can have SDNode instances mixed with LoadSDNodes).
985 Because the elements are individually allocated, pointers to the elements are
986 stable: inserting or removing elements does not invalidate any pointers to other
987 elements.
988 </p>
989
990 </div>
991
992 <!-- _______________________________________________________________________ -->
993 <div class="doc_subsubsection">
994   <a name="dss_set">&lt;set&gt;</a>
995 </div>
996
997 <div class="doc_text">
998
999 <p><tt>std::set</tt> is a reasonable all-around set class, which is decent at
1000 many things but great at nothing.  std::set allocates memory for each element
1001 inserted (thus it is very malloc intensive) and typically stores three pointers
1002 per element in the set (thus adding a large amount of per-element space
1003 overhead).  It offers guaranteed log(n) performance, which is not particularly
1004 fast from a complexity standpoint (particularly if the elements of the set are
1005 expensive to compare, like strings), and has extremely high constant factors for
1006 lookup, insertion and removal.</p>
1007
1008 <p>The advantages of std::set are that its iterators are stable (deleting or
1009 inserting an element from the set does not affect iterators or pointers to other
1010 elements) and that iteration over the set is guaranteed to be in sorted order.
1011 If the elements in the set are large, then the relative overhead of the pointers
1012 and malloc traffic is not a big deal, but if the elements of the set are small,
1013 std::set is almost never a good choice.</p>
1014
1015 </div>
1016
1017 <!-- _______________________________________________________________________ -->
1018 <div class="doc_subsubsection">
1019   <a name="dss_setvector">"llvm/ADT/SetVector.h"</a>
1020 </div>
1021
1022 <div class="doc_text">
1023 <p>LLVM's SetVector&lt;Type&gt; is actually a combination of a set along with
1024 a <a href="#ds_sequential">Sequential Container</a>.  The important property
1025 that this provides is efficient insertion with uniquing (duplicate elements are
1026 ignored) with iteration support.  It implements this by inserting elements into
1027 both a set-like container and the sequential container, using the set-like
1028 container for uniquing and the sequential container for iteration.
1029 </p>
1030
1031 <p>The difference between SetVector and other sets is that the order of
1032 iteration is guaranteed to match the order of insertion into the SetVector.
1033 This property is really important for things like sets of pointers.  Because
1034 pointer values are non-deterministic (e.g. vary across runs of the program on
1035 different machines), iterating over the pointers in a std::set or other set will
1036 not be in a well-defined order.</p>
1037
1038 <p>
1039 The drawback of SetVector is that it requires twice as much space as a normal
1040 set and has the sum of constant factors from the set-like container and the 
1041 sequential container that it uses.  Use it *only* if you need to iterate over 
1042 the elements in a deterministic order.  SetVector is also expensive to delete
1043 elements out of (linear time).
1044 </p>
1045
1046 </div>
1047
1048 <!-- _______________________________________________________________________ -->
1049 <div class="doc_subsubsection">
1050   <a name="dss_uniquevector">"llvm/ADT/UniqueVector.h"</a>
1051 </div>
1052
1053 <div class="doc_text">
1054
1055 <p>
1056 UniqueVector is similar to <a href="#dss_setvector">SetVector</a>, but it
1057 retains a unique ID for each element inserted into the set.  It internally
1058 contains a map and a vector, and it assigns a unique ID for each value inserted
1059 into the set.</p>
1060
1061 <p>UniqueVector is very expensive: its cost is the sum of the cost of
1062 maintaining both the map and vector, it has high complexity, high constant
1063 factors, and produces a lot of malloc traffic.  It should be avoided.</p>
1064
1065 </div>
1066
1067
1068 <!-- _______________________________________________________________________ -->
1069 <div class="doc_subsubsection">
1070   <a name="dss_otherset">Other Set-Like Container Options</a>
1071 </div>
1072
1073 <div class="doc_text">
1074
1075 <p>
1076 The STL provides several other options, such as std::multiset and the various 
1077 "hash_set" like containers (whether from C++ TR1 or from the SGI library).</p>
1078
1079 <p>std::multiset is useful if you're not interested in elimination of
1080 duplicates, but has all the drawbacks of std::set.  A sorted vector (where you 
1081 don't delete duplicate entries) or some other approach is almost always
1082 better.</p>
1083
1084 <p>The various hash_set implementations (exposed portably by
1085 "llvm/ADT/hash_set") is a simple chained hashtable.  This algorithm is as malloc
1086 intensive as std::set (performing an allocation for each element inserted,
1087 thus having really high constant factors) but (usually) provides O(1)
1088 insertion/deletion of elements.  This can be useful if your elements are large
1089 (thus making the constant-factor cost relatively low) or if comparisons are
1090 expensive.  Element iteration does not visit elements in a useful order.</p>
1091
1092 </div>
1093
1094 <!-- ======================================================================= -->
1095 <div class="doc_subsection">
1096   <a name="ds_map">Map-Like Containers (std::map, DenseMap, etc)</a>
1097 </div>
1098
1099 <div class="doc_text">
1100 Map-like containers are useful when you want to associate data to a key.  As
1101 usual, there are a lot of different ways to do this. :)
1102 </div>
1103
1104 <!-- _______________________________________________________________________ -->
1105 <div class="doc_subsubsection">
1106   <a name="dss_sortedvectormap">A sorted 'vector'</a>
1107 </div>
1108
1109 <div class="doc_text">
1110
1111 <p>
1112 If your usage pattern follows a strict insert-then-query approach, you can
1113 trivially use the same approach as <a href="#dss_sortedvectorset">sorted vectors
1114 for set-like containers</a>.  The only difference is that your query function
1115 (which uses std::lower_bound to get efficient log(n) lookup) should only compare
1116 the key, not both the key and value.  This yields the same advantages as sorted
1117 vectors for sets.
1118 </p>
1119 </div>
1120
1121 <!-- _______________________________________________________________________ -->
1122 <div class="doc_subsubsection">
1123   <a name="dss_cstringmap">"llvm/ADT/CStringMap.h"</a>
1124 </div>
1125
1126 <div class="doc_text">
1127
1128 <p>
1129 Strings are commonly used as keys in maps, and they are difficult to support
1130 efficiently: they are variable length, inefficient to hash and compare when
1131 long, expensive to copy, etc.  CStringMap is a specialized container designed to
1132 cope with these issues.  It supports mapping an arbitrary range of bytes that
1133 does not have an embedded nul character in it ("C strings") to an arbitrary
1134 other object.</p>
1135
1136 <p>The CStringMap implementation uses a quadratically-probed hash table, where
1137 the buckets store a pointer to the heap allocated entries (and some other
1138 stuff).  The entries in the map must be heap allocated because the strings are
1139 variable length.  The string data (key) and the element object (value) are
1140 stored in the same allocation with the string data immediately after the element
1141 object.  This container guarantees the "<tt>(char*)(&amp;Value+1)</tt>" points
1142 to the key string for a value.</p>
1143
1144 <p>The CStringMap is very fast for several reasons: quadratic probing is very
1145 cache efficient for lookups, the hash value of strings in buckets is not
1146 recomputed when lookup up an element, CStringMap rarely has to touch the
1147 memory for unrelated objects when looking up a value (even when hash collisions
1148 happen), hash table growth does not recompute the hash values for strings
1149 already in the table, and each pair in the map is store in a single allocation
1150 (the string data is stored in the same allocation as the Value of a pair).</p>
1151
1152 <p>CStringMap also provides query methods that take byte ranges, so it only ever
1153 copies a string if a value is inserted into the table.</p>
1154 </div>
1155
1156 <!-- _______________________________________________________________________ -->
1157 <div class="doc_subsubsection">
1158   <a name="dss_indexedmap">"llvm/ADT/IndexedMap.h"</a>
1159 </div>
1160
1161 <div class="doc_text">
1162 <p>
1163 IndexedMap is a specialized container for mapping small dense integers (or
1164 values that can be mapped to small dense integers) to some other type.  It is
1165 internally implemented as a vector with a mapping function that maps the keys to
1166 the dense integer range.
1167 </p>
1168
1169 <p>
1170 This is useful for cases like virtual registers in the LLVM code generator: they
1171 have a dense mapping that is offset by a compile-time constant (the first
1172 virtual register ID).</p>
1173
1174 </div>
1175
1176 <!-- _______________________________________________________________________ -->
1177 <div class="doc_subsubsection">
1178   <a name="dss_densemap">"llvm/ADT/DenseMap.h"</a>
1179 </div>
1180
1181 <div class="doc_text">
1182
1183 <p>
1184 DenseMap is a simple quadratically probed hash table.  It excels at supporting
1185 small keys and values: it uses a single allocation to hold all of the pairs that
1186 are currently inserted in the map.  DenseMap is a great way to map pointers to
1187 pointers, or map other small types to each other.
1188 </p>
1189
1190 <p>
1191 There are several aspects of DenseMap that you should be aware of, however.  The
1192 iterators in a densemap are invalidated whenever an insertion occurs, unlike
1193 map.  Also, because DenseMap allocates space for a large number of key/value
1194 pairs (it starts with 64 by default) if you have large keys or values, it can
1195 waste a lot of space.  Finally, you must implement a partial specialization of
1196 DenseMapKeyInfo for the key that you want, if it isn't already supported.  This
1197 is required to tell DenseMap about two special marker values (which can never be
1198 inserted into the map).</p>
1199
1200 </div>
1201
1202 <!-- _______________________________________________________________________ -->
1203 <div class="doc_subsubsection">
1204   <a name="dss_map">&lt;map&gt;</a>
1205 </div>
1206
1207 <div class="doc_text">
1208
1209 <p>
1210 std::map has similar characteristics to <a href="#dss_set">std::set</a>: it uses
1211 a single allocation per pair inserted into the map, it offers log(n) lookup with
1212 an extremely large constant factor, imposes a space penalty of 3 pointers per
1213 pair in the map, etc.</p>
1214
1215 <p>std::map is most useful when your keys or values are very large, if you need
1216 to iterate over the collection in sorted order, or if you need stable iterators
1217 into the map (i.e. they don't get invalidated if an insertion or deletion of
1218 another element takes place).</p>
1219
1220 </div>
1221
1222 <!-- _______________________________________________________________________ -->
1223 <div class="doc_subsubsection">
1224   <a name="dss_othermap">Other Map-Like Container Options</a>
1225 </div>
1226
1227 <div class="doc_text">
1228
1229 <p>
1230 The STL provides several other options, such as std::multimap and the various 
1231 "hash_map" like containers (whether from C++ TR1 or from the SGI library).</p>
1232
1233 <p>std::multimap is useful if you want to map a key to multiple values, but has
1234 all the drawbacks of std::map.  A sorted vector or some other approach is almost
1235 always better.</p>
1236
1237 <p>The various hash_map implementations (exposed portably by
1238 "llvm/ADT/hash_map") are simple chained hash tables.  This algorithm is as
1239 malloc intensive as std::map (performing an allocation for each element
1240 inserted, thus having really high constant factors) but (usually) provides O(1)
1241 insertion/deletion of elements.  This can be useful if your elements are large
1242 (thus making the constant-factor cost relatively low) or if comparisons are
1243 expensive.  Element iteration does not visit elements in a useful order.</p>
1244
1245 </div>
1246
1247
1248 <!-- *********************************************************************** -->
1249 <div class="doc_section">
1250   <a name="common">Helpful Hints for Common Operations</a>
1251 </div>
1252 <!-- *********************************************************************** -->
1253
1254 <div class="doc_text">
1255
1256 <p>This section describes how to perform some very simple transformations of
1257 LLVM code.  This is meant to give examples of common idioms used, showing the
1258 practical side of LLVM transformations.  <p> Because this is a "how-to" section,
1259 you should also read about the main classes that you will be working with.  The
1260 <a href="#coreclasses">Core LLVM Class Hierarchy Reference</a> contains details
1261 and descriptions of the main classes that you should know about.</p>
1262
1263 </div>
1264
1265 <!-- NOTE: this section should be heavy on example code -->
1266 <!-- ======================================================================= -->
1267 <div class="doc_subsection">
1268   <a name="inspection">Basic Inspection and Traversal Routines</a>
1269 </div>
1270
1271 <div class="doc_text">
1272
1273 <p>The LLVM compiler infrastructure have many different data structures that may
1274 be traversed.  Following the example of the C++ standard template library, the
1275 techniques used to traverse these various data structures are all basically the
1276 same.  For a enumerable sequence of values, the <tt>XXXbegin()</tt> function (or
1277 method) returns an iterator to the start of the sequence, the <tt>XXXend()</tt>
1278 function returns an iterator pointing to one past the last valid element of the
1279 sequence, and there is some <tt>XXXiterator</tt> data type that is common
1280 between the two operations.</p>
1281
1282 <p>Because the pattern for iteration is common across many different aspects of
1283 the program representation, the standard template library algorithms may be used
1284 on them, and it is easier to remember how to iterate. First we show a few common
1285 examples of the data structures that need to be traversed.  Other data
1286 structures are traversed in very similar ways.</p>
1287
1288 </div>
1289
1290 <!-- _______________________________________________________________________ -->
1291 <div class="doc_subsubsection">
1292   <a name="iterate_function">Iterating over the </a><a
1293   href="#BasicBlock"><tt>BasicBlock</tt></a>s in a <a
1294   href="#Function"><tt>Function</tt></a>
1295 </div>
1296
1297 <div class="doc_text">
1298
1299 <p>It's quite common to have a <tt>Function</tt> instance that you'd like to
1300 transform in some way; in particular, you'd like to manipulate its
1301 <tt>BasicBlock</tt>s.  To facilitate this, you'll need to iterate over all of
1302 the <tt>BasicBlock</tt>s that constitute the <tt>Function</tt>. The following is
1303 an example that prints the name of a <tt>BasicBlock</tt> and the number of
1304 <tt>Instruction</tt>s it contains:</p>
1305
1306 <div class="doc_code">
1307 <pre>
1308 // <i>func is a pointer to a Function instance</i>
1309 for (Function::iterator i = func-&gt;begin(), e = func-&gt;end(); i != e; ++i)
1310   // <i>Print out the name of the basic block if it has one, and then the</i>
1311   // <i>number of instructions that it contains</i>
1312   llvm::cerr &lt;&lt; "Basic block (name=" &lt;&lt; i-&gt;getName() &lt;&lt; ") has "
1313              &lt;&lt; i-&gt;size() &lt;&lt; " instructions.\n";
1314 </pre>
1315 </div>
1316
1317 <p>Note that i can be used as if it were a pointer for the purposes of
1318 invoking member functions of the <tt>Instruction</tt> class.  This is
1319 because the indirection operator is overloaded for the iterator
1320 classes.  In the above code, the expression <tt>i-&gt;size()</tt> is
1321 exactly equivalent to <tt>(*i).size()</tt> just like you'd expect.</p>
1322
1323 </div>
1324
1325 <!-- _______________________________________________________________________ -->
1326 <div class="doc_subsubsection">
1327   <a name="iterate_basicblock">Iterating over the </a><a
1328   href="#Instruction"><tt>Instruction</tt></a>s in a <a
1329   href="#BasicBlock"><tt>BasicBlock</tt></a>
1330 </div>
1331
1332 <div class="doc_text">
1333
1334 <p>Just like when dealing with <tt>BasicBlock</tt>s in <tt>Function</tt>s, it's
1335 easy to iterate over the individual instructions that make up
1336 <tt>BasicBlock</tt>s. Here's a code snippet that prints out each instruction in
1337 a <tt>BasicBlock</tt>:</p>
1338
1339 <div class="doc_code">
1340 <pre>
1341 // <i>blk is a pointer to a BasicBlock instance</i>
1342 for (BasicBlock::iterator i = blk-&gt;begin(), e = blk-&gt;end(); i != e; ++i)
1343    // <i>The next statement works since operator&lt;&lt;(ostream&amp;,...)</i>
1344    // <i>is overloaded for Instruction&amp;</i>
1345    llvm::cerr &lt;&lt; *i &lt;&lt; "\n";
1346 </pre>
1347 </div>
1348
1349 <p>However, this isn't really the best way to print out the contents of a
1350 <tt>BasicBlock</tt>!  Since the ostream operators are overloaded for virtually
1351 anything you'll care about, you could have just invoked the print routine on the
1352 basic block itself: <tt>llvm::cerr &lt;&lt; *blk &lt;&lt; "\n";</tt>.</p>
1353
1354 </div>
1355
1356 <!-- _______________________________________________________________________ -->
1357 <div class="doc_subsubsection">
1358   <a name="iterate_institer">Iterating over the </a><a
1359   href="#Instruction"><tt>Instruction</tt></a>s in a <a
1360   href="#Function"><tt>Function</tt></a>
1361 </div>
1362
1363 <div class="doc_text">
1364
1365 <p>If you're finding that you commonly iterate over a <tt>Function</tt>'s
1366 <tt>BasicBlock</tt>s and then that <tt>BasicBlock</tt>'s <tt>Instruction</tt>s,
1367 <tt>InstIterator</tt> should be used instead. You'll need to include <a
1368 href="/doxygen/InstIterator_8h-source.html"><tt>llvm/Support/InstIterator.h</tt></a>,
1369 and then instantiate <tt>InstIterator</tt>s explicitly in your code.  Here's a
1370 small example that shows how to dump all instructions in a function to the standard error stream:<p>
1371
1372 <div class="doc_code">
1373 <pre>
1374 #include "<a href="/doxygen/InstIterator_8h-source.html">llvm/Support/InstIterator.h</a>"
1375
1376 // <i>F is a ptr to a Function instance</i>
1377 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
1378   llvm::cerr &lt;&lt; *i &lt;&lt; "\n";
1379 </pre>
1380 </div>
1381
1382 <p>Easy, isn't it?  You can also use <tt>InstIterator</tt>s to fill a
1383 worklist with its initial contents.  For example, if you wanted to
1384 initialize a worklist to contain all instructions in a <tt>Function</tt>
1385 F, all you would need to do is something like:</p>
1386
1387 <div class="doc_code">
1388 <pre>
1389 std::set&lt;Instruction*&gt; worklist;
1390 worklist.insert(inst_begin(F), inst_end(F));
1391 </pre>
1392 </div>
1393
1394 <p>The STL set <tt>worklist</tt> would now contain all instructions in the
1395 <tt>Function</tt> pointed to by F.</p>
1396
1397 </div>
1398
1399 <!-- _______________________________________________________________________ -->
1400 <div class="doc_subsubsection">
1401   <a name="iterate_convert">Turning an iterator into a class pointer (and
1402   vice-versa)</a>
1403 </div>
1404
1405 <div class="doc_text">
1406
1407 <p>Sometimes, it'll be useful to grab a reference (or pointer) to a class
1408 instance when all you've got at hand is an iterator.  Well, extracting
1409 a reference or a pointer from an iterator is very straight-forward.
1410 Assuming that <tt>i</tt> is a <tt>BasicBlock::iterator</tt> and <tt>j</tt>
1411 is a <tt>BasicBlock::const_iterator</tt>:</p>
1412
1413 <div class="doc_code">
1414 <pre>
1415 Instruction&amp; inst = *i;   // <i>Grab reference to instruction reference</i>
1416 Instruction* pinst = &amp;*i; // <i>Grab pointer to instruction reference</i>
1417 const Instruction&amp; inst = *j;
1418 </pre>
1419 </div>
1420
1421 <p>However, the iterators you'll be working with in the LLVM framework are
1422 special: they will automatically convert to a ptr-to-instance type whenever they
1423 need to.  Instead of dereferencing the iterator and then taking the address of
1424 the result, you can simply assign the iterator to the proper pointer type and
1425 you get the dereference and address-of operation as a result of the assignment
1426 (behind the scenes, this is a result of overloading casting mechanisms).  Thus
1427 the last line of the last example,</p>
1428
1429 <div class="doc_code">
1430 <pre>
1431 Instruction* pinst = &amp;*i;
1432 </pre>
1433 </div>
1434
1435 <p>is semantically equivalent to</p>
1436
1437 <div class="doc_code">
1438 <pre>
1439 Instruction* pinst = i;
1440 </pre>
1441 </div>
1442
1443 <p>It's also possible to turn a class pointer into the corresponding iterator,
1444 and this is a constant time operation (very efficient).  The following code
1445 snippet illustrates use of the conversion constructors provided by LLVM
1446 iterators.  By using these, you can explicitly grab the iterator of something
1447 without actually obtaining it via iteration over some structure:</p>
1448
1449 <div class="doc_code">
1450 <pre>
1451 void printNextInstruction(Instruction* inst) {
1452   BasicBlock::iterator it(inst);
1453   ++it; // <i>After this line, it refers to the instruction after *inst</i>
1454   if (it != inst-&gt;getParent()-&gt;end()) llvm::cerr &lt;&lt; *it &lt;&lt; "\n";
1455 }
1456 </pre>
1457 </div>
1458
1459 </div>
1460
1461 <!--_______________________________________________________________________-->
1462 <div class="doc_subsubsection">
1463   <a name="iterate_complex">Finding call sites: a slightly more complex
1464   example</a>
1465 </div>
1466
1467 <div class="doc_text">
1468
1469 <p>Say that you're writing a FunctionPass and would like to count all the
1470 locations in the entire module (that is, across every <tt>Function</tt>) where a
1471 certain function (i.e., some <tt>Function</tt>*) is already in scope.  As you'll
1472 learn later, you may want to use an <tt>InstVisitor</tt> to accomplish this in a
1473 much more straight-forward manner, but this example will allow us to explore how
1474 you'd do it if you didn't have <tt>InstVisitor</tt> around. In pseudocode, this
1475 is what we want to do:</p>
1476
1477 <div class="doc_code">
1478 <pre>
1479 initialize callCounter to zero
1480 for each Function f in the Module
1481   for each BasicBlock b in f
1482     for each Instruction i in b
1483       if (i is a CallInst and calls the given function)
1484         increment callCounter
1485 </pre>
1486 </div>
1487
1488 <p>And the actual code is (remember, because we're writing a
1489 <tt>FunctionPass</tt>, our <tt>FunctionPass</tt>-derived class simply has to
1490 override the <tt>runOnFunction</tt> method):</p>
1491
1492 <div class="doc_code">
1493 <pre>
1494 Function* targetFunc = ...;
1495
1496 class OurFunctionPass : public FunctionPass {
1497   public:
1498     OurFunctionPass(): callCounter(0) { }
1499
1500     virtual runOnFunction(Function&amp; F) {
1501       for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) {
1502         for (BasicBlock::iterator i = b-&gt;begin(); ie = b-&gt;end(); i != ie; ++i) {
1503           if (<a href="#CallInst">CallInst</a>* callInst = <a href="#isa">dyn_cast</a>&lt;<a
1504  href="#CallInst">CallInst</a>&gt;(&amp;*i)) {
1505             // <i>We know we've encountered a call instruction, so we</i>
1506             // <i>need to determine if it's a call to the</i>
1507             // <i>function pointed to by m_func or not</i>
1508
1509             if (callInst-&gt;getCalledFunction() == targetFunc)
1510               ++callCounter;
1511           }
1512         }
1513       }
1514     }
1515
1516   private:
1517     unsigned  callCounter;
1518 };
1519 </pre>
1520 </div>
1521
1522 </div>
1523
1524 <!--_______________________________________________________________________-->
1525 <div class="doc_subsubsection">
1526   <a name="calls_and_invokes">Treating calls and invokes the same way</a>
1527 </div>
1528
1529 <div class="doc_text">
1530
1531 <p>You may have noticed that the previous example was a bit oversimplified in
1532 that it did not deal with call sites generated by 'invoke' instructions. In
1533 this, and in other situations, you may find that you want to treat
1534 <tt>CallInst</tt>s and <tt>InvokeInst</tt>s the same way, even though their
1535 most-specific common base class is <tt>Instruction</tt>, which includes lots of
1536 less closely-related things. For these cases, LLVM provides a handy wrapper
1537 class called <a
1538 href="http://llvm.org/doxygen/classllvm_1_1CallSite.html"><tt>CallSite</tt></a>.
1539 It is essentially a wrapper around an <tt>Instruction</tt> pointer, with some
1540 methods that provide functionality common to <tt>CallInst</tt>s and
1541 <tt>InvokeInst</tt>s.</p>
1542
1543 <p>This class has "value semantics": it should be passed by value, not by
1544 reference and it should not be dynamically allocated or deallocated using
1545 <tt>operator new</tt> or <tt>operator delete</tt>. It is efficiently copyable,
1546 assignable and constructable, with costs equivalents to that of a bare pointer.
1547 If you look at its definition, it has only a single pointer member.</p>
1548
1549 </div>
1550
1551 <!--_______________________________________________________________________-->
1552 <div class="doc_subsubsection">
1553   <a name="iterate_chains">Iterating over def-use &amp; use-def chains</a>
1554 </div>
1555
1556 <div class="doc_text">
1557
1558 <p>Frequently, we might have an instance of the <a
1559 href="/doxygen/classllvm_1_1Value.html">Value Class</a> and we want to
1560 determine which <tt>User</tt>s use the <tt>Value</tt>.  The list of all
1561 <tt>User</tt>s of a particular <tt>Value</tt> is called a <i>def-use</i> chain.
1562 For example, let's say we have a <tt>Function*</tt> named <tt>F</tt> to a
1563 particular function <tt>foo</tt>. Finding all of the instructions that
1564 <i>use</i> <tt>foo</tt> is as simple as iterating over the <i>def-use</i> chain
1565 of <tt>F</tt>:</p>
1566
1567 <div class="doc_code">
1568 <pre>
1569 Function* F = ...;
1570
1571 for (Value::use_iterator i = F-&gt;use_begin(), e = F-&gt;use_end(); i != e; ++i)
1572   if (Instruction *Inst = dyn_cast&lt;Instruction&gt;(*i)) {
1573     llvm::cerr &lt;&lt; "F is used in instruction:\n";
1574     llvm::cerr &lt;&lt; *Inst &lt;&lt; "\n";
1575   }
1576 </pre>
1577 </div>
1578
1579 <p>Alternately, it's common to have an instance of the <a
1580 href="/doxygen/classllvm_1_1User.html">User Class</a> and need to know what
1581 <tt>Value</tt>s are used by it.  The list of all <tt>Value</tt>s used by a
1582 <tt>User</tt> is known as a <i>use-def</i> chain.  Instances of class
1583 <tt>Instruction</tt> are common <tt>User</tt>s, so we might want to iterate over
1584 all of the values that a particular instruction uses (that is, the operands of
1585 the particular <tt>Instruction</tt>):</p>
1586
1587 <div class="doc_code">
1588 <pre>
1589 Instruction* pi = ...;
1590
1591 for (User::op_iterator i = pi-&gt;op_begin(), e = pi-&gt;op_end(); i != e; ++i) {
1592   Value* v = *i;
1593   // <i>...</i>
1594 }
1595 </pre>
1596 </div>
1597
1598 <!--
1599   def-use chains ("finding all users of"): Value::use_begin/use_end
1600   use-def chains ("finding all values used"): User::op_begin/op_end [op=operand]
1601 -->
1602
1603 </div>
1604
1605 <!-- ======================================================================= -->
1606 <div class="doc_subsection">
1607   <a name="simplechanges">Making simple changes</a>
1608 </div>
1609
1610 <div class="doc_text">
1611
1612 <p>There are some primitive transformation operations present in the LLVM
1613 infrastructure that are worth knowing about.  When performing
1614 transformations, it's fairly common to manipulate the contents of basic
1615 blocks. This section describes some of the common methods for doing so
1616 and gives example code.</p>
1617
1618 </div>
1619
1620 <!--_______________________________________________________________________-->
1621 <div class="doc_subsubsection">
1622   <a name="schanges_creating">Creating and inserting new
1623   <tt>Instruction</tt>s</a>
1624 </div>
1625
1626 <div class="doc_text">
1627
1628 <p><i>Instantiating Instructions</i></p>
1629
1630 <p>Creation of <tt>Instruction</tt>s is straight-forward: simply call the
1631 constructor for the kind of instruction to instantiate and provide the necessary
1632 parameters. For example, an <tt>AllocaInst</tt> only <i>requires</i> a
1633 (const-ptr-to) <tt>Type</tt>. Thus:</p> 
1634
1635 <div class="doc_code">
1636 <pre>
1637 AllocaInst* ai = new AllocaInst(Type::IntTy);
1638 </pre>
1639 </div>
1640
1641 <p>will create an <tt>AllocaInst</tt> instance that represents the allocation of
1642 one integer in the current stack frame, at runtime. Each <tt>Instruction</tt>
1643 subclass is likely to have varying default parameters which change the semantics
1644 of the instruction, so refer to the <a
1645 href="/doxygen/classllvm_1_1Instruction.html">doxygen documentation for the subclass of
1646 Instruction</a> that you're interested in instantiating.</p>
1647
1648 <p><i>Naming values</i></p>
1649
1650 <p>It is very useful to name the values of instructions when you're able to, as
1651 this facilitates the debugging of your transformations.  If you end up looking
1652 at generated LLVM machine code, you definitely want to have logical names
1653 associated with the results of instructions!  By supplying a value for the
1654 <tt>Name</tt> (default) parameter of the <tt>Instruction</tt> constructor, you
1655 associate a logical name with the result of the instruction's execution at
1656 runtime.  For example, say that I'm writing a transformation that dynamically
1657 allocates space for an integer on the stack, and that integer is going to be
1658 used as some kind of index by some other code.  To accomplish this, I place an
1659 <tt>AllocaInst</tt> at the first point in the first <tt>BasicBlock</tt> of some
1660 <tt>Function</tt>, and I'm intending to use it within the same
1661 <tt>Function</tt>. I might do:</p>
1662
1663 <div class="doc_code">
1664 <pre>
1665 AllocaInst* pa = new AllocaInst(Type::IntTy, 0, "indexLoc");
1666 </pre>
1667 </div>
1668
1669 <p>where <tt>indexLoc</tt> is now the logical name of the instruction's
1670 execution value, which is a pointer to an integer on the runtime stack.</p>
1671
1672 <p><i>Inserting instructions</i></p>
1673
1674 <p>There are essentially two ways to insert an <tt>Instruction</tt>
1675 into an existing sequence of instructions that form a <tt>BasicBlock</tt>:</p>
1676
1677 <ul>
1678   <li>Insertion into an explicit instruction list
1679
1680     <p>Given a <tt>BasicBlock* pb</tt>, an <tt>Instruction* pi</tt> within that
1681     <tt>BasicBlock</tt>, and a newly-created instruction we wish to insert
1682     before <tt>*pi</tt>, we do the following: </p>
1683
1684 <div class="doc_code">
1685 <pre>
1686 BasicBlock *pb = ...;
1687 Instruction *pi = ...;
1688 Instruction *newInst = new Instruction(...);
1689
1690 pb-&gt;getInstList().insert(pi, newInst); // <i>Inserts newInst before pi in pb</i>
1691 </pre>
1692 </div>
1693
1694     <p>Appending to the end of a <tt>BasicBlock</tt> is so common that
1695     the <tt>Instruction</tt> class and <tt>Instruction</tt>-derived
1696     classes provide constructors which take a pointer to a
1697     <tt>BasicBlock</tt> to be appended to. For example code that
1698     looked like: </p>
1699
1700 <div class="doc_code">
1701 <pre>
1702 BasicBlock *pb = ...;
1703 Instruction *newInst = new Instruction(...);
1704
1705 pb-&gt;getInstList().push_back(newInst); // <i>Appends newInst to pb</i>
1706 </pre>
1707 </div>
1708
1709     <p>becomes: </p>
1710
1711 <div class="doc_code">
1712 <pre>
1713 BasicBlock *pb = ...;
1714 Instruction *newInst = new Instruction(..., pb);
1715 </pre>
1716 </div>
1717
1718     <p>which is much cleaner, especially if you are creating
1719     long instruction streams.</p></li>
1720
1721   <li>Insertion into an implicit instruction list
1722
1723     <p><tt>Instruction</tt> instances that are already in <tt>BasicBlock</tt>s
1724     are implicitly associated with an existing instruction list: the instruction
1725     list of the enclosing basic block. Thus, we could have accomplished the same
1726     thing as the above code without being given a <tt>BasicBlock</tt> by doing:
1727     </p>
1728
1729 <div class="doc_code">
1730 <pre>
1731 Instruction *pi = ...;
1732 Instruction *newInst = new Instruction(...);
1733
1734 pi-&gt;getParent()-&gt;getInstList().insert(pi, newInst);
1735 </pre>
1736 </div>
1737
1738     <p>In fact, this sequence of steps occurs so frequently that the
1739     <tt>Instruction</tt> class and <tt>Instruction</tt>-derived classes provide
1740     constructors which take (as a default parameter) a pointer to an
1741     <tt>Instruction</tt> which the newly-created <tt>Instruction</tt> should
1742     precede.  That is, <tt>Instruction</tt> constructors are capable of
1743     inserting the newly-created instance into the <tt>BasicBlock</tt> of a
1744     provided instruction, immediately before that instruction.  Using an
1745     <tt>Instruction</tt> constructor with a <tt>insertBefore</tt> (default)
1746     parameter, the above code becomes:</p>
1747
1748 <div class="doc_code">
1749 <pre>
1750 Instruction* pi = ...;
1751 Instruction* newInst = new Instruction(..., pi);
1752 </pre>
1753 </div>
1754
1755     <p>which is much cleaner, especially if you're creating a lot of
1756     instructions and adding them to <tt>BasicBlock</tt>s.</p></li>
1757 </ul>
1758
1759 </div>
1760
1761 <!--_______________________________________________________________________-->
1762 <div class="doc_subsubsection">
1763   <a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a>
1764 </div>
1765
1766 <div class="doc_text">
1767
1768 <p>Deleting an instruction from an existing sequence of instructions that form a
1769 <a href="#BasicBlock"><tt>BasicBlock</tt></a> is very straight-forward. First,
1770 you must have a pointer to the instruction that you wish to delete.  Second, you
1771 need to obtain the pointer to that instruction's basic block. You use the
1772 pointer to the basic block to get its list of instructions and then use the
1773 erase function to remove your instruction. For example:</p>
1774
1775 <div class="doc_code">
1776 <pre>
1777 <a href="#Instruction">Instruction</a> *I = .. ;
1778 <a href="#BasicBlock">BasicBlock</a> *BB = I-&gt;getParent();
1779
1780 BB-&gt;getInstList().erase(I);
1781 </pre>
1782 </div>
1783
1784 </div>
1785
1786 <!--_______________________________________________________________________-->
1787 <div class="doc_subsubsection">
1788   <a name="schanges_replacing">Replacing an <tt>Instruction</tt> with another
1789   <tt>Value</tt></a>
1790 </div>
1791
1792 <div class="doc_text">
1793
1794 <p><i>Replacing individual instructions</i></p>
1795
1796 <p>Including "<a href="/doxygen/BasicBlockUtils_8h-source.html">llvm/Transforms/Utils/BasicBlockUtils.h</a>"
1797 permits use of two very useful replace functions: <tt>ReplaceInstWithValue</tt>
1798 and <tt>ReplaceInstWithInst</tt>.</p>
1799
1800 <h4><a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a></h4>
1801
1802 <ul>
1803   <li><tt>ReplaceInstWithValue</tt>
1804
1805     <p>This function replaces all uses (within a basic block) of a given
1806     instruction with a value, and then removes the original instruction. The
1807     following example illustrates the replacement of the result of a particular
1808     <tt>AllocaInst</tt> that allocates memory for a single integer with a null
1809     pointer to an integer.</p>
1810
1811 <div class="doc_code">
1812 <pre>
1813 AllocaInst* instToReplace = ...;
1814 BasicBlock::iterator ii(instToReplace);
1815
1816 ReplaceInstWithValue(instToReplace-&gt;getParent()-&gt;getInstList(), ii,
1817                      Constant::getNullValue(PointerType::get(Type::IntTy)));
1818 </pre></div></li>
1819
1820   <li><tt>ReplaceInstWithInst</tt> 
1821
1822     <p>This function replaces a particular instruction with another
1823     instruction. The following example illustrates the replacement of one
1824     <tt>AllocaInst</tt> with another.</p>
1825
1826 <div class="doc_code">
1827 <pre>
1828 AllocaInst* instToReplace = ...;
1829 BasicBlock::iterator ii(instToReplace);
1830
1831 ReplaceInstWithInst(instToReplace-&gt;getParent()-&gt;getInstList(), ii,
1832                     new AllocaInst(Type::IntTy, 0, "ptrToReplacedInt"));
1833 </pre></div></li>
1834 </ul>
1835
1836 <p><i>Replacing multiple uses of <tt>User</tt>s and <tt>Value</tt>s</i></p>
1837
1838 <p>You can use <tt>Value::replaceAllUsesWith</tt> and
1839 <tt>User::replaceUsesOfWith</tt> to change more than one use at a time.  See the
1840 doxygen documentation for the <a href="/doxygen/classllvm_1_1Value.html">Value Class</a>
1841 and <a href="/doxygen/classllvm_1_1User.html">User Class</a>, respectively, for more
1842 information.</p>
1843
1844 <!-- Value::replaceAllUsesWith User::replaceUsesOfWith Point out:
1845 include/llvm/Transforms/Utils/ especially BasicBlockUtils.h with:
1846 ReplaceInstWithValue, ReplaceInstWithInst -->
1847
1848 </div>
1849
1850 <!-- *********************************************************************** -->
1851 <div class="doc_section">
1852   <a name="advanced">Advanced Topics</a>
1853 </div>
1854 <!-- *********************************************************************** -->
1855
1856 <div class="doc_text">
1857 <p>
1858 This section describes some of the advanced or obscure API's that most clients
1859 do not need to be aware of.  These API's tend manage the inner workings of the
1860 LLVM system, and only need to be accessed in unusual circumstances.
1861 </p>
1862 </div>
1863
1864 <!-- ======================================================================= -->
1865 <div class="doc_subsection">
1866   <a name="TypeResolve">LLVM Type Resolution</a>
1867 </div>
1868
1869 <div class="doc_text">
1870
1871 <p>
1872 The LLVM type system has a very simple goal: allow clients to compare types for
1873 structural equality with a simple pointer comparison (aka a shallow compare).
1874 This goal makes clients much simpler and faster, and is used throughout the LLVM
1875 system.
1876 </p>
1877
1878 <p>
1879 Unfortunately achieving this goal is not a simple matter.  In particular,
1880 recursive types and late resolution of opaque types makes the situation very
1881 difficult to handle.  Fortunately, for the most part, our implementation makes
1882 most clients able to be completely unaware of the nasty internal details.  The
1883 primary case where clients are exposed to the inner workings of it are when
1884 building a recursive type.  In addition to this case, the LLVM bytecode reader,
1885 assembly parser, and linker also have to be aware of the inner workings of this
1886 system.
1887 </p>
1888
1889 <p>
1890 For our purposes below, we need three concepts.  First, an "Opaque Type" is 
1891 exactly as defined in the <a href="LangRef.html#t_opaque">language 
1892 reference</a>.  Second an "Abstract Type" is any type which includes an 
1893 opaque type as part of its type graph (for example "<tt>{ opaque, i32 }</tt>").
1894 Third, a concrete type is a type that is not an abstract type (e.g. "<tt>{ i32, 
1895 float }</tt>").
1896 </p>
1897
1898 </div>
1899
1900 <!-- ______________________________________________________________________ -->
1901 <div class="doc_subsubsection">
1902   <a name="BuildRecType">Basic Recursive Type Construction</a>
1903 </div>
1904
1905 <div class="doc_text">
1906
1907 <p>
1908 Because the most common question is "how do I build a recursive type with LLVM",
1909 we answer it now and explain it as we go.  Here we include enough to cause this
1910 to be emitted to an output .ll file:
1911 </p>
1912
1913 <div class="doc_code">
1914 <pre>
1915 %mylist = type { %mylist*, i32 }
1916 </pre>
1917 </div>
1918
1919 <p>
1920 To build this, use the following LLVM APIs:
1921 </p>
1922
1923 <div class="doc_code">
1924 <pre>
1925 // <i>Create the initial outer struct</i>
1926 <a href="#PATypeHolder">PATypeHolder</a> StructTy = OpaqueType::get();
1927 std::vector&lt;const Type*&gt; Elts;
1928 Elts.push_back(PointerType::get(StructTy));
1929 Elts.push_back(Type::IntTy);
1930 StructType *NewSTy = StructType::get(Elts);
1931
1932 // <i>At this point, NewSTy = "{ opaque*, i32 }". Tell VMCore that</i>
1933 // <i>the struct and the opaque type are actually the same.</i>
1934 cast&lt;OpaqueType&gt;(StructTy.get())-&gt;<a href="#refineAbstractTypeTo">refineAbstractTypeTo</a>(NewSTy);
1935
1936 // <i>NewSTy is potentially invalidated, but StructTy (a <a href="#PATypeHolder">PATypeHolder</a>) is</i>
1937 // <i>kept up-to-date</i>
1938 NewSTy = cast&lt;StructType&gt;(StructTy.get());
1939
1940 // <i>Add a name for the type to the module symbol table (optional)</i>
1941 MyModule-&gt;addTypeName("mylist", NewSTy);
1942 </pre>
1943 </div>
1944
1945 <p>
1946 This code shows the basic approach used to build recursive types: build a
1947 non-recursive type using 'opaque', then use type unification to close the cycle.
1948 The type unification step is performed by the <tt><a
1949 href="#refineAbstractTypeTo">refineAbstractTypeTo</a></tt> method, which is
1950 described next.  After that, we describe the <a
1951 href="#PATypeHolder">PATypeHolder class</a>.
1952 </p>
1953
1954 </div>
1955
1956 <!-- ______________________________________________________________________ -->
1957 <div class="doc_subsubsection">
1958   <a name="refineAbstractTypeTo">The <tt>refineAbstractTypeTo</tt> method</a>
1959 </div>
1960
1961 <div class="doc_text">
1962 <p>
1963 The <tt>refineAbstractTypeTo</tt> method starts the type unification process.
1964 While this method is actually a member of the DerivedType class, it is most
1965 often used on OpaqueType instances.  Type unification is actually a recursive
1966 process.  After unification, types can become structurally isomorphic to
1967 existing types, and all duplicates are deleted (to preserve pointer equality).
1968 </p>
1969
1970 <p>
1971 In the example above, the OpaqueType object is definitely deleted.
1972 Additionally, if there is an "{ \2*, i32}" type already created in the system,
1973 the pointer and struct type created are <b>also</b> deleted.  Obviously whenever
1974 a type is deleted, any "Type*" pointers in the program are invalidated.  As
1975 such, it is safest to avoid having <i>any</i> "Type*" pointers to abstract types
1976 live across a call to <tt>refineAbstractTypeTo</tt> (note that non-abstract
1977 types can never move or be deleted).  To deal with this, the <a
1978 href="#PATypeHolder">PATypeHolder</a> class is used to maintain a stable
1979 reference to a possibly refined type, and the <a
1980 href="#AbstractTypeUser">AbstractTypeUser</a> class is used to update more
1981 complex datastructures.
1982 </p>
1983
1984 </div>
1985
1986 <!-- ______________________________________________________________________ -->
1987 <div class="doc_subsubsection">
1988   <a name="PATypeHolder">The PATypeHolder Class</a>
1989 </div>
1990
1991 <div class="doc_text">
1992 <p>
1993 PATypeHolder is a form of a "smart pointer" for Type objects.  When VMCore
1994 happily goes about nuking types that become isomorphic to existing types, it
1995 automatically updates all PATypeHolder objects to point to the new type.  In the
1996 example above, this allows the code to maintain a pointer to the resultant
1997 resolved recursive type, even though the Type*'s are potentially invalidated.
1998 </p>
1999
2000 <p>
2001 PATypeHolder is an extremely light-weight object that uses a lazy union-find
2002 implementation to update pointers.  For example the pointer from a Value to its
2003 Type is maintained by PATypeHolder objects.
2004 </p>
2005
2006 </div>
2007
2008 <!-- ______________________________________________________________________ -->
2009 <div class="doc_subsubsection">
2010   <a name="AbstractTypeUser">The AbstractTypeUser Class</a>
2011 </div>
2012
2013 <div class="doc_text">
2014
2015 <p>
2016 Some data structures need more to perform more complex updates when types get
2017 resolved.  The <a href="#SymbolTable">SymbolTable</a> class, for example, needs
2018 move and potentially merge type planes in its representation when a pointer
2019 changes.</p>
2020
2021 <p>
2022 To support this, a class can derive from the AbstractTypeUser class.  This class
2023 allows it to get callbacks when certain types are resolved.  To register to get
2024 callbacks for a particular type, the DerivedType::{add/remove}AbstractTypeUser
2025 methods can be called on a type.  Note that these methods only work for <i>
2026   abstract</i> types.  Concrete types (those that do not include any opaque 
2027 objects) can never be refined.
2028 </p>
2029 </div>
2030
2031
2032 <!-- ======================================================================= -->
2033 <div class="doc_subsection">
2034   <a name="SymbolTable">The <tt>SymbolTable</tt> class</a>
2035 </div>
2036
2037 <div class="doc_text">
2038 <p>This class provides a symbol table that the <a
2039 href="#Function"><tt>Function</tt></a> and <a href="#Module">
2040 <tt>Module</tt></a> classes use for naming definitions. The symbol table can
2041 provide a name for any <a href="#Value"><tt>Value</tt></a>. 
2042 <tt>SymbolTable</tt> is an abstract data type. It hides the data it contains 
2043 and provides access to it through a controlled interface.</p>
2044
2045 <p>Note that the <tt>SymbolTable</tt> class should not be directly accessed 
2046 by most clients.  It should only be used when iteration over the symbol table 
2047 names themselves are required, which is very special purpose.  Note that not 
2048 all LLVM
2049 <a href="#Value">Value</a>s have names, and those without names (i.e. they have
2050 an empty name) do not exist in the symbol table.
2051 </p>
2052
2053 <p>To use the <tt>SymbolTable</tt> well, you need to understand the 
2054 structure of the information it holds. The class contains two 
2055 <tt>std::map</tt> objects. The first, <tt>pmap</tt>, is a map of 
2056 <tt>Type*</tt> to maps of name (<tt>std::string</tt>) to <tt>Value*</tt>. 
2057 Thus, Values are stored in two-dimensions and accessed by <tt>Type</tt> and 
2058 name.</p> 
2059
2060 <p>The interface of this class provides three basic types of operations:
2061 <ol>
2062   <li><em>Accessors</em>. Accessors provide read-only access to information
2063   such as finding a value for a name with the 
2064   <a href="#SymbolTable_lookup">lookup</a> method.</li> 
2065   <li><em>Mutators</em>. Mutators allow the user to add information to the
2066   <tt>SymbolTable</tt> with methods like 
2067   <a href="#SymbolTable_insert"><tt>insert</tt></a>.</li>
2068   <li><em>Iterators</em>. Iterators allow the user to traverse the content
2069   of the symbol table in well defined ways, such as the method
2070   <a href="#SymbolTable_plane_begin"><tt>plane_begin</tt></a>.</li>
2071 </ol>
2072
2073 <h3>Accessors</h3>
2074 <dl>
2075   <dt><tt>Value* lookup(const Type* Ty, const std::string&amp; name) const</tt>:
2076   </dt>
2077   <dd>The <tt>lookup</tt> method searches the type plane given by the
2078   <tt>Ty</tt> parameter for a <tt>Value</tt> with the provided <tt>name</tt>.
2079   If a suitable <tt>Value</tt> is not found, null is returned.</dd>
2080
2081   <dt><tt>bool isEmpty() const</tt>:</dt>
2082   <dd>This function returns true if both the value and types maps are
2083   empty</dd>
2084 </dl>
2085
2086 <h3>Mutators</h3>
2087 <dl>
2088   <dt><tt>void insert(Value *Val)</tt>:</dt>
2089   <dd>This method adds the provided value to the symbol table.  The Value must
2090   have both a name and a type which are extracted and used to place the value
2091   in the correct type plane under the value's name.</dd>
2092
2093   <dt><tt>void insert(const std::string&amp; Name, Value *Val)</tt>:</dt>
2094   <dd> Inserts a constant or type into the symbol table with the specified
2095   name. There can be a many to one mapping between names and constants
2096   or types.</dd>
2097
2098   <dt><tt>void remove(Value* Val)</tt>:</dt>
2099  <dd> This method removes a named value from the symbol table. The
2100   type and name of the Value are extracted from \p N and used to
2101   lookup the Value in the correct type plane. If the Value is
2102   not in the symbol table, this method silently ignores the
2103   request.</dd>
2104
2105   <dt><tt>Value* remove(const std::string&amp; Name, Value *Val)</tt>:</dt>
2106   <dd> Remove a constant or type with the specified name from the 
2107   symbol table.</dd>
2108
2109   <dt><tt>Value *remove(const value_iterator&amp; It)</tt>:</dt>
2110   <dd> Removes a specific value from the symbol table. 
2111   Returns the removed value.</dd>
2112
2113   <dt><tt>bool strip()</tt>:</dt>
2114   <dd> This method will strip the symbol table of its names leaving
2115   the type and values. </dd>
2116
2117   <dt><tt>void clear()</tt>:</dt>
2118   <dd>Empty the symbol table completely.</dd>
2119 </dl>
2120
2121 <h3>Iteration</h3>
2122 <p>The following functions describe three types of iterators you can obtain
2123 the beginning or end of the sequence for both const and non-const. It is
2124 important to keep track of the different kinds of iterators. There are
2125 three idioms worth pointing out:</p>
2126
2127 <table>
2128   <tr><th>Units</th><th>Iterator</th><th>Idiom</th></tr>
2129   <tr>
2130     <td align="left">Planes Of name/Value maps</td><td>PI</td>
2131     <td align="left"><pre><tt>
2132 for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
2133      PE = ST.plane_end(); PI != PE; ++PI ) {
2134   PI-&gt;first  // <i>This is the Type* of the plane</i>
2135   PI-&gt;second // <i>This is the SymbolTable::ValueMap of name/Value pairs</i>
2136 }
2137     </tt></pre></td>
2138   </tr>
2139   <tr>
2140     <td align="left">name/Value pairs in a plane</td><td>VI</td>
2141     <td align="left"><pre><tt>
2142 for (SymbolTable::value_const_iterator VI = ST.value_begin(SomeType),
2143      VE = ST.value_end(SomeType); VI != VE; ++VI ) {
2144   VI-&gt;first  // <i>This is the name of the Value</i>
2145   VI-&gt;second // <i>This is the Value* value associated with the name</i>
2146 }
2147     </tt></pre></td>
2148   </tr>
2149 </table>
2150
2151 <p>Using the recommended iterator names and idioms will help you avoid
2152 making mistakes. Of particular note, make sure that whenever you use
2153 value_begin(SomeType) that you always compare the resulting iterator
2154 with value_end(SomeType) not value_end(SomeOtherType) or else you 
2155 will loop infinitely.</p>
2156
2157 <dl>
2158
2159   <dt><tt>plane_iterator plane_begin()</tt>:</dt>
2160   <dd>Get an iterator that starts at the beginning of the type planes.
2161   The iterator will iterate over the Type/ValueMap pairs in the
2162   type planes. </dd>
2163
2164   <dt><tt>plane_const_iterator plane_begin() const</tt>:</dt>
2165   <dd>Get a const_iterator that starts at the beginning of the type 
2166   planes.  The iterator will iterate over the Type/ValueMap pairs 
2167   in the type planes. </dd>
2168
2169   <dt><tt>plane_iterator plane_end()</tt>:</dt>
2170   <dd>Get an iterator at the end of the type planes. This serves as
2171   the marker for end of iteration over the type planes.</dd>
2172
2173   <dt><tt>plane_const_iterator plane_end() const</tt>:</dt>
2174   <dd>Get a const_iterator at the end of the type planes. This serves as
2175   the marker for end of iteration over the type planes.</dd>
2176
2177   <dt><tt>value_iterator value_begin(const Type *Typ)</tt>:</dt>
2178   <dd>Get an iterator that starts at the beginning of a type plane.
2179   The iterator will iterate over the name/value pairs in the type plane.
2180   Note: The type plane must already exist before using this.</dd>
2181
2182   <dt><tt>value_const_iterator value_begin(const Type *Typ) const</tt>:</dt>
2183   <dd>Get a const_iterator that starts at the beginning of a type plane.
2184   The iterator will iterate over the name/value pairs in the type plane.
2185   Note: The type plane must already exist before using this.</dd>
2186
2187   <dt><tt>value_iterator value_end(const Type *Typ)</tt>:</dt>
2188   <dd>Get an iterator to the end of a type plane. This serves as the marker
2189   for end of iteration of the type plane.
2190   Note: The type plane must already exist before using this.</dd>
2191
2192   <dt><tt>value_const_iterator value_end(const Type *Typ) const</tt>:</dt>
2193   <dd>Get a const_iterator to the end of a type plane. This serves as the
2194   marker for end of iteration of the type plane.
2195   Note: the type plane must already exist before using this.</dd>
2196
2197   <dt><tt>plane_const_iterator find(const Type* Typ ) const</tt>:</dt>
2198   <dd>This method returns a plane_const_iterator for iteration over
2199   the type planes starting at a specific plane, given by \p Ty.</dd>
2200
2201   <dt><tt>plane_iterator find( const Type* Typ </tt>:</dt>
2202   <dd>This method returns a plane_iterator for iteration over the
2203   type planes starting at a specific plane, given by \p Ty.</dd>
2204
2205 </dl>
2206 </div>
2207
2208
2209
2210 <!-- *********************************************************************** -->
2211 <div class="doc_section">
2212   <a name="coreclasses">The Core LLVM Class Hierarchy Reference </a>
2213 </div>
2214 <!-- *********************************************************************** -->
2215
2216 <div class="doc_text">
2217 <p><tt>#include "<a href="/doxygen/Type_8h-source.html">llvm/Type.h</a>"</tt>
2218 <br>doxygen info: <a href="/doxygen/classllvm_1_1Type.html">Type Class</a></p>
2219
2220 <p>The Core LLVM classes are the primary means of representing the program
2221 being inspected or transformed.  The core LLVM classes are defined in
2222 header files in the <tt>include/llvm/</tt> directory, and implemented in
2223 the <tt>lib/VMCore</tt> directory.</p>
2224
2225 </div>
2226
2227 <!-- ======================================================================= -->
2228 <div class="doc_subsection">
2229   <a name="Type">The <tt>Type</tt> class and Derived Types</a>
2230 </div>
2231
2232 <div class="doc_text">
2233
2234   <p><tt>Type</tt> is a superclass of all type classes. Every <tt>Value</tt> has
2235   a <tt>Type</tt>. <tt>Type</tt> cannot be instantiated directly but only
2236   through its subclasses. Certain primitive types (<tt>VoidType</tt>,
2237   <tt>LabelType</tt>, <tt>FloatType</tt> and <tt>DoubleType</tt>) have hidden 
2238   subclasses. They are hidden because they offer no useful functionality beyond
2239   what the <tt>Type</tt> class offers except to distinguish themselves from 
2240   other subclasses of <tt>Type</tt>.</p>
2241   <p>All other types are subclasses of <tt>DerivedType</tt>.  Types can be 
2242   named, but this is not a requirement. There exists exactly 
2243   one instance of a given shape at any one time.  This allows type equality to
2244   be performed with address equality of the Type Instance. That is, given two 
2245   <tt>Type*</tt> values, the types are identical if the pointers are identical.
2246   </p>
2247 </div>
2248
2249 <!-- _______________________________________________________________________ -->
2250 <div class="doc_subsubsection">
2251   <a name="m_Value">Important Public Methods</a>
2252 </div>
2253
2254 <div class="doc_text">
2255
2256 <ul>
2257   <li><tt>bool isInteger() const</tt>: Returns true for any integer type.</li>
2258
2259   <li><tt>bool isFloatingPoint()</tt>: Return true if this is one of the two
2260   floating point types.</li>
2261
2262   <li><tt>bool isAbstract()</tt>: Return true if the type is abstract (contains
2263   an OpaqueType anywhere in its definition).</li>
2264
2265   <li><tt>bool isSized()</tt>: Return true if the type has known size. Things
2266   that don't have a size are abstract types, labels and void.</li>
2267
2268 </ul>
2269 </div>
2270
2271 <!-- _______________________________________________________________________ -->
2272 <div class="doc_subsubsection">
2273   <a name="m_Value">Important Derived Types</a>
2274 </div>
2275 <div class="doc_text">
2276 <dl>
2277   <dt><tt>IntegerType</tt></dt>
2278   <dd>Subclass of DerivedType that represents integer types of any bit width. 
2279   Any bit width between <tt>IntegerType::MIN_INT_BITS</tt> (1) and 
2280   <tt>IntegerType::MAX_INT_BITS</tt> (~8 million) can be represented.
2281   <ul>
2282     <li><tt>static const IntegerType* get(unsigned NumBits)</tt>: get an integer
2283     type of a specific bit width.</li>
2284     <li><tt>unsigned getBitWidth() const</tt>: Get the bit width of an integer
2285     type.</li>
2286   </ul>
2287   </dd>
2288   <dt><tt>SequentialType</tt></dt>
2289   <dd>This is subclassed by ArrayType and PointerType
2290     <ul>
2291       <li><tt>const Type * getElementType() const</tt>: Returns the type of each
2292       of the elements in the sequential type. </li>
2293     </ul>
2294   </dd>
2295   <dt><tt>ArrayType</tt></dt>
2296   <dd>This is a subclass of SequentialType and defines the interface for array 
2297   types.
2298     <ul>
2299       <li><tt>unsigned getNumElements() const</tt>: Returns the number of 
2300       elements in the array. </li>
2301     </ul>
2302   </dd>
2303   <dt><tt>PointerType</tt></dt>
2304   <dd>Subclass of SequentialType for pointer types.</dd>
2305   <dt><tt>PackedType</tt></dt>
2306   <dd>Subclass of SequentialType for packed (vector) types. A 
2307   packed type is similar to an ArrayType but is distinguished because it is 
2308   a first class type wherease ArrayType is not. Packed types are used for 
2309   vector operations and are usually small vectors of of an integer or floating 
2310   point type.</dd>
2311   <dt><tt>StructType</tt></dt>
2312   <dd>Subclass of DerivedTypes for struct types.</dd>
2313   <dt><tt>FunctionType</tt></dt>
2314   <dd>Subclass of DerivedTypes for function types.
2315     <ul>
2316       <li><tt>bool isVarArg() const</tt>: Returns true if its a vararg
2317       function</li>
2318       <li><tt> const Type * getReturnType() const</tt>: Returns the
2319       return type of the function.</li>
2320       <li><tt>const Type * getParamType (unsigned i)</tt>: Returns
2321       the type of the ith parameter.</li>
2322       <li><tt> const unsigned getNumParams() const</tt>: Returns the
2323       number of formal parameters.</li>
2324     </ul>
2325   </dd>
2326   <dt><tt>OpaqueType</tt></dt>
2327   <dd>Sublcass of DerivedType for abstract types. This class 
2328   defines no content and is used as a placeholder for some other type. Note 
2329   that OpaqueType is used (temporarily) during type resolution for forward 
2330   references of types. Once the referenced type is resolved, the OpaqueType 
2331   is replaced with the actual type. OpaqueType can also be used for data 
2332   abstraction. At link time opaque types can be resolved to actual types 
2333   of the same name.</dd>
2334 </dl>
2335 </div>
2336
2337 <!-- ======================================================================= -->
2338 <div class="doc_subsection">
2339   <a name="Value">The <tt>Value</tt> class</a>
2340 </div>
2341
2342 <div>
2343
2344 <p><tt>#include "<a href="/doxygen/Value_8h-source.html">llvm/Value.h</a>"</tt>
2345 <br> 
2346 doxygen info: <a href="/doxygen/classllvm_1_1Value.html">Value Class</a></p>
2347
2348 <p>The <tt>Value</tt> class is the most important class in the LLVM Source
2349 base.  It represents a typed value that may be used (among other things) as an
2350 operand to an instruction.  There are many different types of <tt>Value</tt>s,
2351 such as <a href="#Constant"><tt>Constant</tt></a>s,<a
2352 href="#Argument"><tt>Argument</tt></a>s. Even <a
2353 href="#Instruction"><tt>Instruction</tt></a>s and <a
2354 href="#Function"><tt>Function</tt></a>s are <tt>Value</tt>s.</p>
2355
2356 <p>A particular <tt>Value</tt> may be used many times in the LLVM representation
2357 for a program.  For example, an incoming argument to a function (represented
2358 with an instance of the <a href="#Argument">Argument</a> class) is "used" by
2359 every instruction in the function that references the argument.  To keep track
2360 of this relationship, the <tt>Value</tt> class keeps a list of all of the <a
2361 href="#User"><tt>User</tt></a>s that is using it (the <a
2362 href="#User"><tt>User</tt></a> class is a base class for all nodes in the LLVM
2363 graph that can refer to <tt>Value</tt>s).  This use list is how LLVM represents
2364 def-use information in the program, and is accessible through the <tt>use_</tt>*
2365 methods, shown below.</p>
2366
2367 <p>Because LLVM is a typed representation, every LLVM <tt>Value</tt> is typed,
2368 and this <a href="#Type">Type</a> is available through the <tt>getType()</tt>
2369 method. In addition, all LLVM values can be named.  The "name" of the
2370 <tt>Value</tt> is a symbolic string printed in the LLVM code:</p>
2371
2372 <div class="doc_code">
2373 <pre>
2374 %<b>foo</b> = add i32 1, 2
2375 </pre>
2376 </div>
2377
2378 <p><a name="#nameWarning">The name of this instruction is "foo".</a> <b>NOTE</b>
2379 that the name of any value may be missing (an empty string), so names should
2380 <b>ONLY</b> be used for debugging (making the source code easier to read,
2381 debugging printouts), they should not be used to keep track of values or map
2382 between them.  For this purpose, use a <tt>std::map</tt> of pointers to the
2383 <tt>Value</tt> itself instead.</p>
2384
2385 <p>One important aspect of LLVM is that there is no distinction between an SSA
2386 variable and the operation that produces it.  Because of this, any reference to
2387 the value produced by an instruction (or the value available as an incoming
2388 argument, for example) is represented as a direct pointer to the instance of
2389 the class that
2390 represents this value.  Although this may take some getting used to, it
2391 simplifies the representation and makes it easier to manipulate.</p>
2392
2393 </div>
2394
2395 <!-- _______________________________________________________________________ -->
2396 <div class="doc_subsubsection">
2397   <a name="m_Value">Important Public Members of the <tt>Value</tt> class</a>
2398 </div>
2399
2400 <div class="doc_text">
2401
2402 <ul>
2403   <li><tt>Value::use_iterator</tt> - Typedef for iterator over the
2404 use-list<br>
2405     <tt>Value::use_const_iterator</tt> - Typedef for const_iterator over
2406 the use-list<br>
2407     <tt>unsigned use_size()</tt> - Returns the number of users of the
2408 value.<br>
2409     <tt>bool use_empty()</tt> - Returns true if there are no users.<br>
2410     <tt>use_iterator use_begin()</tt> - Get an iterator to the start of
2411 the use-list.<br>
2412     <tt>use_iterator use_end()</tt> - Get an iterator to the end of the
2413 use-list.<br>
2414     <tt><a href="#User">User</a> *use_back()</tt> - Returns the last
2415 element in the list.
2416     <p> These methods are the interface to access the def-use
2417 information in LLVM.  As with all other iterators in LLVM, the naming
2418 conventions follow the conventions defined by the <a href="#stl">STL</a>.</p>
2419   </li>
2420   <li><tt><a href="#Type">Type</a> *getType() const</tt>
2421     <p>This method returns the Type of the Value.</p>
2422   </li>
2423   <li><tt>bool hasName() const</tt><br>
2424     <tt>std::string getName() const</tt><br>
2425     <tt>void setName(const std::string &amp;Name)</tt>
2426     <p> This family of methods is used to access and assign a name to a <tt>Value</tt>,
2427 be aware of the <a href="#nameWarning">precaution above</a>.</p>
2428   </li>
2429   <li><tt>void replaceAllUsesWith(Value *V)</tt>
2430
2431     <p>This method traverses the use list of a <tt>Value</tt> changing all <a
2432     href="#User"><tt>User</tt>s</a> of the current value to refer to
2433     "<tt>V</tt>" instead.  For example, if you detect that an instruction always
2434     produces a constant value (for example through constant folding), you can
2435     replace all uses of the instruction with the constant like this:</p>
2436
2437 <div class="doc_code">
2438 <pre>
2439 Inst-&gt;replaceAllUsesWith(ConstVal);
2440 </pre>
2441 </div>
2442
2443 </ul>
2444
2445 </div>
2446
2447 <!-- ======================================================================= -->
2448 <div class="doc_subsection">
2449   <a name="User">The <tt>User</tt> class</a>
2450 </div>
2451
2452 <div class="doc_text">
2453   
2454 <p>
2455 <tt>#include "<a href="/doxygen/User_8h-source.html">llvm/User.h</a>"</tt><br>
2456 doxygen info: <a href="/doxygen/classllvm_1_1User.html">User Class</a><br>
2457 Superclass: <a href="#Value"><tt>Value</tt></a></p>
2458
2459 <p>The <tt>User</tt> class is the common base class of all LLVM nodes that may
2460 refer to <a href="#Value"><tt>Value</tt></a>s.  It exposes a list of "Operands"
2461 that are all of the <a href="#Value"><tt>Value</tt></a>s that the User is
2462 referring to.  The <tt>User</tt> class itself is a subclass of
2463 <tt>Value</tt>.</p>
2464
2465 <p>The operands of a <tt>User</tt> point directly to the LLVM <a
2466 href="#Value"><tt>Value</tt></a> that it refers to.  Because LLVM uses Static
2467 Single Assignment (SSA) form, there can only be one definition referred to,
2468 allowing this direct connection.  This connection provides the use-def
2469 information in LLVM.</p>
2470
2471 </div>
2472
2473 <!-- _______________________________________________________________________ -->
2474 <div class="doc_subsubsection">
2475   <a name="m_User">Important Public Members of the <tt>User</tt> class</a>
2476 </div>
2477
2478 <div class="doc_text">
2479
2480 <p>The <tt>User</tt> class exposes the operand list in two ways: through
2481 an index access interface and through an iterator based interface.</p>
2482
2483 <ul>
2484   <li><tt>Value *getOperand(unsigned i)</tt><br>
2485     <tt>unsigned getNumOperands()</tt>
2486     <p> These two methods expose the operands of the <tt>User</tt> in a
2487 convenient form for direct access.</p></li>
2488
2489   <li><tt>User::op_iterator</tt> - Typedef for iterator over the operand
2490 list<br>
2491     <tt>op_iterator op_begin()</tt> - Get an iterator to the start of 
2492 the operand list.<br>
2493     <tt>op_iterator op_end()</tt> - Get an iterator to the end of the
2494 operand list.
2495     <p> Together, these methods make up the iterator based interface to
2496 the operands of a <tt>User</tt>.</p></li>
2497 </ul>
2498
2499 </div>    
2500
2501 <!-- ======================================================================= -->
2502 <div class="doc_subsection">
2503   <a name="Instruction">The <tt>Instruction</tt> class</a>
2504 </div>
2505
2506 <div class="doc_text">
2507
2508 <p><tt>#include "</tt><tt><a
2509 href="/doxygen/Instruction_8h-source.html">llvm/Instruction.h</a>"</tt><br>
2510 doxygen info: <a href="/doxygen/classllvm_1_1Instruction.html">Instruction Class</a><br>
2511 Superclasses: <a href="#User"><tt>User</tt></a>, <a
2512 href="#Value"><tt>Value</tt></a></p>
2513
2514 <p>The <tt>Instruction</tt> class is the common base class for all LLVM
2515 instructions.  It provides only a few methods, but is a very commonly used
2516 class.  The primary data tracked by the <tt>Instruction</tt> class itself is the
2517 opcode (instruction type) and the parent <a
2518 href="#BasicBlock"><tt>BasicBlock</tt></a> the <tt>Instruction</tt> is embedded
2519 into.  To represent a specific type of instruction, one of many subclasses of
2520 <tt>Instruction</tt> are used.</p>
2521
2522 <p> Because the <tt>Instruction</tt> class subclasses the <a
2523 href="#User"><tt>User</tt></a> class, its operands can be accessed in the same
2524 way as for other <a href="#User"><tt>User</tt></a>s (with the
2525 <tt>getOperand()</tt>/<tt>getNumOperands()</tt> and
2526 <tt>op_begin()</tt>/<tt>op_end()</tt> methods).</p> <p> An important file for
2527 the <tt>Instruction</tt> class is the <tt>llvm/Instruction.def</tt> file. This
2528 file contains some meta-data about the various different types of instructions
2529 in LLVM.  It describes the enum values that are used as opcodes (for example
2530 <tt>Instruction::Add</tt> and <tt>Instruction::ICmp</tt>), as well as the
2531 concrete sub-classes of <tt>Instruction</tt> that implement the instruction (for
2532 example <tt><a href="#BinaryOperator">BinaryOperator</a></tt> and <tt><a
2533 href="#CmpInst">CmpInst</a></tt>).  Unfortunately, the use of macros in
2534 this file confuses doxygen, so these enum values don't show up correctly in the
2535 <a href="/doxygen/classllvm_1_1Instruction.html">doxygen output</a>.</p>
2536
2537 </div>
2538
2539 <!-- _______________________________________________________________________ -->
2540 <div class="doc_subsubsection">
2541   <a name="s_Instruction">Important Subclasses of the <tt>Instruction</tt>
2542   class</a>
2543 </div>
2544 <div class="doc_text">
2545   <ul>
2546     <li><tt><a name="BinaryOperator">BinaryOperator</a></tt>
2547     <p>This subclasses represents all two operand instructions whose operands
2548     must be the same type, except for the comparison instructions.</p></li>
2549     <li><tt><a name="CastInst">CastInst</a></tt>
2550     <p>This subclass is the parent of the 12 casting instructions. It provides
2551     common operations on cast instructions.</p>
2552     <li><tt><a name="CmpInst">CmpInst</a></tt>
2553     <p>This subclass respresents the two comparison instructions, 
2554     <a href="LangRef.html#i_icmp">ICmpInst</a> (integer opreands), and
2555     <a href="LangRef.html#i_fcmp">FCmpInst</a> (floating point operands).</p>
2556     <li><tt><a name="TerminatorInst">TerminatorInst</a></tt>
2557     <p>This subclass is the parent of all terminator instructions (those which
2558     can terminate a block).</p>
2559   </ul>
2560   </div>
2561
2562 <!-- _______________________________________________________________________ -->
2563 <div class="doc_subsubsection">
2564   <a name="m_Instruction">Important Public Members of the <tt>Instruction</tt>
2565   class</a>
2566 </div>
2567
2568 <div class="doc_text">
2569
2570 <ul>
2571   <li><tt><a href="#BasicBlock">BasicBlock</a> *getParent()</tt>
2572     <p>Returns the <a href="#BasicBlock"><tt>BasicBlock</tt></a> that
2573 this  <tt>Instruction</tt> is embedded into.</p></li>
2574   <li><tt>bool mayWriteToMemory()</tt>
2575     <p>Returns true if the instruction writes to memory, i.e. it is a
2576       <tt>call</tt>,<tt>free</tt>,<tt>invoke</tt>, or <tt>store</tt>.</p></li>
2577   <li><tt>unsigned getOpcode()</tt>
2578     <p>Returns the opcode for the <tt>Instruction</tt>.</p></li>
2579   <li><tt><a href="#Instruction">Instruction</a> *clone() const</tt>
2580     <p>Returns another instance of the specified instruction, identical
2581 in all ways to the original except that the instruction has no parent
2582 (ie it's not embedded into a <a href="#BasicBlock"><tt>BasicBlock</tt></a>),
2583 and it has no name</p></li>
2584 </ul>
2585
2586 </div>
2587
2588 <!-- ======================================================================= -->
2589 <div class="doc_subsection">
2590   <a name="BasicBlock">The <tt>BasicBlock</tt> class</a>
2591 </div>
2592
2593 <div class="doc_text">
2594
2595 <p><tt>#include "<a
2596 href="/doxygen/BasicBlock_8h-source.html">llvm/BasicBlock.h</a>"</tt><br>
2597 doxygen info: <a href="/doxygen/structllvm_1_1BasicBlock.html">BasicBlock
2598 Class</a><br>
2599 Superclass: <a href="#Value"><tt>Value</tt></a></p>
2600
2601 <p>This class represents a single entry multiple exit section of the code,
2602 commonly known as a basic block by the compiler community.  The
2603 <tt>BasicBlock</tt> class maintains a list of <a
2604 href="#Instruction"><tt>Instruction</tt></a>s, which form the body of the block.
2605 Matching the language definition, the last element of this list of instructions
2606 is always a terminator instruction (a subclass of the <a
2607 href="#TerminatorInst"><tt>TerminatorInst</tt></a> class).</p>
2608
2609 <p>In addition to tracking the list of instructions that make up the block, the
2610 <tt>BasicBlock</tt> class also keeps track of the <a
2611 href="#Function"><tt>Function</tt></a> that it is embedded into.</p>
2612
2613 <p>Note that <tt>BasicBlock</tt>s themselves are <a
2614 href="#Value"><tt>Value</tt></a>s, because they are referenced by instructions
2615 like branches and can go in the switch tables. <tt>BasicBlock</tt>s have type
2616 <tt>label</tt>.</p>
2617
2618 </div>
2619
2620 <!-- _______________________________________________________________________ -->
2621 <div class="doc_subsubsection">
2622   <a name="m_BasicBlock">Important Public Members of the <tt>BasicBlock</tt>
2623   class</a>
2624 </div>
2625
2626 <div class="doc_text">
2627
2628 <ul>
2629
2630 <li><tt>BasicBlock(const std::string &amp;Name = "", </tt><tt><a
2631  href="#Function">Function</a> *Parent = 0)</tt>
2632
2633 <p>The <tt>BasicBlock</tt> constructor is used to create new basic blocks for
2634 insertion into a function.  The constructor optionally takes a name for the new
2635 block, and a <a href="#Function"><tt>Function</tt></a> to insert it into.  If
2636 the <tt>Parent</tt> parameter is specified, the new <tt>BasicBlock</tt> is
2637 automatically inserted at the end of the specified <a
2638 href="#Function"><tt>Function</tt></a>, if not specified, the BasicBlock must be
2639 manually inserted into the <a href="#Function"><tt>Function</tt></a>.</p></li>
2640
2641 <li><tt>BasicBlock::iterator</tt> - Typedef for instruction list iterator<br>
2642 <tt>BasicBlock::const_iterator</tt> - Typedef for const_iterator.<br>
2643 <tt>begin()</tt>, <tt>end()</tt>, <tt>front()</tt>, <tt>back()</tt>,
2644 <tt>size()</tt>, <tt>empty()</tt>
2645 STL-style functions for accessing the instruction list.
2646
2647 <p>These methods and typedefs are forwarding functions that have the same
2648 semantics as the standard library methods of the same names.  These methods
2649 expose the underlying instruction list of a basic block in a way that is easy to
2650 manipulate.  To get the full complement of container operations (including
2651 operations to update the list), you must use the <tt>getInstList()</tt>
2652 method.</p></li>
2653
2654 <li><tt>BasicBlock::InstListType &amp;getInstList()</tt>
2655
2656 <p>This method is used to get access to the underlying container that actually
2657 holds the Instructions.  This method must be used when there isn't a forwarding
2658 function in the <tt>BasicBlock</tt> class for the operation that you would like
2659 to perform.  Because there are no forwarding functions for "updating"
2660 operations, you need to use this if you want to update the contents of a
2661 <tt>BasicBlock</tt>.</p></li>
2662
2663 <li><tt><a href="#Function">Function</a> *getParent()</tt>
2664
2665 <p> Returns a pointer to <a href="#Function"><tt>Function</tt></a> the block is
2666 embedded into, or a null pointer if it is homeless.</p></li>
2667
2668 <li><tt><a href="#TerminatorInst">TerminatorInst</a> *getTerminator()</tt>
2669
2670 <p> Returns a pointer to the terminator instruction that appears at the end of
2671 the <tt>BasicBlock</tt>.  If there is no terminator instruction, or if the last
2672 instruction in the block is not a terminator, then a null pointer is
2673 returned.</p></li>
2674
2675 </ul>
2676
2677 </div>
2678
2679 <!-- ======================================================================= -->
2680 <div class="doc_subsection">
2681   <a name="GlobalValue">The <tt>GlobalValue</tt> class</a>
2682 </div>
2683
2684 <div class="doc_text">
2685
2686 <p><tt>#include "<a
2687 href="/doxygen/GlobalValue_8h-source.html">llvm/GlobalValue.h</a>"</tt><br>
2688 doxygen info: <a href="/doxygen/classllvm_1_1GlobalValue.html">GlobalValue
2689 Class</a><br>
2690 Superclasses: <a href="#Constant"><tt>Constant</tt></a>, 
2691 <a href="#User"><tt>User</tt></a>, <a href="#Value"><tt>Value</tt></a></p>
2692
2693 <p>Global values (<a href="#GlobalVariable"><tt>GlobalVariable</tt></a>s or <a
2694 href="#Function"><tt>Function</tt></a>s) are the only LLVM values that are
2695 visible in the bodies of all <a href="#Function"><tt>Function</tt></a>s.
2696 Because they are visible at global scope, they are also subject to linking with
2697 other globals defined in different translation units.  To control the linking
2698 process, <tt>GlobalValue</tt>s know their linkage rules. Specifically,
2699 <tt>GlobalValue</tt>s know whether they have internal or external linkage, as
2700 defined by the <tt>LinkageTypes</tt> enumeration.</p>
2701
2702 <p>If a <tt>GlobalValue</tt> has internal linkage (equivalent to being
2703 <tt>static</tt> in C), it is not visible to code outside the current translation
2704 unit, and does not participate in linking.  If it has external linkage, it is
2705 visible to external code, and does participate in linking.  In addition to
2706 linkage information, <tt>GlobalValue</tt>s keep track of which <a
2707 href="#Module"><tt>Module</tt></a> they are currently part of.</p>
2708
2709 <p>Because <tt>GlobalValue</tt>s are memory objects, they are always referred to
2710 by their <b>address</b>. As such, the <a href="#Type"><tt>Type</tt></a> of a
2711 global is always a pointer to its contents. It is important to remember this
2712 when using the <tt>GetElementPtrInst</tt> instruction because this pointer must
2713 be dereferenced first. For example, if you have a <tt>GlobalVariable</tt> (a
2714 subclass of <tt>GlobalValue)</tt> that is an array of 24 ints, type <tt>[24 x
2715 i32]</tt>, then the <tt>GlobalVariable</tt> is a pointer to that array. Although
2716 the address of the first element of this array and the value of the
2717 <tt>GlobalVariable</tt> are the same, they have different types. The
2718 <tt>GlobalVariable</tt>'s type is <tt>[24 x i32]</tt>. The first element's type
2719 is <tt>i32.</tt> Because of this, accessing a global value requires you to
2720 dereference the pointer with <tt>GetElementPtrInst</tt> first, then its elements
2721 can be accessed. This is explained in the <a href="LangRef.html#globalvars">LLVM
2722 Language Reference Manual</a>.</p>
2723
2724 </div>
2725
2726 <!-- _______________________________________________________________________ -->
2727 <div class="doc_subsubsection">
2728   <a name="m_GlobalValue">Important Public Members of the <tt>GlobalValue</tt>
2729   class</a>
2730 </div>
2731
2732 <div class="doc_text">
2733
2734 <ul>
2735   <li><tt>bool hasInternalLinkage() const</tt><br>
2736     <tt>bool hasExternalLinkage() const</tt><br>
2737     <tt>void setInternalLinkage(bool HasInternalLinkage)</tt>
2738     <p> These methods manipulate the linkage characteristics of the <tt>GlobalValue</tt>.</p>
2739     <p> </p>
2740   </li>
2741   <li><tt><a href="#Module">Module</a> *getParent()</tt>
2742     <p> This returns the <a href="#Module"><tt>Module</tt></a> that the
2743 GlobalValue is currently embedded into.</p></li>
2744 </ul>
2745
2746 </div>
2747
2748 <!-- ======================================================================= -->
2749 <div class="doc_subsection">
2750   <a name="Function">The <tt>Function</tt> class</a>
2751 </div>
2752
2753 <div class="doc_text">
2754
2755 <p><tt>#include "<a
2756 href="/doxygen/Function_8h-source.html">llvm/Function.h</a>"</tt><br> doxygen
2757 info: <a href="/doxygen/classllvm_1_1Function.html">Function Class</a><br>
2758 Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>, 
2759 <a href="#Constant"><tt>Constant</tt></a>, 
2760 <a href="#User"><tt>User</tt></a>, 
2761 <a href="#Value"><tt>Value</tt></a></p>
2762
2763 <p>The <tt>Function</tt> class represents a single procedure in LLVM.  It is
2764 actually one of the more complex classes in the LLVM heirarchy because it must
2765 keep track of a large amount of data.  The <tt>Function</tt> class keeps track
2766 of a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, a list of formal 
2767 <a href="#Argument"><tt>Argument</tt></a>s, and a 
2768 <a href="#SymbolTable"><tt>SymbolTable</tt></a>.</p>
2769
2770 <p>The list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s is the most
2771 commonly used part of <tt>Function</tt> objects.  The list imposes an implicit
2772 ordering of the blocks in the function, which indicate how the code will be
2773 layed out by the backend.  Additionally, the first <a
2774 href="#BasicBlock"><tt>BasicBlock</tt></a> is the implicit entry node for the
2775 <tt>Function</tt>.  It is not legal in LLVM to explicitly branch to this initial
2776 block.  There are no implicit exit nodes, and in fact there may be multiple exit
2777 nodes from a single <tt>Function</tt>.  If the <a
2778 href="#BasicBlock"><tt>BasicBlock</tt></a> list is empty, this indicates that
2779 the <tt>Function</tt> is actually a function declaration: the actual body of the
2780 function hasn't been linked in yet.</p>
2781
2782 <p>In addition to a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, the
2783 <tt>Function</tt> class also keeps track of the list of formal <a
2784 href="#Argument"><tt>Argument</tt></a>s that the function receives.  This
2785 container manages the lifetime of the <a href="#Argument"><tt>Argument</tt></a>
2786 nodes, just like the <a href="#BasicBlock"><tt>BasicBlock</tt></a> list does for
2787 the <a href="#BasicBlock"><tt>BasicBlock</tt></a>s.</p>
2788
2789 <p>The <a href="#SymbolTable"><tt>SymbolTable</tt></a> is a very rarely used
2790 LLVM feature that is only used when you have to look up a value by name.  Aside
2791 from that, the <a href="#SymbolTable"><tt>SymbolTable</tt></a> is used
2792 internally to make sure that there are not conflicts between the names of <a
2793 href="#Instruction"><tt>Instruction</tt></a>s, <a
2794 href="#BasicBlock"><tt>BasicBlock</tt></a>s, or <a
2795 href="#Argument"><tt>Argument</tt></a>s in the function body.</p>
2796
2797 <p>Note that <tt>Function</tt> is a <a href="#GlobalValue">GlobalValue</a>
2798 and therefore also a <a href="#Constant">Constant</a>. The value of the function
2799 is its address (after linking) which is guaranteed to be constant.</p>
2800 </div>
2801
2802 <!-- _______________________________________________________________________ -->
2803 <div class="doc_subsubsection">
2804   <a name="m_Function">Important Public Members of the <tt>Function</tt>
2805   class</a>
2806 </div>
2807
2808 <div class="doc_text">
2809
2810 <ul>
2811   <li><tt>Function(const </tt><tt><a href="#FunctionType">FunctionType</a>
2812   *Ty, LinkageTypes Linkage, const std::string &amp;N = "", Module* Parent = 0)</tt>
2813
2814     <p>Constructor used when you need to create new <tt>Function</tt>s to add
2815     the the program.  The constructor must specify the type of the function to
2816     create and what type of linkage the function should have. The <a 
2817     href="#FunctionType"><tt>FunctionType</tt></a> argument
2818     specifies the formal arguments and return value for the function. The same
2819     <a href="#FunctionTypel"><tt>FunctionType</tt></a> value can be used to
2820     create multiple functions. The <tt>Parent</tt> argument specifies the Module
2821     in which the function is defined. If this argument is provided, the function
2822     will automatically be inserted into that module's list of
2823     functions.</p></li>
2824
2825   <li><tt>bool isExternal()</tt>
2826
2827     <p>Return whether or not the <tt>Function</tt> has a body defined.  If the
2828     function is "external", it does not have a body, and thus must be resolved
2829     by linking with a function defined in a different translation unit.</p></li>
2830
2831   <li><tt>Function::iterator</tt> - Typedef for basic block list iterator<br>
2832     <tt>Function::const_iterator</tt> - Typedef for const_iterator.<br>
2833
2834     <tt>begin()</tt>, <tt>end()</tt>
2835     <tt>size()</tt>, <tt>empty()</tt>
2836
2837     <p>These are forwarding methods that make it easy to access the contents of
2838     a <tt>Function</tt> object's <a href="#BasicBlock"><tt>BasicBlock</tt></a>
2839     list.</p></li>
2840
2841   <li><tt>Function::BasicBlockListType &amp;getBasicBlockList()</tt>
2842
2843     <p>Returns the list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s.  This
2844     is necessary to use when you need to update the list or perform a complex
2845     action that doesn't have a forwarding method.</p></li>
2846
2847   <li><tt>Function::arg_iterator</tt> - Typedef for the argument list
2848 iterator<br>
2849     <tt>Function::const_arg_iterator</tt> - Typedef for const_iterator.<br>
2850
2851     <tt>arg_begin()</tt>, <tt>arg_end()</tt>
2852     <tt>arg_size()</tt>, <tt>arg_empty()</tt>
2853
2854     <p>These are forwarding methods that make it easy to access the contents of
2855     a <tt>Function</tt> object's <a href="#Argument"><tt>Argument</tt></a>
2856     list.</p></li>
2857
2858   <li><tt>Function::ArgumentListType &amp;getArgumentList()</tt>
2859
2860     <p>Returns the list of <a href="#Argument"><tt>Argument</tt></a>s.  This is
2861     necessary to use when you need to update the list or perform a complex
2862     action that doesn't have a forwarding method.</p></li>
2863
2864   <li><tt><a href="#BasicBlock">BasicBlock</a> &amp;getEntryBlock()</tt>
2865
2866     <p>Returns the entry <a href="#BasicBlock"><tt>BasicBlock</tt></a> for the
2867     function.  Because the entry block for the function is always the first
2868     block, this returns the first block of the <tt>Function</tt>.</p></li>
2869
2870   <li><tt><a href="#Type">Type</a> *getReturnType()</tt><br>
2871     <tt><a href="#FunctionType">FunctionType</a> *getFunctionType()</tt>
2872
2873     <p>This traverses the <a href="#Type"><tt>Type</tt></a> of the
2874     <tt>Function</tt> and returns the return type of the function, or the <a
2875     href="#FunctionType"><tt>FunctionType</tt></a> of the actual
2876     function.</p></li>
2877
2878   <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
2879
2880     <p> Return a pointer to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
2881     for this <tt>Function</tt>.</p></li>
2882 </ul>
2883
2884 </div>
2885
2886 <!-- ======================================================================= -->
2887 <div class="doc_subsection">
2888   <a name="GlobalVariable">The <tt>GlobalVariable</tt> class</a>
2889 </div>
2890
2891 <div class="doc_text">
2892
2893 <p><tt>#include "<a
2894 href="/doxygen/GlobalVariable_8h-source.html">llvm/GlobalVariable.h</a>"</tt>
2895 <br>
2896 doxygen info: <a href="/doxygen/classllvm_1_1GlobalVariable.html">GlobalVariable
2897  Class</a><br>
2898 Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>, 
2899 <a href="#Constant"><tt>Constant</tt></a>,
2900 <a href="#User"><tt>User</tt></a>,
2901 <a href="#Value"><tt>Value</tt></a></p>
2902
2903 <p>Global variables are represented with the (suprise suprise)
2904 <tt>GlobalVariable</tt> class. Like functions, <tt>GlobalVariable</tt>s are also
2905 subclasses of <a href="#GlobalValue"><tt>GlobalValue</tt></a>, and as such are
2906 always referenced by their address (global values must live in memory, so their
2907 "name" refers to their constant address). See 
2908 <a href="#GlobalValue"><tt>GlobalValue</tt></a> for more on this.  Global 
2909 variables may have an initial value (which must be a 
2910 <a href="#Constant"><tt>Constant</tt></a>), and if they have an initializer, 
2911 they may be marked as "constant" themselves (indicating that their contents 
2912 never change at runtime).</p>
2913 </div>
2914
2915 <!-- _______________________________________________________________________ -->
2916 <div class="doc_subsubsection">
2917   <a name="m_GlobalVariable">Important Public Members of the
2918   <tt>GlobalVariable</tt> class</a>
2919 </div>
2920
2921 <div class="doc_text">
2922
2923 <ul>
2924   <li><tt>GlobalVariable(const </tt><tt><a href="#Type">Type</a> *Ty, bool
2925   isConstant, LinkageTypes&amp; Linkage, <a href="#Constant">Constant</a>
2926   *Initializer = 0, const std::string &amp;Name = "", Module* Parent = 0)</tt>
2927
2928     <p>Create a new global variable of the specified type. If
2929     <tt>isConstant</tt> is true then the global variable will be marked as
2930     unchanging for the program. The Linkage parameter specifies the type of
2931     linkage (internal, external, weak, linkonce, appending) for the variable. If
2932     the linkage is InternalLinkage, WeakLinkage, or LinkOnceLinkage,&nbsp; then
2933     the resultant global variable will have internal linkage.  AppendingLinkage
2934     concatenates together all instances (in different translation units) of the
2935     variable into a single variable but is only applicable to arrays.  &nbsp;See
2936     the <a href="LangRef.html#modulestructure">LLVM Language Reference</a> for
2937     further details on linkage types. Optionally an initializer, a name, and the
2938     module to put the variable into may be specified for the global variable as
2939     well.</p></li>
2940
2941   <li><tt>bool isConstant() const</tt>
2942
2943     <p>Returns true if this is a global variable that is known not to
2944     be modified at runtime.</p></li>
2945
2946   <li><tt>bool hasInitializer()</tt>
2947
2948     <p>Returns true if this <tt>GlobalVariable</tt> has an intializer.</p></li>
2949
2950   <li><tt><a href="#Constant">Constant</a> *getInitializer()</tt>
2951
2952     <p>Returns the intial value for a <tt>GlobalVariable</tt>.  It is not legal
2953     to call this method if there is no initializer.</p></li>
2954 </ul>
2955
2956 </div>
2957
2958 <!-- ======================================================================= -->
2959 <div class="doc_subsection">
2960   <a name="Module">The <tt>Module</tt> class</a>
2961 </div>
2962
2963 <div class="doc_text">
2964
2965 <p><tt>#include "<a
2966 href="/doxygen/Module_8h-source.html">llvm/Module.h</a>"</tt><br> doxygen info:
2967 <a href="/doxygen/classllvm_1_1Module.html">Module Class</a></p>
2968
2969 <p>The <tt>Module</tt> class represents the top level structure present in LLVM
2970 programs.  An LLVM module is effectively either a translation unit of the
2971 original program or a combination of several translation units merged by the
2972 linker.  The <tt>Module</tt> class keeps track of a list of <a
2973 href="#Function"><tt>Function</tt></a>s, a list of <a
2974 href="#GlobalVariable"><tt>GlobalVariable</tt></a>s, and a <a
2975 href="#SymbolTable"><tt>SymbolTable</tt></a>.  Additionally, it contains a few
2976 helpful member functions that try to make common operations easy.</p>
2977
2978 </div>
2979
2980 <!-- _______________________________________________________________________ -->
2981 <div class="doc_subsubsection">
2982   <a name="m_Module">Important Public Members of the <tt>Module</tt> class</a>
2983 </div>
2984
2985 <div class="doc_text">
2986
2987 <ul>
2988   <li><tt>Module::Module(std::string name = "")</tt></li>
2989 </ul>
2990
2991 <p>Constructing a <a href="#Module">Module</a> is easy. You can optionally
2992 provide a name for it (probably based on the name of the translation unit).</p>
2993
2994 <ul>
2995   <li><tt>Module::iterator</tt> - Typedef for function list iterator<br>
2996     <tt>Module::const_iterator</tt> - Typedef for const_iterator.<br>
2997
2998     <tt>begin()</tt>, <tt>end()</tt>
2999     <tt>size()</tt>, <tt>empty()</tt>
3000
3001     <p>These are forwarding methods that make it easy to access the contents of
3002     a <tt>Module</tt> object's <a href="#Function"><tt>Function</tt></a>
3003     list.</p></li>
3004
3005   <li><tt>Module::FunctionListType &amp;getFunctionList()</tt>
3006
3007     <p> Returns the list of <a href="#Function"><tt>Function</tt></a>s.  This is
3008     necessary to use when you need to update the list or perform a complex
3009     action that doesn't have a forwarding method.</p>
3010
3011     <p><!--  Global Variable --></p></li> 
3012 </ul>
3013
3014 <hr>
3015
3016 <ul>
3017   <li><tt>Module::global_iterator</tt> - Typedef for global variable list iterator<br>
3018
3019     <tt>Module::const_global_iterator</tt> - Typedef for const_iterator.<br>
3020
3021     <tt>global_begin()</tt>, <tt>global_end()</tt>
3022     <tt>global_size()</tt>, <tt>global_empty()</tt>
3023
3024     <p> These are forwarding methods that make it easy to access the contents of
3025     a <tt>Module</tt> object's <a
3026     href="#GlobalVariable"><tt>GlobalVariable</tt></a> list.</p></li>
3027
3028   <li><tt>Module::GlobalListType &amp;getGlobalList()</tt>
3029
3030     <p>Returns the list of <a
3031     href="#GlobalVariable"><tt>GlobalVariable</tt></a>s.  This is necessary to
3032     use when you need to update the list or perform a complex action that
3033     doesn't have a forwarding method.</p>
3034
3035     <p><!--  Symbol table stuff --> </p></li>
3036 </ul>
3037
3038 <hr>
3039
3040 <ul>
3041   <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
3042
3043     <p>Return a reference to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
3044     for this <tt>Module</tt>.</p>
3045
3046     <p><!--  Convenience methods --></p></li>
3047 </ul>
3048
3049 <hr>
3050
3051 <ul>
3052   <li><tt><a href="#Function">Function</a> *getFunction(const std::string
3053   &amp;Name, const <a href="#FunctionType">FunctionType</a> *Ty)</tt>
3054
3055     <p>Look up the specified function in the <tt>Module</tt> <a
3056     href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, return
3057     <tt>null</tt>.</p></li>
3058
3059   <li><tt><a href="#Function">Function</a> *getOrInsertFunction(const
3060   std::string &amp;Name, const <a href="#FunctionType">FunctionType</a> *T)</tt>
3061
3062     <p>Look up the specified function in the <tt>Module</tt> <a
3063     href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, add an
3064     external declaration for the function and return it.</p></li>
3065
3066   <li><tt>std::string getTypeName(const <a href="#Type">Type</a> *Ty)</tt>
3067
3068     <p>If there is at least one entry in the <a
3069     href="#SymbolTable"><tt>SymbolTable</tt></a> for the specified <a
3070     href="#Type"><tt>Type</tt></a>, return it.  Otherwise return the empty
3071     string.</p></li>
3072
3073   <li><tt>bool addTypeName(const std::string &amp;Name, const <a
3074   href="#Type">Type</a> *Ty)</tt>
3075
3076     <p>Insert an entry in the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
3077     mapping <tt>Name</tt> to <tt>Ty</tt>. If there is already an entry for this
3078     name, true is returned and the <a
3079     href="#SymbolTable"><tt>SymbolTable</tt></a> is not modified.</p></li>
3080 </ul>
3081
3082 </div>
3083
3084 <!-- ======================================================================= -->
3085 <div class="doc_subsection">
3086   <a name="Constant">The <tt>Constant</tt> class and subclasses</a>
3087 </div>
3088
3089 <div class="doc_text">
3090
3091 <p>Constant represents a base class for different types of constants. It
3092 is subclassed by  ConstantInt, ConstantArray, etc. for representing 
3093 the various types of Constants.</p>
3094
3095 </div>
3096
3097 <!-- _______________________________________________________________________ -->
3098 <div class="doc_subsubsection">
3099   <a name="m_Constant">Important Public Methods</a>
3100 </div>
3101 <div class="doc_text">
3102 </div>
3103
3104 <!-- _______________________________________________________________________ -->
3105 <div class="doc_subsubsection">Important Subclasses of Constant </div>
3106 <div class="doc_text">
3107 <ul>
3108   <li>ConstantInt : This subclass of Constant represents an integer constant of
3109   any width, including boolean (1 bit integer).
3110     <ul>
3111       <li><tt>int64_t getSExtValue() const</tt>: Returns the underlying value of
3112       this constant as a sign extended signed integer value.</li>
3113       <li><tt>uint64_t getZExtValue() const</tt>: Returns the underlying value 
3114       of this constant as a zero extended unsigned integer value.</li>
3115       <li><tt>static ConstantInt* get(const Type *Ty, uint64_t Val)</tt>: 
3116       Returns the ConstantInt object that represents the value provided by 
3117       <tt>Val</tt> for integer type <tt>Ty</tt>.</li>
3118     </ul>
3119   </li>
3120   <li>ConstantFP : This class represents a floating point constant.
3121     <ul>
3122       <li><tt>double getValue() const</tt>: Returns the underlying value of 
3123       this constant. </li>
3124     </ul>
3125   </li>
3126   <li>ConstantArray : This represents a constant array.
3127     <ul>
3128       <li><tt>const std::vector&lt;Use&gt; &amp;getValues() const</tt>: Returns 
3129       a vector of component constants that makeup this array. </li>
3130     </ul>
3131   </li>
3132   <li>ConstantStruct : This represents a constant struct.
3133     <ul>
3134       <li><tt>const std::vector&lt;Use&gt; &amp;getValues() const</tt>: Returns 
3135       a vector of component constants that makeup this array. </li>
3136     </ul>
3137   </li>
3138   <li>GlobalValue : This represents either a global variable or a function. In 
3139   either case, the value is a constant fixed address (after linking). 
3140   </li>
3141 </ul>
3142 </div>
3143 <!-- ======================================================================= -->
3144 <div class="doc_subsection">
3145   <a name="Argument">The <tt>Argument</tt> class</a>
3146 </div>
3147
3148 <div class="doc_text">
3149
3150 <p>This subclass of Value defines the interface for incoming formal
3151 arguments to a function. A Function maintains a list of its formal
3152 arguments. An argument has a pointer to the parent Function.</p>
3153
3154 </div>
3155
3156 <!-- *********************************************************************** -->
3157 <hr>
3158 <address>
3159   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
3160   src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
3161   <a href="http://validator.w3.org/check/referer"><img
3162   src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /></a>
3163
3164   <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a> and
3165   <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
3166   <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
3167   Last modified: $Date$
3168 </address>
3169
3170 </body>
3171 </html>