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