X-Git-Url: http://plrg.eecs.uci.edu/git/?a=blobdiff_plain;f=docs%2FWritingAnLLVMPass.html;h=af1ffa4fb7adeb8e3bd26d0b65b68a8467d624f1;hb=ead66027e8a93dbbb9eec37807c34585aeafe67b;hp=331617937755f26c4cf39af62ebc52234e0d4eb2;hpb=05d0265fef651de152c8127aa701e689555649f3;p=oota-llvm.git diff --git a/docs/WritingAnLLVMPass.html b/docs/WritingAnLLVMPass.html index 33161793775..af1ffa4fb7a 100644 --- a/docs/WritingAnLLVMPass.html +++ b/docs/WritingAnLLVMPass.html @@ -4,7 +4,7 @@ Writing an LLVM Pass - + @@ -126,7 +126,7 @@ -
+

The LLVM Pass Framework is an important part of the LLVM system, because LLVM passes are where most of the interesting parts of the compiler exist. Passes @@ -161,7 +161,7 @@ more advanced features are discussed.

-
+

Here we describe how to write the "hello world" of passes. The "Hello" pass is designed to simply print out the name of non-external functions that exist in @@ -169,14 +169,12 @@ the program being compiled. It does not modify the program at all, it just inspects it. The source code and files for this pass are available in the LLVM source tree in the lib/Transforms/Hello directory.

-
-

Setting up the build environment

-
+

First, configure and build LLVM. This needs to be done directly inside the LLVM source tree rather than in a separate objects directory. @@ -224,16 +222,18 @@ the pass itself.

Basic code required -
+

Now that we have a way to compile our new pass, we just have to write it. Start out with:

-
+
+
 #include "llvm/Pass.h"
 #include "llvm/Function.h"
 #include "llvm/Support/raw_ostream.h"
-
+
+

Which are needed because we are writing a Pass, @@ -242,53 +242,66 @@ href="http://llvm.org/doxygen/classllvm_1_1Function.html">Function's, and we will be doing some printing.

Next we have:

-
+
+
+
 using namespace llvm;
-
+
+
+

... which is required because the functions from the include files -live in the llvm namespace. -

+live in the llvm namespace.

Next we have:

-
+
+
 namespace {
-
+
+

... which starts out an anonymous namespace. Anonymous namespaces are to C++ what the "static" keyword is to C (at global scope). It makes the -things declared inside of the anonymous namespace only visible to the current +things declared inside of the anonymous namespace visible only to the current file. If you're not familiar with them, consult a decent C++ book for more information.

Next, we declare our pass itself:

-
+
+
   struct Hello : public FunctionPass {
-

+

+

This declares a "Hello" class that is a subclass of FunctionPass. The different builtin pass subclasses are described in detail later, but for now, know that FunctionPass's operate a function at a +href="#FunctionPass">FunctionPass's operate on a function at a time.

-
-     static char ID;
-     Hello() : FunctionPass(ID) {}
-

+

+
+    static char ID;
+    Hello() : FunctionPass(ID) {}
+
+
-

This declares pass identifier used by LLVM to identify pass. This allows LLVM to -avoid using expensive C++ runtime information.

+

This declares pass identifier used by LLVM to identify pass. This allows LLVM +to avoid using expensive C++ runtime information.

-
+
+
     virtual bool runOnFunction(Function &F) {
-      errs() << "Hello: " << F.getName() << "\n";
+      errs() << "Hello: ";
+      errs().write_escaped(F.getName()) << "\n";
       return false;
     }
   };  // end of struct Hello
-
+} // end of anonymous namespace +
+

We declare a "runOnFunction" method, which overloads an abstract virtual method inherited from FunctionPass. This is where we are supposed to do our thing, so we just print out our message with the name of each function.

-
-  char Hello::ID = 0;
-
+
+
+char Hello::ID = 0;
+
+
-

We initialize pass ID here. LLVM uses ID's address to identify pass so +

We initialize pass ID here. LLVM uses ID's address to identify a pass, so initialization value is not important.

