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