Update comments; getPassName no longer uses RTTI.
[oota-llvm.git] / lib / VMCore / Pass.cpp
1 //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVM Pass infrastructure.  It is primarily
11 // responsible with ensuring that passes are executed and batched together
12 // optimally.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/PassManager.h"
17 #include "llvm/Module.h"
18 #include "llvm/ModuleProvider.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include <algorithm>
22 #include <set>
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 // Pass Implementation
27 //
28
29 // Force out-of-line virtual method.
30 Pass::~Pass() { 
31   delete Resolver; 
32 }
33
34 // Force out-of-line virtual method.
35 ModulePass::~ModulePass() { }
36
37 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
38   return Resolver->getAnalysisToUpdate(AnalysisID, true) != 0;
39 }
40
41 // dumpPassStructure - Implement the -debug-passes=Structure option
42 void Pass::dumpPassStructure(unsigned Offset) {
43   cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
44 }
45
46 /// getPassName - Return a nice clean name for a pass.  This usually
47 /// implemented in terms of the name that is registered by one of the
48 /// Registration templates, but can be overloaded directly.
49 ///
50 const char *Pass::getPassName() const {
51   if (const PassInfo *PI = getPassInfo())
52     return PI->getPassName();
53   return "Unnamed pass: implement Pass::getPassName()";
54 }
55
56 // print - Print out the internal state of the pass.  This is called by Analyze
57 // to print out the contents of an analysis.  Otherwise it is not necessary to
58 // implement this method.
59 //
60 void Pass::print(std::ostream &O,const Module*) const {
61   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
62 }
63
64 // dump - call print(cerr);
65 void Pass::dump() const {
66   print(*cerr.stream(), 0);
67 }
68
69 //===----------------------------------------------------------------------===//
70 // ImmutablePass Implementation
71 //
72 // Force out-of-line virtual method.
73 ImmutablePass::~ImmutablePass() { }
74
75 //===----------------------------------------------------------------------===//
76 // FunctionPass Implementation
77 //
78
79 // run - On a module, we run this pass by initializing, runOnFunction'ing once
80 // for every function in the module, then by finalizing.
81 //
82 bool FunctionPass::runOnModule(Module &M) {
83   bool Changed = doInitialization(M);
84
85   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
86     if (!I->isDeclaration())      // Passes are not run on external functions!
87     Changed |= runOnFunction(*I);
88
89   return Changed | doFinalization(M);
90 }
91
92 // run - On a function, we simply initialize, run the function, then finalize.
93 //
94 bool FunctionPass::run(Function &F) {
95   // Passes are not run on external functions!
96   if (F.isDeclaration()) return false;
97
98   bool Changed = doInitialization(*F.getParent());
99   Changed |= runOnFunction(F);
100   return Changed | doFinalization(*F.getParent());
101 }
102
103 //===----------------------------------------------------------------------===//
104 // BasicBlockPass Implementation
105 //
106
107 // To run this pass on a function, we simply call runOnBasicBlock once for each
108 // function.
109 //
110 bool BasicBlockPass::runOnFunction(Function &F) {
111   bool Changed = doInitialization(F);
112   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
113     Changed |= runOnBasicBlock(*I);
114   return Changed | doFinalization(F);
115 }
116
117 //===----------------------------------------------------------------------===//
118 // Pass Registration mechanism
119 //
120 namespace {
121 class PassRegistrar {
122   /// PassInfoMap - Keep track of the passinfo object for each registered llvm
123   /// pass.
124   std::map<intptr_t, PassInfo*> PassInfoMap;
125   
126   /// AnalysisGroupInfo - Keep track of information for each analysis group.
127   struct AnalysisGroupInfo {
128     const PassInfo *DefaultImpl;
129     std::set<const PassInfo *> Implementations;
130     AnalysisGroupInfo() : DefaultImpl(0) {}
131   };
132   
133   /// AnalysisGroupInfoMap - Information for each analysis group.
134   std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap;
135
136 public:
137   
138   const PassInfo *GetPassInfo(intptr_t TI) const {
139     std::map<intptr_t, PassInfo*>::const_iterator I = PassInfoMap.find(TI);
140     return I != PassInfoMap.end() ? I->second : 0;
141   }
142   
143   void RegisterPass(PassInfo &PI) {
144     bool Inserted =
145       PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;
146     assert(Inserted && "Pass registered multiple times!");
147   }
148   
149   void UnregisterPass(PassInfo &PI) {
150     std::map<intptr_t, PassInfo*>::iterator I =
151       PassInfoMap.find(PI.getTypeInfo());
152     assert(I != PassInfoMap.end() && "Pass registered but not in map!");
153     
154     // Remove pass from the map.
155     PassInfoMap.erase(I);
156   }
157   
158   void EnumerateWith(PassRegistrationListener *L) {
159     for (std::map<intptr_t, PassInfo*>::const_iterator I = PassInfoMap.begin(),
160          E = PassInfoMap.end(); I != E; ++I)
161       L->passEnumerate(I->second);
162   }
163   
164   
165   /// Analysis Group Mechanisms.
166   void RegisterAnalysisGroup(PassInfo *InterfaceInfo,
167                              const PassInfo *ImplementationInfo,
168                              bool isDefault) {
169     AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];
170     assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
171            "Cannot add a pass to the same analysis group more than once!");
172     AGI.Implementations.insert(ImplementationInfo);
173     if (isDefault) {
174       assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
175              "Default implementation for analysis group already specified!");
176       assert(ImplementationInfo->getNormalCtor() &&
177            "Cannot specify pass as default if it does not have a default ctor");
178       AGI.DefaultImpl = ImplementationInfo;
179       InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
180     }
181   }
182 };
183 }
184
185 static std::vector<PassRegistrationListener*> *Listeners = 0;
186
187 // FIXME: This should use ManagedStatic to manage the pass registrar.
188 // Unfortunately, we can't do this, because passes are registered with static
189 // ctors, and having llvm_shutdown clear this map prevents successful
190 // ressurection after llvm_shutdown is run.
191 static PassRegistrar *getPassRegistrar() {
192   static PassRegistrar *PassRegistrarObj = 0;
193   if (!PassRegistrarObj)
194     PassRegistrarObj = new PassRegistrar();
195   return PassRegistrarObj;
196 }
197
198 // getPassInfo - Return the PassInfo data structure that corresponds to this
199 // pass...
200 const PassInfo *Pass::getPassInfo() const {
201   return lookupPassInfo(PassID);
202 }
203
204 const PassInfo *Pass::lookupPassInfo(intptr_t TI) {
205   return getPassRegistrar()->GetPassInfo(TI);
206 }
207
208 void RegisterPassBase::registerPass() {
209   getPassRegistrar()->RegisterPass(PIObj);
210
211   // Notify any listeners.
212   if (Listeners)
213     for (std::vector<PassRegistrationListener*>::iterator
214            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
215       (*I)->passRegistered(&PIObj);
216 }
217
218 void RegisterPassBase::unregisterPass() {
219   getPassRegistrar()->UnregisterPass(PIObj);
220 }
221
222 //===----------------------------------------------------------------------===//
223 //                  Analysis Group Implementation Code
224 //===----------------------------------------------------------------------===//
225
226 // RegisterAGBase implementation
227 //
228 RegisterAGBase::RegisterAGBase(intptr_t InterfaceID,
229                                intptr_t PassID, bool isDefault)
230   : RegisterPassBase(InterfaceID),
231     ImplementationInfo(0), isDefaultImplementation(isDefault) {
232
233   InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID));
234   if (InterfaceInfo == 0) {
235     // First reference to Interface, register it now.
236     registerPass();
237     InterfaceInfo = &PIObj;
238   }
239   assert(PIObj.isAnalysisGroup() &&
240          "Trying to join an analysis group that is a normal pass!");
241
242   if (PassID) {
243     ImplementationInfo = Pass::lookupPassInfo(PassID);
244     assert(ImplementationInfo &&
245            "Must register pass before adding to AnalysisGroup!");
246
247     // Make sure we keep track of the fact that the implementation implements
248     // the interface.
249     PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
250     IIPI->addInterfaceImplemented(InterfaceInfo);
251     
252     getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
253   }
254 }
255
256 void RegisterAGBase::setGroupName(const char *Name) {
257   assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
258   InterfaceInfo->setPassName(Name);
259 }
260
261
262 //===----------------------------------------------------------------------===//
263 // PassRegistrationListener implementation
264 //
265
266 // PassRegistrationListener ctor - Add the current object to the list of
267 // PassRegistrationListeners...
268 PassRegistrationListener::PassRegistrationListener() {
269   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
270   Listeners->push_back(this);
271 }
272
273 // dtor - Remove object from list of listeners...
274 PassRegistrationListener::~PassRegistrationListener() {
275   std::vector<PassRegistrationListener*>::iterator I =
276     std::find(Listeners->begin(), Listeners->end(), this);
277   assert(Listeners && I != Listeners->end() &&
278          "PassRegistrationListener not registered!");
279   Listeners->erase(I);
280
281   if (Listeners->empty()) {
282     delete Listeners;
283     Listeners = 0;
284   }
285 }
286
287 // enumeratePasses - Iterate over the registered passes, calling the
288 // passEnumerate callback on each PassInfo object.
289 //
290 void PassRegistrationListener::enumeratePasses() {
291   getPassRegistrar()->EnumerateWith(this);
292 }
293
294 //===----------------------------------------------------------------------===//
295 //   AnalysisUsage Class Implementation
296 //
297
298 namespace {
299   struct GetCFGOnlyPasses : public PassRegistrationListener {
300     std::vector<AnalysisID> &CFGOnlyList;
301     GetCFGOnlyPasses(std::vector<AnalysisID> &L) : CFGOnlyList(L) {}
302     
303     void passEnumerate(const PassInfo *P) {
304       if (P->isCFGOnlyPass())
305         CFGOnlyList.push_back(P);
306     }
307   };
308 }
309
310 // setPreservesCFG - This function should be called to by the pass, iff they do
311 // not:
312 //
313 //  1. Add or remove basic blocks from the function
314 //  2. Modify terminator instructions in any way.
315 //
316 // This function annotates the AnalysisUsage info object to say that analyses
317 // that only depend on the CFG are preserved by this pass.
318 //
319 void AnalysisUsage::setPreservesCFG() {
320   // Since this transformation doesn't modify the CFG, it preserves all analyses
321   // that only depend on the CFG (like dominators, loop info, etc...)
322   GetCFGOnlyPasses(Preserved).enumeratePasses();
323 }
324
325