-
-  static RegisterPass<Hello> X("hello", "Hello World Pass",
-                        false /* Only looks at CFG */,
-                        false /* Analysis Pass */);
-}  // end of anonymous namespace
-
+
+
+static RegisterPass<Hello> X("hello", "Hello World Pass",
+                             false /* Only looks at CFG */,
+                             false /* Analysis Pass */);
+
+
-

Lastly, we register our class Hello, -giving it a command line -argument "hello", and a name "Hello World Pass". -Last two arguments describe its behavior. -If a pass walks CFG without modifying it then third argument is set to true. -If a pass is an analysis pass, for example dominator tree pass, then true -is supplied as fourth argument.

+

Lastly, we register our class Hello, +giving it a command line argument "hello", and a name "Hello World +Pass". The last two arguments describe its behavior: if a pass walks CFG +without modifying it then the third argument is set to true; if a pass +is an analysis pass, for example dominator tree pass, then true is +supplied as the fourth argument.

As a whole, the .cpp file looks like:

-
+
+
 #include "llvm/Pass.h"
 #include "llvm/Function.h"
 #include "llvm/Support/raw_ostream.h"
@@ -334,24 +350,26 @@ is supplied as fourth argument. 

Hello() : FunctionPass(ID) {} virtual bool runOnFunction(Function &F) { - errs() << "Hello: " << F.getName() << "\n"; + errs() << "Hello: "; + errs().write_escaped(F.getName()) << '\n'; return false; } + }; - - char Hello::ID = 0; - static RegisterPass<Hello> X("hello", "Hello World Pass", false, false); } - -
+ +char Hello::ID = 0; +static RegisterPass<Hello> X("hello", "Hello World Pass", false, false); +
+

Now that it's all together, compile the file with a simple "gmake" command in the local directory and you should get a new file "Debug+Asserts/lib/Hello.so" under the top level directory of the LLVM source tree (not in the local directory). Note that everything in this file is -contained in an anonymous namespace: this reflects the fact that passes are self -contained units that do not need external interfaces (although they can have -them) to be useful.

+contained in an anonymous namespace — this reflects the fact that passes +are self contained units that do not need external interfaces (although they can +have them) to be useful.

@@ -360,7 +378,7 @@ them) to be useful.

Running a pass with opt -
+

Now that you have a brand new shiny shared object file, we can use the opt command to run an LLVM program through your pass. Because you @@ -399,17 +417,17 @@ USAGE: opt [options] <input bitcode> OPTIONS: Optimizations available: ... - -funcresolve - Resolve Functions - -gcse - Global Common Subexpression Elimination - -globaldce - Dead Global Elimination - -hello - Hello World Pass - -indvars - Canonicalize Induction Variables - -inline - Function Integration/Inlining - -instcombine - Combine redundant instructions + -globalopt - Global Variable Optimizer + -globalsmodref-aa - Simple mod/ref analysis for globals + -gvn - Global Value Numbering + -hello - Hello World Pass + -indvars - Induction Variable Simplification + -inline - Function Integration/Inlining + -insert-edge-profiling - Insert instrumentation for edge profiling ...

-

The pass name get added as the information string for your pass, giving some +

The pass name gets added as the information string for your pass, giving some documentation to users of opt. Now that you have a working pass, you would go ahead and make it do the cool transformations you want. Once you get it all working and tested, it may become useful to find out how fast your pass @@ -446,13 +464,15 @@ about some more details of how they work and how to use them.

+
+

Pass classes and requirements

-
+

One of the first things that you should do when designing a new pass is to decide what class you should subclass for your pass. The -

-

The ImmutablePass class

-
+

The most plain and boring type of pass is the "ImmutablePass" @@ -497,7 +515,7 @@ invalidated, and are never "run".

The ModulePass class -
+

The "ModulePass" @@ -519,17 +537,15 @@ DominatorTree for function definitions, not declarations.

ModulePass and overload the runOnModule method with the following signature:

-
-

The runOnModule method

-
+
-  virtual bool runOnModule(Module &M) = 0;
+virtual bool runOnModule(Module &M) = 0;
 

The runOnModule method performs the interesting work of the pass. @@ -538,12 +554,14 @@ false otherwise.

+
+

The CallGraphSCCPass class

-
+

