blob: 8c6b36be318fd6c84deef07fdc7d4c00bd4bc5ab [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
3<html>
4<head>
Owen Anderson60f87572009-06-16 17:40:28 +00005 <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006 <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>
31and <tt>dyn_cast&lt;&gt;</tt> templates</a> </li>
Daniel Dunbare3572ba2009-07-25 04:41:11 +000032 <li><a href="#string_apis">Passing strings (the <tt>StringRef</tt>
33and <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>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038 <li><a href="#DEBUG">The <tt>DEBUG()</tt> macro and <tt>-debug</tt>
39option</a>
40 <ul>
41 <li><a href="#DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt>
42and 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>
46option</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>
Gabor Greifbb17f652009-02-27 11:37:41 +000064 <li><a href="#dss_ilist">llvm/ADT/ilist.h</a></li>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065 <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>
Chris Lattner77ab46d2007-09-30 00:58:59 +000072 <li><a href="#dss_denseset">"llvm/ADT/DenseSet.h"</a></li>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073 <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>
Chris Lattnerd8b95b72009-07-25 07:22:20 +000088 <li><a href="#ds_string">String-like containers</a>
89 <ul>
90 <!-- todo -->
91 </ul></li>
Daniel Berlin7ea44dc2007-09-24 17:52:25 +000092 <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>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097 </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
104in a <tt>Function</tt></a> </li>
105 <li><a href="#iterate_basicblock">Iterating over the <tt>Instruction</tt>s
106in a <tt>BasicBlock</tt></a> </li>
107 <li><a href="#iterate_institer">Iterating over the <tt>Instruction</tt>s
108in a <tt>Function</tt></a> </li>
109 <li><a href="#iterate_convert">Turning an iterator into a
110class pointer</a> </li>
111 <li><a href="#iterate_complex">Finding call sites: a more
112complex example</a> </li>
113 <li><a href="#calls_and_invokes">Treating calls and invokes
114the same way</a> </li>
115 <li><a href="#iterate_chains">Iterating over def-use &amp;
116use-def chains</a> </li>
Chris Lattner0665e1f2008-01-03 16:56:04 +0000117 <li><a href="#iterate_preds">Iterating over predecessors &amp;
118successors of blocks</a></li>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119 </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>
127with another <tt>Value</tt></a> </li>
128 <li><a href="#schanges_deletingGV">Deleting <tt>GlobalVariable</tt>s</a> </li>
129 </ul>
130 </li>
Jeffrey Yasskin7ebb6ac2009-04-30 22:33:41 +0000131 <li><a href="#create_types">How to Create Types</a></li>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132<!--
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
Owen Andersone8370c02009-06-16 01:17:16 +0000143 <li><a href="#threading">Threads and LLVM</a>
144 <ul>
Owen Andersonb4186902009-06-16 18:04:19 +0000145 <li><a href="#startmultithreaded">Entering and Exiting Multithreaded Mode
146 </a></li>
Owen Andersone8370c02009-06-16 01:17:16 +0000147 <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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 <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
Gabor Greif92e87762008-06-16 21:06:12 +0000162 <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>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000164 </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>,
Gabor Greif92e87762008-06-16 21:06:12 +0000198 <a href="mailto:ggreif@gmail.com">Gabor Greif</a>,
Owen Andersone8370c02009-06-16 01:17:16 +0000199 <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>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202</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
213interfaces available in the LLVM source-base. This manual is not
214intended to explain what LLVM is, how it works, and what LLVM code looks
215like. It assumes that you know the basics of LLVM and are interested
216in writing transformations or otherwise analyzing or manipulating the
217code.</p>
218
219<p>This document should get you oriented so that you can find your
220way in the continuously growing source code that makes up the LLVM
221infrastructure. Note that this manual is not intended to serve as a
222replacement for reading the source code, so if you think there should be
223a method in one of these classes to do something, but it's not listed,
224check the source. Links to the <a href="/doxygen/">doxygen</a> sources
225are provided to make this as easy as possible.</p>
226
227<p>The first section of this document describes general information that is
228useful to know when working in the LLVM infrastructure, and the second describes
229the Core LLVM classes. In the future this manual will be extended with
230information describing how to use extension libraries, such as dominator
231information, CFG traversal routines, and useful utilities like the <tt><a
232href="/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
245in 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),
257perhaps much more than you are used to, or have seen before. Because of
258this, you might want to do a little background reading in the
259techniques used and capabilities of the library. There are many good
260pages that discuss the STL, and several books on the subject that you
261can 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
268reference</a> - an excellent reference for the STL and other parts of the
269standard C++ library.</li>
270
271<li><a href="http://www.tempest-sw.com/cpp/">C++ In a Nutshell</a> - This is an
Gabor Greife39f0e72009-03-12 09:47:03 +0000272O'Reilly book in the making. It has a decent Standard Library
273Reference that rivals Dinkumware's, and is unfortunately no longer free since the
274book has been published.</li>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275
276<li><a href="http://www.parashift.com/c++-faq-lite/">C++ Frequently Asked
277Questions</a></li>
278
279<li><a href="http://www.sgi.com/tech/stl/">SGI's STL Programmer's Guide</a> -
280Contains a useful <a
281href="http://www.sgi.com/tech/stl/stl_introduction.html">Introduction to the
282STL</a>.</li>
283
284<li><a href="http://www.research.att.com/%7Ebs/C++.html">Bjarne Stroustrup's C++
285Page</a></li>
286
287<li><a href="http://64.78.49.204/">
288Bruce Eckel's Thinking in C++, 2nd ed. Volume 2 Revision 4.0 (even better, get
289the book).</a></li>
290
291</ol>
292
293<p>You are also encouraged to take a look at the <a
294href="CodingStandards.html">LLVM Coding Standards</a> guide which focuses on how
295to 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
308Branch and Tag Primer</a></li>
309<li><a href="http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html">Using
310static 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
324know 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.
337These templates have many similarities to the C++ <tt>dynamic_cast&lt;&gt;</tt>
338operator, but they don't have some drawbacks (primarily stemming from
339the fact that <tt>dynamic_cast&lt;&gt;</tt> only works on classes that
340have a v-table). Because they are used so often, you must know what they
341do 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>
343file (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
Chris Lattner1d5610a2008-06-20 05:03:17 +0000357 converts a pointer or reference from a base class to a derived class, causing
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358 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>
365static 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>
394if (<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
430v-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
432to. Describing this is currently outside the scope of this document, but there
433are lots of examples in the LLVM source base.</p>
434
435</div>
436
Daniel Dunbare3572ba2009-07-25 04:41:11 +0000437
438<!-- ======================================================================= -->
439<div class="doc_subsection">
440 <a name="string_apis">Passing strings (the <tt>StringRef</tt>
441and <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
Chris Lattnerc00114f2009-07-25 07:16:59 +0000447several important APIs which take strings. Two important examples are the
Daniel Dunbare3572ba2009-07-25 04:41:11 +0000448Value class -- which has names for instructions, functions, etc. -- and the
449StringMap 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
452may have embedded null characters. Therefore, they cannot simply take
Chris Lattnerc00114f2009-07-25 07:16:59 +0000453a <tt>const char *</tt>, and taking a <tt>const std::string&amp;</tt> requires
Daniel Dunbare3572ba2009-07-25 04:41:11 +0000454clients to perform a heap allocation which is usually unnecessary. Instead,
Chris Lattnerc00114f2009-07-25 07:16:59 +0000455many LLVM APIs use a <tt>const StringRef&amp;</tt> or a <tt>const
456Twine&amp;</tt> for passing strings efficiently.</p>
Daniel Dunbare3572ba2009-07-25 04:41:11 +0000457
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
469on <tt>std:string</tt>, but does not require heap allocation.</p>
470
Chris Lattnerc00114f2009-07-25 07:16:59 +0000471<p>It can be implicitly constructed using a C style null-terminated string,
472an <tt>std::string</tt>, or explicitly with a character pointer and length.
Daniel Dunbare3572ba2009-07-25 04:41:11 +0000473For example, the <tt>StringRef</tt> find function is declared as:</p>
Chris Lattnerc00114f2009-07-25 07:16:59 +0000474
Daniel Dunbare3572ba2009-07-25 04:41:11 +0000475<div class="doc_code">
Chris Lattnerc00114f2009-07-25 07:16:59 +0000476 iterator find(const StringRef &amp;Key);
Daniel Dunbare3572ba2009-07-25 04:41:11 +0000477</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>
490instance, which can be used directly or converted to an <tt>std::string</tt>
491using the <tt>str</tt> member function. See
492"<tt><a href="/doxygen/classllvm_1_1StringRef_8h-source.html">llvm/ADT/StringRef.h</a></tt>"
493for more information.</p>
494
495<p>You should rarely use the <tt>StringRef</tt> class directly, because it contains
496pointers to external memory it is not generally safe to store an instance of the
Chris Lattnerc00114f2009-07-25 07:16:59 +0000497class (unless you know that the external storage will not be freed).</p>
Daniel Dunbare3572ba2009-07-25 04:41:11 +0000498
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
509strings. For example, a common LLVM paradigm is to name one instruction based on
510the 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
519lightweight <a href="http://en.wikipedia.org/wiki/Rope_(computer_science)">rope</a>
520which points to temporary (stack allocated) objects. Twines can be implicitly
521constructed as the result of the plus operator applied to strings (i.e., a C
522strings, an <tt>std::string</tt>, or a <tt>StringRef</tt>). The twine delays the
523actual concatentation of strings until it is actually required, at which point
524it can be efficiently rendered directly into a character array. This avoids
525unnecessary heap allocation involved in constructing the temporary results of
526string concatenation. See
527"<tt><a href="/doxygen/classllvm_1_1Twine_8h-source.html">llvm/ADT/Twine.h</a></tt>"
528for more information.</p></tt>
529
530<p>As with a <tt>StringRef</tt>, <tt>Twine</tt> objects point to external memory
531and should almost never be stored or mentioned directly. They are intended
532solely for use when defining a function which should be able to efficiently
533accept concatenated strings.</p>
534
535</div>
536
537
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538<!-- ======================================================================= -->
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
546and other code into your pass. After you get it working, you want to remove
547it, but you may need it again in the future (to work out new bugs that you run
548across).</p>
549
550<p> Naturally, because of this, you don't want to delete the debug printouts,
551but you don't want them to always be noisy. A standard compromise is to comment
552them 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>"
555file provides a macro named <tt>DEBUG()</tt> that is a much nicer solution to
556this 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
558tool) is run with the '<tt>-debug</tt>' command line argument:</p>
559
560<div class="doc_code">
561<pre>
Daniel Dunbare32f9b22009-07-25 01:55:32 +0000562DEBUG(errs() &lt;&lt; "I am here!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000563</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
573I am here!
574</pre>
575</div>
576
577<p>Using the <tt>DEBUG()</tt> macro instead of a home-brewed solution allows you
578to not have to create "yet another" command line option for the debug output for
579your pass. Note that <tt>DEBUG()</tt> macros are disabled for optimized builds,
580so they do not cause a performance impact at all (for the same reason, they
581should also not contain side-effects!).</p>
582
583<p>One additional nice thing about the <tt>DEBUG()</tt> macro is that you can
584enable 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
586program 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>
600just turns on <b>too much</b> information (such as when working on the code
601generator). If you want to enable debug information with more fine-grained
602control, you define the <tt>DEBUG_TYPE</tt> macro and the <tt>-debug</tt> only
603option as follows:</p>
604
605<div class="doc_code">
606<pre>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607#undef DEBUG_TYPE
Daniel Dunbare32f9b22009-07-25 01:55:32 +0000608DEBUG(errs() &lt;&lt; "No debug type\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000609#define DEBUG_TYPE "foo"
Daniel Dunbare32f9b22009-07-25 01:55:32 +0000610DEBUG(errs() &lt;&lt; "'foo' debug type\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611#undef DEBUG_TYPE
612#define DEBUG_TYPE "bar"
Daniel Dunbare32f9b22009-07-25 01:55:32 +0000613DEBUG(errs() &lt;&lt; "'bar' debug type\n"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614#undef DEBUG_TYPE
615#define DEBUG_TYPE ""
Daniel Dunbare32f9b22009-07-25 01:55:32 +0000616DEBUG(errs() &lt;&lt; "No debug type (2)\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617</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
627No debug type
628'foo' debug type
629'bar' debug type
630No 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
639a file, to specify the debug type for the entire module (if you do this before
640you <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
643conflict. If two different modules use the same string, they will all be turned
644on when the name is specified. This allows, for example, all debug information
645for instruction scheduling to be enabled with <tt>-debug-type=InstrSched</tt>,
646even 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
659href="/doxygen/Statistic_8h-source.html">llvm/ADT/Statistic.h</a></tt>" file
660provides a class named <tt>Statistic</tt> that is used as a unified way to
661keep track of what the LLVM compiler is doing and how effective various
662optimizations are. It is useful to see what optimizations are contributing to
663making 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
666how many times it makes a certain transformation. Although you can do this with
667hand inspection, or some ad-hoc method, this is a real pain and not very useful
668for big programs. Using the <tt>Statistic</tt> class makes it very easy to
669keep track of this information, and the calculated information is presented in a
670uniform 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
673it 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>
681STATISTIC(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
712suite, 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
745stuff is very nice. Making your pass fit well into the framework makes it more
746maintainable 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
758CFGs made out of LLVM <a href="#BasicBlock">BasicBlock</a>s, CFGs made out of
759LLVM <a href="CodeGenerator.html#machinebasicblock">MachineBasicBlock</a>s, and
760<a href="CodeGenerator.html#selectiondag_intro">Instruction Selection
761DAGs</a>. In many cases, while debugging various parts of the compiler, it is
762nice to instantly visualize these graphs.</p>
763
764<p>LLVM provides several callbacks that are available in a debug build to do
765exactly that. If you call the <tt>Function::viewCFG()</tt> method, for example,
766the current LLVM tool will pop up a window containing the CFG for the function
767where each basic block is a node in the graph, and each node contains the
768instructions 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>,
771and the <tt>SelectionDAG::viewGraph()</tt> methods. Within GDB, for example,
772you can usually use something like <tt>call DAG.viewGraph()</tt> to pop
773up a window. Alternatively, you can sprinkle calls to these functions in your
774code in places you want to debug.</p>
775
776<p>Getting this to work requires a small amount of configuration. On Unix
777systems with X11, install the <a href="http://www.graphviz.org">graphviz</a>
778toolkit, and make sure 'dot' and 'gv' are in your path. If you are running on
779Mac OS/X, download and install the Mac OS/X <a
780href="http://www.pixelglow.com/graphviz/">Graphviz program</a>, and add
781<tt>/Applications/Graphviz.app/Contents/MacOS/</tt> (or wherever you install
782it) to your path. Once in your system and path are set up, rerun the LLVM
783configure 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
788next <tt>call DAG.viewGraph()</tt> would highlight the node in the
789specified color (choices of colors can be found at <a
790href="http://www.graphviz.org/doc/info/colors.html">colors</a>.) More
791complex node attributes can be provided with <tt>call
792DAG.setGraphAttrs(<i>node</i>, "<i>attributes</i>")</tt> (choices can be
793found at <a href="http://www.graphviz.org/doc/info/attrs.html">Graph
794Attributes</a>.) If you want to restart and clear all the current graph
795attributes, 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>
812The first step is a choose your own adventure: do you want a sequential
813container, a set-like container, or a map-like container? The most important
814thing when choosing a container is the algorithmic properties of how you plan to
815access 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
Chris Lattnerd8b95b72009-07-25 07:22:20 +0000840<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
Daniel Berlin7ea44dc2007-09-24 17:52:25 +0000844<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>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849</ul>
850
851<p>
852Once the proper category of container is determined, you can fine tune the
853memory use, constant factors, and cache behaviors of access by intelligently
854picking a member of the category. Note that constant factors and cache behavior
855can be a big deal. If you have a vector that usually only contains a few
856elements (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
859cost 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">
869There are a variety of sequential containers available for you, based on your
870needs. 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
880exactly how many elements you have, or you have a (low) upper bound on how many
881you 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
891the number of elements is variable, if you know how many elements you will need
892before the array is allocated, and if the array is usually large (if not,
893consider a <a href="#dss_smallvector">SmallVector</a>). The cost of a heap
894allocated array is the cost of the new/delete (aka malloc/free). Also note that
895if you are allocating an array of a type with a constructor, the constructor and
896destructors will be run for every element in the array (re-sizable vectors only
897construct 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
907just like <tt>vector&lt;Type&gt;</tt>:
908it supports efficient iteration, lays out elements in memory order (so you can
909do pointer arithmetic between elements), supports efficient push_back/pop_back
910operations, supports efficient random access to its elements, etc.</p>
911
912<p>The advantage of SmallVector is that it allocates space for
913some number of elements (N) <b>in the object itself</b>. Because of this, if
914the SmallVector is dynamically smaller than N, no malloc is performed. This can
915be a big win in cases where the malloc/free call is far more expensive than the
916code that fiddles around with the elements.</p>
917
918<p>This is good for vectors that are "usually small" (e.g. the number of
919predecessors/successors of a block is usually less than 8). On the other hand,
920this makes the size of the SmallVector itself large, so you don't want to
921allocate lots of them (doing so will waste a lot of space). As such,
922SmallVectors 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>
936std::vector is well loved and respected. It is useful when SmallVector isn't:
937when the size of the vector is often large (thus the small optimization will
938rarely be a benefit) or if you will be allocating many instances of the vector
939itself (which would waste space for elements that aren't in the container).
940vector 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>
947for ( ... ) {
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>
958std::vector&lt;foo&gt; V;
959for ( ... ) {
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
967the 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
978std::vector, it provides constant time random access and other similar
979properties, but it also provides efficient access to the front of the list. It
980does not guarantee continuity of elements within memory.</p>
981
982<p>In exchange for this extra flexibility, std::deque has significantly higher
983constant factor costs than std::vector. If possible, use std::vector or
984something 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.
994It performs a heap allocation for every element inserted into it, thus having an
995extremely high constant factor, particularly for small data types. std::list
996also 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
999ends of the list (like std::deque, but unlike std::vector or SmallVector). In
1000addition, the iterator invalidation characteristics of std::list are stronger
1001than that of a vector class: inserting or removing an element into the list does
1002not invalidate iterator or pointers to other elements in the list.</p>
1003</div>
1004
1005<!-- _______________________________________________________________________ -->
1006<div class="doc_subsubsection">
Gabor Greifbb17f652009-02-27 11:37:41 +00001007 <a name="dss_ilist">llvm/ADT/ilist.h</a>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008</div>
1009
1010<div class="doc_text">
1011<p><tt>ilist&lt;T&gt;</tt> implements an 'intrusive' doubly-linked list. It is
1012intrusive, because it requires the element to store and provide access to the
1013prev/next pointers for the list.</p>
1014
Gabor Greifb6b21ec2009-02-27 12:02:19 +00001015<p><tt>ilist</tt> has the same drawbacks as <tt>std::list</tt>, and additionally
1016requires an <tt>ilist_traits</tt> implementation for the element type, but it
1017provides some novel characteristics. In particular, it can efficiently store
1018polymorphic objects, the traits class is informed when an element is inserted or
Gabor Greife39f0e72009-03-12 09:47:03 +00001019removed from the list, and <tt>ilist</tt>s are guaranteed to support a
1020constant-time splice operation.</p>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021
Gabor Greife39f0e72009-03-12 09:47:03 +00001022<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>
Gabor Greifbb17f652009-02-27 11:37:41 +00001025
1026Related classes of interest are explained in the following subsections:
1027 <ul>
Gabor Greifa17abe12009-02-27 13:28:07 +00001028 <li><a href="#dss_ilist_traits">ilist_traits</a></li>
Gabor Greifb6b21ec2009-02-27 12:02:19 +00001029 <li><a href="#dss_iplist">iplist</a></li>
Gabor Greifbb17f652009-02-27 11:37:41 +00001030 <li><a href="#dss_ilist_node">llvm/ADT/ilist_node.h</a></li>
Gabor Greifd970d692009-03-12 10:30:31 +00001031 <li><a href="#dss_ilist_sentinel">Sentinels</a></li>
Gabor Greifbb17f652009-02-27 11:37:41 +00001032 </ul>
1033</div>
1034
1035<!-- _______________________________________________________________________ -->
1036<div class="doc_subsubsection">
Gabor Greifa17abe12009-02-27 13:28:07 +00001037 <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
1042mechanism. <tt>iplist&lt;T&gt;</tt> (and consequently <tt>ilist&lt;T&gt;</tt>)
1043publicly derive from this traits class.</p>
1044</div>
1045
1046<!-- _______________________________________________________________________ -->
1047<div class="doc_subsubsection">
Gabor Greifb6b21ec2009-02-27 12:02:19 +00001048 <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
Gabor Greife39f0e72009-03-12 09:47:03 +00001053supports a slightly narrower interface. Notably, inserters from
1054<tt>T&amp;</tt> are absent.</p>
Gabor Greifa17abe12009-02-27 13:28:07 +00001055
1056<p><tt>ilist_traits&lt;T&gt;</tt> is a public base of this class and can be
1057used for a wide variety of customizations.</p>
Gabor Greifb6b21ec2009-02-27 12:02:19 +00001058</div>
1059
1060<!-- _______________________________________________________________________ -->
1061<div class="doc_subsubsection">
Gabor Greifbb17f652009-02-27 11:37:41 +00001062 <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
1067that are expected by the <tt>ilist&lt;T&gt;</tt> (and analogous containers)
1068in the default manner.</p>
1069
1070<p><tt>ilist_node&lt;T&gt;</tt>s are meant to be embedded in the node type
Gabor Greife39f0e72009-03-12 09:47:03 +00001071<tt>T</tt>, usually <tt>T</tt> publicly derives from
1072<tt>ilist_node&lt;T&gt;</tt>.</p>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073</div>
1074
1075<!-- _______________________________________________________________________ -->
1076<div class="doc_subsubsection">
Gabor Greifd970d692009-03-12 10:30:31 +00001077 <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
1082citizen in the C++ ecosystem, it needs to support the standard container
1083operations, 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
1085case 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>
1089iterator, providing the back-link to the last element. However conforming to the
1090C++ convention it is illegal to <tt>operator++</tt> beyond the sentinel and it
1091also must not be dereferenced.</p>
1092
1093<p>These constraints allow for some implementation freedom to the <tt>ilist</tt>
1094how to allocate and store the sentinel. The corresponding policy is dictated
1095by <tt>ilist_traits&lt;T&gt;</tt>. By default a <tt>T</tt> gets heap-allocated
1096whenever 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
1100instances of <tt>ilist</tt>s, the memory overhead of the associated sentinels
1101is wasted. To alleviate the situation with numerous and voluminous
1102<tt>T</tt>-sentinels, sometimes a trick is employed, leading to <i>ghostly
1103sentinels</i>.</p>
1104
1105<p>Ghostly sentinels are obtained by specially-crafted <tt>ilist_traits&lt;T&gt;</tt>
1106which superpose the sentinel with the <tt>ilist</tt> instance in memory. Pointer
1107arithmetic 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
1109extra pointer, which serves as the back-link of the sentinel. This is the only
1110field in the ghostly sentinel which can be legally accessed.</p>
1111</div>
1112
1113<!-- _______________________________________________________________________ -->
1114<div class="doc_subsubsection">
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115 <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,
1122std::priority_queue, std::stack, etc. These provide simplified access to an
1123underlying 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
1136into a single representation. There are several different choices for how to do
1137this, 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
1150great approach is to use a vector (or other sequential container) with
1151std::sort+std::unique to remove duplicates. This approach works really well if
1152your usage pattern has these two distinct phases (insert then query), and can be
1153coupled with a good choice of <a href="#ds_sequential">sequential container</a>.
1154</p>
1155
1156<p>
1157This combination provides the several nice properties: the result data is
1158contiguous in memory (good for cache locality), has few allocations, is easy to
1159address (iterators in the final vector are just indices or pointers), and can be
1160efficiently 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
1172are reasonably small, a <tt>SmallSet&lt;Type, N&gt;</tt> is a good choice. This set
1173has space for N elements in place (thus, if the set is dynamically smaller than
1174N, no malloc traffic is required) and accesses them with a simple linear search.
1175When the set grows beyond 'N' elements, it allocates a more expensive representation that
1176guarantees efficient access (for most types, it falls back to std::set, but for
1177pointers it uses something far better, <a
1178href="#dss_smallptrset">SmallPtrSet</a>).</p>
1179
1180<p>The magic of this class is that it handles small sets extremely efficiently,
1181but gracefully handles extremely large sets without loss of efficiency. The
1182drawback is that the interface is quite small: it supports insertion, queries
1183and 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
1195transparently implemented with a SmallPtrSet), but also supports iterators. If
1196more than 'N' insertions are performed, a single quadratically
1197probed hash table is allocated and grows as needed, providing extremely
1198efficient access (constant time insertion/deleting/queries with low constant
1199factors) and is very stingy with malloc traffic.</p>
1200
1201<p>Note that, unlike std::set, the iterators of SmallPtrSet are invalidated
1202whenever an insertion occurs. Also, the values visited by the iterators are not
1203visited in sorted order.</p>
1204
1205</div>
1206
1207<!-- _______________________________________________________________________ -->
1208<div class="doc_subsubsection">
Chris Lattner77ab46d2007-09-30 00:58:59 +00001209 <a name="dss_denseset">"llvm/ADT/DenseSet.h"</a>
1210</div>
1211
1212<div class="doc_text">
1213
1214<p>
1215DenseSet is a simple quadratically probed hash table. It excels at supporting
1216small values: it uses a single allocation to hold all of the pairs that
1217are currently inserted in the set. DenseSet is a great way to unique small
1218values that are not simple pointers (use <a
1219href="#dss_smallptrset">SmallPtrSet</a> for pointers). Note that DenseSet has
1220the same requirements for the value type that <a
1221href="#dss_densemap">DenseMap</a> has.
1222</p>
1223
1224</div>
1225
1226<!-- _______________________________________________________________________ -->
1227<div class="doc_subsubsection">
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 <a name="dss_FoldingSet">"llvm/ADT/FoldingSet.h"</a>
1229</div>
1230
1231<div class="doc_text">
1232
1233<p>
1234FoldingSet is an aggregate class that is really good at uniquing
1235expensive-to-create or polymorphic objects. It is a combination of a chained
1236hash table with intrusive links (uniqued objects are required to inherit from
1237FoldingSetNode) that uses <a href="#dss_smallvector">SmallVector</a> as part of
1238its ID process.</p>
1239
1240<p>Consider a case where you want to implement a "getOrCreateFoo" method for
1241a complex object (for example, a node in the code generator). The client has a
1242description of *what* it wants to generate (it knows the opcode and all the
1243operands), but we don't want to 'new' a node, then try inserting it into a set
1244only to find out it already exists, at which point we would have to delete it
1245and return the node that already exists.
1246</p>
1247
1248<p>To support this style of client, FoldingSet perform a query with a
1249FoldingSetNodeID (which wraps SmallVector) that can be used to describe the
1250element that we want to query for. The query either returns the element
1251matching the ID or it returns an opaque ID that indicates where insertion should
1252take 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
1255in the set (for example, you can have SDNode instances mixed with LoadSDNodes).
1256Because the elements are individually allocated, pointers to the elements are
1257stable: inserting or removing elements does not invalidate any pointers to other
1258elements.
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
1271many things but great at nothing. std::set allocates memory for each element
1272inserted (thus it is very malloc intensive) and typically stores three pointers
1273per element in the set (thus adding a large amount of per-element space
1274overhead). It offers guaranteed log(n) performance, which is not particularly
1275fast from a complexity standpoint (particularly if the elements of the set are
1276expensive to compare, like strings), and has extremely high constant factors for
1277lookup, insertion and removal.</p>
1278
1279<p>The advantages of std::set are that its iterators are stable (deleting or
1280inserting an element from the set does not affect iterators or pointers to other
1281elements) and that iteration over the set is guaranteed to be in sorted order.
1282If the elements in the set are large, then the relative overhead of the pointers
1283and malloc traffic is not a big deal, but if the elements of the set are small,
1284std::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
1295a set-like container along with a <a href="#ds_sequential">Sequential
1296Container</a>. The important property
1297that this provides is efficient insertion with uniquing (duplicate elements are
1298ignored) with iteration support. It implements this by inserting elements into
1299both a set-like container and the sequential container, using the set-like
1300container 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
1304iteration is guaranteed to match the order of insertion into the SetVector.
1305This property is really important for things like sets of pointers. Because
1306pointer values are non-deterministic (e.g. vary across runs of the program on
1307different machines), iterating over the pointers in the set will
1308not be in a well-defined order.</p>
1309
1310<p>
1311The drawback of SetVector is that it requires twice as much space as a normal
1312set and has the sum of constant factors from the set-like container and the
1313sequential container that it uses. Use it *only* if you need to iterate over
1314the elements in a deterministic order. SetVector is also expensive to delete
1315elements out of (linear time), unless you use it's "pop_back" method, which is
1316faster.
1317</p>
1318
1319<p>SetVector is an adapter class that defaults to using std::vector and std::set
1320for the underlying containers, so it is quite expensive. However,
1321<tt>"llvm/ADT/SetVector.h"</tt> also provides a SmallSetVector class, which
1322defaults to using a SmallVector and SmallSet of a specified size. If you use
1323this, and if your sets are dynamically smaller than N, you will save a lot of
1324heap 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>
1336UniqueVector is similar to <a href="#dss_setvector">SetVector</a>, but it
1337retains a unique ID for each element inserted into the set. It internally
1338contains a map and a vector, and it assigns a unique ID for each value inserted
1339into the set.</p>
1340
1341<p>UniqueVector is very expensive: its cost is the sum of the cost of
1342maintaining both the map and vector, it has high complexity, high constant
1343factors, 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>
1356The STL provides several other options, such as std::multiset and the various
Chris Lattner86a63d02009-03-09 05:20:45 +00001357"hash_set" like containers (whether from C++ TR1 or from the SGI library). We
1358never use hash_set and unordered_set because they are generally very expensive
1359(each insertion requires a malloc) and very non-portable.
1360</p>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361
1362<p>std::multiset is useful if you're not interested in elimination of
1363duplicates, but has all the drawbacks of std::set. A sorted vector (where you
1364don't delete duplicate entries) or some other approach is almost always
1365better.</p>
1366
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367</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">
1375Map-like containers are useful when you want to associate data to a key. As
1376usual, 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>
1387If your usage pattern follows a strict insert-then-query approach, you can
1388trivially use the same approach as <a href="#dss_sortedvectorset">sorted vectors
1389for 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
1391the key, not both the key and value. This yields the same advantages as sorted
1392vectors 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>
1404Strings are commonly used as keys in maps, and they are difficult to support
1405efficiently: they are variable length, inefficient to hash and compare when
1406long, expensive to copy, etc. StringMap is a specialized container designed to
1407cope with these issues. It supports mapping an arbitrary range of bytes to an
1408arbitrary other object.</p>
1409
1410<p>The StringMap implementation uses a quadratically-probed hash table, where
1411the buckets store a pointer to the heap allocated entries (and some other
1412stuff). The entries in the map must be heap allocated because the strings are
1413variable length. The string data (key) and the element object (value) are
1414stored in the same allocation with the string data immediately after the element
1415object. This container guarantees the "<tt>(char*)(&amp;Value+1)</tt>" points
1416to the key string for a value.</p>
1417
1418<p>The StringMap is very fast for several reasons: quadratic probing is very
1419cache efficient for lookups, the hash value of strings in buckets is not
1420recomputed when lookup up an element, StringMap rarely has to touch the
1421memory for unrelated objects when looking up a value (even when hash collisions
1422happen), hash table growth does not recompute the hash values for strings
1423already 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
1427copies 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>
1437IndexedMap is a specialized container for mapping small dense integers (or
1438values that can be mapped to small dense integers) to some other type. It is
1439internally implemented as a vector with a mapping function that maps the keys to
1440the dense integer range.
1441</p>
1442
1443<p>
1444This is useful for cases like virtual registers in the LLVM code generator: they
1445have a dense mapping that is offset by a compile-time constant (the first
1446virtual 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>
1458DenseMap is a simple quadratically probed hash table. It excels at supporting
1459small keys and values: it uses a single allocation to hold all of the pairs that
1460are currently inserted in the map. DenseMap is a great way to map pointers to
1461pointers, or map other small types to each other.
1462</p>
1463
1464<p>
1465There are several aspects of DenseMap that you should be aware of, however. The
1466iterators in a densemap are invalidated whenever an insertion occurs, unlike
1467map. Also, because DenseMap allocates space for a large number of key/value
1468pairs (it starts with 64 by default), it will waste a lot of space if your keys
1469or values are large. Finally, you must implement a partial specialization of
Chris Lattner92eea072007-09-17 18:34:04 +00001470DenseMapInfo for the key that you want, if it isn't already supported. This
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471is required to tell DenseMap about two special marker values (which can never be
1472inserted 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>
1484std::map has similar characteristics to <a href="#dss_set">std::set</a>: it uses
1485a single allocation per pair inserted into the map, it offers log(n) lookup with
1486an extremely large constant factor, imposes a space penalty of 3 pointers per
1487pair in the map, etc.</p>
1488
1489<p>std::map is most useful when your keys or values are very large, if you need
1490to iterate over the collection in sorted order, or if you need stable iterators
1491into the map (i.e. they don't get invalidated if an insertion or deletion of
1492another 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>
1504The STL provides several other options, such as std::multimap and the various
Chris Lattner86a63d02009-03-09 05:20:45 +00001505"hash_map" like containers (whether from C++ TR1 or from the SGI library). We
1506never use hash_set and unordered_set because they are generally very expensive
1507(each insertion requires a malloc) and very non-portable.</p>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001508
1509<p>std::multimap is useful if you want to map a key to multiple values, but has
1510all the drawbacks of std::map. A sorted vector or some other approach is almost
1511always better.</p>
1512
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513</div>
1514
Daniel Berlin7ea44dc2007-09-24 17:52:25 +00001515<!-- ======================================================================= -->
1516<div class="doc_subsection">
Chris Lattnerd8b95b72009-07-25 07:22:20 +00001517 <a name="ds_string">String-like containers</a>
1518</div>
1519
1520<div class="doc_text">
1521
1522<p>
1523TODO: const char* vs stringref vs smallstring vs std::string. Describe twine,
1524xref to #string_apis.
1525</p>
1526
1527</div>
1528
1529<!-- ======================================================================= -->
1530<div class="doc_subsection">
Daniel Berlin7ea44dc2007-09-24 17:52:25 +00001531 <a name="ds_bit">Bit storage containers (BitVector, SparseBitVector)</a>
1532</div>
1533
1534<div class="doc_text">
Chris Lattner62a4eae2007-09-25 22:37:50 +00001535<p>Unlike the other containers, there are only two bit storage containers, and
1536choosing 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
1540implementation in many common compilers (e.g. commonly available versions of
1541GCC) is extremely inefficient and 2) the C++ standards committee is likely to
1542deprecate this container and/or change it significantly somehow. In any case,
1543please don't use it.</p>
Daniel Berlin7ea44dc2007-09-24 17:52:25 +00001544</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.
1553It supports individual bit setting/testing, as well as set operations. The set
1554operations take time O(size of bitvector), but operations are performed one word
1555at a time, instead of one bit at a time. This makes the BitVector very fast for
1556set operations compared to other containers. Use the BitVector when you expect
1557the 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
1568difference: Only the bits that are set, are stored. This makes the
1569SparseBitVector much more space efficient than BitVector when the set is sparse,
1570as well as making set operations O(number of set bits) instead of O(size of
1571universe). 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>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001575
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
1585LLVM code. This is meant to give examples of common idioms used, showing the
1586practical side of LLVM transformations. <p> Because this is a "how-to" section,
1587you 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
1589and 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
1602be traversed. Following the example of the C++ standard template library, the
1603techniques used to traverse these various data structures are all basically the
1604same. For a enumerable sequence of values, the <tt>XXXbegin()</tt> function (or
1605method) returns an iterator to the start of the sequence, the <tt>XXXend()</tt>
1606function returns an iterator pointing to one past the last valid element of the
1607sequence, and there is some <tt>XXXiterator</tt> data type that is common
1608between the two operations.</p>
1609
1610<p>Because the pattern for iteration is common across many different aspects of
1611the program representation, the standard template library algorithms may be used
1612on them, and it is easier to remember how to iterate. First we show a few common
1613examples of the data structures that need to be traversed. Other data
1614structures 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
1628transform 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
1630the <tt>BasicBlock</tt>s that constitute the <tt>Function</tt>. The following is
1631an 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>
1637for (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
1646invoking member functions of the <tt>Instruction</tt> class. This is
1647because the indirection operator is overloaded for the iterator
1648classes. In the above code, the expression <tt>i-&gt;size()</tt> is
1649exactly 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
1663easy 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
1665a <tt>BasicBlock</tt>:</p>
1666
1667<div class="doc_code">
1668<pre>
1669// <i>blk is a pointer to a BasicBlock instance</i>
1670for (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
1679anything you'll care about, you could have just invoked the print routine on the
1680basic 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
1696href="/doxygen/InstIterator_8h-source.html"><tt>llvm/Support/InstIterator.h</tt></a>,
1697and then instantiate <tt>InstIterator</tt>s explicitly in your code. Here's a
1698small 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>
Chris Lattnerfd62ee72008-06-04 18:20:42 +00001705for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
1706 llvm::cerr &lt;&lt; *I &lt;&lt; "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001707</pre>
1708</div>
1709
1710<p>Easy, isn't it? You can also use <tt>InstIterator</tt>s to fill a
1711work list with its initial contents. For example, if you wanted to
1712initialize a work list to contain all instructions in a <tt>Function</tt>
1713F, all you would need to do is something like:</p>
1714
1715<div class="doc_code">
1716<pre>
1717std::set&lt;Instruction*&gt; worklist;
Chris Lattnerfd62ee72008-06-04 18:20:42 +00001718// or better yet, SmallPtrSet&lt;Instruction*, 64&gt; worklist;
1719
1720for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
1721 worklist.insert(&amp;*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722</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
1739instance when all you've got at hand is an iterator. Well, extracting
1740a reference or a pointer from an iterator is very straight-forward.
1741Assuming that <tt>i</tt> is a <tt>BasicBlock::iterator</tt> and <tt>j</tt>
1742is a <tt>BasicBlock::const_iterator</tt>:</p>
1743
1744<div class="doc_code">
1745<pre>
1746Instruction&amp; inst = *i; // <i>Grab reference to instruction reference</i>
1747Instruction* pinst = &amp;*i; // <i>Grab pointer to instruction reference</i>
1748const Instruction&amp; inst = *j;
1749</pre>
1750</div>
1751
1752<p>However, the iterators you'll be working with in the LLVM framework are
1753special: they will automatically convert to a ptr-to-instance type whenever they
1754need to. Instead of dereferencing the iterator and then taking the address of
1755the result, you can simply assign the iterator to the proper pointer type and
1756you 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
1758the last line of the last example,</p>
1759
1760<div class="doc_code">
1761<pre>
Chris Lattner0665e1f2008-01-03 16:56:04 +00001762Instruction *pinst = &amp;*i;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001763</pre>
1764</div>
1765
1766<p>is semantically equivalent to</p>
1767
1768<div class="doc_code">
1769<pre>
Chris Lattner0665e1f2008-01-03 16:56:04 +00001770Instruction *pinst = i;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001771</pre>
1772</div>
1773
1774<p>It's also possible to turn a class pointer into the corresponding iterator,
1775and this is a constant time operation (very efficient). The following code
1776snippet illustrates use of the conversion constructors provided by LLVM
1777iterators. By using these, you can explicitly grab the iterator of something
1778without actually obtaining it via iteration over some structure:</p>
1779
1780<div class="doc_code">
1781<pre>
1782void 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
1801locations in the entire module (that is, across every <tt>Function</tt>) where a
1802certain function (i.e., some <tt>Function</tt>*) is already in scope. As you'll
1803learn later, you may want to use an <tt>InstVisitor</tt> to accomplish this in a
1804much more straight-forward manner, but this example will allow us to explore how
1805you'd do it if you didn't have <tt>InstVisitor</tt> around. In pseudo-code, this
1806is what we want to do:</p>
1807
1808<div class="doc_code">
1809<pre>
1810initialize callCounter to zero
1811for 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
1821override the <tt>runOnFunction</tt> method):</p>
1822
1823<div class="doc_code">
1824<pre>
1825Function* targetFunc = ...;
1826
1827class 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) {
Eric Christopher5fbecf72008-11-08 08:20:49 +00001833 for (BasicBlock::iterator i = b-&gt;begin(), ie = b-&gt;end(); i != ie; ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001834 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>
Chris Lattner0665e1f2008-01-03 16:56:04 +00001838 // <i>function pointed to by m_func or not.</i>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001839 if (callInst-&gt;getCalledFunction() == targetFunc)
1840 ++callCounter;
1841 }
1842 }
1843 }
1844 }
1845
1846 private:
Chris Lattner0665e1f2008-01-03 16:56:04 +00001847 unsigned callCounter;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001848};
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
1862that it did not deal with call sites generated by 'invoke' instructions. In
1863this, 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
1865most-specific common base class is <tt>Instruction</tt>, which includes lots of
1866less closely-related things. For these cases, LLVM provides a handy wrapper
1867class called <a
1868href="http://llvm.org/doxygen/classllvm_1_1CallSite.html"><tt>CallSite</tt></a>.
1869It is essentially a wrapper around an <tt>Instruction</tt> pointer, with some
1870methods 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
1874reference and it should not be dynamically allocated or deallocated using
1875<tt>operator new</tt> or <tt>operator delete</tt>. It is efficiently copyable,
1876assignable and constructable, with costs equivalents to that of a bare pointer.
1877If 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
1889href="/doxygen/classllvm_1_1Value.html">Value Class</a> and we want to
1890determine 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.
1892For example, let's say we have a <tt>Function*</tt> named <tt>F</tt> to a
1893particular 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
1895of <tt>F</tt>:</p>
1896
1897<div class="doc_code">
1898<pre>
Chris Lattner0665e1f2008-01-03 16:56:04 +00001899Function *F = ...;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900
1901for (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
1910href="/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
1914all of the values that a particular instruction uses (that is, the operands of
1915the particular <tt>Instruction</tt>):</p>
1916
1917<div class="doc_code">
1918<pre>
Chris Lattner0665e1f2008-01-03 16:56:04 +00001919Instruction *pi = ...;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001920
1921for (User::op_iterator i = pi-&gt;op_begin(), e = pi-&gt;op_end(); i != e; ++i) {
Chris Lattner0665e1f2008-01-03 16:56:04 +00001922 Value *v = *i;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001923 // <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
Chris Lattner0665e1f2008-01-03 16:56:04 +00001935<!--_______________________________________________________________________-->
1936<div class="doc_subsubsection">
1937 <a name="iterate_preds">Iterating over predecessors &amp;
1938successors 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
1944with the routines defined in <tt>"llvm/Support/CFG.h"</tt>. Just use code like
1945this to iterate over all predecessors of BB:</p>
1946
1947<div class="doc_code">
1948<pre>
1949#include "llvm/Support/CFG.h"
1950BasicBlock *BB = ...;
1951
1952for (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
1960succ_iterator/succ_begin/succ_end.</p>
1961
1962</div>
1963
1964
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001965<!-- ======================================================================= -->
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
1973infrastructure that are worth knowing about. When performing
1974transformations, it's fairly common to manipulate the contents of basic
1975blocks. This section describes some of the common methods for doing so
1976and 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
1991constructor for the kind of instruction to instantiate and provide the necessary
1992parameters. 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>
Nick Lewyckyc004e5b2007-12-03 01:52:52 +00001997AllocaInst* ai = new AllocaInst(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001998</pre>
1999</div>
2000
2001<p>will create an <tt>AllocaInst</tt> instance that represents the allocation of
2002one integer in the current stack frame, at run time. Each <tt>Instruction</tt>
2003subclass is likely to have varying default parameters which change the semantics
2004of the instruction, so refer to the <a
2005href="/doxygen/classllvm_1_1Instruction.html">doxygen documentation for the subclass of
2006Instruction</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
2011this facilitates the debugging of your transformations. If you end up looking
2012at generated LLVM machine code, you definitely want to have logical names
2013associated with the results of instructions! By supplying a value for the
2014<tt>Name</tt> (default) parameter of the <tt>Instruction</tt> constructor, you
2015associate a logical name with the result of the instruction's execution at
2016run time. For example, say that I'm writing a transformation that dynamically
2017allocates space for an integer on the stack, and that integer is going to be
2018used 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>
Nick Lewyckyc004e5b2007-12-03 01:52:52 +00002025AllocaInst* pa = new AllocaInst(Type::Int32Ty, 0, "indexLoc");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002026</pre>
2027</div>
2028
2029<p>where <tt>indexLoc</tt> is now the logical name of the instruction's
2030execution 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>
2035into 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>
2046BasicBlock *pb = ...;
2047Instruction *pi = ...;
2048Instruction *newInst = new Instruction(...);
2049
2050pb-&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>
2062BasicBlock *pb = ...;
2063Instruction *newInst = new Instruction(...);
2064
2065pb-&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>
2073BasicBlock *pb = ...;
2074Instruction *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>
2091Instruction *pi = ...;
2092Instruction *newInst = new Instruction(...);
2093
2094pi-&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>
2110Instruction* pi = ...;
2111Instruction* 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,
2130you must have a pointer to the instruction that you wish to delete. Second, you
2131need to obtain the pointer to that instruction's basic block. You use the
2132pointer to the basic block to get its list of instructions and then use the
2133erase function to remove your instruction. For example:</p>
2134
2135<div class="doc_code">
2136<pre>
2137<a href="#Instruction">Instruction</a> *I = .. ;
Chris Lattner3db8f772008-02-15 22:57:17 +00002138I-&gt;eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002139</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>"
2155permits use of two very useful replace functions: <tt>ReplaceInstWithValue</tt>
2156and <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
Nick Lewycky48d4b032008-09-15 06:31:52 +00002163 <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
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166 <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>
2171AllocaInst* instToReplace = ...;
2172BasicBlock::iterator ii(instToReplace);
2173
2174ReplaceInstWithValue(instToReplace-&gt;getParent()-&gt;getInstList(), ii,
Daniel Dunbar8ce79622008-10-03 22:17:25 +00002175 Constant::getNullValue(PointerType::getUnqual(Type::Int32Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002176</pre></div></li>
2177
2178 <li><tt>ReplaceInstWithInst</tt>
2179
2180 <p>This function replaces a particular instruction with another
Nick Lewycky48d4b032008-09-15 06:31:52 +00002181 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>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002185
2186<div class="doc_code">
2187<pre>
2188AllocaInst* instToReplace = ...;
2189BasicBlock::iterator ii(instToReplace);
2190
2191ReplaceInstWithInst(instToReplace-&gt;getParent()-&gt;getInstList(), ii,
Nick Lewyckyc004e5b2007-12-03 01:52:52 +00002192 new AllocaInst(Type::Int32Ty, 0, "ptrToReplacedInt"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002193</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
2200doxygen documentation for the <a href="/doxygen/classllvm_1_1Value.html">Value Class</a>
2201and <a href="/doxygen/classllvm_1_1User.html">User Class</a>, respectively, for more
2202information.</p>
2203
2204<!-- Value::replaceAllUsesWith User::replaceUsesOfWith Point out:
2205include/llvm/Transforms/Utils/ especially BasicBlockUtils.h with:
2206ReplaceInstWithValue, 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
2218Instruction. 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
2226GV-&gt;eraseFromParent();
2227</pre>
2228</div>
2229
2230</div>
2231
Jeffrey Yasskin7ebb6ac2009-04-30 22:33:41 +00002232<!-- ======================================================================= -->
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
Misha Brukman06725132009-05-01 20:40:51 +00002240statically, you can use <tt>TypeBuilder&lt;...&gt;::get()</tt>, defined
Jeffrey Yasskin7ebb6ac2009-04-30 22:33:41 +00002241in <tt>llvm/Support/TypeBuilder.h</tt>, to retrieve them. <tt>TypeBuilder</tt>
2242has two forms depending on whether you're building types for cross-compilation
Misha Brukman06725132009-05-01 20:40:51 +00002243or native library use. <tt>TypeBuilder&lt;T, true&gt;</tt> requires
Jeffrey Yasskin7ebb6ac2009-04-30 22:33:41 +00002244that <tt>T</tt> be independent of the host environment, meaning that it's built
2245out of types from
2246the <a href="/doxygen/namespacellvm_1_1types.html"><tt>llvm::types</tt></a>
2247namespace and pointers, functions, arrays, etc. built of
Misha Brukman06725132009-05-01 20:40:51 +00002248those. <tt>TypeBuilder&lt;T, false&gt;</tt> additionally allows native C types
Jeffrey Yasskin7ebb6ac2009-04-30 22:33:41 +00002249whose size may depend on the host compiler. For example,</p>
2250
2251<div class="doc_code">
2252<pre>
Misha Brukman06725132009-05-01 20:40:51 +00002253FunctionType *ft = TypeBuilder&lt;types::i&lt;8&gt;(types::i&lt;32&gt;*), true&gt;::get();
Jeffrey Yasskin7ebb6ac2009-04-30 22:33:41 +00002254</pre>
2255</div>
2256
2257<p>is easier to read and write than the equivalent</p>
2258
2259<div class="doc_code">
2260<pre>
Owen Anderson60f87572009-06-16 17:40:28 +00002261std::vector&lt;const Type*&gt; params;
Jeffrey Yasskin7ebb6ac2009-04-30 22:33:41 +00002262params.push_back(PointerType::getUnqual(Type::Int32Ty));
2263FunctionType *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
2268comment</a> for more details.</p>
2269
2270</div>
2271
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272<!-- *********************************************************************** -->
2273<div class="doc_section">
Owen Andersone8370c02009-06-16 01:17:16 +00002274 <a name="threading">Threads and LLVM</a>
2275</div>
2276<!-- *********************************************************************** -->
2277
2278<div class="doc_text">
2279<p>
2280This section describes the interaction of the LLVM APIs with multithreading,
2281both on the part of client applications, and in the JIT, in the hosted
2282application.
2283</p>
2284
2285<p>
2286Note that LLVM's support for multithreading is still relatively young. Up
2287through version 2.5, the execution of threaded hosted applications was
2288supported, but not threaded client access to the APIs. While this use case is
2289now supported, clients <em>must</em> adhere to the guidelines specified below to
2290ensure proper operation in multithreaded mode.
2291</p>
2292
2293<p>
2294Note that, on Unix-like platforms, LLVM requires the presence of GCC's atomic
2295intrinsics in order to support threaded operation. If you need a
2296multhreading-capable LLVM on a platform without a suitably modern system
2297compiler, consider compiling LLVM and LLVM-GCC in single-threaded mode, and
2298using the resultant compiler to build a copy of LLVM with multithreading
2299support.
2300</p>
2301</div>
2302
2303<!-- ======================================================================= -->
2304<div class="doc_subsection">
Owen Andersonb4186902009-06-16 18:04:19 +00002305 <a name="startmultithreaded">Entering and Exiting Multithreaded Mode</a>
Owen Andersone8370c02009-06-16 01:17:16 +00002306</div>
2307
2308<div class="doc_text">
2309
2310<p>
2311In order to properly protect its internal data structures while avoiding
Owen Andersonb4186902009-06-16 18:04:19 +00002312excessive locking overhead in the single-threaded case, the LLVM must intialize
2313certain data structures necessary to provide guards around its internals. To do
2314so, the client program must invoke <tt>llvm_start_multithreaded()</tt> before
2315making any concurrent LLVM API calls. To subsequently tear down these
2316structures, use the <tt>llvm_stop_multithreaded()</tt> call. You can also use
2317the <tt>llvm_is_multithreaded()</tt> call to check the status of multithreaded
2318mode.
Owen Andersone8370c02009-06-16 01:17:16 +00002319</p>
2320
2321<p>
Owen Andersonb4186902009-06-16 18:04:19 +00002322Note that both of these calls must be made <em>in isolation</em>. That is to
2323say that no other LLVM API calls may be executing at any time during the
2324execution 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>
2329The return value of <tt>llvm_start_multithreaded()</tt> indicates the success or
2330failure of the initialization. Failure typically indicates that your copy of
2331LLVM was built without multithreading support, typically because GCC atomic
2332intrinsics were not found in your system compiler. In this case, the LLVM API
2333will not be safe for concurrent calls. However, it <em>will</em> be safe for
2334hosting threaded applications in the JIT, though care must be taken to ensure
2335that side exits and the like do not accidentally result in concurrent LLVM API
2336calls.
Owen Andersone8370c02009-06-16 01:17:16 +00002337</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>
2347When you are done using the LLVM APIs, you should call <tt>llvm_shutdown()</tt>
Owen Andersonb4186902009-06-16 18:04:19 +00002348to deallocate memory used for internal structures. This will also invoke
2349<tt>llvm_stop_multithreaded()</tt> if LLVM is operating in multithreaded mode.
2350As such, <tt>llvm_shutdown()</tt> requires the same isolation guarantees as
2351<tt>llvm_stop_multithreaded()</tt>.
Owen Andersone8370c02009-06-16 01:17:16 +00002352</p>
2353
2354<p>
2355Note 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
2357destructor.
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
2368initialization of static resources, such as the global type tables. Before the
2369invocation of <tt>llvm_shutdown()</tt>, it implements a simple lazy
2370initialization scheme. Once <tt>llvm_start_multithreaded()</tt> returns,
2371however, it uses double-checked locking to implement thread-safe lazy
2372initialization.
2373</p>
2374
2375<p>
2376Note 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>
Owen Andersonb4186902009-06-16 18:04:19 +00002380
2381<p>
2382The <tt>llvm_acquire_global_lock()</tt> and <tt>llvm_release_global_lock</tt>
2383APIs provide access to the global lock used to implement the double-checked
2384locking for lazy initialization. These should only be used internally to LLVM,
2385and only if you know what you're doing!
2386</p>
Owen Andersone8370c02009-06-16 01:17:16 +00002387</div>
2388
2389<!-- *********************************************************************** -->
2390<div class="doc_section">
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002391 <a name="advanced">Advanced Topics</a>
2392</div>
2393<!-- *********************************************************************** -->
2394
2395<div class="doc_text">
2396<p>
2397This section describes some of the advanced or obscure API's that most clients
2398do not need to be aware of. These API's tend manage the inner workings of the
2399LLVM 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>
2411The LLVM type system has a very simple goal: allow clients to compare types for
2412structural equality with a simple pointer comparison (aka a shallow compare).
2413This goal makes clients much simpler and faster, and is used throughout the LLVM
2414system.
2415</p>
2416
2417<p>
2418Unfortunately achieving this goal is not a simple matter. In particular,
2419recursive types and late resolution of opaque types makes the situation very
2420difficult to handle. Fortunately, for the most part, our implementation makes
2421most clients able to be completely unaware of the nasty internal details. The
2422primary case where clients are exposed to the inner workings of it are when
2423building a recursive type. In addition to this case, the LLVM bitcode reader,
2424assembly parser, and linker also have to be aware of the inner workings of this
2425system.
2426</p>
2427
2428<p>
2429For our purposes below, we need three concepts. First, an "Opaque Type" is
2430exactly as defined in the <a href="LangRef.html#t_opaque">language
2431reference</a>. Second an "Abstract Type" is any type which includes an
2432opaque type as part of its type graph (for example "<tt>{ opaque, i32 }</tt>").
2433Third, a concrete type is a type that is not an abstract type (e.g. "<tt>{ i32,
2434float }</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>
2447Because the most common question is "how do I build a recursive type with LLVM",
2448we answer it now and explain it as we go. Here we include enough to cause this
2449to 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>
2459To 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();
2466std::vector&lt;const Type*&gt; Elts;
Daniel Dunbar8ce79622008-10-03 22:17:25 +00002467Elts.push_back(PointerType::getUnqual(StructTy));
Nick Lewyckyc004e5b2007-12-03 01:52:52 +00002468Elts.push_back(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002469StructType *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>
2473cast&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>
2477NewSTy = cast&lt;StructType&gt;(StructTy.get());
2478
2479// <i>Add a name for the type to the module symbol table (optional)</i>
2480MyModule-&gt;addTypeName("mylist", NewSTy);
2481</pre>
2482</div>
2483
2484<p>
2485This code shows the basic approach used to build recursive types: build a
2486non-recursive type using 'opaque', then use type unification to close the cycle.
2487The type unification step is performed by the <tt><a
2488href="#refineAbstractTypeTo">refineAbstractTypeTo</a></tt> method, which is
2489described next. After that, we describe the <a
2490href="#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>
2502The <tt>refineAbstractTypeTo</tt> method starts the type unification process.
2503While this method is actually a member of the DerivedType class, it is most
2504often used on OpaqueType instances. Type unification is actually a recursive
2505process. After unification, types can become structurally isomorphic to
2506existing types, and all duplicates are deleted (to preserve pointer equality).
2507</p>
2508
2509<p>
2510In the example above, the OpaqueType object is definitely deleted.
2511Additionally, if there is an "{ \2*, i32}" type already created in the system,
2512the pointer and struct type created are <b>also</b> deleted. Obviously whenever
2513a type is deleted, any "Type*" pointers in the program are invalidated. As
2514such, it is safest to avoid having <i>any</i> "Type*" pointers to abstract types
2515live across a call to <tt>refineAbstractTypeTo</tt> (note that non-abstract
2516types can never move or be deleted). To deal with this, the <a
2517href="#PATypeHolder">PATypeHolder</a> class is used to maintain a stable
2518reference to a possibly refined type, and the <a
2519href="#AbstractTypeUser">AbstractTypeUser</a> class is used to update more
2520complex 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>
2532PATypeHolder is a form of a "smart pointer" for Type objects. When VMCore
2533happily goes about nuking types that become isomorphic to existing types, it
2534automatically updates all PATypeHolder objects to point to the new type. In the
2535example above, this allows the code to maintain a pointer to the resultant
2536resolved recursive type, even though the Type*'s are potentially invalidated.
2537</p>
2538
2539<p>
2540PATypeHolder is an extremely light-weight object that uses a lazy union-find
2541implementation to update pointers. For example the pointer from a Value to its
2542Type 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>
2555Some data structures need more to perform more complex updates when types get
2556resolved. To support this, a class can derive from the AbstractTypeUser class.
2557This class
2558allows it to get callbacks when certain types are resolved. To register to get
2559callbacks for a particular type, the DerivedType::{add/remove}AbstractTypeUser
2560methods 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
2562objects) 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">
2575ValueSymbolTable</a></tt> class provides a symbol table that the <a
2576href="#Function"><tt>Function</tt></a> and <a href="#Module">
2577<tt>Module</tt></a> classes use for naming value definitions. The symbol table
2578can provide a name for any <a href="#Value"><tt>Value</tt></a>.
2579The <tt><a href="http://llvm.org/doxygen/classllvm_1_1TypeSymbolTable.html">
2580TypeSymbolTable</a></tt> class is used by the <tt>Module</tt> class to store
2581names for types.</p>
2582
2583<p>Note that the <tt>SymbolTable</tt> class should not be directly accessed
2584by most clients. It should only be used when iteration over the symbol table
2585names themselves are required, which is very special purpose. Note that not
2586all LLVM
Gabor Greif92e87762008-06-16 21:06:12 +00002587<tt><a href="#Value">Value</a></tt>s have names, and those without names (i.e. they have
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002588an 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
2592table with <tt>begin/end/iterator</tt> and supports querying to see if a
2593specific name is in the symbol table (with <tt>lookup</tt>). The
2594<tt>ValueSymbolTable</tt> class exposes no public mutator methods, instead,
2595simply call <tt>setName</tt> on a value, which will autoinsert it into the
2596appropriate symbol table. For types, use the Module::addTypeName method to
2597insert entries into the symbol table.</p>
2598
2599</div>
2600
2601
2602
Gabor Greif92e87762008-06-16 21:06:12 +00002603<!-- ======================================================================= -->
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">
Gabor Greif50626fc2009-01-05 16:05:32 +00002610User</a></tt> class provides a basis for expressing the ownership of <tt>User</tt>
Gabor Greif92e87762008-06-16 21:06:12 +00002611towards other <tt><a href="http://llvm.org/doxygen/classllvm_1_1Value.html">
2612Value</a></tt>s. The <tt><a href="http://llvm.org/doxygen/classllvm_1_1Use.html">
Gabor Greif93b462b2008-06-18 13:44:57 +00002613Use</a></tt> helper class is employed to do the bookkeeping and to facilitate <i>O(1)</i>
Gabor Greif92e87762008-06-16 21:06:12 +00002614addition and removal.</p>
2615
Gabor Greif93b462b2008-06-18 13:44:57 +00002616<!-- ______________________________________________________________________ -->
2617<div class="doc_subsubsection">
Gabor Greif50626fc2009-01-05 16:05:32 +00002618 <a name="Use2User">Interaction and relationship between <tt>User</tt> and <tt>Use</tt> objects</a>
Gabor Greif93b462b2008-06-18 13:44:57 +00002619</div>
Gabor Greif92e87762008-06-16 21:06:12 +00002620
Gabor Greif93b462b2008-06-18 13:44:57 +00002621<div class="doc_text">
2622<p>
2623A subclass of <tt>User</tt> can choose between incorporating its <tt>Use</tt> objects
Gabor Greif92e87762008-06-16 21:06:12 +00002624or refer to them out-of-line by means of a pointer. A mixed variant
Gabor Greif93b462b2008-06-18 13:44:57 +00002625(some <tt>Use</tt>s inline others hung off) is impractical and breaks the invariant
2626that the <tt>Use</tt> objects belonging to the same <tt>User</tt> form a contiguous array.
2627</p>
2628</div>
Gabor Greif92e87762008-06-16 21:06:12 +00002629
Gabor Greif93b462b2008-06-18 13:44:57 +00002630<p>
2631We have 2 different layouts in the <tt>User</tt> (sub)classes:
2632<ul>
2633<li><p>Layout a)
2634The <tt>Use</tt> object(s) are inside (resp. at fixed offset) of the <tt>User</tt>
2635object and there are a fixed number of them.</p>
Gabor Greif92e87762008-06-16 21:06:12 +00002636
Gabor Greif93b462b2008-06-18 13:44:57 +00002637<li><p>Layout b)
2638The <tt>Use</tt> object(s) are referenced by a pointer to an
2639array from the <tt>User</tt> object and there may be a variable
2640number of them.</p>
2641</ul>
2642<p>
Gabor Greife247e362008-06-25 00:10:22 +00002643As of v2.4 each layout still possesses a direct pointer to the
Gabor Greif93b462b2008-06-18 13:44:57 +00002644start of the array of <tt>Use</tt>s. Though not mandatory for layout a),
Gabor Greif92e87762008-06-16 21:06:12 +00002645we stick to this redundancy for the sake of simplicity.
Gabor Greife247e362008-06-25 00:10:22 +00002646The <tt>User</tt> object also stores the number of <tt>Use</tt> objects it
Gabor Greif92e87762008-06-16 21:06:12 +00002647has. (Theoretically this information can also be calculated
Gabor Greif93b462b2008-06-18 13:44:57 +00002648given the scheme presented below.)</p>
2649<p>
2650Special forms of allocation operators (<tt>operator new</tt>)
Gabor Greife247e362008-06-25 00:10:22 +00002651enforce the following memory layouts:</p>
Gabor Greif92e87762008-06-16 21:06:12 +00002652
Gabor Greif93b462b2008-06-18 13:44:57 +00002653<ul>
Gabor Greife247e362008-06-25 00:10:22 +00002654<li><p>Layout a) is modelled by prepending the <tt>User</tt> object by the <tt>Use[]</tt> array.</p>
Gabor Greif92e87762008-06-16 21:06:12 +00002655
Gabor Greif93b462b2008-06-18 13:44:57 +00002656<pre>
2657...---.---.---.---.-------...
2658 | P | P | P | P | User
2659'''---'---'---'---'-------'''
2660</pre>
Gabor Greif92e87762008-06-16 21:06:12 +00002661
Gabor Greife247e362008-06-25 00:10:22 +00002662<li><p>Layout b) is modelled by pointing at the <tt>Use[]</tt> array.</p>
Gabor Greif93b462b2008-06-18 13:44:57 +00002663<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>
Gabor Greif92e87762008-06-16 21:06:12 +00002676
Gabor Greif93b462b2008-06-18 13:44:57 +00002677<!-- ______________________________________________________________________ -->
2678<div class="doc_subsubsection">
Gabor Greif50626fc2009-01-05 16:05:32 +00002679 <a name="Waymarking">The waymarking algorithm</a>
Gabor Greif93b462b2008-06-18 13:44:57 +00002680</div>
Gabor Greif92e87762008-06-16 21:06:12 +00002681
Gabor Greif93b462b2008-06-18 13:44:57 +00002682<div class="doc_text">
2683<p>
Gabor Greife247e362008-06-25 00:10:22 +00002684Since the <tt>Use</tt> objects are deprived of the direct (back)pointer to
Gabor Greif93b462b2008-06-18 13:44:57 +00002685their <tt>User</tt> objects, there must be a fast and exact method to
2686recover it. This is accomplished by the following scheme:</p>
2687</div>
Gabor Greif92e87762008-06-16 21:06:12 +00002688
Gabor Greife247e362008-06-25 00:10:22 +00002689A bit-encoding in the 2 LSBits (least significant bits) of the <tt>Use::Prev</tt> allows to find the
Gabor Greif93b462b2008-06-18 13:44:57 +00002690start 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>
2698Given a <tt>Use*</tt>, all we have to do is to walk till we get
2699a stop and we either have a <tt>User</tt> immediately behind or
Gabor Greif92e87762008-06-16 21:06:12 +00002700we have to walk to the next stop picking up digits
Gabor Greif93b462b2008-06-18 13:44:57 +00002701and calculating the offset:</p>
2702<pre>
Gabor Greif92e87762008-06-16 21:06:12 +00002703.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.----------------
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 |__________________________________________________________>
Gabor Greif93b462b2008-06-18 13:44:57 +00002712</pre>
2713<p>
Gabor Greif92e87762008-06-16 21:06:12 +00002714Only the significant number of bits need to be stored between the
Gabor Greif93b462b2008-06-18 13:44:57 +00002715stops, so that the <i>worst case is 20 memory accesses</i> when there are
27161000 <tt>Use</tt> objects associated with a <tt>User</tt>.</p>
Gabor Greif92e87762008-06-16 21:06:12 +00002717
Gabor Greif93b462b2008-06-18 13:44:57 +00002718<!-- ______________________________________________________________________ -->
2719<div class="doc_subsubsection">
Gabor Greif50626fc2009-01-05 16:05:32 +00002720 <a name="ReferenceImpl">Reference implementation</a>
Gabor Greif93b462b2008-06-18 13:44:57 +00002721</div>
Gabor Greif92e87762008-06-16 21:06:12 +00002722
Gabor Greif93b462b2008-06-18 13:44:57 +00002723<div class="doc_text">
2724<p>
2725The following literate Haskell fragment demonstrates the concept:</p>
2726</div>
2727
2728<div class="doc_code">
2729<pre>
Gabor Greif92e87762008-06-16 21:06:12 +00002730> 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>
Gabor Greif93b462b2008-06-18 13:44:57 +00002747</pre>
2748</div>
2749<p>
2750Printing &lt;test&gt; gives: <tt>"1s100000s11010s10100s1111s1010s110s11s1S"</tt></p>
2751<p>
2752The reverse algorithm computes the length of the string just by examining
2753a certain prefix:</p>
Gabor Greif92e87762008-06-16 21:06:12 +00002754
Gabor Greif93b462b2008-06-18 13:44:57 +00002755<div class="doc_code">
2756<pre>
Gabor Greif92e87762008-06-16 21:06:12 +00002757> 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>
Gabor Greif93b462b2008-06-18 13:44:57 +00002766</pre>
2767</div>
2768<p>
2769Now, as expected, printing &lt;pref test&gt; gives <tt>40</tt>.</p>
2770<p>
2771We can <i>quickCheck</i> this with following property:</p>
Gabor Greif92e87762008-06-16 21:06:12 +00002772
Gabor Greif93b462b2008-06-18 13:44:57 +00002773<div class="doc_code">
2774<pre>
Gabor Greif92e87762008-06-16 21:06:12 +00002775> 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
Gabor Greif93b462b2008-06-18 13:44:57 +00002780>
2781</pre>
2782</div>
2783<p>
2784As expected &lt;quickCheck identityProp&gt; gives:</p>
Gabor Greif92e87762008-06-16 21:06:12 +00002785
Gabor Greif93b462b2008-06-18 13:44:57 +00002786<pre>
Gabor Greif92e87762008-06-16 21:06:12 +00002787*Main> quickCheck identityProp
2788OK, passed 100 tests.
Gabor Greif93b462b2008-06-18 13:44:57 +00002789</pre>
2790<p>
2791Let's be a bit more exhaustive:</p>
Gabor Greif92e87762008-06-16 21:06:12 +00002792
Gabor Greif93b462b2008-06-18 13:44:57 +00002793<div class="doc_code">
2794<pre>
Gabor Greif92e87762008-06-16 21:06:12 +00002795>
2796> deepCheck p = check (defaultConfig { configMaxTest = 500 }) p
2797>
Gabor Greif93b462b2008-06-18 13:44:57 +00002798</pre>
2799</div>
2800<p>
2801And here is the result of &lt;deepCheck identityProp&gt;:</p>
Gabor Greif92e87762008-06-16 21:06:12 +00002802
Gabor Greif93b462b2008-06-18 13:44:57 +00002803<pre>
Gabor Greif92e87762008-06-16 21:06:12 +00002804*Main> deepCheck identityProp
2805OK, passed 500 tests.
Gabor Greif92e87762008-06-16 21:06:12 +00002806</pre>
2807
Gabor Greif93b462b2008-06-18 13:44:57 +00002808<!-- ______________________________________________________________________ -->
2809<div class="doc_subsubsection">
Gabor Greif50626fc2009-01-05 16:05:32 +00002810 <a name="Tagging">Tagging considerations</a>
Gabor Greif93b462b2008-06-18 13:44:57 +00002811</div>
2812
2813<p>
2814To maintain the invariant that the 2 LSBits of each <tt>Use**</tt> in <tt>Use</tt>
2815never change after being set up, setters of <tt>Use::Prev</tt> must re-tag the
2816new <tt>Use**</tt> on every modification. Accordingly getters must strip the
2817tag bits.</p>
2818<p>
Gabor Greife247e362008-06-25 00:10:22 +00002819For layout b) instead of the <tt>User</tt> we find a pointer (<tt>User*</tt> with LSBit set).
2820Following this pointer brings us to the <tt>User</tt>. A portable trick ensures
2821that the first bytes of <tt>User</tt> (if interpreted as a pointer) never has
Gabor Greif50626fc2009-01-05 16:05:32 +00002822the 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>
Gabor Greif93b462b2008-06-18 13:44:57 +00002824
Gabor Greif92e87762008-06-16 21:06:12 +00002825</div>
2826
2827 <!-- *********************************************************************** -->
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002828<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
2838being inspected or transformed. The core LLVM classes are defined in
2839header files in the <tt>include/llvm/</tt> directory, and implemented in
2840the <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">
Gabor Greif50626fc2009-01-05 16:05:32 +00002868 <a name="m_Type">Important Public Methods</a>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002869</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">
Gabor Greif50626fc2009-01-05 16:05:32 +00002890 <a name="derivedtypes">Important Derived Types</a>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002891</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
2964href="/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
2968programs. An LLVM module is effectively either a translation unit of the
2969original program or a combination of several translation units merged by the
2970linker. The <tt>Module</tt> class keeps track of a list of <a
2971href="#Function"><tt>Function</tt></a>s, a list of <a
2972href="#GlobalVariable"><tt>GlobalVariable</tt></a>s, and a <a
2973href="#SymbolTable"><tt>SymbolTable</tt></a>. Additionally, it contains a few
2974helpful 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
2990provide 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>
3092doxygen 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
3095base. It represents a typed value that may be used (among other things) as an
3096operand to an instruction. There are many different types of <tt>Value</tt>s,
3097such as <a href="#Constant"><tt>Constant</tt></a>s,<a
3098href="#Argument"><tt>Argument</tt></a>s. Even <a
3099href="#Instruction"><tt>Instruction</tt></a>s and <a
3100href="#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
3103for a program. For example, an incoming argument to a function (represented
3104with an instance of the <a href="#Argument">Argument</a> class) is "used" by
3105every instruction in the function that references the argument. To keep track
3106of this relationship, the <tt>Value</tt> class keeps a list of all of the <a
3107href="#User"><tt>User</tt></a>s that is using it (the <a
3108href="#User"><tt>User</tt></a> class is a base class for all nodes in the LLVM
3109graph that can refer to <tt>Value</tt>s). This use list is how LLVM represents
3110def-use information in the program, and is accessible through the <tt>use_</tt>*
3111methods, shown below.</p>
3112
3113<p>Because LLVM is a typed representation, every LLVM <tt>Value</tt> is typed,
3114and this <a href="#Type">Type</a> is available through the <tt>getType()</tt>
3115method. 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>
3125that 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,
3127debugging printouts), they should not be used to keep track of values or map
3128between 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
3132variable and the operation that produces it. Because of this, any reference to
3133the value produced by an instruction (or the value available as an incoming
3134argument, for example) is represented as a direct pointer to the instance of
3135the class that
3136represents this value. Although this may take some getting used to, it
3137simplifies 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
3150use-list<br>
3151 <tt>Value::use_const_iterator</tt> - Typedef for const_iterator over
3152the use-list<br>
3153 <tt>unsigned use_size()</tt> - Returns the number of users of the
3154value.<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
3157the use-list.<br>
3158 <tt>use_iterator use_end()</tt> - Get an iterator to the end of the
3159use-list.<br>
3160 <tt><a href="#User">User</a> *use_back()</tt> - Returns the last
3161element in the list.
3162 <p> These methods are the interface to access the def-use
3163information in LLVM. As with all other iterators in LLVM, the naming
3164conventions 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>,
3173be 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>
3185Inst-&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>
3202doxygen info: <a href="/doxygen/classllvm_1_1User.html">User Class</a><br>
3203Superclass: <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
3206refer to <a href="#Value"><tt>Value</tt></a>s. It exposes a list of "Operands"
3207that are all of the <a href="#Value"><tt>Value</tt></a>s that the User is
3208referring 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
3212href="#Value"><tt>Value</tt></a> that it refers to. Because LLVM uses Static
3213Single Assignment (SSA) form, there can only be one definition referred to,
3214allowing this direct connection. This connection provides the use-def
3215information 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
3227an 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
3233convenient form for direct access.</p></li>
3234
3235 <li><tt>User::op_iterator</tt> - Typedef for iterator over the operand
3236list<br>
3237 <tt>op_iterator op_begin()</tt> - Get an iterator to the start of
3238the operand list.<br>
3239 <tt>op_iterator op_end()</tt> - Get an iterator to the end of the
3240operand list.
3241 <p> Together, these methods make up the iterator based interface to
3242the 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
3255href="/doxygen/Instruction_8h-source.html">llvm/Instruction.h</a>"</tt><br>
3256doxygen info: <a href="/doxygen/classllvm_1_1Instruction.html">Instruction Class</a><br>
3257Superclasses: <a href="#User"><tt>User</tt></a>, <a
3258href="#Value"><tt>Value</tt></a></p>
3259
3260<p>The <tt>Instruction</tt> class is the common base class for all LLVM
3261instructions. It provides only a few methods, but is a very commonly used
3262class. The primary data tracked by the <tt>Instruction</tt> class itself is the
3263opcode (instruction type) and the parent <a
3264href="#BasicBlock"><tt>BasicBlock</tt></a> the <tt>Instruction</tt> is embedded
3265into. 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
3269href="#User"><tt>User</tt></a> class, its operands can be accessed in the same
3270way 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
3273the <tt>Instruction</tt> class is the <tt>llvm/Instruction.def</tt> file. This
3274file contains some meta-data about the various different types of instructions
3275in 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
3277concrete sub-classes of <tt>Instruction</tt> that implement the instruction (for
3278example <tt><a href="#BinaryOperator">BinaryOperator</a></tt> and <tt><a
3279href="#CmpInst">CmpInst</a></tt>). Unfortunately, the use of macros in
3280this 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
3319this <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
3327in 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>),
3329and 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
3342is subclassed by ConstantInt, ConstantArray, etc. for representing
3343the various types of Constants. <a href="#GlobalValue">GlobalValue</a> is also
3344a 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
3408href="/doxygen/GlobalValue_8h-source.html">llvm/GlobalValue.h</a>"</tt><br>
3409doxygen info: <a href="/doxygen/classllvm_1_1GlobalValue.html">GlobalValue
3410Class</a><br>
3411Superclasses: <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
3415href="#Function"><tt>Function</tt></a>s) are the only LLVM values that are
3416visible in the bodies of all <a href="#Function"><tt>Function</tt></a>s.
3417Because they are visible at global scope, they are also subject to linking with
3418other globals defined in different translation units. To control the linking
3419process, <tt>GlobalValue</tt>s know their linkage rules. Specifically,
3420<tt>GlobalValue</tt>s know whether they have internal or external linkage, as
3421defined 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
3425unit, and does not participate in linking. If it has external linkage, it is
3426visible to external code, and does participate in linking. In addition to
3427linkage information, <tt>GlobalValue</tt>s keep track of which <a
3428href="#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
3431by their <b>address</b>. As such, the <a href="#Type"><tt>Type</tt></a> of a
3432global is always a pointer to its contents. It is important to remember this
3433when using the <tt>GetElementPtrInst</tt> instruction because this pointer must
3434be dereferenced first. For example, if you have a <tt>GlobalVariable</tt> (a
3435subclass of <tt>GlobalValue)</tt> that is an array of 24 ints, type <tt>[24 x
3436i32]</tt>, then the <tt>GlobalVariable</tt> is a pointer to that array. Although
3437the 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
3440is <tt>i32.</tt> Because of this, accessing a global value requires you to
3441dereference the pointer with <tt>GetElementPtrInst</tt> first, then its elements
3442can be accessed. This is explained in the <a href="LangRef.html#globalvars">LLVM
3443Language 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
3464GlobalValue 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
3477href="/doxygen/Function_8h-source.html">llvm/Function.h</a>"</tt><br> doxygen
3478info: <a href="/doxygen/classllvm_1_1Function.html">Function Class</a><br>
3479Superclasses: <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
3485actually one of the more complex classes in the LLVM heirarchy because it must
3486keep track of a large amount of data. The <tt>Function</tt> class keeps track
3487of 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
3492commonly used part of <tt>Function</tt> objects. The list imposes an implicit
3493ordering of the blocks in the function, which indicate how the code will be
3494layed out by the backend. Additionally, the first <a
3495href="#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
3497block. There are no implicit exit nodes, and in fact there may be multiple exit
3498nodes from a single <tt>Function</tt>. If the <a
3499href="#BasicBlock"><tt>BasicBlock</tt></a> list is empty, this indicates that
3500the <tt>Function</tt> is actually a function declaration: the actual body of the
3501function 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
3505href="#Argument"><tt>Argument</tt></a>s that the function receives. This
3506container manages the lifetime of the <a href="#Argument"><tt>Argument</tt></a>
3507nodes, just like the <a href="#BasicBlock"><tt>BasicBlock</tt></a> list does for
3508the <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
3511LLVM feature that is only used when you have to look up a value by name. Aside
3512from that, the <a href="#SymbolTable"><tt>SymbolTable</tt></a> is used
3513internally to make sure that there are not conflicts between the names of <a
3514href="#Instruction"><tt>Instruction</tt></a>s, <a
3515href="#BasicBlock"><tt>BasicBlock</tt></a>s, or <a
3516href="#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>
3519and therefore also a <a href="#Constant">Constant</a>. The value of the function
3520is 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
Chris Lattner5e709572008-11-25 18:34:50 +00003546 <li><tt>bool isDeclaration()</tt>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003547
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
3569iterator<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
3615href="/doxygen/GlobalVariable_8h-source.html">llvm/GlobalVariable.h</a>"</tt>
3616<br>
3617doxygen info: <a href="/doxygen/classllvm_1_1GlobalVariable.html">GlobalVariable
3618 Class</a><br>
3619Superclasses: <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
3626subclasses of <a href="#GlobalValue"><tt>GlobalValue</tt></a>, and as such are
3627always 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
3630variables may have an initial value (which must be a
3631<a href="#Constant"><tt>Constant</tt></a>), and if they have an initializer,
3632they may be marked as "constant" themselves (indicating that their contents
3633never 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
Duncan Sands19d161f2009-03-07 15:45:40 +00003652 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
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003658 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
3689href="/doxygen/BasicBlock_8h-source.html">llvm/BasicBlock.h</a>"</tt><br>
Stefanus Du Toitf017c852009-06-17 21:12:26 +00003690doxygen info: <a href="/doxygen/classllvm_1_1BasicBlock.html">BasicBlock
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691Class</a><br>
3692Superclass: <a href="#Value"><tt>Value</tt></a></p>
3693
3694<p>This class represents a single entry multiple exit section of the code,
3695commonly known as a basic block by the compiler community. The
3696<tt>BasicBlock</tt> class maintains a list of <a
3697href="#Instruction"><tt>Instruction</tt></a>s, which form the body of the block.
3698Matching the language definition, the last element of this list of instructions
3699is always a terminator instruction (a subclass of the <a
3700href="#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
3704href="#Function"><tt>Function</tt></a> that it is embedded into.</p>
3705
3706<p>Note that <tt>BasicBlock</tt>s themselves are <a
3707href="#Value"><tt>Value</tt></a>s, because they are referenced by instructions
3708like 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
3726insertion into a function. The constructor optionally takes a name for the new
3727block, and a <a href="#Function"><tt>Function</tt></a> to insert it into. If
3728the <tt>Parent</tt> parameter is specified, the new <tt>BasicBlock</tt> is
3729automatically inserted at the end of the specified <a
3730href="#Function"><tt>Function</tt></a>, if not specified, the BasicBlock must be
3731manually 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>
3737STL-style functions for accessing the instruction list.
3738
3739<p>These methods and typedefs are forwarding functions that have the same
3740semantics as the standard library methods of the same names. These methods
3741expose the underlying instruction list of a basic block in a way that is easy to
3742manipulate. To get the full complement of container operations (including
3743operations to update the list), you must use the <tt>getInstList()</tt>
3744method.</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
3749holds the Instructions. This method must be used when there isn't a forwarding
3750function in the <tt>BasicBlock</tt> class for the operation that you would like
3751to perform. Because there are no forwarding functions for "updating"
3752operations, 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
3758embedded 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
3763the <tt>BasicBlock</tt>. If there is no terminator instruction, or if the last
3764instruction in the block is not a terminator, then a null pointer is
3765returned.</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
3780arguments to a function. A Function maintains a list of its formal
3781arguments. 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
Misha Brukman947321d2008-12-11 17:34:48 +00003789 src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003790 <a href="http://validator.w3.org/check/referer"><img
Gabor Greif7dabe382008-06-18 14:05:31 +00003791 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01 Strict"></a>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003792
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>