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