The "CallGraphSCCPass" @@ -584,8 +602,6 @@ because it has to handle SCCs with more than one node in it. All of the virtual methods described below should return true if they modified the program, or false if they didn't.

-
-

@@ -593,10 +609,10 @@ false if they didn't.

-
+
-  virtual bool doInitialization(CallGraph &CG);
+virtual bool doInitialization(CallGraph &CG);
 

The doIninitialize method is allowed to do most of the things that @@ -614,10 +630,10 @@ fast).

The runOnSCC method -
+
-  virtual bool runOnSCC(CallGraphSCC &SCC) = 0;
+virtual bool runOnSCC(CallGraphSCC &SCC) = 0;
 

The runOnSCC method performs the interesting work of the pass, and @@ -633,10 +649,10 @@ otherwise.

-
+
-  virtual bool doFinalization(CallGraph &CG);
+virtual bool doFinalization(CallGraph &CG);
 

The doFinalization method is an infrequently used method that is @@ -646,12 +662,14 @@ program being compiled.

+
+

The FunctionPass class

-
+

In contrast to ModulePass subclasses, FunctionPass @@ -676,8 +694,6 @@ href="#basiccode">Hello World pass for example). FunctionPass's may overload three virtual methods to do their work. All of these methods should return true if they modified the program, or false if they didn't.

-
-

@@ -685,10 +701,10 @@ should return true if they modified the program, or false if they didn't.

-
+
-  virtual bool doInitialization(Module &M);
+virtual bool doInitialization(Module &M);
 

The doIninitialize method is allowed to do most of the things that @@ -713,10 +729,10 @@ free functions that it needs, adding prototypes to the module if necessary.

The runOnFunction method -
+
-  virtual bool runOnFunction(Function &F) = 0;
+virtual bool runOnFunction(Function &F) = 0;
 

The runOnFunction method must be implemented by your subclass to do @@ -732,10 +748,10 @@ be returned if the function is modified.

-
+
-  virtual bool doFinalization(Module &M);
+virtual bool doFinalization(Module &M);
 

The doFinalization method is an infrequently used method that is @@ -745,12 +761,14 @@ program being compiled.

+
+

The LoopPass class

-
+

All LoopPass execute on each loop in the function independent of all of the other loops in the function. LoopPass processes loops in @@ -761,7 +779,6 @@ loop nest order such that outer most loop is processed last.

straightforward. LoopPass's may overload three virtual methods to do their work. All these methods should return true if they modified the program, or false if they didn't.

-

@@ -770,10 +787,10 @@ program, or false if they didn't.

-
+
-  virtual bool doInitialization(Loop *, LPPassManager &LPM);
+virtual bool doInitialization(Loop *, LPPassManager &LPM);
 

The doInitialization method is designed to do simple initialization @@ -791,10 +808,10 @@ information.

The runOnLoop method -
+
-  virtual bool runOnLoop(Loop *, LPPassManager &LPM) = 0;
+virtual bool runOnLoop(Loop *, LPPassManager &LPM) = 0;
 

The runOnLoop method must be implemented by your subclass to do @@ -809,10 +826,10 @@ should be used to update loop nest.

The doFinalization() method -
+
-  virtual bool doFinalization();
+virtual bool doFinalization();
 

The doFinalization method is an infrequently used method that is @@ -822,12 +839,14 @@ program being compiled.

+
+

The RegionPass class

-
+

RegionPass is similar to LoopPass, but executes on each single entry single exit region in the function. @@ -839,7 +858,6 @@ the RGPassManager interface. You may overload three virtual methods of RegionPass to implement your own region pass. All these methods should return true if they modified the program, or false if they didn not.

-

@@ -848,10 +866,10 @@ methods should return true if they modified the program, or false if they didn n

-
+
-  virtual bool doInitialization(Region *, RGPassManager &RGM);
+virtual bool doInitialization(Region *, RGPassManager &RGM);
 

The doInitialization method is designed to do simple initialization @@ -869,10 +887,10 @@ information.

The runOnRegion method -
+
-  virtual bool runOnRegion(Region *, RGPassManager &RGM) = 0;
+virtual bool runOnRegion(Region *, RGPassManager &RGM) = 0;
 

