Fixed a typo.
[oota-llvm.git] / docs / WritingAnLLVMPass.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2                       "http://www.w3.org/TR/html4/strict.dtd">
3 <html>
4 <head>
5   <title>Writing an LLVM Pass</title>
6   <link rel="stylesheet" href="llvm.css" type="text/css">
7 </head>
8 <body>
9
10 <div class="doc_title">
11   Writing an LLVM Pass
12 </div>
13
14 <ol>
15   <li><a href="#introduction">Introduction - What is a pass?</a></li>
16   <li><a href="#quickstart">Quick Start - Writing hello world</a>
17     <ul>
18     <li><a href="#makefile">Setting up the build environment</a></li>
19     <li><a href="#basiccode">Basic code required</a></li>
20     <li><a href="#running">Running a pass with <tt>opt</tt>
21                  or <tt>analyze</tt></a></li>
22     </ul></li>
23   <li><a href="#passtype">Pass classes and requirements</a>
24      <ul>
25      <li><a href="#ImmutablePass">The <tt>ImmutablePass</tt> class</a></li>
26      <li><a href="#ModulePass">The <tt>ModulePass</tt> class</a>
27         <ul>
28         <li><a href="#runOnModule">The <tt>runOnModule</tt> method</a></li>
29         </ul></li>
30      <li><a href="#CallGraphSCCPass">The <tt>CallGraphSCCPass</tt> class</a>
31         <ul>
32         <li><a href="#doInitialization_scc">The <tt>doInitialization(Module
33                                            &amp;)</tt> method</a></li>
34         <li><a href="#runOnSCC">The <tt>runOnSCC</tt> method</a></li>
35         <li><a href="#doFinalization_scc">The <tt>doFinalization(Module
36                                            &amp;)</tt> method</a></li>
37         </ul></li>
38      <li><a href="#FunctionPass">The <tt>FunctionPass</tt> class</a>
39         <ul>
40         <li><a href="#doInitialization_mod">The <tt>doInitialization(Module
41                                             &amp;)</tt> method</a></li>
42         <li><a href="#runOnFunction">The <tt>runOnFunction</tt> method</a></li>
43         <li><a href="#doFinalization_mod">The <tt>doFinalization(Module
44                                             &amp;)</tt> method</a></li>
45         </ul></li>
46      <li><a href="#BasicBlockPass">The <tt>BasicBlockPass</tt> class</a>
47         <ul>
48         <li><a href="#doInitialization_fn">The <tt>doInitialization(Function
49                                              &amp;)</tt> method</a></li>
50         <li><a href="#runOnBasicBlock">The <tt>runOnBasicBlock</tt>
51                                        method</a></li>
52         <li><a href="#doFinalization_fn">The <tt>doFinalization(Function
53                                          &amp;)</tt> method</a></li>
54         </ul></li>
55      <li><a href="#MachineFunctionPass">The <tt>MachineFunctionPass</tt>
56                                         class</a>
57         <ul>
58         <li><a href="#runOnMachineFunction">The
59             <tt>runOnMachineFunction(MachineFunction &amp;)</tt> method</a></li>
60         </ul></li>
61      </ul>
62   <li><a href="#registration">Pass Registration</a>
63      <ul>
64      <li><a href="#print">The <tt>print</tt> method</a></li>
65      </ul></li>
66   <li><a href="#interaction">Specifying interactions between passes</a>
67      <ul>
68      <li><a href="#getAnalysisUsage">The <tt>getAnalysisUsage</tt> 
69                                      method</a></li>
70      <li><a href="#AU::addRequired">The <tt>AnalysisUsage::addRequired&lt;&gt;</tt> and <tt>AnalysisUsage::addRequiredTransitive&lt;&gt;</tt> methods</a></li>
71      <li><a href="#AU::addPreserved">The <tt>AnalysisUsage::addPreserved&lt;&gt;</tt> method</a></li>
72      <li><a href="#AU::examples">Example implementations of <tt>getAnalysisUsage</tt></a></li>
73      <li><a href="#getAnalysis">The <tt>getAnalysis&lt;&gt;</tt> and <tt>getAnalysisToUpdate&lt;&gt;</tt> methods</a></li>
74      </ul></li>
75   <li><a href="#analysisgroup">Implementing Analysis Groups</a>
76      <ul>
77      <li><a href="#agconcepts">Analysis Group Concepts</a></li>
78      <li><a href="#registerag">Using <tt>RegisterAnalysisGroup</tt></a></li>
79      </ul></li>
80   <li><a href="#passStatistics">Pass Statistics</a>
81   <li><a href="#passmanager">What PassManager does</a>
82     <ul>
83     <li><a href="#releaseMemory">The <tt>releaseMemory</tt> method</a></li>
84     </ul></li>
85   <li><a href="#debughints">Using GDB with dynamically loaded passes</a>
86     <ul>
87     <li><a href="#breakpoint">Setting a breakpoint in your pass</a></li>
88     <li><a href="#debugmisc">Miscellaneous Problems</a></li>
89     </ul></li>
90   <li><a href="#future">Future extensions planned</a>
91     <ul>
92     <li><a href="#SMP">Multithreaded LLVM</a></li>
93     <li><a href="#PassFunctionPass"><tt>ModulePass</tt>es requiring 
94                                     <tt>FunctionPass</tt>es</a></li>
95     </ul></li>
96 </ol>
97
98 <div class="doc_author">
99   <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
100 </div>
101
102 <!-- *********************************************************************** -->
103 <div class="doc_section">
104   <a name="introduction">Introduction - What is a pass?</a>
105 </div>
106 <!-- *********************************************************************** -->
107
108 <div class="doc_text">
109
110 <p>The LLVM Pass Framework is an important part of the LLVM system, because LLVM
111 passes are where most of the interesting parts of the compiler exist.  Passes
112 perform the transformations and optimizations that make up the compiler, they
113 build the analysis results that are used by these transformations, and they are,
114 above all, a structuring technique for compiler code.</p>
115
116 <p>All LLVM passes are subclasses of the <tt><a
117 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1Pass.html">Pass</a></tt>
118 class, which implement functionality by overriding virtual methods inherited
119 from <tt>Pass</tt>.  Depending on how your pass works, you should inherit from
120 the <tt><a href="#ModulePass">ModulePass</a></tt>, <tt><a
121 href="#CallGraphSCCPass">CallGraphSCCPass</a></tt>, <tt><a
122 href="#FunctionPass">FunctionPass</a></tt>, or <tt><a
123 href="#BasicBlockPass">BasicBlockPass</a></tt> classes, which gives the system
124 more information about what your pass does, and how it can be combined with
125 other passes.  One of the main features of the LLVM Pass Framework is that it
126 schedules passes to run in an efficient way based on the constraints that your
127 pass meets (which are indicated by which class they derive from).</p>
128
129 <p>We start by showing you how to construct a pass, everything from setting up
130 the code, to compiling, loading, and executing it.  After the basics are down,
131 more advanced features are discussed.</p>
132
133 </div>
134
135 <!-- *********************************************************************** -->
136 <div class="doc_section">
137   <a name="quickstart">Quick Start - Writing hello world</a>
138 </div>
139 <!-- *********************************************************************** -->
140
141 <div class="doc_text">
142
143 <p>Here we describe how to write the "hello world" of passes.  The "Hello" pass
144 is designed to simply print out the name of non-external functions that exist in
145 the program being compiled.  It does not modify the program at all, it just
146 inspects it.  The source code and files for this pass are available in the LLVM
147 source tree in the <tt>lib/Transforms/Hello</tt> directory.</p>
148
149 </div>
150
151 <!-- ======================================================================= -->
152 <div class="doc_subsection">
153   <a name="makefile">Setting up the build environment</a>
154 </div>
155
156 <div class="doc_text">
157
158 <p>First thing you need to do is create a new directory somewhere in the LLVM
159 source base.  For this example, we'll assume that you made
160 "<tt>lib/Transforms/Hello</tt>".  The first thing you must do is set up a build
161 script (Makefile) that will compile the source code for the new pass.  To do
162 this, copy this into "<tt>Makefile</tt>":</p>
163
164 <hr>
165
166 <pre>
167 # Makefile for hello pass
168
169 # Path to top level of LLVM heirarchy
170 LEVEL = ../../..
171
172 # Name of the library to build
173 LIBRARYNAME = hello
174
175 # Build a dynamically loadable shared object
176 SHARED_LIBRARY = 1
177
178 # Include the makefile implementation stuff
179 include $(LEVEL)/Makefile.common
180 </pre>
181
182 <p>This makefile specifies that all of the <tt>.cpp</tt> files in the current
183 directory are to be compiled and linked together into a
184 <tt>lib/Debug/libhello.so</tt> shared object that can be dynamically loaded by
185 the <tt>opt</tt> or <tt>analyze</tt> tools.  If your operating system uses a
186 suffix other than .so (such as windows or Mac OS/X), the appropriate extension
187 will be used.</p>
188
189 <p>Now that we have the build scripts set up, we just need to write the code for
190 the pass itself.</p>
191
192 </div>
193
194 <!-- ======================================================================= -->
195 <div class="doc_subsection">
196   <a name="basiccode">Basic code required</a>
197 </div>
198
199 <div class="doc_text">
200
201 <p>Now that we have a way to compile our new pass, we just have to write it.
202 Start out with:</p>
203
204 <pre>
205 <b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Pass_8h-source.html">llvm/Pass.h</a>"
206 <b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Function_8h-source.html">llvm/Function.h</a>"
207 </pre>
208
209 <p>Which are needed because we are writing a <tt><a
210 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1Pass.html">Pass</a></tt>, and
211 we are operating on <tt><a
212 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1Function.html">Function</a></tt>'s.</p>
213
214 <p>Next we have:</p>
215 <pre>
216 <b>using namespace llvm;</b>
217 </pre>
218 <p>... which is required because the functions from the include files 
219 live in the llvm namespace.
220 </p>
221
222 <p>Next we have:</p>
223
224 <pre>
225 <b>namespace</b> {
226 </pre>
227
228 <p>... which starts out an anonymous namespace.  Anonymous namespaces are to C++
229 what the "<tt>static</tt>" keyword is to C (at global scope).  It makes the
230 things declared inside of the anonymous namespace only visible to the current
231 file.  If you're not familiar with them, consult a decent C++ book for more
232 information.</p>
233
234 <p>Next, we declare our pass itself:</p>
235
236 <pre>
237   <b>struct</b> Hello : <b>public</b> <a href="#FunctionPass">FunctionPass</a> {
238 </pre><p>
239
240 <p>This declares a "<tt>Hello</tt>" class that is a subclass of <tt><a
241 href="http://llvm.cs.uiuc.edu/doxygen/structllvm_1_1FunctionPass.html">FunctionPass</a></tt>.
242 The different builtin pass subclasses are described in detail <a
243 href="#passtype">later</a>, but for now, know that <a
244 href="#FunctionPass"><tt>FunctionPass</tt></a>'s operate a function at a
245 time.</p>
246
247 <pre>
248     <b>virtual bool</b> <a href="#runOnFunction">runOnFunction</a>(Function &amp;F) {
249       std::cerr &lt;&lt; "<i>Hello: </i>" &lt;&lt; F.getName() &lt;&lt; "\n";
250       <b>return false</b>;
251     }
252   };  <i>// end of struct Hello</i>
253 </pre>
254
255 <p>We declare a "<a href="#runOnFunction"><tt>runOnFunction</tt></a>" method,
256 which overloads an abstract virtual method inherited from <a
257 href="#FunctionPass"><tt>FunctionPass</tt></a>.  This is where we are supposed
258 to do our thing, so we just print out our message with the name of each
259 function.</p>
260
261 <pre>
262   RegisterOpt&lt;Hello&gt; X("<i>hello</i>", "<i>Hello World Pass</i>");
263 }  <i>// end of anonymous namespace</i>
264 </pre>
265
266 <p>Lastly, we register our class <tt>Hello</tt>, giving it a command line
267 argument "<tt>hello</tt>", and a name "<tt>Hello World Pass</tt>".  There are
268 several different ways of <a href="#registration">registering your pass</a>,
269 depending on what it is to be used for.  For "optimizations" we use the
270 <tt>RegisterOpt</tt> template.</p>
271
272 <p>As a whole, the <tt>.cpp</tt> file looks like:</p>
273
274 <pre>
275 <b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Pass_8h-source.html">llvm/Pass.h</a>"
276 <b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Function_8h-source.html">llvm/Function.h</a>"
277
278 <b>using namespace llvm;</b>
279
280 <b>namespace</b> {
281   <b>struct Hello</b> : <b>public</b> <a href="#FunctionPass">FunctionPass</a> {
282     <b>virtual bool</b> <a href="#runOnFunction">runOnFunction</a>(Function &amp;F) {
283       std::cerr &lt;&lt; "<i>Hello: </i>" &lt;&lt; F.getName() &lt;&lt; "\n";
284       <b>return false</b>;
285     }
286   };
287   
288   RegisterOpt&lt;Hello&gt; X("<i>hello</i>", "<i>Hello World Pass</i>");
289 }
290 </pre>
291
292 <p>Now that it's all together, compile the file with a simple "<tt>gmake</tt>"
293 command in the local directory and you should get a new
294 "<tt>lib/Debug/libhello.so</tt> file.  Note that everything in this file is
295 contained in an anonymous namespace: this reflects the fact that passes are self
296 contained units that do not need external interfaces (although they can have
297 them) to be useful.</p>
298
299 </div>
300
301 <!-- ======================================================================= -->
302 <div class="doc_subsection">
303   <a name="running">Running a pass with <tt>opt</tt> or <tt>analyze</tt></a>
304 </div>
305
306 <div class="doc_text">
307
308 <p>Now that you have a brand new shiny shared object file, we can use the
309 <tt>opt</tt> command to run an LLVM program through your pass.  Because you
310 registered your pass with the <tt>RegisterOpt</tt> template, you will be able to
311 use the <tt>opt</tt> tool to access it, once loaded.</p>
312
313 <p>To test it, follow the example at the end of the <a
314 href="GettingStarted.html">Getting Started Guide</a> to compile "Hello World" to
315 LLVM.  We can now run the bytecode file (<tt>hello.bc</tt>) for the program
316 through our transformation like this (or course, any bytecode file will
317 work):</p>
318
319 <pre>
320 $ opt -load ../../../lib/Debug/libhello.so -hello &lt; hello.bc &gt; /dev/null
321 Hello: __main
322 Hello: puts
323 Hello: main
324 </pre>
325
326 <p>The '<tt>-load</tt>' option specifies that '<tt>opt</tt>' should load your
327 pass as a shared object, which makes '<tt>-hello</tt>' a valid command line
328 argument (which is one reason you need to <a href="#registration">register your
329 pass</a>).  Because the hello pass does not modify the program in any
330 interesting way, we just throw away the result of <tt>opt</tt> (sending it to
331 <tt>/dev/null</tt>).</p>
332
333 <p>To see what happened to the other string you registered, try running
334 <tt>opt</tt> with the <tt>--help</tt> option:</p>
335
336 <pre>
337 $ opt -load ../../../lib/Debug/libhello.so --help
338 OVERVIEW: llvm .bc -&gt; .bc modular optimizer
339
340 USAGE: opt [options] &lt;input bytecode&gt;
341
342 OPTIONS:
343   Optimizations available:
344 ...
345     -funcresolve    - Resolve Functions
346     -gcse           - Global Common Subexpression Elimination
347     -globaldce      - Dead Global Elimination
348     <b>-hello          - Hello World Pass</b>
349     -indvars        - Canonicalize Induction Variables
350     -inline         - Function Integration/Inlining
351     -instcombine    - Combine redundant instructions
352 ...
353 </pre>
354
355 <p>The pass name get added as the information string for your pass, giving some
356 documentation to users of <tt>opt</tt>.  Now that you have a working pass, you
357 would go ahead and make it do the cool transformations you want.  Once you get
358 it all working and tested, it may become useful to find out how fast your pass
359 is.  The <a href="#passManager"><tt>PassManager</tt></a> provides a nice command
360 line option (<tt>--time-passes</tt>) that allows you to get information about
361 the execution time of your pass along with the other passes you queue up.  For
362 example:</p>
363
364 <pre>
365 $ opt -load ../../../lib/Debug/libhello.so -hello -time-passes &lt; hello.bc &gt; /dev/null
366 Hello: __main
367 Hello: puts
368 Hello: main
369 ===============================================================================
370                       ... Pass execution timing report ...
371 ===============================================================================
372   Total Execution Time: 0.02 seconds (0.0479059 wall clock)
373
374    ---User Time---   --System Time--   --User+System--   ---Wall Time---  --- Pass Name ---
375    0.0100 (100.0%)   0.0000 (  0.0%)   0.0100 ( 50.0%)   0.0402 ( 84.0%)  Bytecode Writer
376    0.0000 (  0.0%)   0.0100 (100.0%)   0.0100 ( 50.0%)   0.0031 (  6.4%)  Dominator Set Construction
377    0.0000 (  0.0%)   0.0000 (  0.0%)   0.0000 (  0.0%)   0.0013 (  2.7%)  Module Verifier
378  <b>  0.0000 (  0.0%)   0.0000 (  0.0%)   0.0000 (  0.0%)   0.0033 (  6.9%)  Hello World Pass</b>
379    0.0100 (100.0%)   0.0100 (100.0%)   0.0200 (100.0%)   0.0479 (100.0%)  TOTAL
380 </pre>
381
382 <p>As you can see, our implementation above is pretty fast :).  The additional
383 passes listed are automatically inserted by the '<tt>opt</tt>' tool to verify
384 that the LLVM emitted by your pass is still valid and well formed LLVM, which
385 hasn't been broken somehow.</p>
386
387 <p>Now that you have seen the basics of the mechanics behind passes, we can talk
388 about some more details of how they work and how to use them.</p>
389
390 </div>
391
392 <!-- *********************************************************************** -->
393 <div class="doc_section">
394   <a name="passtype">Pass classes and requirements</a>
395 </div>
396 <!-- *********************************************************************** -->
397
398 <div class="doc_text">
399
400 <p>One of the first things that you should do when designing a new pass is to
401 decide what class you should subclass for your pass.  The <a
402 href="#basiccode">Hello World</a> example uses the <tt><a
403 href="#FunctionPass">FunctionPass</a></tt> class for its implementation, but we
404 did not discuss why or when this should occur.  Here we talk about the classes
405 available, from the most general to the most specific.</p>
406
407 <p>When choosing a superclass for your Pass, you should choose the <b>most
408 specific</b> class possible, while still being able to meet the requirements
409 listed.  This gives the LLVM Pass Infrastructure information necessary to
410 optimize how passes are run, so that the resultant compiler isn't unneccesarily
411 slow.</p>
412
413 </div>
414
415 <!-- ======================================================================= -->
416 <div class="doc_subsection">
417   <a name="ImmutablePass">The <tt>ImmutablePass</tt> class</a>
418 </div>
419
420 <div class="doc_text">
421
422 <p>The most plain and boring type of pass is the "<tt><a
423 href="http://llvm.cs.uiuc.edu/doxygen/structllvm_1_1ImmutablePass.html">ImmutablePass</a></tt>"
424 class.  This pass type is used for passes that do not have to be run, do not
425 change state, and never need to be updated.  This is not a normal type of
426 transformation or analysis, but can provide information about the current
427 compiler configuration.</p>
428
429 <p>Although this pass class is very infrequently used, it is important for
430 providing information about the current target machine being compiled for, and
431 other static information that can affect the various transformations.</p>
432
433 <p><tt>ImmutablePass</tt>es never invalidate other transformations, are never
434 invalidated, and are never "run".</p>
435
436 </div>
437
438 <!-- ======================================================================= -->
439 <div class="doc_subsection">
440   <a name="ModulePass">The <tt>ModulePass</tt> class</a>
441 </div>
442
443 <div class="doc_text">
444
445 <p>The "<tt><a
446 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1ModulePass.html">ModulePass</a></tt>"
447 class is the most general of all superclasses that you can use.  Deriving from
448 <tt>ModulePass</tt> indicates that your pass uses the entire program as a unit,
449 refering to function bodies in no predictable order, or adding and removing
450 functions.  Because nothing is known about the behavior of <tt>ModulePass</tt>
451 subclasses, no optimization can be done for their execution.</p>
452
453 <p>To write a correct <tt>ModulePass</tt> subclass, derive from
454 <tt>ModulePass</tt> and overload the <tt>runOnModule</tt> method with the
455 following signature:</p>
456
457 </div>
458
459 <!-- _______________________________________________________________________ -->
460 <div class="doc_subsubsection">
461   <a name="runOnModule">The <tt>runOnModule</tt> method</a>
462 </div>
463
464 <div class="doc_text">
465
466 <pre>
467   <b>virtual bool</b> runOnModule(Module &amp;M) = 0;
468 </pre>
469
470 <p>The <tt>runOnModule</tt> method performs the interesting work of the pass,
471 and should return true if the module was modified by the transformation, false
472 otherwise.</p>
473
474 </div>
475
476 <!-- ======================================================================= -->
477 <div class="doc_subsection">
478   <a name="CallGraphSCCPass">The <tt>CallGraphSCCPass</tt> class</a>
479 </div>
480
481 <div class="doc_text">
482
483 <p>The "<tt><a
484 href="http://llvm.cs.uiuc.edu/doxygen/structllvm_1_1CallGraphSCCPass.html">CallGraphSCCPass</a></tt>"
485 is used by passes that need to traverse the program bottom-up on the call graph
486 (callees before callers).  Deriving from CallGraphSCCPass provides some
487 mechanics for building and traversing the CallGraph, but also allows the system
488 to optimize execution of CallGraphSCCPass's.  If your pass meets the
489 requirements outlined below, and doesn't meet the requirements of a <tt><a
490 href="#FunctionPass">FunctionPass</a></tt> or <tt><a
491 href="#BasicBlockPass">BasicBlockPass</a></tt>, you should derive from
492 <tt>CallGraphSCCPass</tt>.</p>
493
494 <p><b>TODO</b>: explain briefly what SCC, Tarjan's algo, and B-U mean.</p>
495
496 <p>To be explicit, <tt>CallGraphSCCPass</tt> subclasses are:</p>
497
498 <ol>
499
500 <li>... <em>not allowed</em> to modify any <tt>Function</tt>s that are not in
501 the current SCC.</li>
502
503 <li>... <em>allowed</em> to inspect any Function's other than those in the
504 current SCC and the direct callees of the SCC.</li>
505
506 <li>... <em>required</em> to preserve the current CallGraph object, updating it
507 to reflect any changes made to the program.</li>
508
509 <li>... <em>not allowed</em> to add or remove SCC's from the current Module,
510 though they may change the contents of an SCC.</li>
511
512 <li>... <em>allowed</em> to add or remove global variables from the current
513 Module.</li>
514
515 <li>... <em>allowed</em> to maintain state across invocations of
516     <a href="#runOnSCC"><tt>runOnSCC</tt></a> (including global data).</li>
517 </ol>
518
519 <p>Implementing a <tt>CallGraphSCCPass</tt> is slightly tricky in some cases
520 because it has to handle SCCs with more than one node in it.  All of the virtual
521 methods described below should return true if they modified the program, or
522 false if they didn't.</p>
523
524 </div>
525
526 <!-- _______________________________________________________________________ -->
527 <div class="doc_subsubsection">
528   <a name="doInitialization_scc">The <tt>doInitialization(Module &amp;)</tt>
529   method</a>
530 </div>
531
532 <div class="doc_text">
533
534 <pre>
535   <b>virtual bool</b> doInitialization(Module &amp;M);
536 </pre>
537
538 <p>The <tt>doIninitialize</tt> method is allowed to do most of the things that
539 <tt>CallGraphSCCPass</tt>'s are not allowed to do.  They can add and remove
540 functions, get pointers to functions, etc.  The <tt>doInitialization</tt> method
541 is designed to do simple initialization type of stuff that does not depend on
542 the SCCs being processed.  The <tt>doInitialization</tt> method call is not
543 scheduled to overlap with any other pass executions (thus it should be very
544 fast).</p>
545
546 </div>
547
548 <!-- _______________________________________________________________________ -->
549 <div class="doc_subsubsection">
550   <a name="runOnSCC">The <tt>runOnSCC</tt> method</a>
551 </div>
552
553 <div class="doc_text">
554
555 <pre>
556   <b>virtual bool</b> runOnSCC(const std::vector&lt;CallGraphNode *&gt; &amp;SCCM) = 0;
557 </pre>
558
559 <p>The <tt>runOnSCC</tt> method performs the interesting work of the pass, and
560 should return true if the module was modified by the transformation, false
561 otherwise.</p>
562
563 </div>
564
565 <!-- _______________________________________________________________________ -->
566 <div class="doc_subsubsection">
567   <a name="doFinalization_scc">The <tt>doFinalization(Module
568    &amp;)</tt> method</a>
569 </div>
570
571 <div class="doc_text">
572
573 <pre>
574   <b>virtual bool</b> doFinalization(Module &amp;M);
575 </pre>
576
577 <p>The <tt>doFinalization</tt> method is an infrequently used method that is
578 called when the pass framework has finished calling <a
579 href="#runOnFunction"><tt>runOnFunction</tt></a> for every function in the
580 program being compiled.</p>
581
582 </div>
583
584 <!-- ======================================================================= -->
585 <div class="doc_subsection">
586   <a name="FunctionPass">The <tt>FunctionPass</tt> class</a>
587 </div>
588
589 <div class="doc_text">
590
591 <p>In contrast to <tt>ModulePass</tt> subclasses, <tt><a
592 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1Pass.html">FunctionPass</a></tt>
593 subclasses do have a predictable, local behavior that can be expected by the
594 system.  All <tt>FunctionPass</tt> execute on each function in the program
595 independent of all of the other functions in the program.
596 <tt>FunctionPass</tt>'s do not require that they are executed in a particular
597 order, and <tt>FunctionPass</tt>'s do not modify external functions.</p>
598
599 <p>To be explicit, <tt>FunctionPass</tt> subclasses are not allowed to:</p>
600
601 <ol>
602 <li>Modify a Function other than the one currently being processed.</li>
603 <li>Add or remove Function's from the current Module.</li>
604 <li>Add or remove global variables from the current Module.</li>
605 <li>Maintain state across invocations of
606     <a href="#runOnFunction"><tt>runOnFunction</tt></a> (including global data)</li>
607 </ol>
608
609 <p>Implementing a <tt>FunctionPass</tt> is usually straightforward (See the <a
610 href="#basiccode">Hello World</a> pass for example).  <tt>FunctionPass</tt>'s
611 may overload three virtual methods to do their work.  All of these methods
612 should return true if they modified the program, or false if they didn't.</p>
613
614 </div>
615
616 <!-- _______________________________________________________________________ -->
617 <div class="doc_subsubsection">
618   <a name="doInitialization_mod">The <tt>doInitialization(Module &amp;)</tt>
619   method</a>
620 </div>
621
622 <div class="doc_text">
623
624 <pre>
625   <b>virtual bool</b> doInitialization(Module &amp;M);
626 </pre>
627
628 <p>The <tt>doIninitialize</tt> method is allowed to do most of the things that
629 <tt>FunctionPass</tt>'s are not allowed to do.  They can add and remove
630 functions, get pointers to functions, etc.  The <tt>doInitialization</tt> method
631 is designed to do simple initialization type of stuff that does not depend on
632 the functions being processed.  The <tt>doInitialization</tt> method call is not
633 scheduled to overlap with any other pass executions (thus it should be very
634 fast).</p>
635
636 <p>A good example of how this method should be used is the <a
637 href="http://llvm.cs.uiuc.edu/doxygen/LowerAllocations_8cpp-source.html">LowerAllocations</a>
638 pass.  This pass converts <tt>malloc</tt> and <tt>free</tt> instructions into
639 platform dependent <tt>malloc()</tt> and <tt>free()</tt> function calls.  It
640 uses the <tt>doInitialization</tt> method to get a reference to the malloc and
641 free functions that it needs, adding prototypes to the module if necessary.</p>
642
643 </div>
644
645 <!-- _______________________________________________________________________ -->
646 <div class="doc_subsubsection">
647   <a name="runOnFunction">The <tt>runOnFunction</tt> method</a>
648 </div>
649
650 <div class="doc_text">
651
652 <pre>
653   <b>virtual bool</b> runOnFunction(Function &amp;F) = 0;
654 </pre><p>
655
656 <p>The <tt>runOnFunction</tt> method must be implemented by your subclass to do
657 the transformation or analysis work of your pass.  As usual, a true value should
658 be returned if the function is modified.</p>
659
660 </div>
661
662 <!-- _______________________________________________________________________ -->
663 <div class="doc_subsubsection">
664   <a name="doFinalization_mod">The <tt>doFinalization(Module
665   &amp;)</tt> method</a>
666 </div>
667
668 <div class="doc_text">
669
670 <pre>
671   <b>virtual bool</b> doFinalization(Module &amp;M);
672 </pre>
673
674 <p>The <tt>doFinalization</tt> method is an infrequently used method that is
675 called when the pass framework has finished calling <a
676 href="#runOnFunction"><tt>runOnFunction</tt></a> for every function in the
677 program being compiled.</p>
678
679 </div>
680
681 <!-- ======================================================================= -->
682 <div class="doc_subsection">
683   <a name="BasicBlockPass">The <tt>BasicBlockPass</tt> class</a>
684 </div>
685
686 <div class="doc_text">
687
688 <p><tt>BasicBlockPass</tt>'s are just like <a
689 href="#FunctionPass"><tt>FunctionPass</tt></a>'s, except that they must limit
690 their scope of inspection and modification to a single basic block at a time.
691 As such, they are <b>not</b> allowed to do any of the following:</p>
692
693 <ol>
694 <li>Modify or inspect any basic blocks outside of the current one</li>
695 <li>Maintain state across invocations of
696     <a href="#runOnBasicBlock"><tt>runOnBasicBlock</tt></a></li>
697 <li>Modify the constrol flow graph (by altering terminator instructions)</li>
698 <li>Any of the things verboten for
699     <a href="#FunctionPass"><tt>FunctionPass</tt></a>es.</li>
700 </ol>
701
702 <p><tt>BasicBlockPass</tt>es are useful for traditional local and "peephole"
703 optimizations.  They may override the same <a
704 href="#doInitialization_mod"><tt>doInitialization(Module &amp;)</tt></a> and <a
705 href="#doFinalization_mod"><tt>doFinalization(Module &amp;)</tt></a> methods that <a
706 href="#FunctionPass"><tt>FunctionPass</tt></a>'s have, but also have the following virtual methods that may also be implemented:</p>
707
708 </div>
709
710 <!-- _______________________________________________________________________ -->
711 <div class="doc_subsubsection">
712   <a name="doInitialization_fn">The <tt>doInitialization(Function
713   &amp;)</tt> method</a>
714 </div>
715
716 <div class="doc_text">
717
718 <pre>
719   <b>virtual bool</b> doInitialization(Function &amp;F);
720 </pre>
721
722 <p>The <tt>doIninitialize</tt> method is allowed to do most of the things that
723 <tt>BasicBlockPass</tt>'s are not allowed to do, but that
724 <tt>FunctionPass</tt>'s can.  The <tt>doInitialization</tt> method is designed
725 to do simple initialization type of stuff that does not depend on the
726 BasicBlocks being processed.  The <tt>doInitialization</tt> method call is not
727 scheduled to overlap with any other pass executions (thus it should be very
728 fast).</p>
729
730 </div>
731
732 <!-- _______________________________________________________________________ -->
733 <div class="doc_subsubsection">
734   <a name="runOnBasicBlock">The <tt>runOnBasicBlock</tt> method</a>
735 </div>
736
737 <div class="doc_text">
738
739 <pre>
740   <b>virtual bool</b> runOnBasicBlock(BasicBlock &amp;BB) = 0;
741 </pre>
742
743 <p>Override this function to do the work of the <tt>BasicBlockPass</tt>.  This
744 function is not allowed to inspect or modify basic blocks other than the
745 parameter, and are not allowed to modify the CFG.  A true value must be returned
746 if the basic block is modified.</p>
747
748 </div>
749
750 <!-- _______________________________________________________________________ -->
751 <div class="doc_subsubsection">
752   <a name="doFinalization_fn">The <tt>doFinalization(Function &amp;)</tt> 
753   method</a>
754 </div>
755
756 <div class="doc_text">
757
758 <pre>
759   <b>virtual bool</b> doFinalization(Function &amp;F);
760 </pre>
761
762 <p>The <tt>doFinalization</tt> method is an infrequently used method that is
763 called when the pass framework has finished calling <a
764 href="#runOnBasicBlock"><tt>runOnBasicBlock</tt></a> for every BasicBlock in the
765 program being compiled.  This can be used to perform per-function
766 finalization.</p>
767
768 </div>
769
770 <!-- ======================================================================= -->
771 <div class="doc_subsection">
772   <a name="MachineFunctionPass">The <tt>MachineFunctionPass</tt> class</a>
773 </div>
774
775 <div class="doc_text">
776
777 <p>A <tt>MachineFunctionPass</tt> is a part of the LLVM code generator that
778 executes on the machine-dependent representation of each LLVM function in the
779 program.  A <tt>MachineFunctionPass</tt> is also a <tt>FunctionPass</tt>, so all
780 the restrictions that apply to a <tt>FunctionPass</tt> also apply to it.
781 <tt>MachineFunctionPass</tt>es also have additional restrictions. In particular,
782 <tt>MachineFunctionPass</tt>es are not allowed to do any of the following:</p>
783
784 <ol>
785 <li>Modify any LLVM Instructions, BasicBlocks or Functions.</li>
786 <li>Modify a MachineFunction other than the one currently being processed.</li>
787 <li>Add or remove MachineFunctions from the current Module.</li>
788 <li>Add or remove global variables from the current Module.</li>
789 <li>Maintain state across invocations of <a
790 href="#runOnMachineFunction"><tt>runOnMachineFunction</tt></a> (including global
791 data)</li>
792 </ol>
793
794 </div>
795
796 <!-- _______________________________________________________________________ -->
797 <div class="doc_subsubsection">
798   <a name="runOnMachineFunction">The <tt>runOnMachineFunction(MachineFunction
799   &amp;MF)</tt> method</a>
800 </div>
801
802 <div class="doc_text">
803
804 <pre>
805   <b>virtual bool</b> runOnMachineFunction(MachineFunction &amp;MF) = 0;
806 </pre>
807
808 <p><tt>runOnMachineFunction</tt> can be considered the main entry point of a
809 <tt>MachineFunctionPass</tt>; that is, you should override this method to do the
810 work of your <tt>MachineFunctionPass</tt>.</p>
811
812 <p>The <tt>runOnMachineFunction</tt> method is called on every
813 <tt>MachineFunction</tt> in a <tt>Module</tt>, so that the
814 <tt>MachineFunctionPass</tt> may perform optimizations on the machine-dependent
815 representation of the function. If you want to get at the LLVM <tt>Function</tt>
816 for the <tt>MachineFunction</tt> you're working on, use
817 <tt>MachineFunction</tt>'s <tt>getFunction()</tt> accessor method -- but
818 remember, you may not modify the LLVM <tt>Function</tt> or its contents from a
819 <tt>MachineFunctionPass</tt>.</p>
820
821 </div>
822
823 <!-- *********************************************************************** -->
824 <div class="doc_section">
825   <a name="registration">Pass registration</a>
826 </div>
827 <!-- *********************************************************************** -->
828
829 <div class="doc_text">
830
831 <p>In the <a href="#basiccode">Hello World</a> example pass we illustrated how
832 pass registration works, and discussed some of the reasons that it is used and
833 what it does.  Here we discuss how and why passes are registered.</p>
834
835 <p>Passes can be registered in several different ways.  Depending on the general
836 classification of the pass, you should use one of the following templates to
837 register the pass:</p>
838
839 <ul>
840 <li><b><tt>RegisterOpt</tt></b> - This template should be used when you are
841 registering a pass that logically should be available for use in the
842 '<tt>opt</tt>' utility.</li>
843
844 <li><b><tt>RegisterAnalysis</tt></b> - This template should be used when you are
845 registering a pass that logically should be available for use in the
846 '<tt>analyze</tt>' utility.</li>
847
848 <li><b><tt>RegisterPass</tt></b> - This is the generic form of the
849 <tt>Register*</tt> templates that should be used if you want your pass listed by
850 multiple or no utilities.  This template takes an extra third argument that
851 specifies which tools it should be listed in.  See the <a
852 href="http://llvm.cs.uiuc.edu/doxygen/PassSupport_8h-source.html">PassSupport.h</a>
853 file for more information.</li>
854
855 </ul>
856
857 <p>Regardless of how you register your pass, you must specify at least two
858 parameters.  The first parameter is the name of the pass that is to be used on
859 the command line to specify that the pass should be added to a program (for
860 example <tt>opt</tt> or <tt>analyze</tt>).  The second argument is the name of
861 the pass, which is to be used for the <tt>--help</tt> output of programs, as
862 well as for debug output generated by the <tt>--debug-pass</tt> option.</p>
863
864 <p>If a pass is registered to be used by the <tt>analyze</tt> utility, you
865 should implement the virtual <tt>print</tt> method:</p>
866
867 </div>
868
869 <!-- _______________________________________________________________________ -->
870 <div class="doc_subsubsection">
871   <a name="print">The <tt>print</tt> method</a>
872 </div>
873
874 <div class="doc_text">
875
876 <pre>
877   <b>virtual void</b> print(std::ostream &amp;O, <b>const</b> Module *M) <b>const</b>;
878 </pre>
879
880 <p>The <tt>print</tt> method must be implemented by "analyses" in order to print
881 a human readable version of the analysis results.  This is useful for debugging
882 an analysis itself, as well as for other people to figure out how an analysis
883 works.  The <tt>analyze</tt> tool uses this method to generate its output.</p>
884
885 <p>The <tt>ostream</tt> parameter specifies the stream to write the results on,
886 and the <tt>Module</tt> parameter gives a pointer to the top level module of the
887 program that has been analyzed.  Note however that this pointer may be null in
888 certain circumstances (such as calling the <tt>Pass::dump()</tt> from a
889 debugger), so it should only be used to enhance debug output, it should not be
890 depended on.</p>
891
892 </div>
893
894 <!-- *********************************************************************** -->
895 <div class="doc_section">
896   <a name="interaction">Specifying interactions between passes</a>
897 </div>
898 <!-- *********************************************************************** -->
899
900 <div class="doc_text">
901
902 <p>One of the main responsibilities of the <tt>PassManager</tt> is the make sure
903 that passes interact with each other correctly.  Because <tt>PassManager</tt>
904 tries to <a href="#passmanager">optimize the execution of passes</a> it must
905 know how the passes interact with each other and what dependencies exist between
906 the various passes.  To track this, each pass can declare the set of passes that
907 are required to be executed before the current pass, and the passes which are
908 invalidated by the current pass.</p>
909
910 <p>Typically this functionality is used to require that analysis results are
911 computed before your pass is run.  Running arbitrary transformation passes can
912 invalidate the computed analysis results, which is what the invalidation set
913 specifies.  If a pass does not implement the <tt><a
914 href="#getAnalysisUsage">getAnalysisUsage</a></tt> method, it defaults to not
915 having any prerequisite passes, and invalidating <b>all</b> other passes.</p>
916
917 </div>
918
919 <!-- _______________________________________________________________________ -->
920 <div class="doc_subsubsection">
921   <a name="getAnalysisUsage">The <tt>getAnalysisUsage</tt> method</a>
922 </div>
923
924 <div class="doc_text">
925
926 <pre>
927   <b>virtual void</b> getAnalysisUsage(AnalysisUsage &amp;Info) <b>const</b>;
928 </pre>
929
930 <p>By implementing the <tt>getAnalysisUsage</tt> method, the required and
931 invalidated sets may be specified for your transformation.  The implementation
932 should fill in the <tt><a
933 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1AnalysisUsage.html">AnalysisUsage</a></tt>
934 object with information about which passes are required and not invalidated.  To
935 do this, a pass may call any of the following methods on the AnalysisUsage
936 object:</p>
937 </div>
938
939 <!-- _______________________________________________________________________ -->
940 <div class="doc_subsubsection">
941   <a name="AU::addRequired">The <tt>AnalysisUsage::addRequired&lt;&gt;</tt> and <tt>AnalysisUsage::addRequiredTransitive&lt;&gt;</tt> methods</a>
942 </div>
943
944 <div class="doc_text">
945 <p>
946 If you pass requires a previous pass to be executed (an analysis for example),
947 it can use one of these methods to arrange for it to be run before your pass.
948 LLVM has many different types of analyses and passes that can be required,
949 spaning the range from <tt>DominatorSet</tt> to <tt>BreakCriticalEdges</tt>.
950 requiring <tt>BreakCriticalEdges</tt>, for example, guarantees that there will
951 be no critical edges in the CFG when your pass has been run.
952 </p>
953
954 <p>
955 Some analyses chain to other analyses to do their job.  For example, an <a
956 href="AliasAnalysis.html">AliasAnalysis</a> implementation is required to <a
957 href="AliasAnalysis.html#chaining">chain</a> to other alias analysis passes.  In
958 cases where analyses chain, the <tt>addRequiredTransitive</tt> method should be
959 used instead of the <tt>addRequired</tt> method.  This informs the PassManager
960 that the transitively required pass should be alive as long as the requiring
961 pass is.
962 </p>
963 </div>
964
965 <!-- _______________________________________________________________________ -->
966 <div class="doc_subsubsection">
967   <a name="AU::addPreserved">The <tt>AnalysisUsage::addPreserved&lt;&gt;</tt> method</a>
968 </div>
969
970 <div class="doc_text">
971 <p>
972 One of the jobs of the PassManager is to optimize how and when analyses are run.
973 In particular, it attempts to avoid recomputing data unless it needs to.  For
974 this reason, passes are allowed to declare that they preserve (i.e., they don't
975 invalidate) an existing analysis if it's available.  For example, a simple
976 constant folding pass would not modify the CFG, so it can't possible effect the
977 results of dominator analysis.  By default, all passes are assumed to invalidate
978 all others.
979 </p>
980
981 <p>
982 The <tt>AnalysisUsage</tt> class provides several methods which are useful in
983 certain circumstances that are related to <tt>addPreserved</tt>.  In particular,
984 the <tt>setPreservesAll</tt> method can be called to indicate that the pass does
985 not modify the LLVM program at all (which is true for analyses), and the
986 <tt>setPreservesCFG</tt> method can be used by transformations that change
987 instructions in the program but do not modify the CFG or terminator instructions
988 (note that this property is implicitly set for <a
989 href="#BasicBlockPass">BasicBlockPass</a>'s).
990 </p>
991
992 <p>
993 <tt>addPreserved</tt> is particularly useful for transformations like
994 <tt>BreakCriticalEdges</tt>.  This pass knows how to update a small set of loop
995 and dominator related analyses if they exist, so it can preserve them, despite
996 the fact that it hacks on the CFG.
997 </p>
998 </div>
999
1000 <!-- _______________________________________________________________________ -->
1001 <div class="doc_subsubsection">
1002   <a name="AU::examples">Example implementations of <tt>getAnalysisUsage</tt></a>
1003 </div>
1004
1005 <div class="doc_text">
1006
1007 <pre>
1008   <i>// This is an example implementation from an analysis, which does not modify
1009   // the program at all, yet has a prerequisite.</i>
1010   <b>void</b> <a href="http://llvm.cs.uiuc.edu/doxygen/structllvm_1_1PostDominanceFrontier.html">PostDominanceFrontier</a>::getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
1011     AU.setPreservesAll();
1012     AU.addRequired&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structllvm_1_1PostDominatorTree.html">PostDominatorTree</a>&gt;();
1013   }
1014 </pre>
1015
1016 <p>and:</p>
1017
1018 <pre>
1019   <i>// This example modifies the program, but does not modify the CFG</i>
1020   <b>void</b> <a href="http://llvm.cs.uiuc.edu/doxygen/structLICM.html">LICM</a>::getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
1021     AU.setPreservesCFG();
1022     AU.addRequired&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1LoopInfo.html">LoopInfo</a>&gt;();
1023   }
1024 </pre>
1025
1026 </div>
1027
1028 <!-- _______________________________________________________________________ -->
1029 <div class="doc_subsubsection">
1030   <a name="getAnalysis">The <tt>getAnalysis&lt;&gt;</tt> and <tt>getAnalysisToUpdate&lt;&gt;</tt> methods</a>
1031 </div>
1032
1033 <div class="doc_text">
1034
1035 <p>The <tt>Pass::getAnalysis&lt;&gt;</tt> method is automatically inherited by
1036 your class, providing you with access to the passes that you declared that you
1037 required with the <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a>
1038 method.  It takes a single template argument that specifies which pass class you
1039 want, and returns a reference to that pass.  For example:</p>
1040
1041 <pre>
1042    bool LICM::runOnFunction(Function &amp;F) {
1043      LoopInfo &amp;LI = getAnalysis&lt;LoopInfo&gt;();
1044      ...
1045    }
1046 </pre>
1047
1048 <p>This method call returns a reference to the pass desired.  You may get a
1049 runtime assertion failure if you attempt to get an analysis that you did not
1050 declare as required in your <a
1051 href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> implementation.  This
1052 method can be called by your <tt>run*</tt> method implementation, or by any
1053 other local method invoked by your <tt>run*</tt> method.</p>
1054
1055 <p>
1056 If your pass is capable of updating analyses if they exist (e.g.,
1057 <tt>BreakCriticalEdges</tt>, as described above), you can use the
1058 <tt>getAnalysisToUpdate</tt> method, which returns a pointer to the analysis if
1059 it is active.  For example:</p>
1060
1061 <pre>
1062   ...
1063   if (DominatorSet *DS = getAnalysisToUpdate&lt;DominatorSet&gt;()) {
1064     <i>// A DominatorSet is active.  This code will update it.</i>
1065   }
1066   ...
1067 </pre>
1068
1069 </div>
1070
1071 <!-- *********************************************************************** -->
1072 <div class="doc_section">
1073   <a name="analysisgroup">Implementing Analysis Groups</a>
1074 </div>
1075 <!-- *********************************************************************** -->
1076
1077 <div class="doc_text">
1078
1079 <p>Now that we understand the basics of how passes are defined, how the are
1080 used, and how they are required from other passes, it's time to get a little bit
1081 fancier.  All of the pass relationships that we have seen so far are very
1082 simple: one pass depends on one other specific pass to be run before it can run.
1083 For many applications, this is great, for others, more flexibility is
1084 required.</p>
1085
1086 <p>In particular, some analyses are defined such that there is a single simple
1087 interface to the analysis results, but multiple ways of calculating them.
1088 Consider alias analysis for example.  The most trivial alias analysis returns
1089 "may alias" for any alias query.  The most sophisticated analysis a
1090 flow-sensitive, context-sensitive interprocedural analysis that can take a
1091 significant amount of time to execute (and obviously, there is a lot of room
1092 between these two extremes for other implementations).  To cleanly support
1093 situations like this, the LLVM Pass Infrastructure supports the notion of
1094 Analysis Groups.</p>
1095
1096 </div>
1097
1098 <!-- _______________________________________________________________________ -->
1099 <div class="doc_subsubsection">
1100   <a name="agconcepts">Analysis Group Concepts</a>
1101 </div>
1102
1103 <div class="doc_text">
1104
1105 <p>An Analysis Group is a single simple interface that may be implemented by
1106 multiple different passes.  Analysis Groups can be given human readable names
1107 just like passes, but unlike passes, they need not derive from the <tt>Pass</tt>
1108 class.  An analysis group may have one or more implementations, one of which is
1109 the "default" implementation.</p>
1110
1111 <p>Analysis groups are used by client passes just like other passes are: the
1112 <tt>AnalysisUsage::addRequired()</tt> and <tt>Pass::getAnalysis()</tt> methods.
1113 In order to resolve this requirement, the <a href="#passmanager">PassManager</a>
1114 scans the available passes to see if any implementations of the analysis group
1115 are available.  If none is available, the default implementation is created for
1116 the pass to use.  All standard rules for <A href="#interaction">interaction
1117 between passes</a> still apply.</p>
1118
1119 <p>Although <a href="#registration">Pass Registration</a> is optional for normal
1120 passes, all analysis group implementations must be registered, and must use the
1121 <A href="#registerag"><tt>RegisterAnalysisGroup</tt></a> template to join the
1122 implementation pool.  Also, a default implementation of the interface
1123 <b>must</b> be registered with <A
1124 href="#registerag"><tt>RegisterAnalysisGroup</tt></a>.</p>
1125
1126 <p>As a concrete example of an Analysis Group in action, consider the <a
1127 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a>
1128 analysis group.  The default implementation of the alias analysis interface (the
1129 <tt><a
1130 href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">basicaa</a></tt>
1131 pass) just does a few simple checks that don't require significant analysis to
1132 compute (such as: two different globals can never alias each other, etc).
1133 Passes that use the <tt><a
1134 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a></tt>
1135 interface (for example the <tt><a
1136 href="http://llvm.cs.uiuc.edu/doxygen/structGCSE.html">gcse</a></tt> pass), do
1137 not care which implementation of alias analysis is actually provided, they just
1138 use the designated interface.</p>
1139
1140 <p>From the user's perspective, commands work just like normal.  Issuing the
1141 command '<tt>opt -gcse ...</tt>' will cause the <tt>basicaa</tt> class to be
1142 instantiated and added to the pass sequence.  Issuing the command '<tt>opt
1143 -somefancyaa -gcse ...</tt>' will cause the <tt>gcse</tt> pass to use the
1144 <tt>somefancyaa</tt> alias analysis (which doesn't actually exist, it's just a
1145 hypothetical example) instead.</p>
1146
1147 </div>
1148
1149 <!-- _______________________________________________________________________ -->
1150 <div class="doc_subsubsection">
1151   <a name="registerag">Using <tt>RegisterAnalysisGroup</tt></a>
1152 </div>
1153
1154 <div class="doc_text">
1155
1156 <p>The <tt>RegisterAnalysisGroup</tt> template is used to register the analysis
1157 group itself as well as add pass implementations to the analysis group.  First,
1158 an analysis should be registered, with a human readable name provided for it.
1159 Unlike registration of passes, there is no command line argument to be specified
1160 for the Analysis Group Interface itself, because it is "abstract":</p>
1161
1162 <pre>
1163   <b>static</b> RegisterAnalysisGroup&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a>&gt; A("<i>Alias Analysis</i>");
1164 </pre>
1165
1166 <p>Once the analysis is registered, passes can declare that they are valid
1167 implementations of the interface by using the following code:</p>
1168
1169 <pre>
1170 <b>namespace</b> {
1171   //<i> Analysis Group implementations <b>must</b> be registered normally...</i>
1172   RegisterOpt&lt;FancyAA&gt;
1173   B("<i>somefancyaa</i>", "<i>A more complex alias analysis implementation</i>");
1174
1175   //<i> Declare that we implement the AliasAnalysis interface</i>
1176   RegisterAnalysisGroup&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a>, FancyAA&gt; C;
1177 }
1178 </pre>
1179
1180 <p>This just shows a class <tt>FancyAA</tt> that is registered normally, then
1181 uses the <tt>RegisterAnalysisGroup</tt> template to "join" the <tt><a
1182 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a></tt>
1183 analysis group.  Every implementation of an analysis group should join using
1184 this template.  A single pass may join multiple different analysis groups with
1185 no problem.</p>
1186
1187 <pre>
1188 <b>namespace</b> {
1189   //<i> Analysis Group implementations <b>must</b> be registered normally...</i>
1190   RegisterOpt&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a>&gt;
1191   D("<i>basicaa</i>", "<i>Basic Alias Analysis (default AA impl)</i>");
1192
1193   //<i> Declare that we implement the AliasAnalysis interface</i>
1194   RegisterAnalysisGroup&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a>, <a href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a>, <b>true</b>&gt; E;
1195 }
1196 </pre>
1197
1198 <p>Here we show how the default implementation is specified (using the extra
1199 argument to the <tt>RegisterAnalysisGroup</tt> template).  There must be exactly
1200 one default implementation available at all times for an Analysis Group to be
1201 used.  Here we declare that the <tt><a
1202 href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a></tt>
1203 pass is the default implementation for the interface.</p>
1204
1205 </div>
1206
1207 <!-- *********************************************************************** -->
1208 <div class="doc_section">
1209   <a name="passStatistics">Pass Statistics</a>
1210 </div>
1211 <!-- *********************************************************************** -->
1212
1213 <div class="doc_text">
1214 <p>The <a
1215 href="http:://llvm.cs.uiuc.edu/doxygen/Statistic_8h-source.html"><tt>Statistic</tt></a>
1216 class, is designed to be an easy way to expose various success
1217 metrics from passes.  These statistics are printed at the end of a
1218 run, when the -stats command line option is enabled on the command
1219 line. See the <a href="http://llvm.org/docs/ProgrammersManual.html#Statistic">Statistics section</a> in the Programmer's Manual for details. 
1220
1221 </div>
1222
1223
1224 <!-- *********************************************************************** -->
1225 <div class="doc_section">
1226   <a name="passmanager">What PassManager does</a>
1227 </div>
1228 <!-- *********************************************************************** -->
1229
1230 <div class="doc_text">
1231
1232 <p>The <a
1233 href="http://llvm.cs.uiuc.edu/doxygen/PassManager_8h-source.html"><tt>PassManager</tt></a>
1234 <a
1235 href="http://llvm.cs.uiuc.edu/doxygen/classllvm_1_1PassManager.html">class</a>
1236 takes a list of passes, ensures their <a href="#interaction">prerequisites</a>
1237 are set up correctly, and then schedules passes to run efficiently.  All of the
1238 LLVM tools that run passes use the <tt>PassManager</tt> for execution of these
1239 passes.</p>
1240
1241 <p>The <tt>PassManager</tt> does two main things to try to reduce the execution
1242 time of a series of passes:</p>
1243
1244 <ol>
1245 <li><b>Share analysis results</b> - The PassManager attempts to avoid
1246 recomputing analysis results as much as possible.  This means keeping track of
1247 which analyses are available already, which analyses get invalidated, and which
1248 analyses are needed to be run for a pass.  An important part of work is that the
1249 <tt>PassManager</tt> tracks the exact lifetime of all analysis results, allowing
1250 it to <a href="#releaseMemory">free memory</a> allocated to holding analysis
1251 results as soon as they are no longer needed.</li>
1252
1253 <li><b>Pipeline the execution of passes on the program</b> - The
1254 <tt>PassManager</tt> attempts to get better cache and memory usage behavior out
1255 of a series of passes by pipelining the passes together.  This means that, given
1256 a series of consequtive <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s, it
1257 will execute all of the <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s on
1258 the first function, then all of the <a
1259 href="#FunctionPass"><tt>FunctionPass</tt></a>es on the second function,
1260 etc... until the entire program has been run through the passes.
1261
1262 <p>This improves the cache behavior of the compiler, because it is only touching
1263 the LLVM program representation for a single function at a time, instead of
1264 traversing the entire program.  It reduces the memory consumption of compiler,
1265 because, for example, only one <a
1266 href="http://llvm.cs.uiuc.edu/doxygen/structllvm_1_1DominatorSet.html"><tt>DominatorSet</tt></a>
1267 needs to be calculated at a time.  This also makes it possible some <a
1268 href="#SMP">interesting enhancements</a> in the future.</p></li>
1269
1270 </ol>
1271
1272 <p>The effectiveness of the <tt>PassManager</tt> is influenced directly by how
1273 much information it has about the behaviors of the passes it is scheduling.  For
1274 example, the "preserved" set is intentionally conservative in the face of an
1275 unimplemented <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method.
1276 Not implementing when it should be implemented will have the effect of not
1277 allowing any analysis results to live across the execution of your pass.</p>
1278
1279 <p>The <tt>PassManager</tt> class exposes a <tt>--debug-pass</tt> command line
1280 options that is useful for debugging pass execution, seeing how things work, and
1281 diagnosing when you should be preserving more analyses than you currently are
1282 (To get information about all of the variants of the <tt>--debug-pass</tt>
1283 option, just type '<tt>opt --help-hidden</tt>').</p>
1284
1285 <p>By using the <tt>--debug-pass=Structure</tt> option, for example, we can see
1286 how our <a href="#basiccode">Hello World</a> pass interacts with other passes.
1287 Lets try it out with the <tt>gcse</tt> and <tt>licm</tt> passes:</p>
1288
1289 <pre>
1290 $ opt -load ../../../lib/Debug/libhello.so -gcse -licm --debug-pass=Structure &lt; hello.bc &gt; /dev/null
1291 Module Pass Manager
1292   Function Pass Manager
1293     Dominator Set Construction
1294     Immediate Dominators Construction
1295     Global Common Subexpression Elimination
1296 --  Immediate Dominators Construction
1297 --  Global Common Subexpression Elimination
1298     Natural Loop Construction
1299     Loop Invariant Code Motion
1300 --  Natural Loop Construction
1301 --  Loop Invariant Code Motion
1302     Module Verifier
1303 --  Dominator Set Construction
1304 --  Module Verifier
1305   Bytecode Writer
1306 --Bytecode Writer
1307 </pre>
1308
1309 <p>This output shows us when passes are constructed and when the analysis
1310 results are known to be dead (prefixed with '<tt>--</tt>').  Here we see that
1311 GCSE uses dominator and immediate dominator information to do its job.  The LICM
1312 pass uses natural loop information, which uses dominator sets, but not immediate
1313 dominators.  Because immediate dominators are no longer useful after the GCSE
1314 pass, it is immediately destroyed.  The dominator sets are then reused to
1315 compute natural loop information, which is then used by the LICM pass.</p>
1316
1317 <p>After the LICM pass, the module verifier runs (which is automatically added
1318 by the '<tt>opt</tt>' tool), which uses the dominator set to check that the
1319 resultant LLVM code is well formed.  After it finishes, the dominator set
1320 information is destroyed, after being computed once, and shared by three
1321 passes.</p>
1322
1323 <p>Lets see how this changes when we run the <a href="#basiccode">Hello
1324 World</a> pass in between the two passes:</p>
1325
1326 <pre>
1327 $ opt -load ../../../lib/Debug/libhello.so -gcse -hello -licm --debug-pass=Structure &lt; hello.bc &gt; /dev/null
1328 Module Pass Manager
1329   Function Pass Manager
1330     Dominator Set Construction
1331     Immediate Dominators Construction
1332     Global Common Subexpression Elimination
1333 <b>--  Dominator Set Construction</b>
1334 --  Immediate Dominators Construction
1335 --  Global Common Subexpression Elimination
1336 <b>    Hello World Pass
1337 --  Hello World Pass
1338     Dominator Set Construction</b>
1339     Natural Loop Construction
1340     Loop Invariant Code Motion
1341 --  Natural Loop Construction
1342 --  Loop Invariant Code Motion
1343     Module Verifier
1344 --  Dominator Set Construction
1345 --  Module Verifier
1346   Bytecode Writer
1347 --Bytecode Writer
1348 Hello: __main
1349 Hello: puts
1350 Hello: main
1351 </pre>
1352
1353 <p>Here we see that the <a href="#basiccode">Hello World</a> pass has killed the
1354 Dominator Set pass, even though it doesn't modify the code at all!  To fix this,
1355 we need to add the following <a
1356 href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method to our pass:</p>
1357
1358 <pre>
1359     <i>// We don't modify the program, so we preserve all analyses</i>
1360     <b>virtual void</b> getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
1361       AU.setPreservesAll();
1362     }
1363 </pre>
1364
1365 <p>Now when we run our pass, we get this output:</p>
1366
1367 <pre>
1368 $ opt -load ../../../lib/Debug/libhello.so -gcse -hello -licm --debug-pass=Structure &lt; hello.bc &gt; /dev/null
1369 Pass Arguments:  -gcse -hello -licm
1370 Module Pass Manager
1371   Function Pass Manager
1372     Dominator Set Construction
1373     Immediate Dominators Construction
1374     Global Common Subexpression Elimination
1375 --  Immediate Dominators Construction
1376 --  Global Common Subexpression Elimination
1377     Hello World Pass
1378 --  Hello World Pass
1379     Natural Loop Construction
1380     Loop Invariant Code Motion
1381 --  Loop Invariant Code Motion
1382 --  Natural Loop Construction
1383     Module Verifier
1384 --  Dominator Set Construction
1385 --  Module Verifier
1386   Bytecode Writer
1387 --Bytecode Writer
1388 Hello: __main
1389 Hello: puts
1390 Hello: main
1391 </pre>
1392
1393 <p>Which shows that we don't accidentally invalidate dominator information
1394 anymore, and therefore do not have to compute it twice.</p>
1395
1396 </div>
1397
1398 <!-- _______________________________________________________________________ -->
1399 <div class="doc_subsubsection">
1400   <a name="releaseMemory">The <tt>releaseMemory</tt> method</a>
1401 </div>
1402
1403 <div class="doc_text">
1404
1405 <pre>
1406   <b>virtual void</b> releaseMemory();
1407 </pre>
1408
1409 <p>The <tt>PassManager</tt> automatically determines when to compute analysis
1410 results, and how long to keep them around for.  Because the lifetime of the pass
1411 object itself is effectively the entire duration of the compilation process, we
1412 need some way to free analysis results when they are no longer useful.  The
1413 <tt>releaseMemory</tt> virtual method is the way to do this.</p>
1414
1415 <p>If you are writing an analysis or any other pass that retains a significant
1416 amount of state (for use by another pass which "requires" your pass and uses the
1417 <a href="#getAnalysis">getAnalysis</a> method) you should implement
1418 <tt>releaseMEmory</tt> to, well, release the memory allocated to maintain this
1419 internal state.  This method is called after the <tt>run*</tt> method for the
1420 class, before the next call of <tt>run*</tt> in your pass.</p>
1421
1422 </div>
1423
1424 <!-- *********************************************************************** -->
1425 <div class="doc_section">
1426   <a name="debughints">Using GDB with dynamically loaded passes</a>
1427 </div>
1428 <!-- *********************************************************************** -->
1429
1430 <div class="doc_text">
1431
1432 <p>Unfortunately, using GDB with dynamically loaded passes is not as easy as it
1433 should be.  First of all, you can't set a breakpoint in a shared object that has
1434 not been loaded yet, and second of all there are problems with inlined functions
1435 in shared objects.  Here are some suggestions to debugging your pass with
1436 GDB.</p>
1437
1438 <p>For sake of discussion, I'm going to assume that you are debugging a
1439 transformation invoked by <tt>opt</tt>, although nothing described here depends
1440 on that.</p>
1441
1442 </div>
1443
1444 <!-- _______________________________________________________________________ -->
1445 <div class="doc_subsubsection">
1446   <a name="breakpoint">Setting a breakpoint in your pass</a>
1447 </div>
1448
1449 <div class="doc_text">
1450
1451 <p>First thing you do is start <tt>gdb</tt> on the <tt>opt</tt> process:</p>
1452
1453 <pre>
1454 $ <b>gdb opt</b>
1455 GNU gdb 5.0
1456 Copyright 2000 Free Software Foundation, Inc.
1457 GDB is free software, covered by the GNU General Public License, and you are
1458 welcome to change it and/or distribute copies of it under certain conditions.
1459 Type "show copying" to see the conditions.
1460 There is absolutely no warranty for GDB.  Type "show warranty" for details.
1461 This GDB was configured as "sparc-sun-solaris2.6"...
1462 (gdb)
1463 </pre>
1464
1465 <p>Note that <tt>opt</tt> has a lot of debugging information in it, so it takes
1466 time to load.  Be patient.  Since we cannot set a breakpoint in our pass yet
1467 (the shared object isn't loaded until runtime), we must execute the process, and
1468 have it stop before it invokes our pass, but after it has loaded the shared
1469 object.  The most foolproof way of doing this is to set a breakpoint in
1470 <tt>PassManager::run</tt> and then run the process with the arguments you
1471 want:</p>
1472
1473 <pre>
1474 (gdb) <b>break PassManager::run</b>
1475 Breakpoint 1 at 0x2413bc: file Pass.cpp, line 70.
1476 (gdb) <b>run test.bc -load $(LLVMTOP)/llvm/lib/Debug/[libname].so -[passoption]</b>
1477 Starting program: opt test.bc -load $(LLVMTOP)/llvm/lib/Debug/[libname].so -[passoption]
1478 Breakpoint 1, PassManager::run (this=0xffbef174, M=@0x70b298) at Pass.cpp:70
1479 70      bool PassManager::run(Module &amp;M) { return PM-&gt;run(M); }
1480 (gdb)
1481 </pre>
1482
1483 <p>Once the <tt>opt</tt> stops in the <tt>PassManager::run</tt> method you are
1484 now free to set breakpoints in your pass so that you can trace through execution
1485 or do other standard debugging stuff.</p>
1486
1487 </div>
1488
1489 <!-- _______________________________________________________________________ -->
1490 <div class="doc_subsubsection">
1491   <a name="debugmisc">Miscellaneous Problems</a>
1492 </div>
1493
1494 <div class="doc_text">
1495
1496 <p>Once you have the basics down, there are a couple of problems that GDB has,
1497 some with solutions, some without.</p>
1498
1499 <ul>
1500 <li>Inline functions have bogus stack information.  In general, GDB does a
1501 pretty good job getting stack traces and stepping through inline functions.
1502 When a pass is dynamically loaded however, it somehow completely loses this
1503 capability.  The only solution I know of is to de-inline a function (move it
1504 from the body of a class to a .cpp file).</li>
1505
1506 <li>Restarting the program breaks breakpoints.  After following the information
1507 above, you have succeeded in getting some breakpoints planted in your pass.  Nex
1508 thing you know, you restart the program (i.e., you type '<tt>run</tt>' again),
1509 and you start getting errors about breakpoints being unsettable.  The only way I
1510 have found to "fix" this problem is to <tt>delete</tt> the breakpoints that are
1511 already set in your pass, run the program, and re-set the breakpoints once
1512 execution stops in <tt>PassManager::run</tt>.</li>
1513
1514 </ul>
1515
1516 <p>Hopefully these tips will help with common case debugging situations.  If
1517 you'd like to contribute some tips of your own, just contact <a
1518 href="mailto:sabre@nondot.org">Chris</a>.</p>
1519
1520 </div>
1521
1522 <!-- *********************************************************************** -->
1523 <div class="doc_section">
1524   <a name="future">Future extensions planned</a>
1525 </div>
1526 <!-- *********************************************************************** -->
1527
1528 <div class="doc_text">
1529
1530 <p>Although the LLVM Pass Infrastructure is very capable as it stands, and does
1531 some nifty stuff, there are things we'd like to add in the future.  Here is
1532 where we are going:</p>
1533
1534 </div>
1535
1536 <!-- _______________________________________________________________________ -->
1537 <div class="doc_subsubsection">
1538   <a name="SMP">Multithreaded LLVM</a>
1539 </div>
1540
1541 <div class="doc_text">
1542
1543 <p>Multiple CPU machines are becoming more common and compilation can never be
1544 fast enough: obviously we should allow for a multithreaded compiler.  Because of
1545 the semantics defined for passes above (specifically they cannot maintain state
1546 across invocations of their <tt>run*</tt> methods), a nice clean way to
1547 implement a multithreaded compiler would be for the <tt>PassManager</tt> class
1548 to create multiple instances of each pass object, and allow the separate
1549 instances to be hacking on different parts of the program at the same time.</p>
1550
1551 <p>This implementation would prevent each of the passes from having to implement
1552 multithreaded constructs, requiring only the LLVM core to have locking in a few
1553 places (for global resources).  Although this is a simple extension, we simply
1554 haven't had time (or multiprocessor machines, thus a reason) to implement this.
1555 Despite that, we have kept the LLVM passes SMP ready, and you should too.</p>
1556
1557 </div>
1558
1559 <!-- _______________________________________________________________________ -->
1560 <div class="doc_subsubsection">
1561 <a name="PassFunctionPass"><tt>ModulePass</tt>es requiring <tt>FunctionPass</tt>es</a>
1562 </div>
1563
1564 <div class="doc_text">
1565
1566 <p>Currently it is illegal for a <a href="#ModulePass"><tt>ModulePass</tt></a>
1567 to require a <a href="#FunctionPass"><tt>FunctionPass</tt></a>.  This is because
1568 there is only one instance of the <a
1569 href="#FunctionPass"><tt>FunctionPass</tt></a> object ever created, thus nowhere
1570 to store information for all of the functions in the program at the same time.
1571 Although this has come up a couple of times before, this has always been worked
1572 around by factoring one big complicated pass into a global and an
1573 interprocedural part, both of which are distinct.  In the future, it would be
1574 nice to have this though.</p>
1575
1576 <p>Note that it is no problem for a <a
1577 href="#FunctionPass"><tt>FunctionPass</tt></a> to require the results of a <a
1578 href="#ModulePass"><tt>ModulePass</tt></a>, only the other way around.</p>
1579
1580 </div>
1581
1582 <!-- *********************************************************************** -->
1583 <hr>
1584 <address>
1585   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1586   src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1587   <a href="http://validator.w3.org/check/referer"><img
1588   src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /></a>
1589
1590   <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1591   <a href="http://llvm.cs.uiuc.edu">The LLVM Compiler Infrastructure</a><br>
1592   Last modified: $Date$
1593 </address>
1594
1595 </body>
1596 </html>