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