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