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