ModulePass and ImmutablePass. Force out of line virtual method.
[oota-llvm.git] / lib / VMCore / Pass.cpp
1 //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #ifdef USE_OLD_PASSMANAGER
18 #include "PassManagerT.h"         // PassManagerT implementation
19 #endif
20 #include "llvm/Module.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/TypeInfo.h"
25 #include <set>
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 //   AnalysisResolver Class Implementation
30 //
31
32 AnalysisResolver::~AnalysisResolver() {
33 }
34 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
35   assert(P->Resolver == 0 && "Pass already in a PassManager!");
36   P->Resolver = AR;
37 }
38
39 #ifdef USE_OLD_PASSMANAGER
40 //===----------------------------------------------------------------------===//
41 // PassManager implementation - The PassManager class is a simple Pimpl class
42 // that wraps the PassManagerT template.
43 //
44 PassManager::PassManager() : PM(new ModulePassManager()) {}
45 PassManager::~PassManager() { delete PM; }
46 void PassManager::add(Pass *P) {
47   ModulePass *MP = dynamic_cast<ModulePass*>(P);
48   assert(MP && "Not a modulepass?");
49   PM->add(MP);
50 }
51 bool PassManager::run(Module &M) { return PM->runOnModule(M); }
52
53 //===----------------------------------------------------------------------===//
54 // FunctionPassManager implementation - The FunctionPassManager class
55 // is a simple Pimpl class that wraps the PassManagerT template. It
56 // is like PassManager, but only deals in FunctionPasses.
57 //
58 FunctionPassManager::FunctionPassManager(ModuleProvider *P) :
59   PM(new FunctionPassManagerT()), MP(P) {}
60 FunctionPassManager::~FunctionPassManager() { delete PM; }
61 void FunctionPassManager::add(FunctionPass *P) { PM->add(P); }
62 void FunctionPassManager::add(ImmutablePass *IP) { PM->add(IP); }
63
64 /// doInitialization - Run all of the initializers for the function passes.
65 ///
66 bool FunctionPassManager::doInitialization() {
67   return PM->doInitialization(*MP->getModule());
68 }
69
70 bool FunctionPassManager::run(Function &F) {
71   std::string errstr;
72   if (MP->materializeFunction(&F, &errstr)) {
73     cerr << "Error reading bytecode file: " << errstr << "\n";
74     abort();
75   }
76   return PM->runOnFunction(F);
77 }
78
79 /// doFinalization - Run all of the initializers for the function passes.
80 ///
81 bool FunctionPassManager::doFinalization() {
82   return PM->doFinalization(*MP->getModule());
83 }
84
85
86 //===----------------------------------------------------------------------===//
87 // TimingInfo Class - This class is used to calculate information about the
88 // amount of time each pass takes to execute.  This only happens with
89 // -time-passes is enabled on the command line.
90 //
91 bool llvm::TimePassesIsEnabled = false;
92 static cl::opt<bool,true>
93 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
94             cl::desc("Time each pass, printing elapsed time for each on exit"));
95
96 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
97 // a non null value (if the -time-passes option is enabled) or it leaves it
98 // null.  It may be called multiple times.
99 void TimingInfo::createTheTimeInfo() {
100   if (!TimePassesIsEnabled || TheTimeInfo) return;
101
102   // Constructed the first time this is called, iff -time-passes is enabled.
103   // This guarantees that the object will be constructed before static globals,
104   // thus it will be destroyed before them.
105   static ManagedStatic<TimingInfo> TTI;
106   TheTimeInfo = &*TTI;
107 }
108
109 void PMDebug::PrintArgumentInformation(const Pass *P) {
110   // Print out passes in pass manager...
111   if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
112     for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
113       PrintArgumentInformation(PM->getContainedPass(i));
114
115   } else {  // Normal pass.  Print argument information...
116     // Print out arguments for registered passes that are _optimizations_
117     if (const PassInfo *PI = P->getPassInfo())
118       if (!PI->isAnalysisGroup())
119         cerr << " -" << PI->getPassArgument();
120   }
121 }
122
123 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
124                                    Pass *P, Module *M) {
125   if (PassDebugging >= Executions) {
126     cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
127          << P->getPassName();
128     if (M) cerr << "' on Module '" << M->getModuleIdentifier() << "'\n";
129     cerr << "'...\n";
130   }
131 }
132
133 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
134                                    Pass *P, Function *F) {
135   if (PassDebugging >= Executions) {
136     cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
137          << P->getPassName();
138     if (F) cerr << "' on Function '" << F->getName();
139     cerr << "'...\n";
140   }
141 }
142
143 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
144                                    Pass *P, BasicBlock *BB) {
145   if (PassDebugging >= Executions) {
146     cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
147          << P->getPassName();
148     if (BB) cerr << "' on BasicBlock '" << BB->getName();
149     cerr << "'...\n";
150   }
151 }
152
153 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
154                                    Pass *P, const std::vector<AnalysisID> &Set){
155   if (PassDebugging >= Details && !Set.empty()) {
156     cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
157     for (unsigned i = 0; i != Set.size(); ++i) {
158       if (i) cerr << ",";
159       cerr << " " << Set[i]->getPassName();
160     }
161     cerr << "\n";
162   }
163 }
164 #endif
165
166 //===----------------------------------------------------------------------===//
167 // Pass Implementation
168 //
169
170 #ifdef USE_OLD_PASSMANAGER
171 void ModulePass::addToPassManager(ModulePassManager *PM, AnalysisUsage &AU) {
172   PM->addPass(this, AU);
173 }
174 #else
175 // Force out-of-line virtual method.
176 ModulePass::~ModulePass() { }
177 #endif
178
179 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
180 #ifdef USE_OLD_PASSMANAGER
181   return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
182 #else
183   return Resolver_New->getAnalysisToUpdate(AnalysisID, true) != 0;
184 #endif
185 }
186
187 // dumpPassStructure - Implement the -debug-passes=Structure option
188 void Pass::dumpPassStructure(unsigned Offset) {
189   cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
190 }
191
192 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligible name for the pass.
193 //
194 const char *Pass::getPassName() const {
195   if (const PassInfo *PI = getPassInfo())
196     return PI->getPassName();
197   return typeid(*this).name();
198 }
199
200 // print - Print out the internal state of the pass.  This is called by Analyze
201 // to print out the contents of an analysis.  Otherwise it is not necessary to
202 // implement this method.
203 //
204 void Pass::print(std::ostream &O,const Module*) const {
205   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
206 }
207
208 // dump - call print(cerr);
209 void Pass::dump() const {
210   print(*cerr.stream(), 0);
211 }
212
213 //===----------------------------------------------------------------------===//
214 // ImmutablePass Implementation
215 //
216 #ifdef USE_OLD_PASSMANAGER
217 void ImmutablePass::addToPassManager(ModulePassManager *PM, 
218                                      AnalysisUsage &AU) {
219   PM->addPass(this, AU);
220 }
221 #else
222 // Force out-of-line virtual method.
223 ImmutablePass::~ImmutablePass() { }
224 #endif
225
226 //===----------------------------------------------------------------------===//
227 // FunctionPass Implementation
228 //
229
230 // run - On a module, we run this pass by initializing, runOnFunction'ing once
231 // for every function in the module, then by finalizing.
232 //
233 bool FunctionPass::runOnModule(Module &M) {
234   bool Changed = doInitialization(M);
235
236   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
237     if (!I->isExternal())      // Passes are not run on external functions!
238     Changed |= runOnFunction(*I);
239
240   return Changed | doFinalization(M);
241 }
242
243 // run - On a function, we simply initialize, run the function, then finalize.
244 //
245 bool FunctionPass::run(Function &F) {
246   if (F.isExternal()) return false;// Passes are not run on external functions!
247
248   bool Changed = doInitialization(*F.getParent());
249   Changed |= runOnFunction(F);
250   return Changed | doFinalization(*F.getParent());
251 }
252
253 #ifdef USE_OLD_PASSMANAGER
254 void FunctionPass::addToPassManager(ModulePassManager *PM,
255                                     AnalysisUsage &AU) {
256   PM->addPass(this, AU);
257 }
258
259 void FunctionPass::addToPassManager(FunctionPassManagerT *PM,
260                                     AnalysisUsage &AU) {
261   PM->addPass(this, AU);
262 }
263 #endif
264
265 //===----------------------------------------------------------------------===//
266 // BasicBlockPass Implementation
267 //
268
269 // To run this pass on a function, we simply call runOnBasicBlock once for each
270 // function.
271 //
272 bool BasicBlockPass::runOnFunction(Function &F) {
273   bool Changed = doInitialization(F);
274   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
275     Changed |= runOnBasicBlock(*I);
276   return Changed | doFinalization(F);
277 }
278
279 // To run directly on the basic block, we initialize, runOnBasicBlock, then
280 // finalize.
281 //
282 bool BasicBlockPass::runPass(BasicBlock &BB) {
283   Function &F = *BB.getParent();
284   Module &M = *F.getParent();
285   bool Changed = doInitialization(M);
286   Changed |= doInitialization(F);
287   Changed |= runOnBasicBlock(BB);
288   Changed |= doFinalization(F);
289   Changed |= doFinalization(M);
290   return Changed;
291 }
292
293 #ifdef USE_OLD_PASSMANAGER
294 void BasicBlockPass::addToPassManager(FunctionPassManagerT *PM,
295                                       AnalysisUsage &AU) {
296   PM->addPass(this, AU);
297 }
298
299 void BasicBlockPass::addToPassManager(BasicBlockPassManager *PM,
300                                       AnalysisUsage &AU) {
301   PM->addPass(this, AU);
302 }
303 #endif
304
305 //===----------------------------------------------------------------------===//
306 // Pass Registration mechanism
307 //
308 namespace {
309 class PassRegistrar {
310   /// PassInfoMap - Keep track of the passinfo object for each registered llvm
311   /// pass.
312   std::map<TypeInfo, PassInfo*> PassInfoMap;
313   
314   /// AnalysisGroupInfo - Keep track of information for each analysis group.
315   struct AnalysisGroupInfo {
316     const PassInfo *DefaultImpl;
317     std::set<const PassInfo *> Implementations;
318     AnalysisGroupInfo() : DefaultImpl(0) {}
319   };
320   
321   /// AnalysisGroupInfoMap - Information for each analysis group.
322   std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap;
323
324 public:
325   
326   const PassInfo *GetPassInfo(const std::type_info &TI) const {
327     std::map<TypeInfo, PassInfo*>::const_iterator I = PassInfoMap.find(TI);
328     return I != PassInfoMap.end() ? I->second : 0;
329   }
330   
331   void RegisterPass(PassInfo &PI) {
332     bool Inserted =
333       PassInfoMap.insert(std::make_pair(TypeInfo(PI.getTypeInfo()),&PI)).second;
334     assert(Inserted && "Pass registered multiple times!");
335   }
336   
337   void UnregisterPass(PassInfo &PI) {
338     std::map<TypeInfo, PassInfo*>::iterator I =
339       PassInfoMap.find(PI.getTypeInfo());
340     assert(I != PassInfoMap.end() && "Pass registered but not in map!");
341     
342     // Remove pass from the map.
343     PassInfoMap.erase(I);
344   }
345   
346   void EnumerateWith(PassRegistrationListener *L) {
347     for (std::map<TypeInfo, PassInfo*>::const_iterator I = PassInfoMap.begin(),
348          E = PassInfoMap.end(); I != E; ++I)
349       L->passEnumerate(I->second);
350   }
351   
352   
353   /// Analysis Group Mechanisms.
354   void RegisterAnalysisGroup(PassInfo *InterfaceInfo,
355                              const PassInfo *ImplementationInfo,
356                              bool isDefault) {
357     AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];
358     assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
359            "Cannot add a pass to the same analysis group more than once!");
360     AGI.Implementations.insert(ImplementationInfo);
361     if (isDefault) {
362       assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
363              "Default implementation for analysis group already specified!");
364       assert(ImplementationInfo->getNormalCtor() &&
365            "Cannot specify pass as default if it does not have a default ctor");
366       AGI.DefaultImpl = ImplementationInfo;
367       InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
368     }
369   }
370 };
371 }
372
373 static ManagedStatic<PassRegistrar> PassRegistrarObj;
374 static std::vector<PassRegistrationListener*> *Listeners = 0;
375
376 // getPassInfo - Return the PassInfo data structure that corresponds to this
377 // pass...
378 const PassInfo *Pass::getPassInfo() const {
379   if (PassInfoCache) return PassInfoCache;
380   return lookupPassInfo(typeid(*this));
381 }
382
383 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
384   return PassRegistrarObj->GetPassInfo(TI);
385 }
386
387 void RegisterPassBase::registerPass() {
388   PassRegistrarObj->RegisterPass(PIObj);
389
390   // Notify any listeners.
391   if (Listeners)
392     for (std::vector<PassRegistrationListener*>::iterator
393            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
394       (*I)->passRegistered(&PIObj);
395 }
396
397 void RegisterPassBase::unregisterPass() {
398   PassRegistrarObj->UnregisterPass(PIObj);
399 }
400
401 //===----------------------------------------------------------------------===//
402 //                  Analysis Group Implementation Code
403 //===----------------------------------------------------------------------===//
404
405 // RegisterAGBase implementation
406 //
407 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
408                                const std::type_info *Pass, bool isDefault)
409   : RegisterPassBase(Interface),
410     ImplementationInfo(0), isDefaultImplementation(isDefault) {
411
412   InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
413   if (InterfaceInfo == 0) {
414     // First reference to Interface, register it now.
415     registerPass();
416     InterfaceInfo = &PIObj;
417   }
418   assert(PIObj.isAnalysisGroup() &&
419          "Trying to join an analysis group that is a normal pass!");
420
421   if (Pass) {
422     ImplementationInfo = Pass::lookupPassInfo(*Pass);
423     assert(ImplementationInfo &&
424            "Must register pass before adding to AnalysisGroup!");
425
426     // Make sure we keep track of the fact that the implementation implements
427     // the interface.
428     PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
429     IIPI->addInterfaceImplemented(InterfaceInfo);
430     
431     PassRegistrarObj->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
432   }
433 }
434
435 void RegisterAGBase::setGroupName(const char *Name) {
436   assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
437   InterfaceInfo->setPassName(Name);
438 }
439
440
441 //===----------------------------------------------------------------------===//
442 // PassRegistrationListener implementation
443 //
444
445 // PassRegistrationListener ctor - Add the current object to the list of
446 // PassRegistrationListeners...
447 PassRegistrationListener::PassRegistrationListener() {
448   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
449   Listeners->push_back(this);
450 }
451
452 // dtor - Remove object from list of listeners...
453 PassRegistrationListener::~PassRegistrationListener() {
454   std::vector<PassRegistrationListener*>::iterator I =
455     std::find(Listeners->begin(), Listeners->end(), this);
456   assert(Listeners && I != Listeners->end() &&
457          "PassRegistrationListener not registered!");
458   Listeners->erase(I);
459
460   if (Listeners->empty()) {
461     delete Listeners;
462     Listeners = 0;
463   }
464 }
465
466 // enumeratePasses - Iterate over the registered passes, calling the
467 // passEnumerate callback on each PassInfo object.
468 //
469 void PassRegistrationListener::enumeratePasses() {
470   PassRegistrarObj->EnumerateWith(this);
471 }
472
473 //===----------------------------------------------------------------------===//
474 //   AnalysisUsage Class Implementation
475 //
476
477 namespace {
478   struct GetCFGOnlyPasses : public PassRegistrationListener {
479     std::vector<AnalysisID> &CFGOnlyList;
480     GetCFGOnlyPasses(std::vector<AnalysisID> &L) : CFGOnlyList(L) {}
481     
482     void passEnumerate(const PassInfo *P) {
483       if (P->isCFGOnlyPass())
484         CFGOnlyList.push_back(P);
485     }
486   };
487 }
488
489 // setPreservesCFG - This function should be called to by the pass, iff they do
490 // not:
491 //
492 //  1. Add or remove basic blocks from the function
493 //  2. Modify terminator instructions in any way.
494 //
495 // This function annotates the AnalysisUsage info object to say that analyses
496 // that only depend on the CFG are preserved by this pass.
497 //
498 void AnalysisUsage::setPreservesCFG() {
499   // Since this transformation doesn't modify the CFG, it preserves all analyses
500   // that only depend on the CFG (like dominators, loop info, etc...)
501   GetCFGOnlyPasses(Preserved).enumeratePasses();
502 }
503
504