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