115aba1771f325aef32d4f1c47f33cd1998aeac0
[oota-llvm.git] / lib / VMCore / Pass.cpp
1 //===- Pass.cpp - LLVM Pass Infrastructure Impementation ------------------===//
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 <typeinfo>
15 #include <sys/time.h>
16 #include <stdio.h>
17
18 //===----------------------------------------------------------------------===//
19 //   AnalysisID Class Implementation
20 //
21
22 static std::vector<const PassInfo*> CFGOnlyAnalyses;
23
24 void RegisterPassBase::setPreservesCFG() {
25   CFGOnlyAnalyses.push_back(PIObj);
26 }
27
28 //===----------------------------------------------------------------------===//
29 //   AnalysisResolver Class Implementation
30 //
31
32 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
33   assert(P->Resolver == 0 && "Pass already in a PassManager!");
34   P->Resolver = AR;
35 }
36
37 //===----------------------------------------------------------------------===//
38 //   AnalysisUsage Class Implementation
39 //
40
41 // preservesCFG - This function should be called to by the pass, iff they do
42 // not:
43 //
44 //  1. Add or remove basic blocks from the function
45 //  2. Modify terminator instructions in any way.
46 //
47 // This function annotates the AnalysisUsage info object to say that analyses
48 // that only depend on the CFG are preserved by this pass.
49 //
50 void AnalysisUsage::preservesCFG() {
51   // Since this transformation doesn't modify the CFG, it preserves all analyses
52   // that only depend on the CFG (like dominators, loop info, etc...)
53   //
54   Preserved.insert(Preserved.end(),
55                    CFGOnlyAnalyses.begin(), CFGOnlyAnalyses.end());
56 }
57
58
59 //===----------------------------------------------------------------------===//
60 // PassManager implementation - The PassManager class is a simple Pimpl class
61 // that wraps the PassManagerT template.
62 //
63 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
64 PassManager::~PassManager() { delete PM; }
65 void PassManager::add(Pass *P) { PM->add(P); }
66 bool PassManager::run(Module &M) { return PM->run(M); }
67
68
69 //===----------------------------------------------------------------------===//
70 // TimingInfo Class - This class is used to calculate information about the
71 // amount of time each pass takes to execute.  This only happens with
72 // -time-passes is enabled on the command line.
73 //
74 static cl::opt<bool>
75 EnableTiming("time-passes",
76             cl::desc("Time each pass, printing elapsed time for each on exit"));
77
78 static double getTime() {
79   struct timeval T;
80   gettimeofday(&T, 0);
81   return T.tv_sec + T.tv_usec/1000000.0;
82 }
83
84 // Create method.  If Timing is enabled, this creates and returns a new timing
85 // object, otherwise it returns null.
86 //
87 TimingInfo *TimingInfo::create() {
88   return EnableTiming ? new TimingInfo() : 0;
89 }
90
91 void TimingInfo::passStarted(Pass *P) { TimingData[P] -= getTime(); }
92 void TimingInfo::passEnded(Pass *P) { TimingData[P] += getTime(); }
93
94 // TimingDtor - Print out information about timing information
95 TimingInfo::~TimingInfo() {
96   // Iterate over all of the data, converting it into the dual of the data map,
97   // so that the data is sorted by amount of time taken, instead of pointer.
98   //
99   std::vector<std::pair<double, Pass*> > Data;
100   double TotalTime = 0;
101   for (std::map<Pass*, double>::iterator I = TimingData.begin(),
102          E = TimingData.end(); I != E; ++I)
103     // Throw out results for "grouping" pass managers...
104     if (!dynamic_cast<AnalysisResolver*>(I->first)) {
105       Data.push_back(std::make_pair(I->second, I->first));
106       TotalTime += I->second;
107     }
108   
109   // Sort the data by time as the primary key, in reverse order...
110   std::sort(Data.begin(), Data.end(), std::greater<std::pair<double, Pass*> >());
111
112   // Print out timing header...
113   std::cerr << std::string(79, '=') << "\n"
114        << "                      ... Pass execution timing report ...\n"
115        << std::string(79, '=') << "\n  Total Execution Time: " << TotalTime
116        << " seconds\n\n  % Time: Seconds:\tPass Name:\n";
117
118   // Loop through all of the timing data, printing it out...
119   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
120     fprintf(stderr, "  %6.2f%% %fs\t%s\n", Data[i].first*100 / TotalTime,
121             Data[i].first, Data[i].second->getPassName());
122   }
123   std::cerr << "  100.00% " << TotalTime << "s\tTOTAL\n"
124        << std::string(79, '=') << "\n";
125 }
126
127
128 void PMDebug::PrintArgumentInformation(const Pass *P) {
129   // Print out passes in pass manager...
130   if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
131     for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
132       PrintArgumentInformation(PM->getContainedPass(i));
133
134   } else {  // Normal pass.  Print argument information...
135     // Print out arguments for registered passes that are _optimizations_
136     if (const PassInfo *PI = P->getPassInfo())
137       if (PI->getPassType() & PassInfo::Optimization)
138         std::cerr << " -" << PI->getPassArgument();
139   }
140 }
141
142 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
143                                    Pass *P, Annotable *V) {
144   if (PassDebugging >= Executions) {
145     std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '" 
146               << P->getPassName();
147     if (V) {
148       std::cerr << "' on ";
149
150       if (dynamic_cast<Module*>(V)) {
151         std::cerr << "Module\n"; return;
152       } else if (Function *F = dynamic_cast<Function*>(V))
153         std::cerr << "Function '" << F->getName();
154       else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
155         std::cerr << "BasicBlock '" << BB->getName();
156       else if (Value *Val = dynamic_cast<Value*>(V))
157         std::cerr << typeid(*Val).name() << " '" << Val->getName();
158     }
159     std::cerr << "'...\n";
160   }
161 }
162
163 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
164                                    Pass *P, const std::vector<AnalysisID> &Set){
165   if (PassDebugging >= Details && !Set.empty()) {
166     std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
167     for (unsigned i = 0; i != Set.size(); ++i)
168       std::cerr << "  " << Set[i]->getPassName();
169     std::cerr << "\n";
170   }
171 }
172
173 //===----------------------------------------------------------------------===//
174 // Pass Implementation
175 //
176
177 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
178   PM->addPass(this, AU);
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 Analyse
195 // to print out the contents of an analysis.  Otherwise it is not neccesary 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 // FunctionPass Implementation
209 //
210
211 // run - On a module, we run this pass by initializing, runOnFunction'ing once
212 // for every function in the module, then by finalizing.
213 //
214 bool FunctionPass::run(Module &M) {
215   bool Changed = doInitialization(M);
216   
217   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
218     if (!I->isExternal())      // Passes are not run on external functions!
219     Changed |= runOnFunction(*I);
220   
221   return Changed | doFinalization(M);
222 }
223
224 // run - On a function, we simply initialize, run the function, then finalize.
225 //
226 bool FunctionPass::run(Function &F) {
227   if (F.isExternal()) return false;// Passes are not run on external functions!
228
229   return doInitialization(*F.getParent()) | runOnFunction(F)
230        | doFinalization(*F.getParent());
231 }
232
233 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
234                                     AnalysisUsage &AU) {
235   PM->addPass(this, AU);
236 }
237
238 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
239                                     AnalysisUsage &AU) {
240   PM->addPass(this, AU);
241 }
242
243 //===----------------------------------------------------------------------===//
244 // BasicBlockPass Implementation
245 //
246
247 // To run this pass on a function, we simply call runOnBasicBlock once for each
248 // function.
249 //
250 bool BasicBlockPass::runOnFunction(Function &F) {
251   bool Changed = false;
252   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
253     Changed |= runOnBasicBlock(*I);
254   return Changed;
255 }
256
257 // To run directly on the basic block, we initialize, runOnBasicBlock, then
258 // finalize.
259 //
260 bool BasicBlockPass::run(BasicBlock &BB) {
261   Module &M = *BB.getParent()->getParent();
262   return doInitialization(M) | runOnBasicBlock(BB) | doFinalization(M);
263 }
264
265 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
266                                       AnalysisUsage &AU) {
267   PM->addPass(this, AU);
268 }
269
270 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
271                                       AnalysisUsage &AU) {
272   PM->addPass(this, AU);
273 }
274
275
276 //===----------------------------------------------------------------------===//
277 // Pass Registration mechanism
278 //
279 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
280 static std::vector<PassRegistrationListener*> *Listeners = 0;
281
282 // getPassInfo - Return the PassInfo data structure that corresponds to this
283 // pass...
284 const PassInfo *Pass::getPassInfo() const {
285   if (PassInfoCache) return PassInfoCache;
286   if (PassInfoMap == 0) return 0;
287   std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(typeid(*this));
288   return (I != PassInfoMap->end()) ? I->second : 0;
289 }
290
291 void RegisterPassBase::registerPass(PassInfo *PI) {
292   if (PassInfoMap == 0)
293     PassInfoMap = new std::map<TypeInfo, PassInfo*>();
294
295   assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
296          "Pass already registered!");
297   PIObj = PI;
298   PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
299
300   // Notify any listeners...
301   if (Listeners)
302     for (std::vector<PassRegistrationListener*>::iterator
303            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
304       (*I)->passRegistered(PI);
305 }
306
307 RegisterPassBase::~RegisterPassBase() {
308   assert(PassInfoMap && "Pass registered but not in map!");
309   std::map<TypeInfo, PassInfo*>::iterator I =
310     PassInfoMap->find(PIObj->getTypeInfo());
311   assert(I != PassInfoMap->end() && "Pass registered but not in map!");
312
313   // Remove pass from the map...
314   PassInfoMap->erase(I);
315   if (PassInfoMap->empty()) {
316     delete PassInfoMap;
317     PassInfoMap = 0;
318   }
319
320   // Notify any listeners...
321   if (Listeners)
322     for (std::vector<PassRegistrationListener*>::iterator
323            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
324       (*I)->passUnregistered(PIObj);
325
326   // Delete the PassInfo object itself...
327   delete PIObj;
328 }
329
330
331
332 //===----------------------------------------------------------------------===//
333 // PassRegistrationListener implementation
334 //
335
336 // PassRegistrationListener ctor - Add the current object to the list of
337 // PassRegistrationListeners...
338 PassRegistrationListener::PassRegistrationListener() {
339   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
340   Listeners->push_back(this);
341 }
342
343 // dtor - Remove object from list of listeners...
344 PassRegistrationListener::~PassRegistrationListener() {
345   std::vector<PassRegistrationListener*>::iterator I =
346     std::find(Listeners->begin(), Listeners->end(), this);
347   assert(Listeners && I != Listeners->end() &&
348          "PassRegistrationListener not registered!");
349   Listeners->erase(I);
350
351   if (Listeners->empty()) {
352     delete Listeners;
353     Listeners = 0;
354   }
355 }
356
357 // enumeratePasses - Iterate over the registered passes, calling the
358 // passEnumerate callback on each PassInfo object.
359 //
360 void PassRegistrationListener::enumeratePasses() {
361   if (PassInfoMap)
362     for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
363            E = PassInfoMap->end(); I != E; ++I)
364       passEnumerate(I->second);
365 }