The runOnRegion method must be implemented by your subclass to do @@ -887,10 +905,10 @@ should be used to update region tree.

The doFinalization() method -
+
-  virtual bool doFinalization();
+virtual bool doFinalization();
 

The doFinalization method is an infrequently used method that is @@ -900,14 +918,14 @@ program being compiled.

- +

The BasicBlockPass class

-
+

BasicBlockPass's are just like FunctionPass's, except that they must limit @@ -929,8 +947,6 @@ href="#doInitialization_mod">doInitialization(Module &) and doFinalization(Module &) methods that FunctionPass's have, but also have the following virtual methods that may also be implemented:

-
-

@@ -938,10 +954,10 @@ href="#FunctionPass">FunctionPass's have, but also have the followi

-
+
-  virtual bool doInitialization(Function &F);
+virtual bool doInitialization(Function &F);
 

The doIninitialize method is allowed to do most of the things that @@ -959,10 +975,10 @@ fast).

The runOnBasicBlock method -
+
-  virtual bool runOnBasicBlock(BasicBlock &BB) = 0;
+virtual bool runOnBasicBlock(BasicBlock &BB) = 0;
 

Override this function to do the work of the BasicBlockPass. This @@ -979,10 +995,10 @@ if the basic block is modified.

-
+
-  virtual bool doFinalization(Function &F);
+virtual bool doFinalization(Function &F);
 

The doFinalization method is an infrequently used method that is @@ -993,12 +1009,14 @@ finalization.

+
+

The MachineFunctionPass class

-
+

A MachineFunctionPass is a part of the LLVM code generator that executes on the machine-dependent representation of each LLVM function in the @@ -1023,8 +1041,6 @@ href="#runOnMachineFunction">runOnMachineFunction (including global data) -

-

@@ -1032,10 +1048,10 @@ data)

-
+
-  virtual bool runOnMachineFunction(MachineFunction &MF) = 0;
+virtual bool runOnMachineFunction(MachineFunction &MF) = 0;
 

runOnMachineFunction can be considered the main entry point of a @@ -1053,13 +1069,17 @@ remember, you may not modify the LLVM Function or its contents from a

+
+ +
+

Pass registration

-
+

In the Hello World example pass we illustrated how pass registration works, and discussed some of the reasons that it is used and @@ -1076,17 +1096,15 @@ well as for debug output generated by the --debug-pass option.

If you want your pass to be easily dumpable, you should implement the virtual print method:

-
-

The print method

-
+
-  virtual void print(std::ostream &O, const Module *M) const;
+virtual void print(std::ostream &O, const Module *M) const;
 

The print method must be implemented by "analyses" in order to print @@ -1103,13 +1121,15 @@ depended on.

+
+

Specifying interactions between passes

-
+

One of the main responsibilities of the PassManager is to make sure that passes interact with each other correctly. Because PassManager @@ -1126,17 +1146,15 @@ specifies. If a pass does not implement the getAnalysisUsage method, it defaults to not having any prerequisite passes, and invalidating all other passes.

-
-

The getAnalysisUsage method

-
+
-  virtual void getAnalysisUsage(AnalysisUsage &Info) const;
+virtual void getAnalysisUsage(AnalysisUsage &Info) const;
 

By implementing the getAnalysisUsage method, the required and @@ -1156,7 +1174,7 @@ object:

-
+

If your pass requires a previous pass to be executed (an analysis for example), it can use one of these methods to arrange for it to be run before your pass. @@ -1184,7 +1202,7 @@ pass is. -

+

One of the jobs of the PassManager is to optimize how and when analyses are run. In particular, it attempts to avoid recomputing data unless it needs to. For @@ -1221,14 +1239,14 @@ the fact that it hacks on the CFG. -

+
-  // This example modifies the program, but does not modify the CFG
-  void LICM::getAnalysisUsage(AnalysisUsage &AU) const {
-    AU.setPreservesCFG();
-    AU.addRequired<LoopInfo>();
-  }
+// This example modifies the program, but does not modify the CFG
+void LICM::getAnalysisUsage(AnalysisUsage &AU) const {
+  AU.setPreservesCFG();
+  AU.addRequired<LoopInfo>();
+}
 
