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