blob: 414ed1226c7623bee4786b7b804473c916c76130 [file] [log] [blame]
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2<html><head><title>Writing an LLVM Pass</title></head>
3
Chris Lattnerc6bb8242002-08-08 20:11:18 +00004<body bgcolor=white>
5
6<table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
7<tr><td>&nbsp; <font size=+3 color="#EEEEFF" face="Georgia,Palatino,Times,Roman"><b>Writing an LLVM Pass</b></font></td>
8</tr></table>
9
10
11<ol>
12 <li><a href="#introduction">Introduction - What is a pass?</a>
13 <li><a href="#quickstart">Quick Start - Writing hello world</a>
14 <ul>
15 <li><a href="#makefile">Setting up the build environment</a>
16 <li><a href="#basiccode">Basic code required</a>
17 <li><a href="#running">Running a pass with <tt>opt</tt>
18 or <tt>analyze</tt></a>
19 </ul>
20 <li><a href="#passtype">Pass classes and requirements</a>
21 <ul>
Chris Lattnerf004f9a2002-09-25 22:31:38 +000022 <li><a href="#ImmutablePass">The <tt>ImmutablePass</tt> class</a>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000023 <li><a href="#Pass">The <tt>Pass</tt> class</a>
24 <ul>
25 <li><a href="#run">The <tt>run</tt> method</a>
26 </ul>
27 <li><a href="#FunctionPass">The <tt>FunctionPass</tt> class</a>
28 <ul>
Chris Lattnerd0713f92002-09-12 17:06:43 +000029 <li><a href="#doInitialization_mod">The <tt>doInitialization(Module
30 &amp;)</tt> method</a>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000031 <li><a href="#runOnFunction">The <tt>runOnFunction</tt> method</a>
Chris Lattnerd0713f92002-09-12 17:06:43 +000032 <li><a href="#doFinalization_mod">The <tt>doFinalization(Module
33 &amp;)</tt> method</a>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000034 </ul>
35 <li><a href="#BasicBlockPass">The <tt>BasicBlockPass</tt> class</a>
36 <ul>
Chris Lattnerd0713f92002-09-12 17:06:43 +000037 <li><a href="#doInitialization_fn">The <tt>doInitialization(Function
38 &amp;)</tt> method</a>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000039 <li><a href="#runOnBasicBlock">The <tt>runOnBasicBlock</tt> method</a>
Chris Lattnerd0713f92002-09-12 17:06:43 +000040 <li><a href="#doFinalization_fn">The <tt>doFinalization(Function
41 &amp;)</tt> method</a>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000042 </ul>
Brian Gaekecab8b6f2003-07-17 18:53:20 +000043 <li><a href="#MachineFunctionPass">The <tt>MachineFunctionPass</tt>
44 class</a>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000045 </ul>
46 <li><a href="#registration">Pass Registration</a>
47 <ul>
48 <li><a href="#print">The <tt>print</tt> method</a>
49 </ul>
50 <li><a href="#interaction">Specifying interactions between passes</a>
51 <ul>
52 <li><a href="#getAnalysisUsage">The <tt>getAnalysisUsage</tt> method</a>
53 <li><a href="#getAnalysis">The <tt>getAnalysis</tt> method</a>
54 </ul>
Chris Lattner79910702002-08-22 19:21:04 +000055 <li><a href="#analysisgroup">Implementing Analysis Groups</a>
56 <ul>
57 <li><a href="#agconcepts">Analysis Group Concepts</a>
58 <li><a href="#registerag">Using <tt>RegisterAnalysisGroup</tt></a>
59 </ul>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000060 <li><a href="#passmanager">What PassManager does</a>
61 <ul>
62 <li><a href="#releaseMemory">The <tt>releaseMemory</tt> method</a>
63 </ul>
Chris Lattner480e2ef2002-09-06 02:02:58 +000064 <li><a href="#debughints">Using GDB with dynamically loaded passes</a>
65 <ul>
66 <li><a href="#breakpoint">Setting a breakpoint in your pass
67 <li><a href="#debugmisc">Miscellaneous Problems
68 </ul>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000069 <li><a href="#future">Future extensions planned</a>
70 <ul>
71 <li><a href="#SMP">Multithreaded LLVM</a>
72 <li><a href="#ModuleSource">A new <tt>ModuleSource</tt> interface</a>
73 <li><a href="#PassFunctionPass"><tt>Pass</tt>'s requiring <tt>FunctionPass</tt>'s</a>
74 </ul>
Chris Lattner38c633d2002-08-08 20:23:41 +000075
76 <p><b>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></b><p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000077</ol><p>
78
79
80
81<!-- *********************************************************************** -->
82<table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
83<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
84<a name="introduction">Introduction - What is a pass?
85</b></font></td></tr></table><ul>
86<!-- *********************************************************************** -->
87
88The LLVM Pass Framework is an important part of the LLVM system, because LLVM
89passes are where the interesting parts of the compiler exist. Passes perform
90the transformations and optimizations that make up the compiler, they build
91the analysis results that are used by these transformations, and they are, above
92all, a structuring technique for compiler code.<p>
93
94All LLVM passes are subclasses of the <tt><a
95href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">Pass</a></tt> class, which
96implement functionality by overriding virtual methods inherited from
97<tt>Pass</tt>. Depending on how your pass works, you may be able to inherit
98from the <tt><a
99href="http://llvm.cs.uiuc.edu/doxygen/structFunctionPass.html">FunctionPass</a></tt>
100or <tt><a
101href="http://llvm.cs.uiuc.edu/doxygen/structBasicBlockPass.html">BasicBlockPass</a></tt>,
102which gives the system more information about what your pass does, and how it
103can be combined with other passes. One of the main features of the LLVM Pass
104Framework is that it schedules passes to run in an efficient way based on the
105constraints that your pass has.<p>
106
107We start by showing you how to construct a pass, everything from setting up the
108code, to compiling, loading, and executing it. After the basics are down, more
109advanced features are discussed.<p>
110
111
112<!-- *********************************************************************** -->
113</ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
114<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
115<a name="quickstart">Quick Start - Writing hello world
116</b></font></td></tr></table><ul>
117<!-- *********************************************************************** -->
118
119Here we describe how to write the "hello world" of passes. The "Hello" pass is
120designed to simply print out the name of non-external functions that exist in
121the program being compiled. It does not modify the program at all, just
122inspects it. The source code and files for this pass are available in the LLVM
123source tree in the <tt>lib/Transforms/Hello</tt> directory.<p>
124
125
126<!-- ======================================================================= -->
127</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
128<tr><td>&nbsp;</td><td width="100%">&nbsp;
129<font color="#EEEEFF" face="Georgia,Palatino"><b>
130<a name="makefile">Setting up the build environment
131</b></font></td></tr></table><ul>
132
133First thing you need to do is create a new directory somewhere in the LLVM
134source base. For this example, we'll assume that you made
135"<tt>lib/Transforms/Hello</tt>". The first thing you must do is set up a build
136script (Makefile) that will compile the source code for the new pass. To do
Chris Lattnerfd214762002-09-16 22:37:56 +0000137this, copy this into "<tt>Makefile</tt>":<p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000138
139</ul><hr><ul><pre>
140# Makefile for hello pass
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000141
Chris Lattner17a4c3e2002-08-14 20:06:13 +0000142# Path to top level of LLVM heirarchy
Chris Lattner7ce83e52002-08-14 20:07:01 +0000143LEVEL = ../../..
Chris Lattner17a4c3e2002-08-14 20:06:13 +0000144
145# Name of the library to build
Chris Lattner7ce83e52002-08-14 20:07:01 +0000146LIBRARYNAME = hello
Chris Lattner17a4c3e2002-08-14 20:06:13 +0000147
148# Build a dynamically loadable shared object
149SHARED_LIBRARY = 1
150
151# Include the makefile implementation stuff
152include $(LEVEL)/Makefile.common
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000153</pre></ul><hr><ul><p>
154
155This makefile specifies that all of the <tt>.cpp</tt> files in the current
156directory are to be compiled and linked together into a
157<tt>lib/Debug/libhello.so</tt> shared object that can be dynamically loaded by
158the <tt>opt</tt> or <tt>analyze</tt> tools.<p>
159
160Now that we have the build scripts set up, we just need to write the code for
161the pass itself.<p>
162
163
164<!-- ======================================================================= -->
165</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
166<tr><td>&nbsp;</td><td width="100%">&nbsp;
167<font color="#EEEEFF" face="Georgia,Palatino"><b>
168<a name="basiccode">Basic code required
169</b></font></td></tr></table><ul>
170
171Now that we have a way to compile our new pass, we just have to write it. Start
172out with:<p>
173
174<pre>
175<b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Pass_8h-source.html">llvm/Pass.h</a>"
176<b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Function_8h-source.html">llvm/Function.h</a>"
177</pre>
178
179Which are needed because we are writing a <tt><a
180href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">Pass</a></tt>, and we are
181operating on <tt><a
182href="http://llvm.cs.uiuc.edu/doxygen/classFunction.html">Function</a></tt>'s.<p>
183
184Next we have:<p>
185
186<pre>
187<b>namespace</b> {
188</pre><p>
189
190... which starts out an anonymous namespace. Anonymous namespaces are to C++
191what the "<tt>static</tt>" keyword is to C (at global scope). It makes the
192things declared inside of the anonymous namespace only visible to the current
193file. If you're not familiar with them, consult a decent C++ book for more
194information.<p>
195
196Next, we declare our pass itself:<p>
197
198<pre>
199 <b>struct</b> Hello : <b>public</b> <a href="#FunctionPass">FunctionPass</a> {
200</pre><p>
201
202This declares a "<tt>Hello</tt>" class that is a subclass of <tt><a
203href="http://llvm.cs.uiuc.edu/doxygen/structFunctionPass.html">FunctionPass</a></tt>.
Chris Lattnerd6ea9262002-09-09 03:48:46 +0000204The different builtin pass subclasses are described in detail <a
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000205href="#passtype">later</a>, but for now, know that <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s
206operate a function at a time.<p>
207
208<pre>
209 <b>virtual bool</b> <a href="#runOnFunction">runOnFunction</a>(Function &F) {
210 std::cerr &lt;&lt; "<i>Hello: </i>" &lt;&lt; F.getName() &lt;&lt; "\n";
211 <b>return false</b>;
212 }
213 }; <i>// end of struct Hello</i>
214</pre>
215
216We declare a "<a href="#runOnFunction"><tt>runOnFunction</tt></a>" method, which
217overloads an abstract virtual method inherited from <a
218href="#FunctionPass"><tt>FunctionPass</tt></a>. This is where we are supposed
219to do our thing, so we just print out our message with the name of each
220function.<p>
221
222<pre>
223 RegisterOpt&lt;Hello&gt; X("<i>hello</i>", "<i>Hello World Pass</i>");
224} <i>// end of anonymous namespace</i>
225</pre><p>
226
227Lastly, we register our class <tt>Hello</tt>, giving it a command line argument
228"<tt>hello</tt>", and a name "<tt>Hello World Pass</tt>". There are several
229different ways of <a href="#registration">registering your pass</a>, depending
230on what it is to be used for. For "optimizations" we use the
231<tt>RegisterOpt</tt> template.<p>
232
233As a whole, the <tt>.cpp</tt> file looks like:<p>
234
235<pre>
236<b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Pass_8h-source.html">llvm/Pass.h</a>"
237<b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Function_8h-source.html">llvm/Function.h</a>"
238
239<b>namespace</b> {
240 <b>struct Hello</b> : <b>public</b> <a href="#FunctionPass">FunctionPass</a> {
241 <b>virtual bool</b> <a href="#runOnFunction">runOnFunction</a>(Function &F) {
242 std::cerr &lt;&lt; "<i>Hello: </i>" &lt;&lt; F.getName() &lt;&lt; "\n";
243 <b>return false</b>;
244 }
245 };
246
247 RegisterOpt&lt;Hello&gt; X("<i>hello</i>", "<i>Hello World Pass</i>");
248}
249</pre><p>
250
251Now that it's all together, compile the file with a simple "<tt>gmake</tt>"
252command in the local directory and you should get a new
253"<tt>lib/Debug/libhello.so</tt> file. Note that everything in this file is
254contained in an anonymous namespace: this reflects the fact that passes are self
255contained units that do not need external interfaces (although they can have
256them) to be useful.<p>
257
258
259<!-- ======================================================================= -->
260</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
261<tr><td>&nbsp;</td><td width="100%">&nbsp;
262<font color="#EEEEFF" face="Georgia,Palatino"><b>
263<a name="running">Running a pass with <tt>opt</tt> or <tt>analyze</tt>
264</b></font></td></tr></table><ul>
265
266Now that you have a brand new shiny <tt>.so</tt> file, we can use the
267<tt>opt</tt> command to run an LLVM program through your pass. Because you
268registered your pass with the <tt>RegisterOpt</tt> template, you will be able to
269use the <tt>opt</tt> tool to access it, once loaded.<p>
270
271To test it, follow the example at the end of the <a
272href="GettingStarted.html">Getting Started Guide</a> to compile "Hello World" to
273LLVM. We can now run the bytecode file (<tt>hello.bc</tt>) for the program
274through our transformation like this (or course, any bytecode file will
275work):<p>
276
277<pre>
278$ opt -load ../../../lib/Debug/libhello.so -hello &lt; hello.bc &gt; /dev/null
279Hello: __main
280Hello: puts
281Hello: main
282</pre><p>
283
284The '<tt>-load</tt>' option specifies that '<tt>opt</tt>' should load your pass
285as a shared object, which makes '<tt>-hello</tt>' a valid command line argument
286(which is one reason you need to <a href="#registration">register your
287pass</a>). Because the hello pass does not modify the program in any
288interesting way, we just throw away the result of <tt>opt</tt> (sending it to
289<tt>/dev/null</tt>).<p>
290
291To see what happened to the other string you registered, try running
292<tt>opt</tt> with the <tt>--help</tt> option:<p>
293
294<pre>
295$ opt -load ../../../lib/Debug/libhello.so --help
296OVERVIEW: llvm .bc -&gt; .bc modular optimizer
297
298USAGE: opt [options] &lt;input bytecode&gt;
299
300OPTIONS:
301 Optimizations available:
302...
303 -funcresolve - Resolve Functions
304 -gcse - Global Common Subexpression Elimination
305 -globaldce - Dead Global Elimination
306 <b>-hello - Hello World Pass</b>
307 -indvars - Cannonicalize Induction Variables
308 -inline - Function Integration/Inlining
309 -instcombine - Combine redundant instructions
310...
311</pre><p>
312
313The pass name get added as the information string for your pass, giving some
314documentation to users of <tt>opt</tt>. Now that you have a working pass, you
315would go ahead and make it do the cool transformations you want. Once you get
316it all working and tested, it may become useful to find out how fast your pass
317is. The <a href="#passManager"><tt>PassManager</tt></a> provides a nice command
318line option (<tt>--time-passes</tt>) that allows you to get information about
319the execution time of your pass along with the other passes you queue up. For
320example:<p>
321
322<pre>
323$ opt -load ../../../lib/Debug/libhello.so -hello -time-passes &lt; hello.bc &gt; /dev/null
324Hello: __main
325Hello: puts
326Hello: main
327===============================================================================
328 ... Pass execution timing report ...
329===============================================================================
330 Total Execution Time: 0.02 seconds (0.0479059 wall clock)
331
332 ---User Time--- --System Time-- --User+System-- ---Wall Time--- --- Pass Name ---
333 0.0100 (100.0%) 0.0000 ( 0.0%) 0.0100 ( 50.0%) 0.0402 ( 84.0%) Bytecode Writer
334 0.0000 ( 0.0%) 0.0100 (100.0%) 0.0100 ( 50.0%) 0.0031 ( 6.4%) Dominator Set Construction
335 0.0000 ( 0.0%) 0.0000 ( 0.0%) 0.0000 ( 0.0%) 0.0013 ( 2.7%) Module Verifier
336 <b> 0.0000 ( 0.0%) 0.0000 ( 0.0%) 0.0000 ( 0.0%) 0.0033 ( 6.9%) Hello World Pass</b>
337 0.0100 (100.0%) 0.0100 (100.0%) 0.0200 (100.0%) 0.0479 (100.0%) TOTAL
338</pre><p>
339
340As you can see, our implementation above is pretty fast :). The additional
341passes listed are automatically inserted by the '<tt>opt</tt>' tool to verify
342that the LLVM emitted by your pass is still valid and well formed LLVM, which
343hasn't been broken somehow.
344
345Now that you have seen the basics of the mechanics behind passes, we can talk
346about some more details of how they work and how to use them.<p>
347
348
349
350<!-- *********************************************************************** -->
351</ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
352<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
353<a name="passtype">Pass classes and requirements
354</b></font></td></tr></table><ul>
355<!-- *********************************************************************** -->
356
357One of the first things that you should do when designing a new pass is to
358decide what class you should subclass for your pass. The <a
359href="#basiccode">Hello World</a> example uses the <tt><a
360href="#FunctionPass">FunctionPass</a></tt> class for its implementation, but we
361did not discuss why or when this should occur. Here we talk about the classes
362available, from the most general to the most specific.<p>
363
Chris Lattner79910702002-08-22 19:21:04 +0000364When choosing a superclass for your Pass, you should choose the <b>most
365specific</b> class possible, while still being able to meet the requirements
366listed. This gives the LLVM Pass Infrastructure information neccesary to
367optimize how passes are run, so that the resultant compiler isn't unneccesarily
368slow.<p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000369
370
Chris Lattnerf004f9a2002-09-25 22:31:38 +0000371<!-- ======================================================================= -->
372</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
373<tr><td>&nbsp;</td><td width="100%">&nbsp;
374<font color="#EEEEFF" face="Georgia,Palatino"><b>
375<a name="ImmutablePass">The <tt>ImmutablePass</tt> class
376</b></font></td></tr></table><ul>
377
378The most plain and boring type of pass is the "<tt><a
379href="http://llvm.cs.uiuc.edu/doxygen/structImmutablePass.html">ImmutablePass</a></tt>"
380class. This pass type is used for passes that do not have to be run, do not
381change state, and never need to be updated. This is not a normal type of
382transformation or analysis, but can provide information about the current
383compiler configuration.<p>
384
385Although this pass class is very infrequently used, it is important for
386providing information about the current target machine being compiled for, and
387other static information that can affect the various transformations.<p>
388
389<tt>ImmutablePass</tt>'s never invalidate other transformations, are never
390invalidated, and are never "run".<p>
391
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000392
393<!-- ======================================================================= -->
394</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
395<tr><td>&nbsp;</td><td width="100%">&nbsp;
396<font color="#EEEEFF" face="Georgia,Palatino"><b>
397<a name="Pass">The <tt>Pass</tt> class
398</b></font></td></tr></table><ul>
399
400The "<tt><a href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">Pass</a></tt>"
401class is the most general of all superclasses that you can use. Deriving from
402<tt>Pass</tt> indicates that your pass uses the entire program as a unit,
403refering to function bodies in no predictable order, or adding and removing
404functions. Because nothing is known about the behavior of direct <tt>Pass</tt>
405subclasses, no optimization can be done for their execution.<p>
406
407To write a correct <tt>Pass</tt> subclass, derive from <tt>Pass</tt> and
408overload the <tt>run</tt> method with the following signature:<p>
409
410<!-- _______________________________________________________________________ -->
411</ul><h4><a name="run"><hr size=0>The <tt>run</tt> method</h4><ul>
412
413
414<pre>
415 <b>virtual bool</b> run(Module &amp;M) = 0;
416</pre><p>
417
418The <tt>run</tt> method performs the interesting work of the pass, and should
419return true if the module was modified by the transformation, false
420otherwise.<p>
421
422
423
424<!-- ======================================================================= -->
425</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
426<tr><td>&nbsp;</td><td width="100%">&nbsp;
427<font color="#EEEEFF" face="Georgia,Palatino"><b>
428<a name="FunctionPass">The <tt>FunctionPass</tt> class
429</b></font></td></tr></table><ul>
430
431In contrast to direct <tt>Pass</tt> subclasses, direct <tt><a
432href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">FunctionPass</a></tt>
433subclasses do have a predictable, local behavior that can be expected by the
434system. All <tt>FunctionPass</tt> execute on each function in the program
435independant of all of the other functions in the program.
436<tt>FunctionPass</tt>'s do not require that they are executed in a particular
437order, and <tt>FunctionPass</tt>'s do not modify external functions.<p>
438
439To be explicit, <tt>FunctionPass</tt> subclasses are not allowed to:<p>
440
441<ol>
442<li>Modify a Function other than the one currently being processed.
443<li>Add or remove Function's from the current Module.
444<li>Add or remove global variables from the current Module.
445<li>Maintain state across invocations of
446 <a href="#runOnFunction"><tt>runOnFunction</tt></a> (including global data)
447</ol><p>
448
449Implementing a <tt>FunctionPass</tt> is usually straightforward (See the <a
450href="#basiccode">Hello World</a> pass for example). <tt>FunctionPass</tt>'s
451may overload three virtual methods to do their work. All of these methods
452should return true if they modified the program, or false if they didn't.<p>
453
454<!-- _______________________________________________________________________ -->
Chris Lattnerd0713f92002-09-12 17:06:43 +0000455</ul><h4><a name="doInitialization_mod"><hr size=0>The
456<tt>doInitialization(Module &amp;)</tt> method</h4><ul>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000457
458<pre>
459 <b>virtual bool</b> doInitialization(Module &amp;M);
460</pre><p>
461
462The <tt>doIninitialize</tt> method is allowed to do most of the things that
463<tt>FunctionPass</tt>'s are not allowed to do. They can add and remove
Chris Lattnerd0713f92002-09-12 17:06:43 +0000464functions, get pointers to functions, etc. The <tt>doInitialization</tt> method
465is designed to do simple initialization type of stuff that does not depend on
466the functions being processed. The <tt>doInitialization</tt> method call is not
467scheduled to overlap with any other pass executions (thus it should be very
468fast).<p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000469
470A good example of how this method should be used is the <a
471href="http://llvm.cs.uiuc.edu/doxygen/LowerAllocations_8cpp-source.html">LowerAllocations</a>
472pass. This pass converts <tt>malloc</tt> and <tt>free</tt> instructions into
473platform dependant <tt>malloc()</tt> and <tt>free()</tt> function calls. It
474uses the <tt>doInitialization</tt> method to get a reference to the malloc and
475free functions that it needs, adding prototypes to the module if neccesary.<p>
476
477<!-- _______________________________________________________________________ -->
478</ul><h4><a name="runOnFunction"><hr size=0>The <tt>runOnFunction</tt> method</h4><ul>
479
480<pre>
481 <b>virtual bool</b> runOnFunction(Function &amp;F) = 0;
482</pre><p>
483
484The <tt>runOnFunction</tt> method must be implemented by your subclass to do the
485transformation or analysis work of your pass. As usual, a true value should be
486returned if the function is modified.<p>
487
488<!-- _______________________________________________________________________ -->
Chris Lattnerd0713f92002-09-12 17:06:43 +0000489</ul><h4><a name="doFinalization_mod"><hr size=0>The <tt>doFinalization(Module &amp;)</tt> method</h4><ul>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000490
491<pre>
492 <b>virtual bool</b> doFinalization(Module &amp;M);
Misha Brukmane3443a62003-07-14 17:05:20 +0000493</pre></p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000494
495The <tt>doFinalization</tt> method is an infrequently used method that is called
496when the pass framework has finished calling <a
497href="#runOnFunction"><tt>runOnFunction</tt></a> for every function in the
498program being compiled.<p>
499
500
501
502<!-- ======================================================================= -->
503</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
504<tr><td>&nbsp;</td><td width="100%">&nbsp;
505<font color="#EEEEFF" face="Georgia,Palatino"><b>
506<a name="BasicBlockPass">The <tt>BasicBlockPass</tt> class</a>
507</b></font></td></tr></table><ul>
508
509<tt>BasicBlockPass</tt>'s are just like <a
510href="#FunctionPass"><tt>FunctionPass</tt></a>'s, except that they must limit
511their scope of inspection and modification to a single basic block at a time.
512As such, they are <b>not</b> allowed to do any of the following:<p>
513
514<ol>
515<li>Modify or inspect any basic blocks outside of the current one
516<li>Maintain state across invocations of
517 <a href="#runOnBasicBlock"><tt>runOnBasicBlock</tt></a>
518<li>Modify the constrol flow graph (by altering terminator instructions)
519<li>Any of the things verboten for
520 <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s.
521</ol><p>
522
523<tt>BasicBlockPass</tt>'s are useful for traditional local and "peephole"
524optimizations. They may override the same <a
Chris Lattnerd0713f92002-09-12 17:06:43 +0000525href="#doInitialization_mod"><tt>doInitialization(Module &amp;)</tt></a> and <a
526href="#doFinalization_mod"><tt>doFinalization(Module &amp;)</tt></a> methods that <a
527href="#FunctionPass"><tt>FunctionPass</tt></a>'s have, but also have the following virtual methods that may also be implemented:<p>
528
529<!-- _______________________________________________________________________ -->
530</ul><h4><a name="doInitialization_fn"><hr size=0>The
531<tt>doInitialization(Function &amp;)</tt> method</h4><ul>
532
533<pre>
534 <b>virtual bool</b> doInitialization(Function &amp;F);
535</pre><p>
536
537The <tt>doIninitialize</tt> method is allowed to do most of the things that
538<tt>BasicBlockPass</tt>'s are not allowed to do, but that
539<tt>FunctionPass</tt>'s can. The <tt>doInitialization</tt> method is designed
540to do simple initialization type of stuff that does not depend on the
541BasicBlocks being processed. The <tt>doInitialization</tt> method call is not
542scheduled to overlap with any other pass executions (thus it should be very
543fast).<p>
544
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000545
546<!-- _______________________________________________________________________ -->
547</ul><h4><a name="runOnBasicBlock"><hr size=0>The <tt>runOnBasicBlock</tt> method</h4><ul>
548
549<pre>
550 <b>virtual bool</b> runOnBasicBlock(BasicBlock &amp;BB) = 0;
551</pre><p>
552
553Override this function to do the work of the <tt>BasicBlockPass</tt>. This
554function is not allowed to inspect or modify basic blocks other than the
555parameter, and are not allowed to modify the CFG. A true value must be returned
556if the basic block is modified.<p>
557
558
Chris Lattnerd0713f92002-09-12 17:06:43 +0000559<!-- _______________________________________________________________________ -->
560</ul><h4><a name="doFinalization_fn"><hr size=0>The <tt>doFinalization(Function
561&amp;)</tt> method</h4><ul>
562
563<pre>
564 <b>virtual bool</b> doFinalization(Function &amp;F);
Misha Brukmane3443a62003-07-14 17:05:20 +0000565</pre></p>
Chris Lattnerd0713f92002-09-12 17:06:43 +0000566
567The <tt>doFinalization</tt> method is an infrequently used method that is called
568when the pass framework has finished calling <a
569href="#runOnBasicBlock"><tt>runOnBasicBlock</tt></a> for every BasicBlock in the
570program being compiled. This can be used to perform per-function
571finalization.<p>
572
573
Brian Gaekecab8b6f2003-07-17 18:53:20 +0000574<!-- ======================================================================= -->
575</ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
576<tr><td>&nbsp;</td><td width="100%">&nbsp;
577<font color="#EEEEFF" face="Georgia,Palatino"><b>
578<a name="MachineFunctionPass">The <tt>MachineFunctionPass</tt> class
579</b></font></td></tr></table><ul>
580
581A <tt>MachineFunctionPass</tt> executes on the machine-dependent
582representation of each LLVM function in the program,
583independent of all of the other functions in the program.
584A <tt>MachineFunctionPass</tt> is also a <tt>FunctionPass</tt>, so all
585the restrictions that apply to a <tt>FunctionPass</tt> also apply to it.
586<tt>MachineFunctionPass</tt>es also have additional restrictions. In
587particular, <tt>MachineFunctionPass</tt>es are not allowed to do any of
588the following:
589
590<ol>
591<li>Modify any LLVM Instructions, BasicBlocks or Functions.
592<li>Modify a MachineFunction other than the one currently being processed.
593<li>Add or remove MachineFunctions from the current Module.
594<li>Add or remove global variables from the current Module.
595<li>Maintain state across invocations of
596 <a href="#runOnMachineFunction"><tt>runOnMachineFunction</tt></a> (including global data)
597</ol><p>
598
Chris Lattnerd0713f92002-09-12 17:06:43 +0000599
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000600<!-- *********************************************************************** -->
601</ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
602<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
603<a name="registration">Pass registration
604</b></font></td></tr></table><ul>
605<!-- *********************************************************************** -->
606
607In the <a href="#basiccode">Hello World</a> example pass we illustrated how pass
608registration works, and discussed some of the reasons that it is used and what
609it does. Here we discuss how and why passes are registered.<p>
610
611Passes can be registered in several different ways. Depending on the general
612classification of the pass, you should use one of the following templates to
613register the pass:<p>
614
615<ul>
616<li><b><tt>RegisterOpt</tt></b> - This template should be used when you are
617registering a pass that logically should be available for use in the
618'<tt>opt</tt>' utility.<p>
619
620<li><b><tt>RegisterAnalysis</tt></b> - This template should be used when you are
621registering a pass that logically should be available for use in the
622'<tt>analysis</tt>' utility.<p>
623
624<li><b><tt>RegisterLLC</tt></b> - This template should be used when you are
625registering a pass that logically should be available for use in the
626'<tt>llc</tt>' utility.<p>
627
628<li><b><tt>RegisterPass</tt></b> - This is the generic form of the
629<tt>Register*</tt> templates that should be used if you want your pass listed by
630multiple or no utilities. This template takes an extra third argument that
631specifies which tools it should be listed in. See the <a
632href="http://llvm.cs.uiuc.edu/doxygen/PassSupport_8h-source.html">PassSupport.h</a>
633file for more information.<p>
634</ul><p>
635
636Regardless of how you register your pass, you must specify at least two
637parameters. The first parameter is the name of the pass that is to be used on
638the command line to specify that the pass should be added to a program (for
639example <tt>opt</tt> or <tt>analyze</tt>). The second argument is the name of
640the pass, which is to be used for the <tt>--help</tt> output of programs, as
641well as for debug output generated by the <tt>--debug-pass</tt> option.<p>
642
643If you pass is constructed by its default constructor, you only ever have to
644pass these two arguments. If, on the other hand, you require other information
645(like target specific information), you must pass an additional argument. This
646argument is a pointer to a function used to create the pass. For an example of
647how this works, look at the <a
648href="http://llvm.cs.uiuc.edu/doxygen/LowerAllocations_8cpp-source.html">LowerAllocations.cpp</a>
649file.<p>
650
651If a pass is registered to be used by the <tt>analyze</tt> utility, you should
652implement the virtual <tt>print</tt> method:<p>
653
654<!-- _______________________________________________________________________ -->
655</ul><h4><a name="print"><hr size=0>The <tt>print</tt> method</h4><ul>
656
657<pre>
658 <b>virtual void</b> print(std::ostream &amp;O, <b>const</b> Module *M) <b>const</b>;
659</pre><p>
660
661The <tt>print</tt> method must be implemented by "analyses" in order to print a
662human readable version of the analysis results. This is useful for debugging an
663analysis itself, as well as for other people to figure out how an analysis
664works. The <tt>analyze</tt> tool uses this method to generate its output.<p>
665
666The <tt>ostream</tt> parameter specifies the stream to write the results on, and
667the <tt>Module</tt> parameter gives a pointer to the top level module of the
668program that has been analyzed. Note however that this pointer may be null in
669certain circumstances (such as calling the <tt>Pass::dump()</tt> from a
670debugger), so it should only be used to enhance debug output, it should not be
671depended on.<p>
672
673
674<!-- *********************************************************************** -->
675</ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
676<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
677<a name="interaction">Specifying interactions between passes
678</b></font></td></tr></table><ul>
679<!-- *********************************************************************** -->
680
681One of the main responsibilities of the <tt>PassManager</tt> is the make sure
682that passes interact with each other correctly. Because <tt>PassManager</tt>
683tries to <a href="#passmanager">optimize the execution of passes</a> it must
684know how the passes interact with each other and what dependencies exist between
685the various passes. To track this, each pass can declare the set of passes that
686are required to be executed before the current pass, and the passes which are
687invalidated by the current pass.<p>
688
689Typically this functionality is used to require that analysis results are
690computed before your pass is run. Running arbitrary transformation passes can
691invalidate the computed analysis results, which is what the invalidation set
692specifies. If a pass does not implement the <tt><a
693href="#getAnalysisUsage">getAnalysisUsage</a></tt> method, it defaults to not
694having any prerequisite passes, and invalidating <b>all</b> other passes.<p>
695
696
697<!-- _______________________________________________________________________ -->
698</ul><h4><a name="getAnalysisUsage"><hr size=0>The <tt>getAnalysisUsage</tt> method</h4><ul>
699
700<pre>
701 <b>virtual void</b> getAnalysisUsage(AnalysisUsage &amp;Info) <b>const</b>;
702</pre><p>
703
704By implementing the <tt>getAnalysisUsage</tt> method, the required and
705invalidated sets may be specified for your transformation. The implementation
706should fill in the <tt><a
707href="http://llvm.cs.uiuc.edu/doxygen/classAnalysisUsage.html">AnalysisUsage</a></tt>
708object with information about which passes are required and not invalidated. To do this, the following set methods are provided by the <tt><a
709href="http://llvm.cs.uiuc.edu/doxygen/classAnalysisUsage.html">AnalysisUsage</a></tt> class:<p>
710
711<pre>
712 <i>// addRequires - Add the specified pass to the required set for your pass.</i>
713 <b>template</b>&lt;<b>class</b> PassClass&gt;
714 AnalysisUsage &amp;AnalysisUsage::addRequired();
715
716 <i>// addPreserved - Add the specified pass to the set of analyses preserved by
717 // this pass</i>
718 <b>template</b>&lt;<b>class</b> PassClass&gt;
719 AnalysisUsage &amp;AnalysisUsage::addPreserved();
720
721 <i>// setPreservesAll - Call this if the pass does not modify its input at all</i>
722 <b>void</b> AnalysisUsage::setPreservesAll();
723
Chris Lattner8291e042002-10-21 19:57:59 +0000724 <i>// setPreservesCFG - This function should be called by the pass, iff they do not:
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000725 //
726 // 1. Add or remove basic blocks from the function
727 // 2. Modify terminator instructions in any way.
728 //
729 // This is automatically implied for <a href="#BasicBlockPass">BasicBlockPass</a>'s
730 //</i>
Chris Lattner8291e042002-10-21 19:57:59 +0000731 <b>void</b> AnalysisUsage::setPreservesCFG();
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000732</pre><p>
733
734Some examples of how to use these methods are:<p>
735
736<pre>
737 <i>// This is an example implementation from an analysis, which does not modify
738 // the program at all, yet has a prerequisite.</i>
739 <b>void</b> <a href="http://llvm.cs.uiuc.edu/doxygen/structPostDominanceFrontier.html">PostDominanceFrontier</a>::getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
740 AU.setPreservesAll();
741 AU.addRequired&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structPostDominatorTree.html">PostDominatorTree</a>&gt;();
742 }
743</pre><p>
744
745and:<p>
746
747<pre>
748 <i>// This example modifies the program, but does not modify the CFG</i>
749 <b>void</b> <a href="http://llvm.cs.uiuc.edu/doxygen/structLICM.html">LICM</a>::getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
Chris Lattner8291e042002-10-21 19:57:59 +0000750 AU.setPreservesCFG();
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000751 AU.addRequired&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/classLoopInfo.html">LoopInfo</a>&gt;();
752 }
753</pre><p>
754
755<!-- _______________________________________________________________________ -->
756</ul><h4><a name="getAnalysis"><hr size=0>The <tt>getAnalysis&lt;&gt;</tt> method</h4><ul>
757
758The <tt>Pass::getAnalysis&lt;&gt;</tt> method is inherited by your class,
759providing you with access to the passes that you declared that you required with
760the <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method. It takes
761a single template argument that specifies which pass class you want, and returns
762a reference to that pass.<p>
763
764<pre>
765 <b>template</b>&lt;<b>typename</b> PassClass&gt;
766 AnalysisType &amp;getAnalysis();
767</pre><p>
768
769This method call returns a reference to the pass desired. You may get a runtime
770assertion failure if you attempt to get an analysis that you did not declare as
771required in your <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a>
772implementation. This method can be called by your <tt>run*</tt> method
773implementation, or by any other local method invoked by your <tt>run*</tt>
774method.<p>
775
Chris Lattner79910702002-08-22 19:21:04 +0000776<!-- *********************************************************************** -->
777</ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
778<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
779<a name="analysisgroup">Implementing Analysis Groups
780</b></font></td></tr></table><ul>
781<!-- *********************************************************************** -->
782
783Now that we understand the basics of how passes are defined, how the are used,
784and how they are required from other passes, it's time to get a little bit
785fancier. All of the pass relationships that we have seen so far are very
786simple: one pass depends on one other specific pass to be run before it can run.
787For many applications, this is great, for others, more flexibility is
788required.<p>
789
790In particular, some analyses are defined such that there is a single simple
791interface to the analysis results, but multiple ways of calculating them.
792Consider alias analysis for example. The most trivial alias analysis returns
793"may alias" for any alias query. The most sophisticated analysis a
794flow-sensitive, context-sensitive interprocedural analysis that can take a
795significant amount of time to execute (and obviously, there is a lot of room
796between these two extremes for other implementations). To cleanly support
797situations like this, the LLVM Pass Infrastructure supports the notion of
798Analysis Groups.<p>
799
800<!-- _______________________________________________________________________ -->
801</ul><h4><a name="agconcepts"><hr size=0>Analysis Group Concepts</h4><ul>
802
803An Analysis Group is a single simple interface that may be implemented by
804multiple different passes. Analysis Groups can be given human readable names
805just like passes, but unlike passes, they need not derive from the <tt>Pass</tt>
806class. An analysis group may have one or more implementations, one of which is
807the "default" implementation.<p>
808
809Analysis groups are used by client passes just like other passes are: the
810<tt>AnalysisUsage::addRequired()</tt> and <tt>Pass::getAnalysis()</tt> methods.
811In order to resolve this requirement, the <a href="#passmanager">PassManager</a>
812scans the available passes to see if any implementations of the analysis group
813are available. If none is available, the default implementation is created for
814the pass to use. All standard rules for <A href="#interaction">interaction
815between passes</a> still apply.<p>
816
817Although <a href="#registration">Pass Registration</a> is optional for normal
818passes, all analysis group implementations must be registered, and must use the
819<A href="#registerag"><tt>RegisterAnalysisGroup</tt></a> template to join the
820implementation pool. Also, a default implementation of the interface
821<b>must</b> be registered with <A
822href="#registerag"><tt>RegisterAnalysisGroup</tt></a>.<p>
823
824As a concrete example of an Analysis Group in action, consider the <a
825href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a>
826analysis group. The default implementation of the alias analysis interface (the
827<tt><a
828href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">basicaa</a></tt>
829pass) just does a few simple checks that don't require significant analysis to
830compute (such as: two different globals can never alias each other, etc).
831Passes that use the <tt><a
832href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a></tt>
833interface (for example the <tt><a
834href="http://llvm.cs.uiuc.edu/doxygen/classGCSE.html">gcse</a></tt> pass), do not care which implementation
835of alias analysis is actually provided, they just use the designated
836interface.<p>
837
838From the user's perspective, commands work just like normal. Issuing the
839command '<tt>opt -gcse ...</tt>' will cause the <tt>basicaa</tt> class to be
840instantiated and added to the pass sequence. Issuing the command '<tt>opt
841-somefancyaa -gcse ...</tt>' will cause the <tt>gcse</tt> pass to use the
842<tt>somefancyaa</tt> alias analysis (which doesn't actually exist, it's just a
843hypothetical example) instead.<p>
844
845
846<!-- _______________________________________________________________________ -->
847</ul><h4><a name="registerag"><hr size=0>Using <tt>RegisterAnalysisGroup</tt></h4><ul>
848
849The <tt>RegisterAnalysisGroup</tt> template is used to register the analysis
850group itself as well as add pass implementations to the analysis group. First,
851an analysis should be registered, with a human readable name provided for it.
852Unlike registration of passes, there is no command line argument to be specified
853for the Analysis Group Interface itself, because it is "abstract":<p>
854
855<pre>
856 <b>static</b> RegisterAnalysisGroup&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a>&gt; A("<i>Alias Analysis</i>");
857</pre><p>
858
859Once the analysis is registered, passes can declare that they are valid
860implementations of the interface by using the following code:<p>
861
862<pre>
863<b>namespace</b> {
864 //<i> Analysis Group implementations <b>must</b> be registered normally...</i>
865 RegisterOpt&lt;FancyAA&gt;
866 B("<i>somefancyaa</i>", "<i>A more complex alias analysis implementation</i>");
867
868 //<i> Declare that we implement the AliasAnalysis interface</i>
869 RegisterAnalysisGroup&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a>, FancyAA&gt; C;
870}
871</pre><p>
872
873This just shows a class <tt>FancyAA</tt> that is registered normally, then uses
874the <tt>RegisterAnalysisGroup</tt> template to "join" the <tt><a
875href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a></tt>
876analysis group. Every implementation of an analysis group should join using
877this template. A single pass may join multiple different analysis groups with
878no problem.<p>
879
880<pre>
881<b>namespace</b> {
882 //<i> Analysis Group implementations <b>must</b> be registered normally...</i>
883 RegisterOpt&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a>&gt;
884 D("<i>basicaa</i>", "<i>Basic Alias Analysis (default AA impl)</i>");
885
886 //<i> Declare that we implement the AliasAnalysis interface</i>
887 RegisterAnalysisGroup&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a>, <a href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a>, <b>true</b>&gt; E;
888}
889</pre><p>
890
891Here we show how the default implementation is specified (using the extra
892argument to the <tt>RegisterAnalysisGroup</tt> template). There must be exactly
893one default implementation available at all times for an Analysis Group to be
894used. Here we declare that the <tt><a
895href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a></tt>
896pass is the default implementation for the interface.<p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000897
898
899<!-- *********************************************************************** -->
900</ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
901<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
902<a name="passmanager">What PassManager does
903</b></font></td></tr></table><ul>
904<!-- *********************************************************************** -->
905
906The <a
907href="http://llvm.cs.uiuc.edu/doxygen/PassManager_8h-source.html"><tt>PassManager</tt></a>
908<a href="http://llvm.cs.uiuc.edu/doxygen/classPassManager.html">class</a> takes
909a list of passes, ensures their <a href="#interaction">prerequisites</a> are set
910up correctly, and then schedules passes to run efficiently. All of the LLVM
911tools that run passes use the <tt>PassManager</tt> for execution of these
912passes.<p>
913
914The <tt>PassManager</tt> does two main things to try to reduce the execution
915time of a series of passes:<p>
916
917<ol>
918<li><b>Share analysis results</b> - The PassManager attempts to avoid
919recomputing analysis results as much as possible. This means keeping track of
920which analyses are available already, which analyses get invalidated, and which
921analyses are needed to be run for a pass. An important part of work is that the
922<tt>PassManager</tt> tracks the exact lifetime of all analysis results, allowing
923it to <a href="#releaseMemory">free memory</a> allocated to holding analysis
924results as soon as they are no longer needed.<p>
925
926<li><b>Pipeline the execution of passes on the program</b> - The
927<tt>PassManager</tt> attempts to get better cache and memory usage behavior out
928of a series of passes by pipelining the passes together. This means that, given
929a series of consequtive <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s, it
930will execute all of the <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s on
931the first function, then all of the <a
932href="#FunctionPass"><tt>FunctionPass</tt></a>'s on the second function,
933etc... until the entire program has been run through the passes.<p>
934
935This improves the cache behavior of the compiler, because it is only touching
936the LLVM program representation for a single function at a time, instead of
937traversing the entire program. It reduces the memory consumption of compiler,
938because, for example, only one <a
939href="http://llvm.cs.uiuc.edu/doxygen/structDominatorSet.html"><tt>DominatorSet</tt></a>
940needs to be calculated at a time. This also makes it possible some <a
941href="#SMP">interesting enhancements</a> in the future.<p>
942
943</ol><p>
944
945The effectiveness of the <tt>PassManager</tt> is influenced directly by how much
946information it has about the behaviors of the passes it is scheduling. For
947example, the "preserved" set is intentionally conservative in the face of an
948unimplemented <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method.
949Not implementing when it should be implemented will have the effect of not
950allowing any analysis results to live across the execution of your pass.<p>
951
952The <tt>PassManager</tt> class exposes a <tt>--debug-pass</tt> command line
953options that is useful for debugging pass execution, seeing how things work, and
954diagnosing when you should be preserving more analyses than you currently are
955(To get information about all of the variants of the <tt>--debug-pass</tt>
956option, just type '<tt>opt --help-hidden</tt>').<p>
957
958By using the <tt>--debug-pass=Structure</tt> option, for example, we can see how
959our <a href="#basiccode">Hello World</a> pass interacts with other passes. Lets
960try it out with the <tt>gcse</tt> and <tt>licm</tt> passes:<p>
961
962<pre>
963$ opt -load ../../../lib/Debug/libhello.so -gcse -licm --debug-pass=Structure &lt; hello.bc &gt; /dev/null
964Module Pass Manager
965 Function Pass Manager
966 Dominator Set Construction
967 Immediate Dominators Construction
968 Global Common Subexpression Elimination
969-- Immediate Dominators Construction
970-- Global Common Subexpression Elimination
971 Natural Loop Construction
972 Loop Invariant Code Motion
973-- Natural Loop Construction
974-- Loop Invariant Code Motion
975 Module Verifier
976-- Dominator Set Construction
977-- Module Verifier
978 Bytecode Writer
979--Bytecode Writer
980</pre><p>
981
982This output shows us when passes are constructed and when the analysis results
983are known to be dead (prefixed with '<tt>--</tt>'). Here we see that GCSE uses
984dominator and immediate dominator information to do its job. The LICM pass uses
985natural loop information, which uses dominator sets, but not immediate
986dominators. Because immediate dominators are no longer useful after the GCSE
987pass, it is immediately destroyed. The dominator sets are then reused to
988compute natural loop information, which is then used by the LICM pass.<p>
989
990After the LICM pass, the module verifier runs (which is automatically added by
991the '<tt>opt</tt>' tool), which uses the dominator set to check that the
992resultant LLVM code is well formed. After it finishes, the dominator set
993information is destroyed, after being computed once, and shared by three
994passes.<p>
995
996Lets see how this changes when we run the <a href="#basiccode">Hello World</a>
997pass in between the two passes:<p>
998
999<pre>
1000$ opt -load ../../../lib/Debug/libhello.so -gcse -hello -licm --debug-pass=Structure &lt; hello.bc &gt; /dev/null
1001Module Pass Manager
1002 Function Pass Manager
1003 Dominator Set Construction
1004 Immediate Dominators Construction
1005 Global Common Subexpression Elimination
1006<b>-- Dominator Set Construction</b>
1007-- Immediate Dominators Construction
1008-- Global Common Subexpression Elimination
1009<b> Hello World Pass
1010-- Hello World Pass
1011 Dominator Set Construction</b>
1012 Natural Loop Construction
1013 Loop Invariant Code Motion
1014-- Natural Loop Construction
1015-- Loop Invariant Code Motion
1016 Module Verifier
1017-- Dominator Set Construction
1018-- Module Verifier
1019 Bytecode Writer
1020--Bytecode Writer
1021Hello: __main
1022Hello: puts
1023Hello: main
1024</pre><p>
1025
1026Here we see that the <a href="#basiccode">Hello World</a> pass has killed the
1027Dominator Set pass, even though it doesn't modify the code at all! To fix this,
1028we need to add the following <a
1029href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method to our pass:<p>
1030
1031<pre>
1032 <i>// We don't modify the program, so we preserve all analyses</i>
1033 <b>virtual void</b> getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
1034 AU.setPreservesAll();
1035 }
1036</pre><p>
1037
1038Now when we run our pass, we get this output:<p>
1039
1040<pre>
1041$ opt -load ../../../lib/Debug/libhello.so -gcse -hello -licm --debug-pass=Structure < hello.bc > /dev/null
1042Pass Arguments: -gcse -hello -licm
1043Module Pass Manager
1044 Function Pass Manager
1045 Dominator Set Construction
1046 Immediate Dominators Construction
1047 Global Common Subexpression Elimination
1048-- Immediate Dominators Construction
1049-- Global Common Subexpression Elimination
1050 Hello World Pass
1051-- Hello World Pass
1052 Natural Loop Construction
1053 Loop Invariant Code Motion
1054-- Loop Invariant Code Motion
1055-- Natural Loop Construction
1056 Module Verifier
1057-- Dominator Set Construction
1058-- Module Verifier
1059 Bytecode Writer
1060--Bytecode Writer
1061Hello: __main
1062Hello: puts
1063Hello: main
1064</pre><p>
1065
1066Which shows that we don't accidentally invalidate dominator information
1067anymore, and therefore do not have to compute it twice.<p>
1068
1069
1070<!-- _______________________________________________________________________ -->
1071</ul><h4><a name="releaseMemory"><hr size=0>The <tt>releaseMemory</tt> method</h4><ul>
1072
1073<pre>
1074 <b>virtual void</b> releaseMemory();
1075</pre><p>
1076
1077The <tt>PassManager</tt> automatically determines when to compute analysis
1078results, and how long to keep them around for. Because the lifetime of the pass
1079object itself is effectively the entire duration of the compilation process, we
1080need some way to free analysis results when they are no longer useful. The
1081<tt>releaseMemory</tt> virtual method is the way to do this.<p>
1082
1083If you are writing an analysis or any other pass that retains a significant
1084amount of state (for use by another pass which "requires" your pass and uses the
1085<a href="#getAnalysis">getAnalysis</a> method) you should implement
1086<tt>releaseMEmory</tt> to, well, release the memory allocated to maintain this
1087internal state. This method is called after the <tt>run*</tt> method for the
1088class, before the next call of <tt>run*</tt> in your pass.<p>
1089
1090
1091<!-- *********************************************************************** -->
1092</ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
1093<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
Chris Lattner480e2ef2002-09-06 02:02:58 +00001094<a name="debughints">Using GDB with dynamically loaded passes
1095</b></font></td></tr></table><ul>
1096<!-- *********************************************************************** -->
1097
1098Unfortunately, using GDB with dynamically loaded passes is not as easy as it
1099should be. First of all, you can't set a breakpoint in a shared object that has
1100not been loaded yet, and second of all there are problems with inlined functions
1101in shared objects. Here are some suggestions to debugging your pass with
1102GDB.<p>
1103
1104For sake of discussion, I'm going to assume that you are debugging a
1105transformation invoked by <tt>opt</tt>, although nothing described here depends
1106on that.<p>
1107
1108<!-- _______________________________________________________________________ -->
1109</ul><h4><a name="breakpoint"><hr size=0>Setting a breakpoint in your pass</h4><ul>
1110
1111First thing you do is start <tt>gdb</tt> on the <tt>opt</tt> process:<p>
1112
1113<pre>
1114$ <b>gdb opt</b>
1115GNU gdb 5.0
1116Copyright 2000 Free Software Foundation, Inc.
1117GDB is free software, covered by the GNU General Public License, and you are
1118welcome to change it and/or distribute copies of it under certain conditions.
1119Type "show copying" to see the conditions.
1120There is absolutely no warranty for GDB. Type "show warranty" for details.
1121This GDB was configured as "sparc-sun-solaris2.6"...
1122(gdb)
1123</pre><p>
1124
1125Note that <tt>opt</tt> has a lot of debugging information in it, so it takes
1126time to load. Be patient. Since we cannot set a breakpoint in our pass yet
1127(the shared object isn't loaded until runtime), we must execute the process, and
1128have it stop before it invokes our pass, but after it has loaded the shared
1129object. The most foolproof way of doing this is to set a breakpoint in
1130<tt>PassManager::run</tt> and then run the process with the arguments you
1131want:<p>
1132
1133<pre>
1134(gdb) <b>break PassManager::run</b>
1135Breakpoint 1 at 0x2413bc: file Pass.cpp, line 70.
1136(gdb) <b>run test.bc -load /shared/lattner/cvs/llvm/lib/Debug/[libname].so -[passoption]</b>
1137Starting program: /shared/lattner/cvs/llvm/tools/Debug/opt test.bc
1138 -load /shared/lattner/cvs/llvm/lib/Debug/[libname].so -[passoption]
1139Breakpoint 1, PassManager::run (this=0xffbef174, M=@0x70b298) at Pass.cpp:70
114070 bool PassManager::run(Module &amp;M) { return PM-&gt;run(M); }
1141(gdb)
1142</pre></p>
1143
1144Once the <tt>opt</tt> stops in the <tt>PassManager::run</tt> method you are now
1145free to set breakpoints in your pass so that you can trace through execution or
1146do other standard debugging stuff.<p>
1147
1148
1149<!-- _______________________________________________________________________ -->
1150</ul><h4><a name="debugmisc"><hr size=0>Miscellaneous Problems</h4><ul>
1151
1152Once you have the basics down, there are a couple of problems that GDB has, some
1153with solutions, some without.<p>
1154
1155<ul>
1156<li>Inline functions have bogus stack information. In general, GDB does a
1157pretty good job getting stack traces and stepping through inline functions.
1158When a pass is dynamically loaded however, it somehow completely loses this
1159capability. The only solution I know of is to de-inline a function (move it
1160from the body of a class to a .cpp file).<p>
1161
1162<li>Restarting the program breaks breakpoints. After following the information
1163above, you have succeeded in getting some breakpoints planted in your pass. Nex
1164thing you know, you restart the program (i.e., you type '<tt>run</tt>' again),
1165and you start getting errors about breakpoints being unsettable. The only way I
1166have found to "fix" this problem is to <tt>delete</tt> the breakpoints that are
1167already set in your pass, run the program, and re-set the breakpoints once
1168execution stops in <tt>PassManager::run</tt>.<p>
1169
1170</ul>
1171
1172Hopefully these tips will help with common case debugging situations. If you'd
1173like to contribute some tips of your own, just contact <a
1174href="mailto:sabre@nondot.org">Chris</a>.<p>
1175
1176
1177<!-- *********************************************************************** -->
1178</ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
1179<tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001180<a name="future">Future extensions planned
1181</b></font></td></tr></table><ul>
1182<!-- *********************************************************************** -->
1183
1184Although the LLVM Pass Infrastructure is very capable as it stands, and does
1185some nifty stuff, there are things we'd like to add in the future. Here is
1186where we are going:<p>
1187
1188<!-- _______________________________________________________________________ -->
1189</ul><h4><a name="SMP"><hr size=0>Multithreaded LLVM</h4><ul>
1190
Chris Lattnered2e7a92002-09-17 16:47:06 +00001191Multiple CPU machines are becoming more common and compilation can never be
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001192fast enough: obviously we should allow for a multithreaded compiler. Because of
1193the semantics defined for passes above (specifically they cannot maintain state
1194across invocations of their <tt>run*</tt> methods), a nice clean way to
1195implement a multithreaded compiler would be for the <tt>PassManager</tt> class
Misha Brukmanbc0e9982003-07-14 17:20:40 +00001196to create multiple instances of each pass object, and allow the separate
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001197instances to be hacking on different parts of the program at the same time.<p>
1198
1199This implementation would prevent each of the passes from having to implement
1200multithreaded constructs, requiring only the LLVM core to have locking in a few
1201places (for global resources). Although this is a simple extension, we simply
1202haven't had time (or multiprocessor machines, thus a reason) to implement this.
1203Despite that, we have kept the LLVM passes SMP ready, and you should too.<p>
1204
1205
1206<!-- _______________________________________________________________________ -->
1207</ul><h4><a name="ModuleSource"><hr size=0>A new <tt>ModuleSource</tt> interface</h4><ul>
1208
1209Currently, the <tt>PassManager</tt>'s <tt>run</tt> method takes a <tt><a
1210href="http://llvm.cs.uiuc.edu/doxygen/classModule.html">Module</a></tt> as
1211input, and runs all of the passes on this module. The problem with this
1212approach is that none of the <tt>PassManager</tt> features can be used for
1213timing and debugging the actual <b>loading</b> of the module from disk or
1214standard input.<p>
1215
1216To solve this problem, eventually the <tt>PassManger</tt> class will accept a
1217<tt>ModuleSource</tt> object instead of a Module itself. When complete, this
1218will also allow for streaming of functions out of the bytecode representation,
1219allowing us to avoid holding the entire program in memory at once if we only are
1220dealing with <a href="#FunctionPass">FunctionPass</a>'s.<p>
1221
1222As part of a different issue, eventually the bytecode loader will be extended to
1223allow on-demand loading of functions from the bytecode representation, in order
1224to better support the runtime reoptimizer. The bytecode format is already
1225capable of this, the loader just needs to be reworked a bit.<p>
1226
1227
1228<!-- _______________________________________________________________________ -->
1229</ul><h4><a name="PassFunctionPass"><hr size=0><tt>Pass</tt>'s requiring <tt>FunctionPass</tt>'s</h4><ul>
1230
1231Currently it is illegal for a <a href="#Pass"><tt>Pass</tt></a> to require a <a
1232href="#FunctionPass"><tt>FunctionPass</tt></a>. This is because there is only
1233one instance of the <a href="#FunctionPass"><tt>FunctionPass</tt></a> object
1234ever created, thus nowhere to store information for all of the functions in the
1235program at the same time. Although this has come up a couple of times before,
1236this has always been worked around by factoring one big complicated pass into a
1237global and an interprocedural part, both of which are distinct. In the future,
1238it would be nice to have this though.<p>
1239
1240Note that it is no problem for a <a
1241href="#FunctionPass"><tt>FunctionPass</tt></a> to require the results of a <a
1242href="#Pass"><tt>Pass</tt></a>, only the other way around.<p>
1243
1244
1245<!-- *********************************************************************** -->
1246</ul>
1247<!-- *********************************************************************** -->
1248
1249<hr><font size-1>
Chris Lattner480e2ef2002-09-06 02:02:58 +00001250<address><a href="mailto:sabre@nondot.org">Chris Lattner</a></address>
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001251<!-- Created: Tue Aug 6 15:00:33 CDT 2002 -->
1252<!-- hhmts start -->
Misha Brukmanbc0e9982003-07-14 17:20:40 +00001253Last modified: Mon Jul 14 12:12:53 CDT 2003
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001254<!-- hhmts end -->
1255</font></body></html>