@@ -1241,7 +1259,7 @@ the fact that it hacks on the CFG. -
+

The Pass::getAnalysis<> method is automatically inherited by your class, providing you with access to the passes that you declared that you @@ -1250,10 +1268,10 @@ method. It takes a single template argument that specifies which pass class you want, and returns a reference to that pass. For example:

-   bool LICM::runOnFunction(Function &F) {
-     LoopInfo &LI = getAnalysis<LoopInfo>();
-     ...
-   }
+bool LICM::runOnFunction(Function &F) {
+  LoopInfo &LI = getAnalysis<LoopInfo>();
+  ...
+}
 

This method call returns a reference to the pass desired. You may get a @@ -1267,11 +1285,11 @@ A module level pass can use function level analysis info using this interface. For example:

-   bool ModuleLevelPass::runOnModule(Module &M) {
-     ...
-     DominatorTree &DT = getAnalysis<DominatorTree>(Func);
-     ...
-   }
+bool ModuleLevelPass::runOnModule(Module &M) {
+  ...
+  DominatorTree &DT = getAnalysis<DominatorTree>(Func);
+  ...
+}
 

In above example, runOnFunction for DominatorTree is called by pass manager @@ -1284,22 +1302,24 @@ If your pass is capable of updating analyses if they exist (e.g., if it is active. For example:

-  ...
-  if (DominatorSet *DS = getAnalysisIfAvailable<DominatorSet>()) {
-    // A DominatorSet is active.  This code will update it.
-  }
-  ...
+...
+if (DominatorSet *DS = getAnalysisIfAvailable<DominatorSet>()) {
+  // A DominatorSet is active.  This code will update it.
+}
+...
 
+
+

Implementing Analysis Groups

-
+

Now that we understand the basics of how passes are defined, how they are used, and how they are required from other passes, it's time to get a little bit @@ -1318,14 +1338,12 @@ between these two extremes for other implementations). To cleanly support situations like this, the LLVM Pass Infrastructure supports the notion of Analysis Groups.

-
-

Analysis Group Concepts

-
+

An Analysis Group is a single simple interface that may be implemented by multiple different passes. Analysis Groups can be given human readable names @@ -1376,7 +1394,7 @@ hypothetical example) instead.

Using RegisterAnalysisGroup -
+

The RegisterAnalysisGroup template is used to register the analysis group itself, while the INITIALIZE_AG_PASS is used to add pass @@ -1387,7 +1405,7 @@ Unlike registration of passes, there is no command line argument to be specified for the Analysis Group Interface itself, because it is "abstract":

-  static RegisterAnalysisGroup<AliasAnalysis> A("Alias Analysis");
+static RegisterAnalysisGroup<AliasAnalysis> A("Alias Analysis");
 

Once the analysis is registered, passes can declare that they are valid @@ -1398,10 +1416,9 @@ implementations of the interface by using the following code:

// Declare that we implement the AliasAnalysis interface INITIALIZE_AG_PASS(FancyAA, AliasAnalysis, "somefancyaa", "A more complex alias analysis implementation", - false, // Is CFG Only? - true, // Is Analysis? - false, // Is default Analysis Group implementation? - ); + false, // Is CFG Only? + true, // Is Analysis? + false); // Is default Analysis Group implementation? }
@@ -1418,8 +1435,7 @@ this macro.

"Basic Alias Analysis (default AA impl)", false, // Is CFG Only? true, // Is Analysis? - true, // Is default Analysis Group implementation? - ); + true); // Is default Analysis Group implementation? }
@@ -1433,13 +1449,15 @@ pass is the default implementation for the interface.

+
+

Pass Statistics

-
+

The Statistic class is designed to be an easy way to expose various success @@ -1456,7 +1474,7 @@ line. See the St -

+

The PassManager @@ -1586,10 +1604,10 @@ we need to add the following getAnalysisUsage method to our pass:

-    // We don't modify the program, so we preserve all analyses
-    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
-      AU.setPreservesAll();
-    }
+// We don't modify the program, so we preserve all analyses
+virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+  AU.setPreservesAll();
+}
 

Now when we run our pass, we get this output:

