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