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