@@ -1623,14 +1641,12 @@ Hello: main

Which shows that we don't accidentally invalidate dominator information anymore, and therefore do not have to compute it twice.

-
-

The releaseMemory method

-
+
   virtual void releaseMemory();
@@ -1651,13 +1667,15 @@ class, before the next call of run* in your pass.

+
+

Registering dynamically loaded passes

-
+

Size matters when constructing production quality tools using llvm, both for the purposes of distribution, and for regulating the resident code size @@ -1684,14 +1702,12 @@ the static destructor unregisters. Thus a pass that is statically linked in the tool will be registered at start up. A dynamically loaded pass will register on load and unregister at unload.

-
-

Using existing registries

-
+

There are predefined registries to track instruction scheduling (RegisterScheduler) and register allocation (RegisterRegAlloc) @@ -1699,19 +1715,19 @@ machine passes. Here we will describe how to register a register allocator machine pass.

Implement your register allocator machine pass. In your register allocator -.cpp file add the following include;

+.cpp file add the following include;

-  #include "llvm/CodeGen/RegAllocRegistry.h"
+#include "llvm/CodeGen/RegAllocRegistry.h"
 

Also in your register allocator .cpp file, define a creator function in the form;

-  FunctionPass *createMyRegisterAllocator() {
-    return new MyRegisterAllocator();
-  }
+FunctionPass *createMyRegisterAllocator() {
+  return new MyRegisterAllocator();
+}
 

Note that the signature of this function should match the type of @@ -1719,9 +1735,9 @@ form;

"installing" declaration, in the form;

-  static RegisterRegAlloc myRegAlloc("myregalloc",
-    "  my register allocator help string",
-    createMyRegisterAllocator);
+static RegisterRegAlloc myRegAlloc("myregalloc",
+                                   "my register allocator help string",
+                                   createMyRegisterAllocator);
 

Note the two spaces prior to the help string produces a tidy result on the @@ -1756,7 +1772,7 @@ call line to llvm/Codegen/LinkAllCodegenComponents.h.

Creating new registries -
+

The easiest way to get started is to clone one of the existing registries; we recommend llvm/CodeGen/RegAllocRegistry.h. The key things to modify @@ -1772,11 +1788,11 @@ MachinePassRegistry RegisterMyPasses::Registry;

And finally, declare the command line option for your passes. Example:

-  cl::opt<RegisterMyPasses::FunctionPassCtor, false,
-          RegisterPassParser<RegisterMyPasses> >
-  MyPassOpt("mypass",
-            cl::init(&createDefaultMyPass),
-            cl::desc("my pass option help")); 
+cl::opt<RegisterMyPasses::FunctionPassCtor, false,
+        RegisterPassParser<RegisterMyPasses> >
+MyPassOpt("mypass",
+          cl::init(&createDefaultMyPass),
+          cl::desc("my pass option help")); 
 

Here the command option is "mypass", with createDefaultMyPass as the default @@ -1784,13 +1800,15 @@ creator.

+
+

Using GDB with dynamically loaded passes

-
+

Unfortunately, using GDB with dynamically loaded passes is not as easy as it should be. First of all, you can't set a breakpoint in a shared object that has @@ -1802,14 +1820,12 @@ GDB.

transformation invoked by opt, although nothing described here depends on that.

-
-

Setting a breakpoint in your pass

-
+

First thing you do is start gdb on the opt process:

@@ -1854,7 +1870,7 @@ or do other standard debugging stuff.

Miscellaneous Problems -
+

Once you have the basics down, there are a couple of problems that GDB has, some with solutions, some without.

@@ -1882,26 +1898,26 @@ href="mailto:sabre@nondot.org">Chris.

+
+

Future extensions planned

-
+

Although the LLVM Pass Infrastructure is very capable as it stands, and does some nifty stuff, there are things we'd like to add in the future. Here is where we are going:

-
-

Multithreaded LLVM

-
+

Multiple CPU machines are becoming more common and compilation can never be fast enough: obviously we should allow for a multithreaded compiler. Because of @@ -1919,6 +1935,8 @@ Despite that, we have kept the LLVM passes SMP ready, and you should too.

+
+