xref: /aosp_15_r20/external/llvm/docs/WritingAnLLVMPass.rst (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker====================
2*9880d681SAndroid Build Coastguard WorkerWriting an LLVM Pass
3*9880d681SAndroid Build Coastguard Worker====================
4*9880d681SAndroid Build Coastguard Worker
5*9880d681SAndroid Build Coastguard Worker.. contents::
6*9880d681SAndroid Build Coastguard Worker    :local:
7*9880d681SAndroid Build Coastguard Worker
8*9880d681SAndroid Build Coastguard WorkerIntroduction --- What is a pass?
9*9880d681SAndroid Build Coastguard Worker================================
10*9880d681SAndroid Build Coastguard Worker
11*9880d681SAndroid Build Coastguard WorkerThe LLVM Pass Framework is an important part of the LLVM system, because LLVM
12*9880d681SAndroid Build Coastguard Workerpasses are where most of the interesting parts of the compiler exist.  Passes
13*9880d681SAndroid Build Coastguard Workerperform the transformations and optimizations that make up the compiler, they
14*9880d681SAndroid Build Coastguard Workerbuild the analysis results that are used by these transformations, and they
15*9880d681SAndroid Build Coastguard Workerare, above all, a structuring technique for compiler code.
16*9880d681SAndroid Build Coastguard Worker
17*9880d681SAndroid Build Coastguard WorkerAll LLVM passes are subclasses of the `Pass
18*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/classllvm_1_1Pass.html>`_ class, which implement
19*9880d681SAndroid Build Coastguard Workerfunctionality by overriding virtual methods inherited from ``Pass``.  Depending
20*9880d681SAndroid Build Coastguard Workeron how your pass works, you should inherit from the :ref:`ModulePass
21*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-ModulePass>` , :ref:`CallGraphSCCPass
22*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-CallGraphSCCPass>`, :ref:`FunctionPass
23*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-FunctionPass>` , or :ref:`LoopPass
24*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-LoopPass>`, or :ref:`RegionPass
25*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-RegionPass>`, or :ref:`BasicBlockPass
26*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-BasicBlockPass>` classes, which gives the system more
27*9880d681SAndroid Build Coastguard Workerinformation about what your pass does, and how it can be combined with other
28*9880d681SAndroid Build Coastguard Workerpasses.  One of the main features of the LLVM Pass Framework is that it
29*9880d681SAndroid Build Coastguard Workerschedules passes to run in an efficient way based on the constraints that your
30*9880d681SAndroid Build Coastguard Workerpass meets (which are indicated by which class they derive from).
31*9880d681SAndroid Build Coastguard Worker
32*9880d681SAndroid Build Coastguard WorkerWe start by showing you how to construct a pass, everything from setting up the
33*9880d681SAndroid Build Coastguard Workercode, to compiling, loading, and executing it.  After the basics are down, more
34*9880d681SAndroid Build Coastguard Workeradvanced features are discussed.
35*9880d681SAndroid Build Coastguard Worker
36*9880d681SAndroid Build Coastguard WorkerQuick Start --- Writing hello world
37*9880d681SAndroid Build Coastguard Worker===================================
38*9880d681SAndroid Build Coastguard Worker
39*9880d681SAndroid Build Coastguard WorkerHere we describe how to write the "hello world" of passes.  The "Hello" pass is
40*9880d681SAndroid Build Coastguard Workerdesigned to simply print out the name of non-external functions that exist in
41*9880d681SAndroid Build Coastguard Workerthe program being compiled.  It does not modify the program at all, it just
42*9880d681SAndroid Build Coastguard Workerinspects it.  The source code and files for this pass are available in the LLVM
43*9880d681SAndroid Build Coastguard Workersource tree in the ``lib/Transforms/Hello`` directory.
44*9880d681SAndroid Build Coastguard Worker
45*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-makefile:
46*9880d681SAndroid Build Coastguard Worker
47*9880d681SAndroid Build Coastguard WorkerSetting up the build environment
48*9880d681SAndroid Build Coastguard Worker--------------------------------
49*9880d681SAndroid Build Coastguard Worker
50*9880d681SAndroid Build Coastguard WorkerFirst, configure and build LLVM.  Next, you need to create a new directory
51*9880d681SAndroid Build Coastguard Workersomewhere in the LLVM source base.  For this example, we'll assume that you
52*9880d681SAndroid Build Coastguard Workermade ``lib/Transforms/Hello``.  Finally, you must set up a build script
53*9880d681SAndroid Build Coastguard Worker(``Makefile``) that will compile the source code for the new pass.  To do this,
54*9880d681SAndroid Build Coastguard Workercopy the following into ``Makefile``:
55*9880d681SAndroid Build Coastguard Worker
56*9880d681SAndroid Build Coastguard Worker.. code-block:: make
57*9880d681SAndroid Build Coastguard Worker
58*9880d681SAndroid Build Coastguard Worker    # Makefile for hello pass
59*9880d681SAndroid Build Coastguard Worker
60*9880d681SAndroid Build Coastguard Worker    # Path to top level of LLVM hierarchy
61*9880d681SAndroid Build Coastguard Worker    LEVEL = ../../..
62*9880d681SAndroid Build Coastguard Worker
63*9880d681SAndroid Build Coastguard Worker    # Name of the library to build
64*9880d681SAndroid Build Coastguard Worker    LIBRARYNAME = Hello
65*9880d681SAndroid Build Coastguard Worker
66*9880d681SAndroid Build Coastguard Worker    # Make the shared library become a loadable module so the tools can
67*9880d681SAndroid Build Coastguard Worker    # dlopen/dlsym on the resulting library.
68*9880d681SAndroid Build Coastguard Worker    LOADABLE_MODULE = 1
69*9880d681SAndroid Build Coastguard Worker
70*9880d681SAndroid Build Coastguard Worker    # Include the makefile implementation stuff
71*9880d681SAndroid Build Coastguard Worker    include $(LEVEL)/Makefile.common
72*9880d681SAndroid Build Coastguard Worker
73*9880d681SAndroid Build Coastguard WorkerThis makefile specifies that all of the ``.cpp`` files in the current directory
74*9880d681SAndroid Build Coastguard Workerare to be compiled and linked together into a shared object
75*9880d681SAndroid Build Coastguard Worker``$(LEVEL)/Debug+Asserts/lib/Hello.so`` that can be dynamically loaded by the
76*9880d681SAndroid Build Coastguard Worker:program:`opt` or :program:`bugpoint` tools via their :option:`-load` options.
77*9880d681SAndroid Build Coastguard WorkerIf your operating system uses a suffix other than ``.so`` (such as Windows or Mac
78*9880d681SAndroid Build Coastguard WorkerOS X), the appropriate extension will be used.
79*9880d681SAndroid Build Coastguard Worker
80*9880d681SAndroid Build Coastguard WorkerIf you are used CMake to build LLVM, see :ref:`cmake-out-of-source-pass`.
81*9880d681SAndroid Build Coastguard Worker
82*9880d681SAndroid Build Coastguard WorkerNow that we have the build scripts set up, we just need to write the code for
83*9880d681SAndroid Build Coastguard Workerthe pass itself.
84*9880d681SAndroid Build Coastguard Worker
85*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-basiccode:
86*9880d681SAndroid Build Coastguard Worker
87*9880d681SAndroid Build Coastguard WorkerBasic code required
88*9880d681SAndroid Build Coastguard Worker-------------------
89*9880d681SAndroid Build Coastguard Worker
90*9880d681SAndroid Build Coastguard WorkerNow that we have a way to compile our new pass, we just have to write it.
91*9880d681SAndroid Build Coastguard WorkerStart out with:
92*9880d681SAndroid Build Coastguard Worker
93*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
94*9880d681SAndroid Build Coastguard Worker
95*9880d681SAndroid Build Coastguard Worker  #include "llvm/Pass.h"
96*9880d681SAndroid Build Coastguard Worker  #include "llvm/IR/Function.h"
97*9880d681SAndroid Build Coastguard Worker  #include "llvm/Support/raw_ostream.h"
98*9880d681SAndroid Build Coastguard Worker
99*9880d681SAndroid Build Coastguard WorkerWhich are needed because we are writing a `Pass
100*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/classllvm_1_1Pass.html>`_, we are operating on
101*9880d681SAndroid Build Coastguard Worker`Function <http://llvm.org/doxygen/classllvm_1_1Function.html>`_\ s, and we will
102*9880d681SAndroid Build Coastguard Workerbe doing some printing.
103*9880d681SAndroid Build Coastguard Worker
104*9880d681SAndroid Build Coastguard WorkerNext we have:
105*9880d681SAndroid Build Coastguard Worker
106*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
107*9880d681SAndroid Build Coastguard Worker
108*9880d681SAndroid Build Coastguard Worker  using namespace llvm;
109*9880d681SAndroid Build Coastguard Worker
110*9880d681SAndroid Build Coastguard Worker... which is required because the functions from the include files live in the
111*9880d681SAndroid Build Coastguard Workerllvm namespace.
112*9880d681SAndroid Build Coastguard Worker
113*9880d681SAndroid Build Coastguard WorkerNext we have:
114*9880d681SAndroid Build Coastguard Worker
115*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
116*9880d681SAndroid Build Coastguard Worker
117*9880d681SAndroid Build Coastguard Worker  namespace {
118*9880d681SAndroid Build Coastguard Worker
119*9880d681SAndroid Build Coastguard Worker... which starts out an anonymous namespace.  Anonymous namespaces are to C++
120*9880d681SAndroid Build Coastguard Workerwhat the "``static``" keyword is to C (at global scope).  It makes the things
121*9880d681SAndroid Build Coastguard Workerdeclared inside of the anonymous namespace visible only to the current file.
122*9880d681SAndroid Build Coastguard WorkerIf you're not familiar with them, consult a decent C++ book for more
123*9880d681SAndroid Build Coastguard Workerinformation.
124*9880d681SAndroid Build Coastguard Worker
125*9880d681SAndroid Build Coastguard WorkerNext, we declare our pass itself:
126*9880d681SAndroid Build Coastguard Worker
127*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
128*9880d681SAndroid Build Coastguard Worker
129*9880d681SAndroid Build Coastguard Worker  struct Hello : public FunctionPass {
130*9880d681SAndroid Build Coastguard Worker
131*9880d681SAndroid Build Coastguard WorkerThis declares a "``Hello``" class that is a subclass of :ref:`FunctionPass
132*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-FunctionPass>`.  The different builtin pass subclasses
133*9880d681SAndroid Build Coastguard Workerare described in detail :ref:`later <writing-an-llvm-pass-pass-classes>`, but
134*9880d681SAndroid Build Coastguard Workerfor now, know that ``FunctionPass`` operates on a function at a time.
135*9880d681SAndroid Build Coastguard Worker
136*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
137*9880d681SAndroid Build Coastguard Worker
138*9880d681SAndroid Build Coastguard Worker    static char ID;
139*9880d681SAndroid Build Coastguard Worker    Hello() : FunctionPass(ID) {}
140*9880d681SAndroid Build Coastguard Worker
141*9880d681SAndroid Build Coastguard WorkerThis declares pass identifier used by LLVM to identify pass.  This allows LLVM
142*9880d681SAndroid Build Coastguard Workerto avoid using expensive C++ runtime information.
143*9880d681SAndroid Build Coastguard Worker
144*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
145*9880d681SAndroid Build Coastguard Worker
146*9880d681SAndroid Build Coastguard Worker      bool runOnFunction(Function &F) override {
147*9880d681SAndroid Build Coastguard Worker        errs() << "Hello: ";
148*9880d681SAndroid Build Coastguard Worker        errs().write_escaped(F.getName()) << "\n";
149*9880d681SAndroid Build Coastguard Worker        return false;
150*9880d681SAndroid Build Coastguard Worker      }
151*9880d681SAndroid Build Coastguard Worker    }; // end of struct Hello
152*9880d681SAndroid Build Coastguard Worker  }  // end of anonymous namespace
153*9880d681SAndroid Build Coastguard Worker
154*9880d681SAndroid Build Coastguard WorkerWe declare a :ref:`runOnFunction <writing-an-llvm-pass-runOnFunction>` method,
155*9880d681SAndroid Build Coastguard Workerwhich overrides an abstract virtual method inherited from :ref:`FunctionPass
156*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-FunctionPass>`.  This is where we are supposed to do our
157*9880d681SAndroid Build Coastguard Workerthing, so we just print out our message with the name of each function.
158*9880d681SAndroid Build Coastguard Worker
159*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
160*9880d681SAndroid Build Coastguard Worker
161*9880d681SAndroid Build Coastguard Worker  char Hello::ID = 0;
162*9880d681SAndroid Build Coastguard Worker
163*9880d681SAndroid Build Coastguard WorkerWe initialize pass ID here.  LLVM uses ID's address to identify a pass, so
164*9880d681SAndroid Build Coastguard Workerinitialization value is not important.
165*9880d681SAndroid Build Coastguard Worker
166*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
167*9880d681SAndroid Build Coastguard Worker
168*9880d681SAndroid Build Coastguard Worker  static RegisterPass<Hello> X("hello", "Hello World Pass",
169*9880d681SAndroid Build Coastguard Worker                               false /* Only looks at CFG */,
170*9880d681SAndroid Build Coastguard Worker                               false /* Analysis Pass */);
171*9880d681SAndroid Build Coastguard Worker
172*9880d681SAndroid Build Coastguard WorkerLastly, we :ref:`register our class <writing-an-llvm-pass-registration>`
173*9880d681SAndroid Build Coastguard Worker``Hello``, giving it a command line argument "``hello``", and a name "Hello
174*9880d681SAndroid Build Coastguard WorkerWorld Pass".  The last two arguments describe its behavior: if a pass walks CFG
175*9880d681SAndroid Build Coastguard Workerwithout modifying it then the third argument is set to ``true``; if a pass is
176*9880d681SAndroid Build Coastguard Workeran analysis pass, for example dominator tree pass, then ``true`` is supplied as
177*9880d681SAndroid Build Coastguard Workerthe fourth argument.
178*9880d681SAndroid Build Coastguard Worker
179*9880d681SAndroid Build Coastguard WorkerAs a whole, the ``.cpp`` file looks like:
180*9880d681SAndroid Build Coastguard Worker
181*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
182*9880d681SAndroid Build Coastguard Worker
183*9880d681SAndroid Build Coastguard Worker    #include "llvm/Pass.h"
184*9880d681SAndroid Build Coastguard Worker    #include "llvm/IR/Function.h"
185*9880d681SAndroid Build Coastguard Worker    #include "llvm/Support/raw_ostream.h"
186*9880d681SAndroid Build Coastguard Worker
187*9880d681SAndroid Build Coastguard Worker    using namespace llvm;
188*9880d681SAndroid Build Coastguard Worker
189*9880d681SAndroid Build Coastguard Worker    namespace {
190*9880d681SAndroid Build Coastguard Worker      struct Hello : public FunctionPass {
191*9880d681SAndroid Build Coastguard Worker        static char ID;
192*9880d681SAndroid Build Coastguard Worker        Hello() : FunctionPass(ID) {}
193*9880d681SAndroid Build Coastguard Worker
194*9880d681SAndroid Build Coastguard Worker        bool runOnFunction(Function &F) override {
195*9880d681SAndroid Build Coastguard Worker          errs() << "Hello: ";
196*9880d681SAndroid Build Coastguard Worker          errs().write_escaped(F.getName()) << '\n';
197*9880d681SAndroid Build Coastguard Worker          return false;
198*9880d681SAndroid Build Coastguard Worker        }
199*9880d681SAndroid Build Coastguard Worker      };
200*9880d681SAndroid Build Coastguard Worker    }
201*9880d681SAndroid Build Coastguard Worker
202*9880d681SAndroid Build Coastguard Worker    char Hello::ID = 0;
203*9880d681SAndroid Build Coastguard Worker    static RegisterPass<Hello> X("hello", "Hello World Pass", false, false);
204*9880d681SAndroid Build Coastguard Worker
205*9880d681SAndroid Build Coastguard WorkerNow that it's all together, compile the file with a simple "``gmake``" command
206*9880d681SAndroid Build Coastguard Workerfrom the top level of your build directory and you should get a new file
207*9880d681SAndroid Build Coastguard Worker"``Debug+Asserts/lib/Hello.so``".  Note that everything in this file is
208*9880d681SAndroid Build Coastguard Workercontained in an anonymous namespace --- this reflects the fact that passes
209*9880d681SAndroid Build Coastguard Workerare self contained units that do not need external interfaces (although they
210*9880d681SAndroid Build Coastguard Workercan have them) to be useful.
211*9880d681SAndroid Build Coastguard Worker
212*9880d681SAndroid Build Coastguard WorkerRunning a pass with ``opt``
213*9880d681SAndroid Build Coastguard Worker---------------------------
214*9880d681SAndroid Build Coastguard Worker
215*9880d681SAndroid Build Coastguard WorkerNow that you have a brand new shiny shared object file, we can use the
216*9880d681SAndroid Build Coastguard Worker:program:`opt` command to run an LLVM program through your pass.  Because you
217*9880d681SAndroid Build Coastguard Workerregistered your pass with ``RegisterPass``, you will be able to use the
218*9880d681SAndroid Build Coastguard Worker:program:`opt` tool to access it, once loaded.
219*9880d681SAndroid Build Coastguard Worker
220*9880d681SAndroid Build Coastguard WorkerTo test it, follow the example at the end of the :doc:`GettingStarted` to
221*9880d681SAndroid Build Coastguard Workercompile "Hello World" to LLVM.  We can now run the bitcode file (hello.bc) for
222*9880d681SAndroid Build Coastguard Workerthe program through our transformation like this (or course, any bitcode file
223*9880d681SAndroid Build Coastguard Workerwill work):
224*9880d681SAndroid Build Coastguard Worker
225*9880d681SAndroid Build Coastguard Worker.. code-block:: console
226*9880d681SAndroid Build Coastguard Worker
227*9880d681SAndroid Build Coastguard Worker  $ opt -load ../../Debug+Asserts/lib/Hello.so -hello < hello.bc > /dev/null
228*9880d681SAndroid Build Coastguard Worker  Hello: __main
229*9880d681SAndroid Build Coastguard Worker  Hello: puts
230*9880d681SAndroid Build Coastguard Worker  Hello: main
231*9880d681SAndroid Build Coastguard Worker
232*9880d681SAndroid Build Coastguard WorkerThe :option:`-load` option specifies that :program:`opt` should load your pass
233*9880d681SAndroid Build Coastguard Workeras a shared object, which makes "``-hello``" a valid command line argument
234*9880d681SAndroid Build Coastguard Worker(which is one reason you need to :ref:`register your pass
235*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-registration>`).  Because the Hello pass does not modify
236*9880d681SAndroid Build Coastguard Workerthe program in any interesting way, we just throw away the result of
237*9880d681SAndroid Build Coastguard Worker:program:`opt` (sending it to ``/dev/null``).
238*9880d681SAndroid Build Coastguard Worker
239*9880d681SAndroid Build Coastguard WorkerTo see what happened to the other string you registered, try running
240*9880d681SAndroid Build Coastguard Worker:program:`opt` with the :option:`-help` option:
241*9880d681SAndroid Build Coastguard Worker
242*9880d681SAndroid Build Coastguard Worker.. code-block:: console
243*9880d681SAndroid Build Coastguard Worker
244*9880d681SAndroid Build Coastguard Worker  $ opt -load ../../Debug+Asserts/lib/Hello.so -help
245*9880d681SAndroid Build Coastguard Worker  OVERVIEW: llvm .bc -> .bc modular optimizer
246*9880d681SAndroid Build Coastguard Worker
247*9880d681SAndroid Build Coastguard Worker  USAGE: opt [options] <input bitcode>
248*9880d681SAndroid Build Coastguard Worker
249*9880d681SAndroid Build Coastguard Worker  OPTIONS:
250*9880d681SAndroid Build Coastguard Worker    Optimizations available:
251*9880d681SAndroid Build Coastguard Worker  ...
252*9880d681SAndroid Build Coastguard Worker      -globalopt                - Global Variable Optimizer
253*9880d681SAndroid Build Coastguard Worker      -globalsmodref-aa         - Simple mod/ref analysis for globals
254*9880d681SAndroid Build Coastguard Worker      -gvn                      - Global Value Numbering
255*9880d681SAndroid Build Coastguard Worker      -hello                    - Hello World Pass
256*9880d681SAndroid Build Coastguard Worker      -indvars                  - Induction Variable Simplification
257*9880d681SAndroid Build Coastguard Worker      -inline                   - Function Integration/Inlining
258*9880d681SAndroid Build Coastguard Worker  ...
259*9880d681SAndroid Build Coastguard Worker
260*9880d681SAndroid Build Coastguard WorkerThe pass name gets added as the information string for your pass, giving some
261*9880d681SAndroid Build Coastguard Workerdocumentation to users of :program:`opt`.  Now that you have a working pass,
262*9880d681SAndroid Build Coastguard Workeryou would go ahead and make it do the cool transformations you want.  Once you
263*9880d681SAndroid Build Coastguard Workerget it all working and tested, it may become useful to find out how fast your
264*9880d681SAndroid Build Coastguard Workerpass is.  The :ref:`PassManager <writing-an-llvm-pass-passmanager>` provides a
265*9880d681SAndroid Build Coastguard Workernice command line option (:option:`--time-passes`) that allows you to get
266*9880d681SAndroid Build Coastguard Workerinformation about the execution time of your pass along with the other passes
267*9880d681SAndroid Build Coastguard Workeryou queue up.  For example:
268*9880d681SAndroid Build Coastguard Worker
269*9880d681SAndroid Build Coastguard Worker.. code-block:: console
270*9880d681SAndroid Build Coastguard Worker
271*9880d681SAndroid Build Coastguard Worker  $ opt -load ../../Debug+Asserts/lib/Hello.so -hello -time-passes < hello.bc > /dev/null
272*9880d681SAndroid Build Coastguard Worker  Hello: __main
273*9880d681SAndroid Build Coastguard Worker  Hello: puts
274*9880d681SAndroid Build Coastguard Worker  Hello: main
275*9880d681SAndroid Build Coastguard Worker  ===============================================================================
276*9880d681SAndroid Build Coastguard Worker                        ... Pass execution timing report ...
277*9880d681SAndroid Build Coastguard Worker  ===============================================================================
278*9880d681SAndroid Build Coastguard Worker    Total Execution Time: 0.02 seconds (0.0479059 wall clock)
279*9880d681SAndroid Build Coastguard Worker
280*9880d681SAndroid Build Coastguard Worker     ---User Time---   --System Time--   --User+System--   ---Wall Time---  --- Pass Name ---
281*9880d681SAndroid Build Coastguard Worker     0.0100 (100.0%)   0.0000 (  0.0%)   0.0100 ( 50.0%)   0.0402 ( 84.0%)  Bitcode Writer
282*9880d681SAndroid Build Coastguard Worker     0.0000 (  0.0%)   0.0100 (100.0%)   0.0100 ( 50.0%)   0.0031 (  6.4%)  Dominator Set Construction
283*9880d681SAndroid Build Coastguard Worker     0.0000 (  0.0%)   0.0000 (  0.0%)   0.0000 (  0.0%)   0.0013 (  2.7%)  Module Verifier
284*9880d681SAndroid Build Coastguard Worker     0.0000 (  0.0%)   0.0000 (  0.0%)   0.0000 (  0.0%)   0.0033 (  6.9%)  Hello World Pass
285*9880d681SAndroid Build Coastguard Worker     0.0100 (100.0%)   0.0100 (100.0%)   0.0200 (100.0%)   0.0479 (100.0%)  TOTAL
286*9880d681SAndroid Build Coastguard Worker
287*9880d681SAndroid Build Coastguard WorkerAs you can see, our implementation above is pretty fast.  The additional
288*9880d681SAndroid Build Coastguard Workerpasses listed are automatically inserted by the :program:`opt` tool to verify
289*9880d681SAndroid Build Coastguard Workerthat the LLVM emitted by your pass is still valid and well formed LLVM, which
290*9880d681SAndroid Build Coastguard Workerhasn't been broken somehow.
291*9880d681SAndroid Build Coastguard Worker
292*9880d681SAndroid Build Coastguard WorkerNow that you have seen the basics of the mechanics behind passes, we can talk
293*9880d681SAndroid Build Coastguard Workerabout some more details of how they work and how to use them.
294*9880d681SAndroid Build Coastguard Worker
295*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-pass-classes:
296*9880d681SAndroid Build Coastguard Worker
297*9880d681SAndroid Build Coastguard WorkerPass classes and requirements
298*9880d681SAndroid Build Coastguard Worker=============================
299*9880d681SAndroid Build Coastguard Worker
300*9880d681SAndroid Build Coastguard WorkerOne of the first things that you should do when designing a new pass is to
301*9880d681SAndroid Build Coastguard Workerdecide what class you should subclass for your pass.  The :ref:`Hello World
302*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-basiccode>` example uses the :ref:`FunctionPass
303*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-FunctionPass>` class for its implementation, but we did
304*9880d681SAndroid Build Coastguard Workernot discuss why or when this should occur.  Here we talk about the classes
305*9880d681SAndroid Build Coastguard Workeravailable, from the most general to the most specific.
306*9880d681SAndroid Build Coastguard Worker
307*9880d681SAndroid Build Coastguard WorkerWhen choosing a superclass for your ``Pass``, you should choose the **most
308*9880d681SAndroid Build Coastguard Workerspecific** class possible, while still being able to meet the requirements
309*9880d681SAndroid Build Coastguard Workerlisted.  This gives the LLVM Pass Infrastructure information necessary to
310*9880d681SAndroid Build Coastguard Workeroptimize how passes are run, so that the resultant compiler isn't unnecessarily
311*9880d681SAndroid Build Coastguard Workerslow.
312*9880d681SAndroid Build Coastguard Worker
313*9880d681SAndroid Build Coastguard WorkerThe ``ImmutablePass`` class
314*9880d681SAndroid Build Coastguard Worker---------------------------
315*9880d681SAndroid Build Coastguard Worker
316*9880d681SAndroid Build Coastguard WorkerThe most plain and boring type of pass is the "`ImmutablePass
317*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/classllvm_1_1ImmutablePass.html>`_" class.  This pass
318*9880d681SAndroid Build Coastguard Workertype is used for passes that do not have to be run, do not change state, and
319*9880d681SAndroid Build Coastguard Workernever need to be updated.  This is not a normal type of transformation or
320*9880d681SAndroid Build Coastguard Workeranalysis, but can provide information about the current compiler configuration.
321*9880d681SAndroid Build Coastguard Worker
322*9880d681SAndroid Build Coastguard WorkerAlthough this pass class is very infrequently used, it is important for
323*9880d681SAndroid Build Coastguard Workerproviding information about the current target machine being compiled for, and
324*9880d681SAndroid Build Coastguard Workerother static information that can affect the various transformations.
325*9880d681SAndroid Build Coastguard Worker
326*9880d681SAndroid Build Coastguard Worker``ImmutablePass``\ es never invalidate other transformations, are never
327*9880d681SAndroid Build Coastguard Workerinvalidated, and are never "run".
328*9880d681SAndroid Build Coastguard Worker
329*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-ModulePass:
330*9880d681SAndroid Build Coastguard Worker
331*9880d681SAndroid Build Coastguard WorkerThe ``ModulePass`` class
332*9880d681SAndroid Build Coastguard Worker------------------------
333*9880d681SAndroid Build Coastguard Worker
334*9880d681SAndroid Build Coastguard WorkerThe `ModulePass <http://llvm.org/doxygen/classllvm_1_1ModulePass.html>`_ class
335*9880d681SAndroid Build Coastguard Workeris the most general of all superclasses that you can use.  Deriving from
336*9880d681SAndroid Build Coastguard Worker``ModulePass`` indicates that your pass uses the entire program as a unit,
337*9880d681SAndroid Build Coastguard Workerreferring to function bodies in no predictable order, or adding and removing
338*9880d681SAndroid Build Coastguard Workerfunctions.  Because nothing is known about the behavior of ``ModulePass``
339*9880d681SAndroid Build Coastguard Workersubclasses, no optimization can be done for their execution.
340*9880d681SAndroid Build Coastguard Worker
341*9880d681SAndroid Build Coastguard WorkerA module pass can use function level passes (e.g. dominators) using the
342*9880d681SAndroid Build Coastguard Worker``getAnalysis`` interface ``getAnalysis<DominatorTree>(llvm::Function *)`` to
343*9880d681SAndroid Build Coastguard Workerprovide the function to retrieve analysis result for, if the function pass does
344*9880d681SAndroid Build Coastguard Workernot require any module or immutable passes.  Note that this can only be done
345*9880d681SAndroid Build Coastguard Workerfor functions for which the analysis ran, e.g. in the case of dominators you
346*9880d681SAndroid Build Coastguard Workershould only ask for the ``DominatorTree`` for function definitions, not
347*9880d681SAndroid Build Coastguard Workerdeclarations.
348*9880d681SAndroid Build Coastguard Worker
349*9880d681SAndroid Build Coastguard WorkerTo write a correct ``ModulePass`` subclass, derive from ``ModulePass`` and
350*9880d681SAndroid Build Coastguard Workeroverload the ``runOnModule`` method with the following signature:
351*9880d681SAndroid Build Coastguard Worker
352*9880d681SAndroid Build Coastguard WorkerThe ``runOnModule`` method
353*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^
354*9880d681SAndroid Build Coastguard Worker
355*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
356*9880d681SAndroid Build Coastguard Worker
357*9880d681SAndroid Build Coastguard Worker  virtual bool runOnModule(Module &M) = 0;
358*9880d681SAndroid Build Coastguard Worker
359*9880d681SAndroid Build Coastguard WorkerThe ``runOnModule`` method performs the interesting work of the pass.  It
360*9880d681SAndroid Build Coastguard Workershould return ``true`` if the module was modified by the transformation and
361*9880d681SAndroid Build Coastguard Worker``false`` otherwise.
362*9880d681SAndroid Build Coastguard Worker
363*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-CallGraphSCCPass:
364*9880d681SAndroid Build Coastguard Worker
365*9880d681SAndroid Build Coastguard WorkerThe ``CallGraphSCCPass`` class
366*9880d681SAndroid Build Coastguard Worker------------------------------
367*9880d681SAndroid Build Coastguard Worker
368*9880d681SAndroid Build Coastguard WorkerThe `CallGraphSCCPass
369*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/classllvm_1_1CallGraphSCCPass.html>`_ is used by
370*9880d681SAndroid Build Coastguard Workerpasses that need to traverse the program bottom-up on the call graph (callees
371*9880d681SAndroid Build Coastguard Workerbefore callers).  Deriving from ``CallGraphSCCPass`` provides some mechanics
372*9880d681SAndroid Build Coastguard Workerfor building and traversing the ``CallGraph``, but also allows the system to
373*9880d681SAndroid Build Coastguard Workeroptimize execution of ``CallGraphSCCPass``\ es.  If your pass meets the
374*9880d681SAndroid Build Coastguard Workerrequirements outlined below, and doesn't meet the requirements of a
375*9880d681SAndroid Build Coastguard Worker:ref:`FunctionPass <writing-an-llvm-pass-FunctionPass>` or :ref:`BasicBlockPass
376*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-BasicBlockPass>`, you should derive from
377*9880d681SAndroid Build Coastguard Worker``CallGraphSCCPass``.
378*9880d681SAndroid Build Coastguard Worker
379*9880d681SAndroid Build Coastguard Worker``TODO``: explain briefly what SCC, Tarjan's algo, and B-U mean.
380*9880d681SAndroid Build Coastguard Worker
381*9880d681SAndroid Build Coastguard WorkerTo be explicit, CallGraphSCCPass subclasses are:
382*9880d681SAndroid Build Coastguard Worker
383*9880d681SAndroid Build Coastguard Worker#. ... *not allowed* to inspect or modify any ``Function``\ s other than those
384*9880d681SAndroid Build Coastguard Worker   in the current SCC and the direct callers and direct callees of the SCC.
385*9880d681SAndroid Build Coastguard Worker#. ... *required* to preserve the current ``CallGraph`` object, updating it to
386*9880d681SAndroid Build Coastguard Worker   reflect any changes made to the program.
387*9880d681SAndroid Build Coastguard Worker#. ... *not allowed* to add or remove SCC's from the current Module, though
388*9880d681SAndroid Build Coastguard Worker   they may change the contents of an SCC.
389*9880d681SAndroid Build Coastguard Worker#. ... *allowed* to add or remove global variables from the current Module.
390*9880d681SAndroid Build Coastguard Worker#. ... *allowed* to maintain state across invocations of :ref:`runOnSCC
391*9880d681SAndroid Build Coastguard Worker   <writing-an-llvm-pass-runOnSCC>` (including global data).
392*9880d681SAndroid Build Coastguard Worker
393*9880d681SAndroid Build Coastguard WorkerImplementing a ``CallGraphSCCPass`` is slightly tricky in some cases because it
394*9880d681SAndroid Build Coastguard Workerhas to handle SCCs with more than one node in it.  All of the virtual methods
395*9880d681SAndroid Build Coastguard Workerdescribed below should return ``true`` if they modified the program, or
396*9880d681SAndroid Build Coastguard Worker``false`` if they didn't.
397*9880d681SAndroid Build Coastguard Worker
398*9880d681SAndroid Build Coastguard WorkerThe ``doInitialization(CallGraph &)`` method
399*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
400*9880d681SAndroid Build Coastguard Worker
401*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
402*9880d681SAndroid Build Coastguard Worker
403*9880d681SAndroid Build Coastguard Worker  virtual bool doInitialization(CallGraph &CG);
404*9880d681SAndroid Build Coastguard Worker
405*9880d681SAndroid Build Coastguard WorkerThe ``doInitialization`` method is allowed to do most of the things that
406*9880d681SAndroid Build Coastguard Worker``CallGraphSCCPass``\ es are not allowed to do.  They can add and remove
407*9880d681SAndroid Build Coastguard Workerfunctions, get pointers to functions, etc.  The ``doInitialization`` method is
408*9880d681SAndroid Build Coastguard Workerdesigned to do simple initialization type of stuff that does not depend on the
409*9880d681SAndroid Build Coastguard WorkerSCCs being processed.  The ``doInitialization`` method call is not scheduled to
410*9880d681SAndroid Build Coastguard Workeroverlap with any other pass executions (thus it should be very fast).
411*9880d681SAndroid Build Coastguard Worker
412*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-runOnSCC:
413*9880d681SAndroid Build Coastguard Worker
414*9880d681SAndroid Build Coastguard WorkerThe ``runOnSCC`` method
415*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^
416*9880d681SAndroid Build Coastguard Worker
417*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
418*9880d681SAndroid Build Coastguard Worker
419*9880d681SAndroid Build Coastguard Worker  virtual bool runOnSCC(CallGraphSCC &SCC) = 0;
420*9880d681SAndroid Build Coastguard Worker
421*9880d681SAndroid Build Coastguard WorkerThe ``runOnSCC`` method performs the interesting work of the pass, and should
422*9880d681SAndroid Build Coastguard Workerreturn ``true`` if the module was modified by the transformation, ``false``
423*9880d681SAndroid Build Coastguard Workerotherwise.
424*9880d681SAndroid Build Coastguard Worker
425*9880d681SAndroid Build Coastguard WorkerThe ``doFinalization(CallGraph &)`` method
426*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
427*9880d681SAndroid Build Coastguard Worker
428*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
429*9880d681SAndroid Build Coastguard Worker
430*9880d681SAndroid Build Coastguard Worker  virtual bool doFinalization(CallGraph &CG);
431*9880d681SAndroid Build Coastguard Worker
432*9880d681SAndroid Build Coastguard WorkerThe ``doFinalization`` method is an infrequently used method that is called
433*9880d681SAndroid Build Coastguard Workerwhen the pass framework has finished calling :ref:`runOnSCC
434*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-runOnSCC>` for every SCC in the program being compiled.
435*9880d681SAndroid Build Coastguard Worker
436*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-FunctionPass:
437*9880d681SAndroid Build Coastguard Worker
438*9880d681SAndroid Build Coastguard WorkerThe ``FunctionPass`` class
439*9880d681SAndroid Build Coastguard Worker--------------------------
440*9880d681SAndroid Build Coastguard Worker
441*9880d681SAndroid Build Coastguard WorkerIn contrast to ``ModulePass`` subclasses, `FunctionPass
442*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/classllvm_1_1Pass.html>`_ subclasses do have a
443*9880d681SAndroid Build Coastguard Workerpredictable, local behavior that can be expected by the system.  All
444*9880d681SAndroid Build Coastguard Worker``FunctionPass`` execute on each function in the program independent of all of
445*9880d681SAndroid Build Coastguard Workerthe other functions in the program.  ``FunctionPass``\ es do not require that
446*9880d681SAndroid Build Coastguard Workerthey are executed in a particular order, and ``FunctionPass``\ es do not modify
447*9880d681SAndroid Build Coastguard Workerexternal functions.
448*9880d681SAndroid Build Coastguard Worker
449*9880d681SAndroid Build Coastguard WorkerTo be explicit, ``FunctionPass`` subclasses are not allowed to:
450*9880d681SAndroid Build Coastguard Worker
451*9880d681SAndroid Build Coastguard Worker#. Inspect or modify a ``Function`` other than the one currently being processed.
452*9880d681SAndroid Build Coastguard Worker#. Add or remove ``Function``\ s from the current ``Module``.
453*9880d681SAndroid Build Coastguard Worker#. Add or remove global variables from the current ``Module``.
454*9880d681SAndroid Build Coastguard Worker#. Maintain state across invocations of :ref:`runOnFunction
455*9880d681SAndroid Build Coastguard Worker   <writing-an-llvm-pass-runOnFunction>` (including global data).
456*9880d681SAndroid Build Coastguard Worker
457*9880d681SAndroid Build Coastguard WorkerImplementing a ``FunctionPass`` is usually straightforward (See the :ref:`Hello
458*9880d681SAndroid Build Coastguard WorkerWorld <writing-an-llvm-pass-basiccode>` pass for example).
459*9880d681SAndroid Build Coastguard Worker``FunctionPass``\ es may overload three virtual methods to do their work.  All
460*9880d681SAndroid Build Coastguard Workerof these methods should return ``true`` if they modified the program, or
461*9880d681SAndroid Build Coastguard Worker``false`` if they didn't.
462*9880d681SAndroid Build Coastguard Worker
463*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-doInitialization-mod:
464*9880d681SAndroid Build Coastguard Worker
465*9880d681SAndroid Build Coastguard WorkerThe ``doInitialization(Module &)`` method
466*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
467*9880d681SAndroid Build Coastguard Worker
468*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
469*9880d681SAndroid Build Coastguard Worker
470*9880d681SAndroid Build Coastguard Worker  virtual bool doInitialization(Module &M);
471*9880d681SAndroid Build Coastguard Worker
472*9880d681SAndroid Build Coastguard WorkerThe ``doInitialization`` method is allowed to do most of the things that
473*9880d681SAndroid Build Coastguard Worker``FunctionPass``\ es are not allowed to do.  They can add and remove functions,
474*9880d681SAndroid Build Coastguard Workerget pointers to functions, etc.  The ``doInitialization`` method is designed to
475*9880d681SAndroid Build Coastguard Workerdo simple initialization type of stuff that does not depend on the functions
476*9880d681SAndroid Build Coastguard Workerbeing processed.  The ``doInitialization`` method call is not scheduled to
477*9880d681SAndroid Build Coastguard Workeroverlap with any other pass executions (thus it should be very fast).
478*9880d681SAndroid Build Coastguard Worker
479*9880d681SAndroid Build Coastguard WorkerA good example of how this method should be used is the `LowerAllocations
480*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/LowerAllocations_8cpp-source.html>`_ pass.  This pass
481*9880d681SAndroid Build Coastguard Workerconverts ``malloc`` and ``free`` instructions into platform dependent
482*9880d681SAndroid Build Coastguard Worker``malloc()`` and ``free()`` function calls.  It uses the ``doInitialization``
483*9880d681SAndroid Build Coastguard Workermethod to get a reference to the ``malloc`` and ``free`` functions that it
484*9880d681SAndroid Build Coastguard Workerneeds, adding prototypes to the module if necessary.
485*9880d681SAndroid Build Coastguard Worker
486*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-runOnFunction:
487*9880d681SAndroid Build Coastguard Worker
488*9880d681SAndroid Build Coastguard WorkerThe ``runOnFunction`` method
489*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^
490*9880d681SAndroid Build Coastguard Worker
491*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
492*9880d681SAndroid Build Coastguard Worker
493*9880d681SAndroid Build Coastguard Worker  virtual bool runOnFunction(Function &F) = 0;
494*9880d681SAndroid Build Coastguard Worker
495*9880d681SAndroid Build Coastguard WorkerThe ``runOnFunction`` method must be implemented by your subclass to do the
496*9880d681SAndroid Build Coastguard Workertransformation or analysis work of your pass.  As usual, a ``true`` value
497*9880d681SAndroid Build Coastguard Workershould be returned if the function is modified.
498*9880d681SAndroid Build Coastguard Worker
499*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-doFinalization-mod:
500*9880d681SAndroid Build Coastguard Worker
501*9880d681SAndroid Build Coastguard WorkerThe ``doFinalization(Module &)`` method
502*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
503*9880d681SAndroid Build Coastguard Worker
504*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
505*9880d681SAndroid Build Coastguard Worker
506*9880d681SAndroid Build Coastguard Worker  virtual bool doFinalization(Module &M);
507*9880d681SAndroid Build Coastguard Worker
508*9880d681SAndroid Build Coastguard WorkerThe ``doFinalization`` method is an infrequently used method that is called
509*9880d681SAndroid Build Coastguard Workerwhen the pass framework has finished calling :ref:`runOnFunction
510*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-runOnFunction>` for every function in the program being
511*9880d681SAndroid Build Coastguard Workercompiled.
512*9880d681SAndroid Build Coastguard Worker
513*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-LoopPass:
514*9880d681SAndroid Build Coastguard Worker
515*9880d681SAndroid Build Coastguard WorkerThe ``LoopPass`` class
516*9880d681SAndroid Build Coastguard Worker----------------------
517*9880d681SAndroid Build Coastguard Worker
518*9880d681SAndroid Build Coastguard WorkerAll ``LoopPass`` execute on each loop in the function independent of all of the
519*9880d681SAndroid Build Coastguard Workerother loops in the function.  ``LoopPass`` processes loops in loop nest order
520*9880d681SAndroid Build Coastguard Workersuch that outer most loop is processed last.
521*9880d681SAndroid Build Coastguard Worker
522*9880d681SAndroid Build Coastguard Worker``LoopPass`` subclasses are allowed to update loop nest using ``LPPassManager``
523*9880d681SAndroid Build Coastguard Workerinterface.  Implementing a loop pass is usually straightforward.
524*9880d681SAndroid Build Coastguard Worker``LoopPass``\ es may overload three virtual methods to do their work.  All
525*9880d681SAndroid Build Coastguard Workerthese methods should return ``true`` if they modified the program, or ``false``
526*9880d681SAndroid Build Coastguard Workerif they didn't.
527*9880d681SAndroid Build Coastguard Worker
528*9880d681SAndroid Build Coastguard WorkerA ``LoopPass`` subclass which is intended to run as part of the main loop pass
529*9880d681SAndroid Build Coastguard Workerpipeline needs to preserve all of the same *function* analyses that the other
530*9880d681SAndroid Build Coastguard Workerloop passes in its pipeline require. To make that easier,
531*9880d681SAndroid Build Coastguard Workera ``getLoopAnalysisUsage`` function is provided by ``LoopUtils.h``. It can be
532*9880d681SAndroid Build Coastguard Workercalled within the subclass's ``getAnalysisUsage`` override to get consistent
533*9880d681SAndroid Build Coastguard Workerand correct behavior. Analogously, ``INITIALIZE_PASS_DEPENDENCY(LoopPass)``
534*9880d681SAndroid Build Coastguard Workerwill initialize this set of function analyses.
535*9880d681SAndroid Build Coastguard Worker
536*9880d681SAndroid Build Coastguard WorkerThe ``doInitialization(Loop *, LPPassManager &)`` method
537*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
538*9880d681SAndroid Build Coastguard Worker
539*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
540*9880d681SAndroid Build Coastguard Worker
541*9880d681SAndroid Build Coastguard Worker  virtual bool doInitialization(Loop *, LPPassManager &LPM);
542*9880d681SAndroid Build Coastguard Worker
543*9880d681SAndroid Build Coastguard WorkerThe ``doInitialization`` method is designed to do simple initialization type of
544*9880d681SAndroid Build Coastguard Workerstuff that does not depend on the functions being processed.  The
545*9880d681SAndroid Build Coastguard Worker``doInitialization`` method call is not scheduled to overlap with any other
546*9880d681SAndroid Build Coastguard Workerpass executions (thus it should be very fast).  ``LPPassManager`` interface
547*9880d681SAndroid Build Coastguard Workershould be used to access ``Function`` or ``Module`` level analysis information.
548*9880d681SAndroid Build Coastguard Worker
549*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-runOnLoop:
550*9880d681SAndroid Build Coastguard Worker
551*9880d681SAndroid Build Coastguard WorkerThe ``runOnLoop`` method
552*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^
553*9880d681SAndroid Build Coastguard Worker
554*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
555*9880d681SAndroid Build Coastguard Worker
556*9880d681SAndroid Build Coastguard Worker  virtual bool runOnLoop(Loop *, LPPassManager &LPM) = 0;
557*9880d681SAndroid Build Coastguard Worker
558*9880d681SAndroid Build Coastguard WorkerThe ``runOnLoop`` method must be implemented by your subclass to do the
559*9880d681SAndroid Build Coastguard Workertransformation or analysis work of your pass.  As usual, a ``true`` value
560*9880d681SAndroid Build Coastguard Workershould be returned if the function is modified.  ``LPPassManager`` interface
561*9880d681SAndroid Build Coastguard Workershould be used to update loop nest.
562*9880d681SAndroid Build Coastguard Worker
563*9880d681SAndroid Build Coastguard WorkerThe ``doFinalization()`` method
564*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
565*9880d681SAndroid Build Coastguard Worker
566*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
567*9880d681SAndroid Build Coastguard Worker
568*9880d681SAndroid Build Coastguard Worker  virtual bool doFinalization();
569*9880d681SAndroid Build Coastguard Worker
570*9880d681SAndroid Build Coastguard WorkerThe ``doFinalization`` method is an infrequently used method that is called
571*9880d681SAndroid Build Coastguard Workerwhen the pass framework has finished calling :ref:`runOnLoop
572*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-runOnLoop>` for every loop in the program being compiled.
573*9880d681SAndroid Build Coastguard Worker
574*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-RegionPass:
575*9880d681SAndroid Build Coastguard Worker
576*9880d681SAndroid Build Coastguard WorkerThe ``RegionPass`` class
577*9880d681SAndroid Build Coastguard Worker------------------------
578*9880d681SAndroid Build Coastguard Worker
579*9880d681SAndroid Build Coastguard Worker``RegionPass`` is similar to :ref:`LoopPass <writing-an-llvm-pass-LoopPass>`,
580*9880d681SAndroid Build Coastguard Workerbut executes on each single entry single exit region in the function.
581*9880d681SAndroid Build Coastguard Worker``RegionPass`` processes regions in nested order such that the outer most
582*9880d681SAndroid Build Coastguard Workerregion is processed last.
583*9880d681SAndroid Build Coastguard Worker
584*9880d681SAndroid Build Coastguard Worker``RegionPass`` subclasses are allowed to update the region tree by using the
585*9880d681SAndroid Build Coastguard Worker``RGPassManager`` interface.  You may overload three virtual methods of
586*9880d681SAndroid Build Coastguard Worker``RegionPass`` to implement your own region pass.  All these methods should
587*9880d681SAndroid Build Coastguard Workerreturn ``true`` if they modified the program, or ``false`` if they did not.
588*9880d681SAndroid Build Coastguard Worker
589*9880d681SAndroid Build Coastguard WorkerThe ``doInitialization(Region *, RGPassManager &)`` method
590*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
591*9880d681SAndroid Build Coastguard Worker
592*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
593*9880d681SAndroid Build Coastguard Worker
594*9880d681SAndroid Build Coastguard Worker  virtual bool doInitialization(Region *, RGPassManager &RGM);
595*9880d681SAndroid Build Coastguard Worker
596*9880d681SAndroid Build Coastguard WorkerThe ``doInitialization`` method is designed to do simple initialization type of
597*9880d681SAndroid Build Coastguard Workerstuff that does not depend on the functions being processed.  The
598*9880d681SAndroid Build Coastguard Worker``doInitialization`` method call is not scheduled to overlap with any other
599*9880d681SAndroid Build Coastguard Workerpass executions (thus it should be very fast).  ``RPPassManager`` interface
600*9880d681SAndroid Build Coastguard Workershould be used to access ``Function`` or ``Module`` level analysis information.
601*9880d681SAndroid Build Coastguard Worker
602*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-runOnRegion:
603*9880d681SAndroid Build Coastguard Worker
604*9880d681SAndroid Build Coastguard WorkerThe ``runOnRegion`` method
605*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^
606*9880d681SAndroid Build Coastguard Worker
607*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
608*9880d681SAndroid Build Coastguard Worker
609*9880d681SAndroid Build Coastguard Worker  virtual bool runOnRegion(Region *, RGPassManager &RGM) = 0;
610*9880d681SAndroid Build Coastguard Worker
611*9880d681SAndroid Build Coastguard WorkerThe ``runOnRegion`` method must be implemented by your subclass to do the
612*9880d681SAndroid Build Coastguard Workertransformation or analysis work of your pass.  As usual, a true value should be
613*9880d681SAndroid Build Coastguard Workerreturned if the region is modified.  ``RGPassManager`` interface should be used to
614*9880d681SAndroid Build Coastguard Workerupdate region tree.
615*9880d681SAndroid Build Coastguard Worker
616*9880d681SAndroid Build Coastguard WorkerThe ``doFinalization()`` method
617*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
618*9880d681SAndroid Build Coastguard Worker
619*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
620*9880d681SAndroid Build Coastguard Worker
621*9880d681SAndroid Build Coastguard Worker  virtual bool doFinalization();
622*9880d681SAndroid Build Coastguard Worker
623*9880d681SAndroid Build Coastguard WorkerThe ``doFinalization`` method is an infrequently used method that is called
624*9880d681SAndroid Build Coastguard Workerwhen the pass framework has finished calling :ref:`runOnRegion
625*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-runOnRegion>` for every region in the program being
626*9880d681SAndroid Build Coastguard Workercompiled.
627*9880d681SAndroid Build Coastguard Worker
628*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-BasicBlockPass:
629*9880d681SAndroid Build Coastguard Worker
630*9880d681SAndroid Build Coastguard WorkerThe ``BasicBlockPass`` class
631*9880d681SAndroid Build Coastguard Worker----------------------------
632*9880d681SAndroid Build Coastguard Worker
633*9880d681SAndroid Build Coastguard Worker``BasicBlockPass``\ es are just like :ref:`FunctionPass's
634*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-FunctionPass>` , except that they must limit their scope
635*9880d681SAndroid Build Coastguard Workerof inspection and modification to a single basic block at a time.  As such,
636*9880d681SAndroid Build Coastguard Workerthey are **not** allowed to do any of the following:
637*9880d681SAndroid Build Coastguard Worker
638*9880d681SAndroid Build Coastguard Worker#. Modify or inspect any basic blocks outside of the current one.
639*9880d681SAndroid Build Coastguard Worker#. Maintain state across invocations of :ref:`runOnBasicBlock
640*9880d681SAndroid Build Coastguard Worker   <writing-an-llvm-pass-runOnBasicBlock>`.
641*9880d681SAndroid Build Coastguard Worker#. Modify the control flow graph (by altering terminator instructions)
642*9880d681SAndroid Build Coastguard Worker#. Any of the things forbidden for :ref:`FunctionPasses
643*9880d681SAndroid Build Coastguard Worker   <writing-an-llvm-pass-FunctionPass>`.
644*9880d681SAndroid Build Coastguard Worker
645*9880d681SAndroid Build Coastguard Worker``BasicBlockPass``\ es are useful for traditional local and "peephole"
646*9880d681SAndroid Build Coastguard Workeroptimizations.  They may override the same :ref:`doInitialization(Module &)
647*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-doInitialization-mod>` and :ref:`doFinalization(Module &)
648*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-doFinalization-mod>` methods that :ref:`FunctionPass's
649*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-FunctionPass>` have, but also have the following virtual
650*9880d681SAndroid Build Coastguard Workermethods that may also be implemented:
651*9880d681SAndroid Build Coastguard Worker
652*9880d681SAndroid Build Coastguard WorkerThe ``doInitialization(Function &)`` method
653*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
654*9880d681SAndroid Build Coastguard Worker
655*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
656*9880d681SAndroid Build Coastguard Worker
657*9880d681SAndroid Build Coastguard Worker  virtual bool doInitialization(Function &F);
658*9880d681SAndroid Build Coastguard Worker
659*9880d681SAndroid Build Coastguard WorkerThe ``doInitialization`` method is allowed to do most of the things that
660*9880d681SAndroid Build Coastguard Worker``BasicBlockPass``\ es are not allowed to do, but that ``FunctionPass``\ es
661*9880d681SAndroid Build Coastguard Workercan.  The ``doInitialization`` method is designed to do simple initialization
662*9880d681SAndroid Build Coastguard Workerthat does not depend on the ``BasicBlock``\ s being processed.  The
663*9880d681SAndroid Build Coastguard Worker``doInitialization`` method call is not scheduled to overlap with any other
664*9880d681SAndroid Build Coastguard Workerpass executions (thus it should be very fast).
665*9880d681SAndroid Build Coastguard Worker
666*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-runOnBasicBlock:
667*9880d681SAndroid Build Coastguard Worker
668*9880d681SAndroid Build Coastguard WorkerThe ``runOnBasicBlock`` method
669*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
670*9880d681SAndroid Build Coastguard Worker
671*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
672*9880d681SAndroid Build Coastguard Worker
673*9880d681SAndroid Build Coastguard Worker  virtual bool runOnBasicBlock(BasicBlock &BB) = 0;
674*9880d681SAndroid Build Coastguard Worker
675*9880d681SAndroid Build Coastguard WorkerOverride this function to do the work of the ``BasicBlockPass``.  This function
676*9880d681SAndroid Build Coastguard Workeris not allowed to inspect or modify basic blocks other than the parameter, and
677*9880d681SAndroid Build Coastguard Workerare not allowed to modify the CFG.  A ``true`` value must be returned if the
678*9880d681SAndroid Build Coastguard Workerbasic block is modified.
679*9880d681SAndroid Build Coastguard Worker
680*9880d681SAndroid Build Coastguard WorkerThe ``doFinalization(Function &)`` method
681*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
682*9880d681SAndroid Build Coastguard Worker
683*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
684*9880d681SAndroid Build Coastguard Worker
685*9880d681SAndroid Build Coastguard Worker    virtual bool doFinalization(Function &F);
686*9880d681SAndroid Build Coastguard Worker
687*9880d681SAndroid Build Coastguard WorkerThe ``doFinalization`` method is an infrequently used method that is called
688*9880d681SAndroid Build Coastguard Workerwhen the pass framework has finished calling :ref:`runOnBasicBlock
689*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-runOnBasicBlock>` for every ``BasicBlock`` in the program
690*9880d681SAndroid Build Coastguard Workerbeing compiled.  This can be used to perform per-function finalization.
691*9880d681SAndroid Build Coastguard Worker
692*9880d681SAndroid Build Coastguard WorkerThe ``MachineFunctionPass`` class
693*9880d681SAndroid Build Coastguard Worker---------------------------------
694*9880d681SAndroid Build Coastguard Worker
695*9880d681SAndroid Build Coastguard WorkerA ``MachineFunctionPass`` is a part of the LLVM code generator that executes on
696*9880d681SAndroid Build Coastguard Workerthe machine-dependent representation of each LLVM function in the program.
697*9880d681SAndroid Build Coastguard Worker
698*9880d681SAndroid Build Coastguard WorkerCode generator passes are registered and initialized specially by
699*9880d681SAndroid Build Coastguard Worker``TargetMachine::addPassesToEmitFile`` and similar routines, so they cannot
700*9880d681SAndroid Build Coastguard Workergenerally be run from the :program:`opt` or :program:`bugpoint` commands.
701*9880d681SAndroid Build Coastguard Worker
702*9880d681SAndroid Build Coastguard WorkerA ``MachineFunctionPass`` is also a ``FunctionPass``, so all the restrictions
703*9880d681SAndroid Build Coastguard Workerthat apply to a ``FunctionPass`` also apply to it.  ``MachineFunctionPass``\ es
704*9880d681SAndroid Build Coastguard Workeralso have additional restrictions.  In particular, ``MachineFunctionPass``\ es
705*9880d681SAndroid Build Coastguard Workerare not allowed to do any of the following:
706*9880d681SAndroid Build Coastguard Worker
707*9880d681SAndroid Build Coastguard Worker#. Modify or create any LLVM IR ``Instruction``\ s, ``BasicBlock``\ s,
708*9880d681SAndroid Build Coastguard Worker   ``Argument``\ s, ``Function``\ s, ``GlobalVariable``\ s,
709*9880d681SAndroid Build Coastguard Worker   ``GlobalAlias``\ es, or ``Module``\ s.
710*9880d681SAndroid Build Coastguard Worker#. Modify a ``MachineFunction`` other than the one currently being processed.
711*9880d681SAndroid Build Coastguard Worker#. Maintain state across invocations of :ref:`runOnMachineFunction
712*9880d681SAndroid Build Coastguard Worker   <writing-an-llvm-pass-runOnMachineFunction>` (including global data).
713*9880d681SAndroid Build Coastguard Worker
714*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-runOnMachineFunction:
715*9880d681SAndroid Build Coastguard Worker
716*9880d681SAndroid Build Coastguard WorkerThe ``runOnMachineFunction(MachineFunction &MF)`` method
717*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
718*9880d681SAndroid Build Coastguard Worker
719*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
720*9880d681SAndroid Build Coastguard Worker
721*9880d681SAndroid Build Coastguard Worker  virtual bool runOnMachineFunction(MachineFunction &MF) = 0;
722*9880d681SAndroid Build Coastguard Worker
723*9880d681SAndroid Build Coastguard Worker``runOnMachineFunction`` can be considered the main entry point of a
724*9880d681SAndroid Build Coastguard Worker``MachineFunctionPass``; that is, you should override this method to do the
725*9880d681SAndroid Build Coastguard Workerwork of your ``MachineFunctionPass``.
726*9880d681SAndroid Build Coastguard Worker
727*9880d681SAndroid Build Coastguard WorkerThe ``runOnMachineFunction`` method is called on every ``MachineFunction`` in a
728*9880d681SAndroid Build Coastguard Worker``Module``, so that the ``MachineFunctionPass`` may perform optimizations on
729*9880d681SAndroid Build Coastguard Workerthe machine-dependent representation of the function.  If you want to get at
730*9880d681SAndroid Build Coastguard Workerthe LLVM ``Function`` for the ``MachineFunction`` you're working on, use
731*9880d681SAndroid Build Coastguard Worker``MachineFunction``'s ``getFunction()`` accessor method --- but remember, you
732*9880d681SAndroid Build Coastguard Workermay not modify the LLVM ``Function`` or its contents from a
733*9880d681SAndroid Build Coastguard Worker``MachineFunctionPass``.
734*9880d681SAndroid Build Coastguard Worker
735*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-registration:
736*9880d681SAndroid Build Coastguard Worker
737*9880d681SAndroid Build Coastguard WorkerPass registration
738*9880d681SAndroid Build Coastguard Worker-----------------
739*9880d681SAndroid Build Coastguard Worker
740*9880d681SAndroid Build Coastguard WorkerIn the :ref:`Hello World <writing-an-llvm-pass-basiccode>` example pass we
741*9880d681SAndroid Build Coastguard Workerillustrated how pass registration works, and discussed some of the reasons that
742*9880d681SAndroid Build Coastguard Workerit is used and what it does.  Here we discuss how and why passes are
743*9880d681SAndroid Build Coastguard Workerregistered.
744*9880d681SAndroid Build Coastguard Worker
745*9880d681SAndroid Build Coastguard WorkerAs we saw above, passes are registered with the ``RegisterPass`` template.  The
746*9880d681SAndroid Build Coastguard Workertemplate parameter is the name of the pass that is to be used on the command
747*9880d681SAndroid Build Coastguard Workerline to specify that the pass should be added to a program (for example, with
748*9880d681SAndroid Build Coastguard Worker:program:`opt` or :program:`bugpoint`).  The first argument is the name of the
749*9880d681SAndroid Build Coastguard Workerpass, which is to be used for the :option:`-help` output of programs, as well
750*9880d681SAndroid Build Coastguard Workeras for debug output generated by the :option:`--debug-pass` option.
751*9880d681SAndroid Build Coastguard Worker
752*9880d681SAndroid Build Coastguard WorkerIf you want your pass to be easily dumpable, you should implement the virtual
753*9880d681SAndroid Build Coastguard Workerprint method:
754*9880d681SAndroid Build Coastguard Worker
755*9880d681SAndroid Build Coastguard WorkerThe ``print`` method
756*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^
757*9880d681SAndroid Build Coastguard Worker
758*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
759*9880d681SAndroid Build Coastguard Worker
760*9880d681SAndroid Build Coastguard Worker  virtual void print(llvm::raw_ostream &O, const Module *M) const;
761*9880d681SAndroid Build Coastguard Worker
762*9880d681SAndroid Build Coastguard WorkerThe ``print`` method must be implemented by "analyses" in order to print a
763*9880d681SAndroid Build Coastguard Workerhuman readable version of the analysis results.  This is useful for debugging
764*9880d681SAndroid Build Coastguard Workeran analysis itself, as well as for other people to figure out how an analysis
765*9880d681SAndroid Build Coastguard Workerworks.  Use the opt ``-analyze`` argument to invoke this method.
766*9880d681SAndroid Build Coastguard Worker
767*9880d681SAndroid Build Coastguard WorkerThe ``llvm::raw_ostream`` parameter specifies the stream to write the results
768*9880d681SAndroid Build Coastguard Workeron, and the ``Module`` parameter gives a pointer to the top level module of the
769*9880d681SAndroid Build Coastguard Workerprogram that has been analyzed.  Note however that this pointer may be ``NULL``
770*9880d681SAndroid Build Coastguard Workerin certain circumstances (such as calling the ``Pass::dump()`` from a
771*9880d681SAndroid Build Coastguard Workerdebugger), so it should only be used to enhance debug output, it should not be
772*9880d681SAndroid Build Coastguard Workerdepended on.
773*9880d681SAndroid Build Coastguard Worker
774*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-interaction:
775*9880d681SAndroid Build Coastguard Worker
776*9880d681SAndroid Build Coastguard WorkerSpecifying interactions between passes
777*9880d681SAndroid Build Coastguard Worker--------------------------------------
778*9880d681SAndroid Build Coastguard Worker
779*9880d681SAndroid Build Coastguard WorkerOne of the main responsibilities of the ``PassManager`` is to make sure that
780*9880d681SAndroid Build Coastguard Workerpasses interact with each other correctly.  Because ``PassManager`` tries to
781*9880d681SAndroid Build Coastguard Worker:ref:`optimize the execution of passes <writing-an-llvm-pass-passmanager>` it
782*9880d681SAndroid Build Coastguard Workermust know how the passes interact with each other and what dependencies exist
783*9880d681SAndroid Build Coastguard Workerbetween the various passes.  To track this, each pass can declare the set of
784*9880d681SAndroid Build Coastguard Workerpasses that are required to be executed before the current pass, and the passes
785*9880d681SAndroid Build Coastguard Workerwhich are invalidated by the current pass.
786*9880d681SAndroid Build Coastguard Worker
787*9880d681SAndroid Build Coastguard WorkerTypically this functionality is used to require that analysis results are
788*9880d681SAndroid Build Coastguard Workercomputed before your pass is run.  Running arbitrary transformation passes can
789*9880d681SAndroid Build Coastguard Workerinvalidate the computed analysis results, which is what the invalidation set
790*9880d681SAndroid Build Coastguard Workerspecifies.  If a pass does not implement the :ref:`getAnalysisUsage
791*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-getAnalysisUsage>` method, it defaults to not having any
792*9880d681SAndroid Build Coastguard Workerprerequisite passes, and invalidating **all** other passes.
793*9880d681SAndroid Build Coastguard Worker
794*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-getAnalysisUsage:
795*9880d681SAndroid Build Coastguard Worker
796*9880d681SAndroid Build Coastguard WorkerThe ``getAnalysisUsage`` method
797*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
798*9880d681SAndroid Build Coastguard Worker
799*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
800*9880d681SAndroid Build Coastguard Worker
801*9880d681SAndroid Build Coastguard Worker  virtual void getAnalysisUsage(AnalysisUsage &Info) const;
802*9880d681SAndroid Build Coastguard Worker
803*9880d681SAndroid Build Coastguard WorkerBy implementing the ``getAnalysisUsage`` method, the required and invalidated
804*9880d681SAndroid Build Coastguard Workersets may be specified for your transformation.  The implementation should fill
805*9880d681SAndroid Build Coastguard Workerin the `AnalysisUsage
806*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/classllvm_1_1AnalysisUsage.html>`_ object with
807*9880d681SAndroid Build Coastguard Workerinformation about which passes are required and not invalidated.  To do this, a
808*9880d681SAndroid Build Coastguard Workerpass may call any of the following methods on the ``AnalysisUsage`` object:
809*9880d681SAndroid Build Coastguard Worker
810*9880d681SAndroid Build Coastguard WorkerThe ``AnalysisUsage::addRequired<>`` and ``AnalysisUsage::addRequiredTransitive<>`` methods
811*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
812*9880d681SAndroid Build Coastguard Worker
813*9880d681SAndroid Build Coastguard WorkerIf your pass requires a previous pass to be executed (an analysis for example),
814*9880d681SAndroid Build Coastguard Workerit can use one of these methods to arrange for it to be run before your pass.
815*9880d681SAndroid Build Coastguard WorkerLLVM has many different types of analyses and passes that can be required,
816*9880d681SAndroid Build Coastguard Workerspanning the range from ``DominatorSet`` to ``BreakCriticalEdges``.  Requiring
817*9880d681SAndroid Build Coastguard Worker``BreakCriticalEdges``, for example, guarantees that there will be no critical
818*9880d681SAndroid Build Coastguard Workeredges in the CFG when your pass has been run.
819*9880d681SAndroid Build Coastguard Worker
820*9880d681SAndroid Build Coastguard WorkerSome analyses chain to other analyses to do their job.  For example, an
821*9880d681SAndroid Build Coastguard Worker`AliasAnalysis <AliasAnalysis>` implementation is required to :ref:`chain
822*9880d681SAndroid Build Coastguard Worker<aliasanalysis-chaining>` to other alias analysis passes.  In cases where
823*9880d681SAndroid Build Coastguard Workeranalyses chain, the ``addRequiredTransitive`` method should be used instead of
824*9880d681SAndroid Build Coastguard Workerthe ``addRequired`` method.  This informs the ``PassManager`` that the
825*9880d681SAndroid Build Coastguard Workertransitively required pass should be alive as long as the requiring pass is.
826*9880d681SAndroid Build Coastguard Worker
827*9880d681SAndroid Build Coastguard WorkerThe ``AnalysisUsage::addPreserved<>`` method
828*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
829*9880d681SAndroid Build Coastguard Worker
830*9880d681SAndroid Build Coastguard WorkerOne of the jobs of the ``PassManager`` is to optimize how and when analyses are
831*9880d681SAndroid Build Coastguard Workerrun.  In particular, it attempts to avoid recomputing data unless it needs to.
832*9880d681SAndroid Build Coastguard WorkerFor this reason, passes are allowed to declare that they preserve (i.e., they
833*9880d681SAndroid Build Coastguard Workerdon't invalidate) an existing analysis if it's available.  For example, a
834*9880d681SAndroid Build Coastguard Workersimple constant folding pass would not modify the CFG, so it can't possibly
835*9880d681SAndroid Build Coastguard Workeraffect the results of dominator analysis.  By default, all passes are assumed
836*9880d681SAndroid Build Coastguard Workerto invalidate all others.
837*9880d681SAndroid Build Coastguard Worker
838*9880d681SAndroid Build Coastguard WorkerThe ``AnalysisUsage`` class provides several methods which are useful in
839*9880d681SAndroid Build Coastguard Workercertain circumstances that are related to ``addPreserved``.  In particular, the
840*9880d681SAndroid Build Coastguard Worker``setPreservesAll`` method can be called to indicate that the pass does not
841*9880d681SAndroid Build Coastguard Workermodify the LLVM program at all (which is true for analyses), and the
842*9880d681SAndroid Build Coastguard Worker``setPreservesCFG`` method can be used by transformations that change
843*9880d681SAndroid Build Coastguard Workerinstructions in the program but do not modify the CFG or terminator
844*9880d681SAndroid Build Coastguard Workerinstructions (note that this property is implicitly set for
845*9880d681SAndroid Build Coastguard Worker:ref:`BasicBlockPass <writing-an-llvm-pass-BasicBlockPass>`\ es).
846*9880d681SAndroid Build Coastguard Worker
847*9880d681SAndroid Build Coastguard Worker``addPreserved`` is particularly useful for transformations like
848*9880d681SAndroid Build Coastguard Worker``BreakCriticalEdges``.  This pass knows how to update a small set of loop and
849*9880d681SAndroid Build Coastguard Workerdominator related analyses if they exist, so it can preserve them, despite the
850*9880d681SAndroid Build Coastguard Workerfact that it hacks on the CFG.
851*9880d681SAndroid Build Coastguard Worker
852*9880d681SAndroid Build Coastguard WorkerExample implementations of ``getAnalysisUsage``
853*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
854*9880d681SAndroid Build Coastguard Worker
855*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
856*9880d681SAndroid Build Coastguard Worker
857*9880d681SAndroid Build Coastguard Worker  // This example modifies the program, but does not modify the CFG
858*9880d681SAndroid Build Coastguard Worker  void LICM::getAnalysisUsage(AnalysisUsage &AU) const {
859*9880d681SAndroid Build Coastguard Worker    AU.setPreservesCFG();
860*9880d681SAndroid Build Coastguard Worker    AU.addRequired<LoopInfoWrapperPass>();
861*9880d681SAndroid Build Coastguard Worker  }
862*9880d681SAndroid Build Coastguard Worker
863*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-getAnalysis:
864*9880d681SAndroid Build Coastguard Worker
865*9880d681SAndroid Build Coastguard WorkerThe ``getAnalysis<>`` and ``getAnalysisIfAvailable<>`` methods
866*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
867*9880d681SAndroid Build Coastguard Worker
868*9880d681SAndroid Build Coastguard WorkerThe ``Pass::getAnalysis<>`` method is automatically inherited by your class,
869*9880d681SAndroid Build Coastguard Workerproviding you with access to the passes that you declared that you required
870*9880d681SAndroid Build Coastguard Workerwith the :ref:`getAnalysisUsage <writing-an-llvm-pass-getAnalysisUsage>`
871*9880d681SAndroid Build Coastguard Workermethod.  It takes a single template argument that specifies which pass class
872*9880d681SAndroid Build Coastguard Workeryou want, and returns a reference to that pass.  For example:
873*9880d681SAndroid Build Coastguard Worker
874*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
875*9880d681SAndroid Build Coastguard Worker
876*9880d681SAndroid Build Coastguard Worker  bool LICM::runOnFunction(Function &F) {
877*9880d681SAndroid Build Coastguard Worker    LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
878*9880d681SAndroid Build Coastguard Worker    //...
879*9880d681SAndroid Build Coastguard Worker  }
880*9880d681SAndroid Build Coastguard Worker
881*9880d681SAndroid Build Coastguard WorkerThis method call returns a reference to the pass desired.  You may get a
882*9880d681SAndroid Build Coastguard Workerruntime assertion failure if you attempt to get an analysis that you did not
883*9880d681SAndroid Build Coastguard Workerdeclare as required in your :ref:`getAnalysisUsage
884*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-getAnalysisUsage>` implementation.  This method can be
885*9880d681SAndroid Build Coastguard Workercalled by your ``run*`` method implementation, or by any other local method
886*9880d681SAndroid Build Coastguard Workerinvoked by your ``run*`` method.
887*9880d681SAndroid Build Coastguard Worker
888*9880d681SAndroid Build Coastguard WorkerA module level pass can use function level analysis info using this interface.
889*9880d681SAndroid Build Coastguard WorkerFor example:
890*9880d681SAndroid Build Coastguard Worker
891*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
892*9880d681SAndroid Build Coastguard Worker
893*9880d681SAndroid Build Coastguard Worker  bool ModuleLevelPass::runOnModule(Module &M) {
894*9880d681SAndroid Build Coastguard Worker    //...
895*9880d681SAndroid Build Coastguard Worker    DominatorTree &DT = getAnalysis<DominatorTree>(Func);
896*9880d681SAndroid Build Coastguard Worker    //...
897*9880d681SAndroid Build Coastguard Worker  }
898*9880d681SAndroid Build Coastguard Worker
899*9880d681SAndroid Build Coastguard WorkerIn above example, ``runOnFunction`` for ``DominatorTree`` is called by pass
900*9880d681SAndroid Build Coastguard Workermanager before returning a reference to the desired pass.
901*9880d681SAndroid Build Coastguard Worker
902*9880d681SAndroid Build Coastguard WorkerIf your pass is capable of updating analyses if they exist (e.g.,
903*9880d681SAndroid Build Coastguard Worker``BreakCriticalEdges``, as described above), you can use the
904*9880d681SAndroid Build Coastguard Worker``getAnalysisIfAvailable`` method, which returns a pointer to the analysis if
905*9880d681SAndroid Build Coastguard Workerit is active.  For example:
906*9880d681SAndroid Build Coastguard Worker
907*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
908*9880d681SAndroid Build Coastguard Worker
909*9880d681SAndroid Build Coastguard Worker  if (DominatorSet *DS = getAnalysisIfAvailable<DominatorSet>()) {
910*9880d681SAndroid Build Coastguard Worker    // A DominatorSet is active.  This code will update it.
911*9880d681SAndroid Build Coastguard Worker  }
912*9880d681SAndroid Build Coastguard Worker
913*9880d681SAndroid Build Coastguard WorkerImplementing Analysis Groups
914*9880d681SAndroid Build Coastguard Worker----------------------------
915*9880d681SAndroid Build Coastguard Worker
916*9880d681SAndroid Build Coastguard WorkerNow that we understand the basics of how passes are defined, how they are used,
917*9880d681SAndroid Build Coastguard Workerand how they are required from other passes, it's time to get a little bit
918*9880d681SAndroid Build Coastguard Workerfancier.  All of the pass relationships that we have seen so far are very
919*9880d681SAndroid Build Coastguard Workersimple: one pass depends on one other specific pass to be run before it can
920*9880d681SAndroid Build Coastguard Workerrun.  For many applications, this is great, for others, more flexibility is
921*9880d681SAndroid Build Coastguard Workerrequired.
922*9880d681SAndroid Build Coastguard Worker
923*9880d681SAndroid Build Coastguard WorkerIn particular, some analyses are defined such that there is a single simple
924*9880d681SAndroid Build Coastguard Workerinterface to the analysis results, but multiple ways of calculating them.
925*9880d681SAndroid Build Coastguard WorkerConsider alias analysis for example.  The most trivial alias analysis returns
926*9880d681SAndroid Build Coastguard Worker"may alias" for any alias query.  The most sophisticated analysis a
927*9880d681SAndroid Build Coastguard Workerflow-sensitive, context-sensitive interprocedural analysis that can take a
928*9880d681SAndroid Build Coastguard Workersignificant amount of time to execute (and obviously, there is a lot of room
929*9880d681SAndroid Build Coastguard Workerbetween these two extremes for other implementations).  To cleanly support
930*9880d681SAndroid Build Coastguard Workersituations like this, the LLVM Pass Infrastructure supports the notion of
931*9880d681SAndroid Build Coastguard WorkerAnalysis Groups.
932*9880d681SAndroid Build Coastguard Worker
933*9880d681SAndroid Build Coastguard WorkerAnalysis Group Concepts
934*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^
935*9880d681SAndroid Build Coastguard Worker
936*9880d681SAndroid Build Coastguard WorkerAn Analysis Group is a single simple interface that may be implemented by
937*9880d681SAndroid Build Coastguard Workermultiple different passes.  Analysis Groups can be given human readable names
938*9880d681SAndroid Build Coastguard Workerjust like passes, but unlike passes, they need not derive from the ``Pass``
939*9880d681SAndroid Build Coastguard Workerclass.  An analysis group may have one or more implementations, one of which is
940*9880d681SAndroid Build Coastguard Workerthe "default" implementation.
941*9880d681SAndroid Build Coastguard Worker
942*9880d681SAndroid Build Coastguard WorkerAnalysis groups are used by client passes just like other passes are: the
943*9880d681SAndroid Build Coastguard Worker``AnalysisUsage::addRequired()`` and ``Pass::getAnalysis()`` methods.  In order
944*9880d681SAndroid Build Coastguard Workerto resolve this requirement, the :ref:`PassManager
945*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-passmanager>` scans the available passes to see if any
946*9880d681SAndroid Build Coastguard Workerimplementations of the analysis group are available.  If none is available, the
947*9880d681SAndroid Build Coastguard Workerdefault implementation is created for the pass to use.  All standard rules for
948*9880d681SAndroid Build Coastguard Worker:ref:`interaction between passes <writing-an-llvm-pass-interaction>` still
949*9880d681SAndroid Build Coastguard Workerapply.
950*9880d681SAndroid Build Coastguard Worker
951*9880d681SAndroid Build Coastguard WorkerAlthough :ref:`Pass Registration <writing-an-llvm-pass-registration>` is
952*9880d681SAndroid Build Coastguard Workeroptional for normal passes, all analysis group implementations must be
953*9880d681SAndroid Build Coastguard Workerregistered, and must use the :ref:`INITIALIZE_AG_PASS
954*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-RegisterAnalysisGroup>` template to join the
955*9880d681SAndroid Build Coastguard Workerimplementation pool.  Also, a default implementation of the interface **must**
956*9880d681SAndroid Build Coastguard Workerbe registered with :ref:`RegisterAnalysisGroup
957*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-RegisterAnalysisGroup>`.
958*9880d681SAndroid Build Coastguard Worker
959*9880d681SAndroid Build Coastguard WorkerAs a concrete example of an Analysis Group in action, consider the
960*9880d681SAndroid Build Coastguard Worker`AliasAnalysis <http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`_
961*9880d681SAndroid Build Coastguard Workeranalysis group.  The default implementation of the alias analysis interface
962*9880d681SAndroid Build Coastguard Worker(the `basicaa <http://llvm.org/doxygen/structBasicAliasAnalysis.html>`_ pass)
963*9880d681SAndroid Build Coastguard Workerjust does a few simple checks that don't require significant analysis to
964*9880d681SAndroid Build Coastguard Workercompute (such as: two different globals can never alias each other, etc).
965*9880d681SAndroid Build Coastguard WorkerPasses that use the `AliasAnalysis
966*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`_ interface (for
967*9880d681SAndroid Build Coastguard Workerexample the `gcse <http://llvm.org/doxygen/structGCSE.html>`_ pass), do not
968*9880d681SAndroid Build Coastguard Workercare which implementation of alias analysis is actually provided, they just use
969*9880d681SAndroid Build Coastguard Workerthe designated interface.
970*9880d681SAndroid Build Coastguard Worker
971*9880d681SAndroid Build Coastguard WorkerFrom the user's perspective, commands work just like normal.  Issuing the
972*9880d681SAndroid Build Coastguard Workercommand ``opt -gcse ...`` will cause the ``basicaa`` class to be instantiated
973*9880d681SAndroid Build Coastguard Workerand added to the pass sequence.  Issuing the command ``opt -somefancyaa -gcse
974*9880d681SAndroid Build Coastguard Worker...`` will cause the ``gcse`` pass to use the ``somefancyaa`` alias analysis
975*9880d681SAndroid Build Coastguard Worker(which doesn't actually exist, it's just a hypothetical example) instead.
976*9880d681SAndroid Build Coastguard Worker
977*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-RegisterAnalysisGroup:
978*9880d681SAndroid Build Coastguard Worker
979*9880d681SAndroid Build Coastguard WorkerUsing ``RegisterAnalysisGroup``
980*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
981*9880d681SAndroid Build Coastguard Worker
982*9880d681SAndroid Build Coastguard WorkerThe ``RegisterAnalysisGroup`` template is used to register the analysis group
983*9880d681SAndroid Build Coastguard Workeritself, while the ``INITIALIZE_AG_PASS`` is used to add pass implementations to
984*9880d681SAndroid Build Coastguard Workerthe analysis group.  First, an analysis group should be registered, with a
985*9880d681SAndroid Build Coastguard Workerhuman readable name provided for it.  Unlike registration of passes, there is
986*9880d681SAndroid Build Coastguard Workerno command line argument to be specified for the Analysis Group Interface
987*9880d681SAndroid Build Coastguard Workeritself, because it is "abstract":
988*9880d681SAndroid Build Coastguard Worker
989*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
990*9880d681SAndroid Build Coastguard Worker
991*9880d681SAndroid Build Coastguard Worker  static RegisterAnalysisGroup<AliasAnalysis> A("Alias Analysis");
992*9880d681SAndroid Build Coastguard Worker
993*9880d681SAndroid Build Coastguard WorkerOnce the analysis is registered, passes can declare that they are valid
994*9880d681SAndroid Build Coastguard Workerimplementations of the interface by using the following code:
995*9880d681SAndroid Build Coastguard Worker
996*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
997*9880d681SAndroid Build Coastguard Worker
998*9880d681SAndroid Build Coastguard Worker  namespace {
999*9880d681SAndroid Build Coastguard Worker    // Declare that we implement the AliasAnalysis interface
1000*9880d681SAndroid Build Coastguard Worker    INITIALIZE_AG_PASS(FancyAA, AliasAnalysis , "somefancyaa",
1001*9880d681SAndroid Build Coastguard Worker        "A more complex alias analysis implementation",
1002*9880d681SAndroid Build Coastguard Worker        false,  // Is CFG Only?
1003*9880d681SAndroid Build Coastguard Worker        true,   // Is Analysis?
1004*9880d681SAndroid Build Coastguard Worker        false); // Is default Analysis Group implementation?
1005*9880d681SAndroid Build Coastguard Worker  }
1006*9880d681SAndroid Build Coastguard Worker
1007*9880d681SAndroid Build Coastguard WorkerThis just shows a class ``FancyAA`` that uses the ``INITIALIZE_AG_PASS`` macro
1008*9880d681SAndroid Build Coastguard Workerboth to register and to "join" the `AliasAnalysis
1009*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`_ analysis group.
1010*9880d681SAndroid Build Coastguard WorkerEvery implementation of an analysis group should join using this macro.
1011*9880d681SAndroid Build Coastguard Worker
1012*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1013*9880d681SAndroid Build Coastguard Worker
1014*9880d681SAndroid Build Coastguard Worker  namespace {
1015*9880d681SAndroid Build Coastguard Worker    // Declare that we implement the AliasAnalysis interface
1016*9880d681SAndroid Build Coastguard Worker    INITIALIZE_AG_PASS(BasicAA, AliasAnalysis, "basicaa",
1017*9880d681SAndroid Build Coastguard Worker        "Basic Alias Analysis (default AA impl)",
1018*9880d681SAndroid Build Coastguard Worker        false, // Is CFG Only?
1019*9880d681SAndroid Build Coastguard Worker        true,  // Is Analysis?
1020*9880d681SAndroid Build Coastguard Worker        true); // Is default Analysis Group implementation?
1021*9880d681SAndroid Build Coastguard Worker  }
1022*9880d681SAndroid Build Coastguard Worker
1023*9880d681SAndroid Build Coastguard WorkerHere we show how the default implementation is specified (using the final
1024*9880d681SAndroid Build Coastguard Workerargument to the ``INITIALIZE_AG_PASS`` template).  There must be exactly one
1025*9880d681SAndroid Build Coastguard Workerdefault implementation available at all times for an Analysis Group to be used.
1026*9880d681SAndroid Build Coastguard WorkerOnly default implementation can derive from ``ImmutablePass``.  Here we declare
1027*9880d681SAndroid Build Coastguard Workerthat the `BasicAliasAnalysis
1028*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/structBasicAliasAnalysis.html>`_ pass is the default
1029*9880d681SAndroid Build Coastguard Workerimplementation for the interface.
1030*9880d681SAndroid Build Coastguard Worker
1031*9880d681SAndroid Build Coastguard WorkerPass Statistics
1032*9880d681SAndroid Build Coastguard Worker===============
1033*9880d681SAndroid Build Coastguard Worker
1034*9880d681SAndroid Build Coastguard WorkerThe `Statistic <http://llvm.org/doxygen/Statistic_8h-source.html>`_ class is
1035*9880d681SAndroid Build Coastguard Workerdesigned to be an easy way to expose various success metrics from passes.
1036*9880d681SAndroid Build Coastguard WorkerThese statistics are printed at the end of a run, when the :option:`-stats`
1037*9880d681SAndroid Build Coastguard Workercommand line option is enabled on the command line.  See the :ref:`Statistics
1038*9880d681SAndroid Build Coastguard Workersection <Statistic>` in the Programmer's Manual for details.
1039*9880d681SAndroid Build Coastguard Worker
1040*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-passmanager:
1041*9880d681SAndroid Build Coastguard Worker
1042*9880d681SAndroid Build Coastguard WorkerWhat PassManager does
1043*9880d681SAndroid Build Coastguard Worker---------------------
1044*9880d681SAndroid Build Coastguard Worker
1045*9880d681SAndroid Build Coastguard WorkerThe `PassManager <http://llvm.org/doxygen/PassManager_8h-source.html>`_ `class
1046*9880d681SAndroid Build Coastguard Worker<http://llvm.org/doxygen/classllvm_1_1PassManager.html>`_ takes a list of
1047*9880d681SAndroid Build Coastguard Workerpasses, ensures their :ref:`prerequisites <writing-an-llvm-pass-interaction>`
1048*9880d681SAndroid Build Coastguard Workerare set up correctly, and then schedules passes to run efficiently.  All of the
1049*9880d681SAndroid Build Coastguard WorkerLLVM tools that run passes use the PassManager for execution of these passes.
1050*9880d681SAndroid Build Coastguard Worker
1051*9880d681SAndroid Build Coastguard WorkerThe PassManager does two main things to try to reduce the execution time of a
1052*9880d681SAndroid Build Coastguard Workerseries of passes:
1053*9880d681SAndroid Build Coastguard Worker
1054*9880d681SAndroid Build Coastguard Worker#. **Share analysis results.**  The ``PassManager`` attempts to avoid
1055*9880d681SAndroid Build Coastguard Worker   recomputing analysis results as much as possible.  This means keeping track
1056*9880d681SAndroid Build Coastguard Worker   of which analyses are available already, which analyses get invalidated, and
1057*9880d681SAndroid Build Coastguard Worker   which analyses are needed to be run for a pass.  An important part of work
1058*9880d681SAndroid Build Coastguard Worker   is that the ``PassManager`` tracks the exact lifetime of all analysis
1059*9880d681SAndroid Build Coastguard Worker   results, allowing it to :ref:`free memory
1060*9880d681SAndroid Build Coastguard Worker   <writing-an-llvm-pass-releaseMemory>` allocated to holding analysis results
1061*9880d681SAndroid Build Coastguard Worker   as soon as they are no longer needed.
1062*9880d681SAndroid Build Coastguard Worker
1063*9880d681SAndroid Build Coastguard Worker#. **Pipeline the execution of passes on the program.**  The ``PassManager``
1064*9880d681SAndroid Build Coastguard Worker   attempts to get better cache and memory usage behavior out of a series of
1065*9880d681SAndroid Build Coastguard Worker   passes by pipelining the passes together.  This means that, given a series
1066*9880d681SAndroid Build Coastguard Worker   of consecutive :ref:`FunctionPass <writing-an-llvm-pass-FunctionPass>`, it
1067*9880d681SAndroid Build Coastguard Worker   will execute all of the :ref:`FunctionPass
1068*9880d681SAndroid Build Coastguard Worker   <writing-an-llvm-pass-FunctionPass>` on the first function, then all of the
1069*9880d681SAndroid Build Coastguard Worker   :ref:`FunctionPasses <writing-an-llvm-pass-FunctionPass>` on the second
1070*9880d681SAndroid Build Coastguard Worker   function, etc... until the entire program has been run through the passes.
1071*9880d681SAndroid Build Coastguard Worker
1072*9880d681SAndroid Build Coastguard Worker   This improves the cache behavior of the compiler, because it is only
1073*9880d681SAndroid Build Coastguard Worker   touching the LLVM program representation for a single function at a time,
1074*9880d681SAndroid Build Coastguard Worker   instead of traversing the entire program.  It reduces the memory consumption
1075*9880d681SAndroid Build Coastguard Worker   of compiler, because, for example, only one `DominatorSet
1076*9880d681SAndroid Build Coastguard Worker   <http://llvm.org/doxygen/classllvm_1_1DominatorSet.html>`_ needs to be
1077*9880d681SAndroid Build Coastguard Worker   calculated at a time.  This also makes it possible to implement some
1078*9880d681SAndroid Build Coastguard Worker   :ref:`interesting enhancements <writing-an-llvm-pass-SMP>` in the future.
1079*9880d681SAndroid Build Coastguard Worker
1080*9880d681SAndroid Build Coastguard WorkerThe effectiveness of the ``PassManager`` is influenced directly by how much
1081*9880d681SAndroid Build Coastguard Workerinformation it has about the behaviors of the passes it is scheduling.  For
1082*9880d681SAndroid Build Coastguard Workerexample, the "preserved" set is intentionally conservative in the face of an
1083*9880d681SAndroid Build Coastguard Workerunimplemented :ref:`getAnalysisUsage <writing-an-llvm-pass-getAnalysisUsage>`
1084*9880d681SAndroid Build Coastguard Workermethod.  Not implementing when it should be implemented will have the effect of
1085*9880d681SAndroid Build Coastguard Workernot allowing any analysis results to live across the execution of your pass.
1086*9880d681SAndroid Build Coastguard Worker
1087*9880d681SAndroid Build Coastguard WorkerThe ``PassManager`` class exposes a ``--debug-pass`` command line options that
1088*9880d681SAndroid Build Coastguard Workeris useful for debugging pass execution, seeing how things work, and diagnosing
1089*9880d681SAndroid Build Coastguard Workerwhen you should be preserving more analyses than you currently are.  (To get
1090*9880d681SAndroid Build Coastguard Workerinformation about all of the variants of the ``--debug-pass`` option, just type
1091*9880d681SAndroid Build Coastguard Worker"``opt -help-hidden``").
1092*9880d681SAndroid Build Coastguard Worker
1093*9880d681SAndroid Build Coastguard WorkerBy using the --debug-pass=Structure option, for example, we can see how our
1094*9880d681SAndroid Build Coastguard Worker:ref:`Hello World <writing-an-llvm-pass-basiccode>` pass interacts with other
1095*9880d681SAndroid Build Coastguard Workerpasses.  Lets try it out with the gcse and licm passes:
1096*9880d681SAndroid Build Coastguard Worker
1097*9880d681SAndroid Build Coastguard Worker.. code-block:: console
1098*9880d681SAndroid Build Coastguard Worker
1099*9880d681SAndroid Build Coastguard Worker  $ opt -load ../../Debug+Asserts/lib/Hello.so -gcse -licm --debug-pass=Structure < hello.bc > /dev/null
1100*9880d681SAndroid Build Coastguard Worker  Module Pass Manager
1101*9880d681SAndroid Build Coastguard Worker    Function Pass Manager
1102*9880d681SAndroid Build Coastguard Worker      Dominator Set Construction
1103*9880d681SAndroid Build Coastguard Worker      Immediate Dominators Construction
1104*9880d681SAndroid Build Coastguard Worker      Global Common Subexpression Elimination
1105*9880d681SAndroid Build Coastguard Worker  --  Immediate Dominators Construction
1106*9880d681SAndroid Build Coastguard Worker  --  Global Common Subexpression Elimination
1107*9880d681SAndroid Build Coastguard Worker      Natural Loop Construction
1108*9880d681SAndroid Build Coastguard Worker      Loop Invariant Code Motion
1109*9880d681SAndroid Build Coastguard Worker  --  Natural Loop Construction
1110*9880d681SAndroid Build Coastguard Worker  --  Loop Invariant Code Motion
1111*9880d681SAndroid Build Coastguard Worker      Module Verifier
1112*9880d681SAndroid Build Coastguard Worker  --  Dominator Set Construction
1113*9880d681SAndroid Build Coastguard Worker  --  Module Verifier
1114*9880d681SAndroid Build Coastguard Worker    Bitcode Writer
1115*9880d681SAndroid Build Coastguard Worker  --Bitcode Writer
1116*9880d681SAndroid Build Coastguard Worker
1117*9880d681SAndroid Build Coastguard WorkerThis output shows us when passes are constructed and when the analysis results
1118*9880d681SAndroid Build Coastguard Workerare known to be dead (prefixed with "``--``").  Here we see that GCSE uses
1119*9880d681SAndroid Build Coastguard Workerdominator and immediate dominator information to do its job.  The LICM pass
1120*9880d681SAndroid Build Coastguard Workeruses natural loop information, which uses dominator sets, but not immediate
1121*9880d681SAndroid Build Coastguard Workerdominators.  Because immediate dominators are no longer useful after the GCSE
1122*9880d681SAndroid Build Coastguard Workerpass, it is immediately destroyed.  The dominator sets are then reused to
1123*9880d681SAndroid Build Coastguard Workercompute natural loop information, which is then used by the LICM pass.
1124*9880d681SAndroid Build Coastguard Worker
1125*9880d681SAndroid Build Coastguard WorkerAfter the LICM pass, the module verifier runs (which is automatically added by
1126*9880d681SAndroid Build Coastguard Workerthe :program:`opt` tool), which uses the dominator set to check that the
1127*9880d681SAndroid Build Coastguard Workerresultant LLVM code is well formed.  After it finishes, the dominator set
1128*9880d681SAndroid Build Coastguard Workerinformation is destroyed, after being computed once, and shared by three
1129*9880d681SAndroid Build Coastguard Workerpasses.
1130*9880d681SAndroid Build Coastguard Worker
1131*9880d681SAndroid Build Coastguard WorkerLets see how this changes when we run the :ref:`Hello World
1132*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-basiccode>` pass in between the two passes:
1133*9880d681SAndroid Build Coastguard Worker
1134*9880d681SAndroid Build Coastguard Worker.. code-block:: console
1135*9880d681SAndroid Build Coastguard Worker
1136*9880d681SAndroid Build Coastguard Worker  $ opt -load ../../Debug+Asserts/lib/Hello.so -gcse -hello -licm --debug-pass=Structure < hello.bc > /dev/null
1137*9880d681SAndroid Build Coastguard Worker  Module Pass Manager
1138*9880d681SAndroid Build Coastguard Worker    Function Pass Manager
1139*9880d681SAndroid Build Coastguard Worker      Dominator Set Construction
1140*9880d681SAndroid Build Coastguard Worker      Immediate Dominators Construction
1141*9880d681SAndroid Build Coastguard Worker      Global Common Subexpression Elimination
1142*9880d681SAndroid Build Coastguard Worker  --  Dominator Set Construction
1143*9880d681SAndroid Build Coastguard Worker  --  Immediate Dominators Construction
1144*9880d681SAndroid Build Coastguard Worker  --  Global Common Subexpression Elimination
1145*9880d681SAndroid Build Coastguard Worker      Hello World Pass
1146*9880d681SAndroid Build Coastguard Worker  --  Hello World Pass
1147*9880d681SAndroid Build Coastguard Worker      Dominator Set Construction
1148*9880d681SAndroid Build Coastguard Worker      Natural Loop Construction
1149*9880d681SAndroid Build Coastguard Worker      Loop Invariant Code Motion
1150*9880d681SAndroid Build Coastguard Worker  --  Natural Loop Construction
1151*9880d681SAndroid Build Coastguard Worker  --  Loop Invariant Code Motion
1152*9880d681SAndroid Build Coastguard Worker      Module Verifier
1153*9880d681SAndroid Build Coastguard Worker  --  Dominator Set Construction
1154*9880d681SAndroid Build Coastguard Worker  --  Module Verifier
1155*9880d681SAndroid Build Coastguard Worker    Bitcode Writer
1156*9880d681SAndroid Build Coastguard Worker  --Bitcode Writer
1157*9880d681SAndroid Build Coastguard Worker  Hello: __main
1158*9880d681SAndroid Build Coastguard Worker  Hello: puts
1159*9880d681SAndroid Build Coastguard Worker  Hello: main
1160*9880d681SAndroid Build Coastguard Worker
1161*9880d681SAndroid Build Coastguard WorkerHere we see that the :ref:`Hello World <writing-an-llvm-pass-basiccode>` pass
1162*9880d681SAndroid Build Coastguard Workerhas killed the Dominator Set pass, even though it doesn't modify the code at
1163*9880d681SAndroid Build Coastguard Workerall!  To fix this, we need to add the following :ref:`getAnalysisUsage
1164*9880d681SAndroid Build Coastguard Worker<writing-an-llvm-pass-getAnalysisUsage>` method to our pass:
1165*9880d681SAndroid Build Coastguard Worker
1166*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1167*9880d681SAndroid Build Coastguard Worker
1168*9880d681SAndroid Build Coastguard Worker  // We don't modify the program, so we preserve all analyses
1169*9880d681SAndroid Build Coastguard Worker  void getAnalysisUsage(AnalysisUsage &AU) const override {
1170*9880d681SAndroid Build Coastguard Worker    AU.setPreservesAll();
1171*9880d681SAndroid Build Coastguard Worker  }
1172*9880d681SAndroid Build Coastguard Worker
1173*9880d681SAndroid Build Coastguard WorkerNow when we run our pass, we get this output:
1174*9880d681SAndroid Build Coastguard Worker
1175*9880d681SAndroid Build Coastguard Worker.. code-block:: console
1176*9880d681SAndroid Build Coastguard Worker
1177*9880d681SAndroid Build Coastguard Worker  $ opt -load ../../Debug+Asserts/lib/Hello.so -gcse -hello -licm --debug-pass=Structure < hello.bc > /dev/null
1178*9880d681SAndroid Build Coastguard Worker  Pass Arguments:  -gcse -hello -licm
1179*9880d681SAndroid Build Coastguard Worker  Module Pass Manager
1180*9880d681SAndroid Build Coastguard Worker    Function Pass Manager
1181*9880d681SAndroid Build Coastguard Worker      Dominator Set Construction
1182*9880d681SAndroid Build Coastguard Worker      Immediate Dominators Construction
1183*9880d681SAndroid Build Coastguard Worker      Global Common Subexpression Elimination
1184*9880d681SAndroid Build Coastguard Worker  --  Immediate Dominators Construction
1185*9880d681SAndroid Build Coastguard Worker  --  Global Common Subexpression Elimination
1186*9880d681SAndroid Build Coastguard Worker      Hello World Pass
1187*9880d681SAndroid Build Coastguard Worker  --  Hello World Pass
1188*9880d681SAndroid Build Coastguard Worker      Natural Loop Construction
1189*9880d681SAndroid Build Coastguard Worker      Loop Invariant Code Motion
1190*9880d681SAndroid Build Coastguard Worker  --  Loop Invariant Code Motion
1191*9880d681SAndroid Build Coastguard Worker  --  Natural Loop Construction
1192*9880d681SAndroid Build Coastguard Worker      Module Verifier
1193*9880d681SAndroid Build Coastguard Worker  --  Dominator Set Construction
1194*9880d681SAndroid Build Coastguard Worker  --  Module Verifier
1195*9880d681SAndroid Build Coastguard Worker    Bitcode Writer
1196*9880d681SAndroid Build Coastguard Worker  --Bitcode Writer
1197*9880d681SAndroid Build Coastguard Worker  Hello: __main
1198*9880d681SAndroid Build Coastguard Worker  Hello: puts
1199*9880d681SAndroid Build Coastguard Worker  Hello: main
1200*9880d681SAndroid Build Coastguard Worker
1201*9880d681SAndroid Build Coastguard WorkerWhich shows that we don't accidentally invalidate dominator information
1202*9880d681SAndroid Build Coastguard Workeranymore, and therefore do not have to compute it twice.
1203*9880d681SAndroid Build Coastguard Worker
1204*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-releaseMemory:
1205*9880d681SAndroid Build Coastguard Worker
1206*9880d681SAndroid Build Coastguard WorkerThe ``releaseMemory`` method
1207*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1208*9880d681SAndroid Build Coastguard Worker
1209*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1210*9880d681SAndroid Build Coastguard Worker
1211*9880d681SAndroid Build Coastguard Worker  virtual void releaseMemory();
1212*9880d681SAndroid Build Coastguard Worker
1213*9880d681SAndroid Build Coastguard WorkerThe ``PassManager`` automatically determines when to compute analysis results,
1214*9880d681SAndroid Build Coastguard Workerand how long to keep them around for.  Because the lifetime of the pass object
1215*9880d681SAndroid Build Coastguard Workeritself is effectively the entire duration of the compilation process, we need
1216*9880d681SAndroid Build Coastguard Workersome way to free analysis results when they are no longer useful.  The
1217*9880d681SAndroid Build Coastguard Worker``releaseMemory`` virtual method is the way to do this.
1218*9880d681SAndroid Build Coastguard Worker
1219*9880d681SAndroid Build Coastguard WorkerIf you are writing an analysis or any other pass that retains a significant
1220*9880d681SAndroid Build Coastguard Workeramount of state (for use by another pass which "requires" your pass and uses
1221*9880d681SAndroid Build Coastguard Workerthe :ref:`getAnalysis <writing-an-llvm-pass-getAnalysis>` method) you should
1222*9880d681SAndroid Build Coastguard Workerimplement ``releaseMemory`` to, well, release the memory allocated to maintain
1223*9880d681SAndroid Build Coastguard Workerthis internal state.  This method is called after the ``run*`` method for the
1224*9880d681SAndroid Build Coastguard Workerclass, before the next call of ``run*`` in your pass.
1225*9880d681SAndroid Build Coastguard Worker
1226*9880d681SAndroid Build Coastguard WorkerRegistering dynamically loaded passes
1227*9880d681SAndroid Build Coastguard Worker=====================================
1228*9880d681SAndroid Build Coastguard Worker
1229*9880d681SAndroid Build Coastguard Worker*Size matters* when constructing production quality tools using LLVM, both for
1230*9880d681SAndroid Build Coastguard Workerthe purposes of distribution, and for regulating the resident code size when
1231*9880d681SAndroid Build Coastguard Workerrunning on the target system.  Therefore, it becomes desirable to selectively
1232*9880d681SAndroid Build Coastguard Workeruse some passes, while omitting others and maintain the flexibility to change
1233*9880d681SAndroid Build Coastguard Workerconfigurations later on.  You want to be able to do all this, and, provide
1234*9880d681SAndroid Build Coastguard Workerfeedback to the user.  This is where pass registration comes into play.
1235*9880d681SAndroid Build Coastguard Worker
1236*9880d681SAndroid Build Coastguard WorkerThe fundamental mechanisms for pass registration are the
1237*9880d681SAndroid Build Coastguard Worker``MachinePassRegistry`` class and subclasses of ``MachinePassRegistryNode``.
1238*9880d681SAndroid Build Coastguard Worker
1239*9880d681SAndroid Build Coastguard WorkerAn instance of ``MachinePassRegistry`` is used to maintain a list of
1240*9880d681SAndroid Build Coastguard Worker``MachinePassRegistryNode`` objects.  This instance maintains the list and
1241*9880d681SAndroid Build Coastguard Workercommunicates additions and deletions to the command line interface.
1242*9880d681SAndroid Build Coastguard Worker
1243*9880d681SAndroid Build Coastguard WorkerAn instance of ``MachinePassRegistryNode`` subclass is used to maintain
1244*9880d681SAndroid Build Coastguard Workerinformation provided about a particular pass.  This information includes the
1245*9880d681SAndroid Build Coastguard Workercommand line name, the command help string and the address of the function used
1246*9880d681SAndroid Build Coastguard Workerto create an instance of the pass.  A global static constructor of one of these
1247*9880d681SAndroid Build Coastguard Workerinstances *registers* with a corresponding ``MachinePassRegistry``, the static
1248*9880d681SAndroid Build Coastguard Workerdestructor *unregisters*.  Thus a pass that is statically linked in the tool
1249*9880d681SAndroid Build Coastguard Workerwill be registered at start up.  A dynamically loaded pass will register on
1250*9880d681SAndroid Build Coastguard Workerload and unregister at unload.
1251*9880d681SAndroid Build Coastguard Worker
1252*9880d681SAndroid Build Coastguard WorkerUsing existing registries
1253*9880d681SAndroid Build Coastguard Worker-------------------------
1254*9880d681SAndroid Build Coastguard Worker
1255*9880d681SAndroid Build Coastguard WorkerThere are predefined registries to track instruction scheduling
1256*9880d681SAndroid Build Coastguard Worker(``RegisterScheduler``) and register allocation (``RegisterRegAlloc``) machine
1257*9880d681SAndroid Build Coastguard Workerpasses.  Here we will describe how to *register* a register allocator machine
1258*9880d681SAndroid Build Coastguard Workerpass.
1259*9880d681SAndroid Build Coastguard Worker
1260*9880d681SAndroid Build Coastguard WorkerImplement your register allocator machine pass.  In your register allocator
1261*9880d681SAndroid Build Coastguard Worker``.cpp`` file add the following include:
1262*9880d681SAndroid Build Coastguard Worker
1263*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1264*9880d681SAndroid Build Coastguard Worker
1265*9880d681SAndroid Build Coastguard Worker  #include "llvm/CodeGen/RegAllocRegistry.h"
1266*9880d681SAndroid Build Coastguard Worker
1267*9880d681SAndroid Build Coastguard WorkerAlso in your register allocator ``.cpp`` file, define a creator function in the
1268*9880d681SAndroid Build Coastguard Workerform:
1269*9880d681SAndroid Build Coastguard Worker
1270*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1271*9880d681SAndroid Build Coastguard Worker
1272*9880d681SAndroid Build Coastguard Worker  FunctionPass *createMyRegisterAllocator() {
1273*9880d681SAndroid Build Coastguard Worker    return new MyRegisterAllocator();
1274*9880d681SAndroid Build Coastguard Worker  }
1275*9880d681SAndroid Build Coastguard Worker
1276*9880d681SAndroid Build Coastguard WorkerNote that the signature of this function should match the type of
1277*9880d681SAndroid Build Coastguard Worker``RegisterRegAlloc::FunctionPassCtor``.  In the same file add the "installing"
1278*9880d681SAndroid Build Coastguard Workerdeclaration, in the form:
1279*9880d681SAndroid Build Coastguard Worker
1280*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1281*9880d681SAndroid Build Coastguard Worker
1282*9880d681SAndroid Build Coastguard Worker  static RegisterRegAlloc myRegAlloc("myregalloc",
1283*9880d681SAndroid Build Coastguard Worker                                     "my register allocator help string",
1284*9880d681SAndroid Build Coastguard Worker                                     createMyRegisterAllocator);
1285*9880d681SAndroid Build Coastguard Worker
1286*9880d681SAndroid Build Coastguard WorkerNote the two spaces prior to the help string produces a tidy result on the
1287*9880d681SAndroid Build Coastguard Worker:option:`-help` query.
1288*9880d681SAndroid Build Coastguard Worker
1289*9880d681SAndroid Build Coastguard Worker.. code-block:: console
1290*9880d681SAndroid Build Coastguard Worker
1291*9880d681SAndroid Build Coastguard Worker  $ llc -help
1292*9880d681SAndroid Build Coastguard Worker    ...
1293*9880d681SAndroid Build Coastguard Worker    -regalloc                    - Register allocator to use (default=linearscan)
1294*9880d681SAndroid Build Coastguard Worker      =linearscan                -   linear scan register allocator
1295*9880d681SAndroid Build Coastguard Worker      =local                     -   local register allocator
1296*9880d681SAndroid Build Coastguard Worker      =simple                    -   simple register allocator
1297*9880d681SAndroid Build Coastguard Worker      =myregalloc                -   my register allocator help string
1298*9880d681SAndroid Build Coastguard Worker    ...
1299*9880d681SAndroid Build Coastguard Worker
1300*9880d681SAndroid Build Coastguard WorkerAnd that's it.  The user is now free to use ``-regalloc=myregalloc`` as an
1301*9880d681SAndroid Build Coastguard Workeroption.  Registering instruction schedulers is similar except use the
1302*9880d681SAndroid Build Coastguard Worker``RegisterScheduler`` class.  Note that the
1303*9880d681SAndroid Build Coastguard Worker``RegisterScheduler::FunctionPassCtor`` is significantly different from
1304*9880d681SAndroid Build Coastguard Worker``RegisterRegAlloc::FunctionPassCtor``.
1305*9880d681SAndroid Build Coastguard Worker
1306*9880d681SAndroid Build Coastguard WorkerTo force the load/linking of your register allocator into the
1307*9880d681SAndroid Build Coastguard Worker:program:`llc`/:program:`lli` tools, add your creator function's global
1308*9880d681SAndroid Build Coastguard Workerdeclaration to ``Passes.h`` and add a "pseudo" call line to
1309*9880d681SAndroid Build Coastguard Worker``llvm/Codegen/LinkAllCodegenComponents.h``.
1310*9880d681SAndroid Build Coastguard Worker
1311*9880d681SAndroid Build Coastguard WorkerCreating new registries
1312*9880d681SAndroid Build Coastguard Worker-----------------------
1313*9880d681SAndroid Build Coastguard Worker
1314*9880d681SAndroid Build Coastguard WorkerThe easiest way to get started is to clone one of the existing registries; we
1315*9880d681SAndroid Build Coastguard Workerrecommend ``llvm/CodeGen/RegAllocRegistry.h``.  The key things to modify are
1316*9880d681SAndroid Build Coastguard Workerthe class name and the ``FunctionPassCtor`` type.
1317*9880d681SAndroid Build Coastguard Worker
1318*9880d681SAndroid Build Coastguard WorkerThen you need to declare the registry.  Example: if your pass registry is
1319*9880d681SAndroid Build Coastguard Worker``RegisterMyPasses`` then define:
1320*9880d681SAndroid Build Coastguard Worker
1321*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1322*9880d681SAndroid Build Coastguard Worker
1323*9880d681SAndroid Build Coastguard Worker  MachinePassRegistry RegisterMyPasses::Registry;
1324*9880d681SAndroid Build Coastguard Worker
1325*9880d681SAndroid Build Coastguard WorkerAnd finally, declare the command line option for your passes.  Example:
1326*9880d681SAndroid Build Coastguard Worker
1327*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1328*9880d681SAndroid Build Coastguard Worker
1329*9880d681SAndroid Build Coastguard Worker  cl::opt<RegisterMyPasses::FunctionPassCtor, false,
1330*9880d681SAndroid Build Coastguard Worker          RegisterPassParser<RegisterMyPasses> >
1331*9880d681SAndroid Build Coastguard Worker  MyPassOpt("mypass",
1332*9880d681SAndroid Build Coastguard Worker            cl::init(&createDefaultMyPass),
1333*9880d681SAndroid Build Coastguard Worker            cl::desc("my pass option help"));
1334*9880d681SAndroid Build Coastguard Worker
1335*9880d681SAndroid Build Coastguard WorkerHere the command option is "``mypass``", with ``createDefaultMyPass`` as the
1336*9880d681SAndroid Build Coastguard Workerdefault creator.
1337*9880d681SAndroid Build Coastguard Worker
1338*9880d681SAndroid Build Coastguard WorkerUsing GDB with dynamically loaded passes
1339*9880d681SAndroid Build Coastguard Worker----------------------------------------
1340*9880d681SAndroid Build Coastguard Worker
1341*9880d681SAndroid Build Coastguard WorkerUnfortunately, using GDB with dynamically loaded passes is not as easy as it
1342*9880d681SAndroid Build Coastguard Workershould be.  First of all, you can't set a breakpoint in a shared object that
1343*9880d681SAndroid Build Coastguard Workerhas not been loaded yet, and second of all there are problems with inlined
1344*9880d681SAndroid Build Coastguard Workerfunctions in shared objects.  Here are some suggestions to debugging your pass
1345*9880d681SAndroid Build Coastguard Workerwith GDB.
1346*9880d681SAndroid Build Coastguard Worker
1347*9880d681SAndroid Build Coastguard WorkerFor sake of discussion, I'm going to assume that you are debugging a
1348*9880d681SAndroid Build Coastguard Workertransformation invoked by :program:`opt`, although nothing described here
1349*9880d681SAndroid Build Coastguard Workerdepends on that.
1350*9880d681SAndroid Build Coastguard Worker
1351*9880d681SAndroid Build Coastguard WorkerSetting a breakpoint in your pass
1352*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1353*9880d681SAndroid Build Coastguard Worker
1354*9880d681SAndroid Build Coastguard WorkerFirst thing you do is start gdb on the opt process:
1355*9880d681SAndroid Build Coastguard Worker
1356*9880d681SAndroid Build Coastguard Worker.. code-block:: console
1357*9880d681SAndroid Build Coastguard Worker
1358*9880d681SAndroid Build Coastguard Worker  $ gdb opt
1359*9880d681SAndroid Build Coastguard Worker  GNU gdb 5.0
1360*9880d681SAndroid Build Coastguard Worker  Copyright 2000 Free Software Foundation, Inc.
1361*9880d681SAndroid Build Coastguard Worker  GDB is free software, covered by the GNU General Public License, and you are
1362*9880d681SAndroid Build Coastguard Worker  welcome to change it and/or distribute copies of it under certain conditions.
1363*9880d681SAndroid Build Coastguard Worker  Type "show copying" to see the conditions.
1364*9880d681SAndroid Build Coastguard Worker  There is absolutely no warranty for GDB.  Type "show warranty" for details.
1365*9880d681SAndroid Build Coastguard Worker  This GDB was configured as "sparc-sun-solaris2.6"...
1366*9880d681SAndroid Build Coastguard Worker  (gdb)
1367*9880d681SAndroid Build Coastguard Worker
1368*9880d681SAndroid Build Coastguard WorkerNote that :program:`opt` has a lot of debugging information in it, so it takes
1369*9880d681SAndroid Build Coastguard Workertime to load.  Be patient.  Since we cannot set a breakpoint in our pass yet
1370*9880d681SAndroid Build Coastguard Worker(the shared object isn't loaded until runtime), we must execute the process,
1371*9880d681SAndroid Build Coastguard Workerand have it stop before it invokes our pass, but after it has loaded the shared
1372*9880d681SAndroid Build Coastguard Workerobject.  The most foolproof way of doing this is to set a breakpoint in
1373*9880d681SAndroid Build Coastguard Worker``PassManager::run`` and then run the process with the arguments you want:
1374*9880d681SAndroid Build Coastguard Worker
1375*9880d681SAndroid Build Coastguard Worker.. code-block:: console
1376*9880d681SAndroid Build Coastguard Worker
1377*9880d681SAndroid Build Coastguard Worker  $ (gdb) break llvm::PassManager::run
1378*9880d681SAndroid Build Coastguard Worker  Breakpoint 1 at 0x2413bc: file Pass.cpp, line 70.
1379*9880d681SAndroid Build Coastguard Worker  (gdb) run test.bc -load $(LLVMTOP)/llvm/Debug+Asserts/lib/[libname].so -[passoption]
1380*9880d681SAndroid Build Coastguard Worker  Starting program: opt test.bc -load $(LLVMTOP)/llvm/Debug+Asserts/lib/[libname].so -[passoption]
1381*9880d681SAndroid Build Coastguard Worker  Breakpoint 1, PassManager::run (this=0xffbef174, M=@0x70b298) at Pass.cpp:70
1382*9880d681SAndroid Build Coastguard Worker  70      bool PassManager::run(Module &M) { return PM->run(M); }
1383*9880d681SAndroid Build Coastguard Worker  (gdb)
1384*9880d681SAndroid Build Coastguard Worker
1385*9880d681SAndroid Build Coastguard WorkerOnce the :program:`opt` stops in the ``PassManager::run`` method you are now
1386*9880d681SAndroid Build Coastguard Workerfree to set breakpoints in your pass so that you can trace through execution or
1387*9880d681SAndroid Build Coastguard Workerdo other standard debugging stuff.
1388*9880d681SAndroid Build Coastguard Worker
1389*9880d681SAndroid Build Coastguard WorkerMiscellaneous Problems
1390*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^
1391*9880d681SAndroid Build Coastguard Worker
1392*9880d681SAndroid Build Coastguard WorkerOnce you have the basics down, there are a couple of problems that GDB has,
1393*9880d681SAndroid Build Coastguard Workersome with solutions, some without.
1394*9880d681SAndroid Build Coastguard Worker
1395*9880d681SAndroid Build Coastguard Worker* Inline functions have bogus stack information.  In general, GDB does a pretty
1396*9880d681SAndroid Build Coastguard Worker  good job getting stack traces and stepping through inline functions.  When a
1397*9880d681SAndroid Build Coastguard Worker  pass is dynamically loaded however, it somehow completely loses this
1398*9880d681SAndroid Build Coastguard Worker  capability.  The only solution I know of is to de-inline a function (move it
1399*9880d681SAndroid Build Coastguard Worker  from the body of a class to a ``.cpp`` file).
1400*9880d681SAndroid Build Coastguard Worker
1401*9880d681SAndroid Build Coastguard Worker* Restarting the program breaks breakpoints.  After following the information
1402*9880d681SAndroid Build Coastguard Worker  above, you have succeeded in getting some breakpoints planted in your pass.
1403*9880d681SAndroid Build Coastguard Worker  Next thing you know, you restart the program (i.e., you type "``run``" again),
1404*9880d681SAndroid Build Coastguard Worker  and you start getting errors about breakpoints being unsettable.  The only
1405*9880d681SAndroid Build Coastguard Worker  way I have found to "fix" this problem is to delete the breakpoints that are
1406*9880d681SAndroid Build Coastguard Worker  already set in your pass, run the program, and re-set the breakpoints once
1407*9880d681SAndroid Build Coastguard Worker  execution stops in ``PassManager::run``.
1408*9880d681SAndroid Build Coastguard Worker
1409*9880d681SAndroid Build Coastguard WorkerHopefully these tips will help with common case debugging situations.  If you'd
1410*9880d681SAndroid Build Coastguard Workerlike to contribute some tips of your own, just contact `Chris
1411*9880d681SAndroid Build Coastguard Worker<mailto:[email protected]>`_.
1412*9880d681SAndroid Build Coastguard Worker
1413*9880d681SAndroid Build Coastguard WorkerFuture extensions planned
1414*9880d681SAndroid Build Coastguard Worker-------------------------
1415*9880d681SAndroid Build Coastguard Worker
1416*9880d681SAndroid Build Coastguard WorkerAlthough the LLVM Pass Infrastructure is very capable as it stands, and does
1417*9880d681SAndroid Build Coastguard Workersome nifty stuff, there are things we'd like to add in the future.  Here is
1418*9880d681SAndroid Build Coastguard Workerwhere we are going:
1419*9880d681SAndroid Build Coastguard Worker
1420*9880d681SAndroid Build Coastguard Worker.. _writing-an-llvm-pass-SMP:
1421*9880d681SAndroid Build Coastguard Worker
1422*9880d681SAndroid Build Coastguard WorkerMultithreaded LLVM
1423*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^
1424*9880d681SAndroid Build Coastguard Worker
1425*9880d681SAndroid Build Coastguard WorkerMultiple CPU machines are becoming more common and compilation can never be
1426*9880d681SAndroid Build Coastguard Workerfast enough: obviously we should allow for a multithreaded compiler.  Because
1427*9880d681SAndroid Build Coastguard Workerof the semantics defined for passes above (specifically they cannot maintain
1428*9880d681SAndroid Build Coastguard Workerstate across invocations of their ``run*`` methods), a nice clean way to
1429*9880d681SAndroid Build Coastguard Workerimplement a multithreaded compiler would be for the ``PassManager`` class to
1430*9880d681SAndroid Build Coastguard Workercreate multiple instances of each pass object, and allow the separate instances
1431*9880d681SAndroid Build Coastguard Workerto be hacking on different parts of the program at the same time.
1432*9880d681SAndroid Build Coastguard Worker
1433*9880d681SAndroid Build Coastguard WorkerThis implementation would prevent each of the passes from having to implement
1434*9880d681SAndroid Build Coastguard Workermultithreaded constructs, requiring only the LLVM core to have locking in a few
1435*9880d681SAndroid Build Coastguard Workerplaces (for global resources).  Although this is a simple extension, we simply
1436*9880d681SAndroid Build Coastguard Workerhaven't had time (or multiprocessor machines, thus a reason) to implement this.
1437*9880d681SAndroid Build Coastguard WorkerDespite that, we have kept the LLVM passes SMP ready, and you should too.
1438*9880d681SAndroid Build Coastguard Worker
1439