- Implement the new AnalysisGroup feature, neccesary for Value#ing and pointer analysis
[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 <stdio.h>
15 #include <sys/resource.h>
16 #include <sys/unistd.h>
17 #include <set>
18
19 //===----------------------------------------------------------------------===//
20 //   AnalysisID Class Implementation
21 //
22
23 static std::vector<const PassInfo*> CFGOnlyAnalyses;
24
25 void RegisterPassBase::setPreservesCFG() {
26   CFGOnlyAnalyses.push_back(PIObj);
27 }
28
29 //===----------------------------------------------------------------------===//
30 //   AnalysisResolver Class Implementation
31 //
32
33 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
34   assert(P->Resolver == 0 && "Pass already in a PassManager!");
35   P->Resolver = AR;
36 }
37
38 //===----------------------------------------------------------------------===//
39 //   AnalysisUsage Class Implementation
40 //
41
42 // preservesCFG - This function should be called to by the pass, iff they do
43 // not:
44 //
45 //  1. Add or remove basic blocks from the function
46 //  2. Modify terminator instructions in any way.
47 //
48 // This function annotates the AnalysisUsage info object to say that analyses
49 // that only depend on the CFG are preserved by this pass.
50 //
51 void AnalysisUsage::preservesCFG() {
52   // Since this transformation doesn't modify the CFG, it preserves all analyses
53   // that only depend on the CFG (like dominators, loop info, etc...)
54   //
55   Preserved.insert(Preserved.end(),
56                    CFGOnlyAnalyses.begin(), CFGOnlyAnalyses.end());
57 }
58
59
60 //===----------------------------------------------------------------------===//
61 // PassManager implementation - The PassManager class is a simple Pimpl class
62 // that wraps the PassManagerT template.
63 //
64 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
65 PassManager::~PassManager() { delete PM; }
66 void PassManager::add(Pass *P) { PM->add(P); }
67 bool PassManager::run(Module &M) { return PM->run(M); }
68
69
70 //===----------------------------------------------------------------------===//
71 // TimingInfo Class - This class is used to calculate information about the
72 // amount of time each pass takes to execute.  This only happens with
73 // -time-passes is enabled on the command line.
74 //
75 static cl::opt<bool>
76 EnableTiming("time-passes",
77             cl::desc("Time each pass, printing elapsed time for each on exit"));
78
79 static TimeRecord getTimeRecord() {
80   static unsigned long PageSize = 0;
81
82   if (PageSize == 0) {
83 #ifdef _SC_PAGE_SIZE
84     PageSize = sysconf(_SC_PAGE_SIZE);
85 #else
86 #ifdef _SC_PAGESIZE
87     PageSize = sysconf(_SC_PAGESIZE);
88 #else
89     PageSize = getpagesize();
90 #endif
91 #endif
92   }
93
94   struct rusage RU;
95   struct timeval T;
96   gettimeofday(&T, 0);
97   if (getrusage(RUSAGE_SELF, &RU)) {
98     perror("getrusage call failed: -time-passes info incorrect!");
99   }
100
101   TimeRecord Result;
102   Result.Elapsed    =           T.tv_sec +           T.tv_usec/1000000.0;
103   Result.UserTime   = RU.ru_utime.tv_sec + RU.ru_utime.tv_usec/1000000.0;
104   Result.SystemTime = RU.ru_stime.tv_sec + RU.ru_stime.tv_usec/1000000.0;
105   Result.MaxRSS = RU.ru_maxrss*PageSize;
106
107   return Result;
108 }
109
110 bool TimeRecord::operator<(const TimeRecord &TR) const {
111   // Primary sort key is User+System time
112   if (UserTime+SystemTime < TR.UserTime+TR.SystemTime)
113     return true;
114   if (UserTime+SystemTime > TR.UserTime+TR.SystemTime)
115     return false;
116
117   // Secondary sort key is Wall Time
118   return Elapsed < TR.Elapsed;
119 }
120
121 void TimeRecord::passStart(const TimeRecord &T) {
122   Elapsed    -= T.Elapsed;
123   UserTime   -= T.UserTime;
124   SystemTime -= T.SystemTime;
125   RSSTemp     = T.MaxRSS;
126 }
127
128 void TimeRecord::passEnd(const TimeRecord &T) {
129   Elapsed    += T.Elapsed;
130   UserTime   += T.UserTime;
131   SystemTime += T.SystemTime;
132   RSSTemp     = T.MaxRSS - RSSTemp;
133   MaxRSS      = std::max(MaxRSS, RSSTemp);
134 }
135
136 static void printVal(double Val, double Total) {
137   if (Total < 1e-7)   // Avoid dividing by zero...
138     fprintf(stderr, "        -----     ");
139   else
140     fprintf(stderr, "  %7.4f (%5.1f%%)", Val, Val*100/Total);
141 }
142
143 void TimeRecord::print(const char *PassName, const TimeRecord &Total) const {
144   printVal(UserTime, Total.UserTime);
145   printVal(SystemTime, Total.SystemTime);
146   printVal(UserTime+SystemTime, Total.UserTime+Total.SystemTime);
147   printVal(Elapsed, Total.Elapsed);
148   
149   fprintf(stderr, "  ");
150
151   if (Total.MaxRSS)
152     std::cerr << MaxRSS << "\t";
153   std::cerr << PassName << "\n";
154 }
155
156
157 // Create method.  If Timing is enabled, this creates and returns a new timing
158 // object, otherwise it returns null.
159 //
160 TimingInfo *TimingInfo::create() {
161   return EnableTiming ? new TimingInfo() : 0;
162 }
163
164 void TimingInfo::passStarted(Pass *P) {
165   TimingData[P].passStart(getTimeRecord());
166 }
167 void TimingInfo::passEnded(Pass *P) {
168   TimingData[P].passEnd(getTimeRecord());
169 }
170 void TimeRecord::sum(const TimeRecord &TR) {
171   Elapsed    += TR.Elapsed;
172   UserTime   += TR.UserTime;
173   SystemTime += TR.SystemTime;
174   MaxRSS     += TR.MaxRSS;
175 }
176
177 // TimingDtor - Print out information about timing information
178 TimingInfo::~TimingInfo() {
179   // Iterate over all of the data, converting it into the dual of the data map,
180   // so that the data is sorted by amount of time taken, instead of pointer.
181   //
182   std::vector<std::pair<TimeRecord, Pass*> > Data;
183   TimeRecord Total;
184   for (std::map<Pass*, TimeRecord>::iterator I = TimingData.begin(),
185          E = TimingData.end(); I != E; ++I)
186     // Throw out results for "grouping" pass managers...
187     if (!dynamic_cast<AnalysisResolver*>(I->first)) {
188       Data.push_back(std::make_pair(I->second, I->first));
189       Total.sum(I->second);
190     }
191   
192   // Sort the data by time as the primary key, in reverse order...
193   std::sort(Data.begin(), Data.end(),
194             std::greater<std::pair<TimeRecord, Pass*> >());
195
196   // Print out timing header...
197   std::cerr << std::string(79, '=') << "\n"
198             << "                      ... Pass execution timing report ...\n"
199             << std::string(79, '=') << "\n  Total Execution Time: "
200             << (Total.UserTime+Total.SystemTime) << " seconds ("
201             << Total.Elapsed << " wall clock)\n\n   ---User Time---   "
202             << "--System Time--   --User+System--   ---Wall Time---";
203
204   if (Total.MaxRSS)
205     std::cerr << " ---Mem---";
206   std::cerr << "  --- Pass Name ---\n";
207
208   // Loop through all of the timing data, printing it out...
209   for (unsigned i = 0, e = Data.size(); i != e; ++i)
210     Data[i].first.print(Data[i].second->getPassName(), Total);
211
212   Total.print("TOTAL", Total);
213 }
214
215
216 void PMDebug::PrintArgumentInformation(const Pass *P) {
217   // Print out passes in pass manager...
218   if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
219     for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
220       PrintArgumentInformation(PM->getContainedPass(i));
221
222   } else {  // Normal pass.  Print argument information...
223     // Print out arguments for registered passes that are _optimizations_
224     if (const PassInfo *PI = P->getPassInfo())
225       if (PI->getPassType() & PassInfo::Optimization)
226         std::cerr << " -" << PI->getPassArgument();
227   }
228 }
229
230 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
231                                    Pass *P, Annotable *V) {
232   if (PassDebugging >= Executions) {
233     std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '" 
234               << P->getPassName();
235     if (V) {
236       std::cerr << "' on ";
237
238       if (dynamic_cast<Module*>(V)) {
239         std::cerr << "Module\n"; return;
240       } else if (Function *F = dynamic_cast<Function*>(V))
241         std::cerr << "Function '" << F->getName();
242       else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
243         std::cerr << "BasicBlock '" << BB->getName();
244       else if (Value *Val = dynamic_cast<Value*>(V))
245         std::cerr << typeid(*Val).name() << " '" << Val->getName();
246     }
247     std::cerr << "'...\n";
248   }
249 }
250
251 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
252                                    Pass *P, const std::vector<AnalysisID> &Set){
253   if (PassDebugging >= Details && !Set.empty()) {
254     std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
255     for (unsigned i = 0; i != Set.size(); ++i)
256       std::cerr << "  " << Set[i]->getPassName();
257     std::cerr << "\n";
258   }
259 }
260
261 //===----------------------------------------------------------------------===//
262 // Pass Implementation
263 //
264
265 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
266   PM->addPass(this, AU);
267 }
268
269 // dumpPassStructure - Implement the -debug-passes=Structure option
270 void Pass::dumpPassStructure(unsigned Offset) {
271   std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
272 }
273
274 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
275 //
276 const char *Pass::getPassName() const {
277   if (const PassInfo *PI = getPassInfo())
278     return PI->getPassName();
279   return typeid(*this).name();
280 }
281
282 // print - Print out the internal state of the pass.  This is called by Analyse
283 // to print out the contents of an analysis.  Otherwise it is not neccesary to
284 // implement this method.
285 //
286 void Pass::print(std::ostream &O) const {
287   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
288 }
289
290 // dump - call print(std::cerr);
291 void Pass::dump() const {
292   print(std::cerr, 0);
293 }
294
295 //===----------------------------------------------------------------------===//
296 // FunctionPass Implementation
297 //
298
299 // run - On a module, we run this pass by initializing, runOnFunction'ing once
300 // for every function in the module, then by finalizing.
301 //
302 bool FunctionPass::run(Module &M) {
303   bool Changed = doInitialization(M);
304   
305   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
306     if (!I->isExternal())      // Passes are not run on external functions!
307     Changed |= runOnFunction(*I);
308   
309   return Changed | doFinalization(M);
310 }
311
312 // run - On a function, we simply initialize, run the function, then finalize.
313 //
314 bool FunctionPass::run(Function &F) {
315   if (F.isExternal()) return false;// Passes are not run on external functions!
316
317   return doInitialization(*F.getParent()) | runOnFunction(F)
318        | doFinalization(*F.getParent());
319 }
320
321 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
322                                     AnalysisUsage &AU) {
323   PM->addPass(this, AU);
324 }
325
326 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
327                                     AnalysisUsage &AU) {
328   PM->addPass(this, AU);
329 }
330
331 //===----------------------------------------------------------------------===//
332 // BasicBlockPass Implementation
333 //
334
335 // To run this pass on a function, we simply call runOnBasicBlock once for each
336 // function.
337 //
338 bool BasicBlockPass::runOnFunction(Function &F) {
339   bool Changed = false;
340   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
341     Changed |= runOnBasicBlock(*I);
342   return Changed;
343 }
344
345 // To run directly on the basic block, we initialize, runOnBasicBlock, then
346 // finalize.
347 //
348 bool BasicBlockPass::run(BasicBlock &BB) {
349   Module &M = *BB.getParent()->getParent();
350   return doInitialization(M) | runOnBasicBlock(BB) | doFinalization(M);
351 }
352
353 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
354                                       AnalysisUsage &AU) {
355   PM->addPass(this, AU);
356 }
357
358 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
359                                       AnalysisUsage &AU) {
360   PM->addPass(this, AU);
361 }
362
363
364 //===----------------------------------------------------------------------===//
365 // Pass Registration mechanism
366 //
367 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
368 static std::vector<PassRegistrationListener*> *Listeners = 0;
369
370 // getPassInfo - Return the PassInfo data structure that corresponds to this
371 // pass...
372 const PassInfo *Pass::getPassInfo() const {
373   if (PassInfoCache) return PassInfoCache;
374   return lookupPassInfo(typeid(*this));
375 }
376
377 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
378   if (PassInfoMap == 0) return 0;
379   std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
380   return (I != PassInfoMap->end()) ? I->second : 0;
381 }
382
383 void RegisterPassBase::registerPass(PassInfo *PI) {
384   if (PassInfoMap == 0)
385     PassInfoMap = new std::map<TypeInfo, PassInfo*>();
386
387   assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
388          "Pass already registered!");
389   PIObj = PI;
390   PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
391
392   // Notify any listeners...
393   if (Listeners)
394     for (std::vector<PassRegistrationListener*>::iterator
395            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
396       (*I)->passRegistered(PI);
397 }
398
399 void RegisterPassBase::unregisterPass(PassInfo *PI) {
400   assert(PassInfoMap && "Pass registered but not in map!");
401   std::map<TypeInfo, PassInfo*>::iterator I =
402     PassInfoMap->find(PI->getTypeInfo());
403   assert(I != PassInfoMap->end() && "Pass registered but not in map!");
404
405   // Remove pass from the map...
406   PassInfoMap->erase(I);
407   if (PassInfoMap->empty()) {
408     delete PassInfoMap;
409     PassInfoMap = 0;
410   }
411
412   // Notify any listeners...
413   if (Listeners)
414     for (std::vector<PassRegistrationListener*>::iterator
415            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
416       (*I)->passUnregistered(PI);
417
418   // Delete the PassInfo object itself...
419   delete PI;
420 }
421
422 //===----------------------------------------------------------------------===//
423 //                  Analysis Group Implementation Code
424 //===----------------------------------------------------------------------===//
425
426 struct AnalysisGroupInfo {
427   const PassInfo *DefaultImpl;
428   std::set<const PassInfo *> Implementations;
429   AnalysisGroupInfo() : DefaultImpl(0) {}
430 };
431
432 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
433
434 // RegisterAGBase implementation
435 //
436 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
437                                const std::type_info *Pass, bool isDefault)
438   : ImplementationInfo(0), isDefaultImplementation(isDefault) {
439
440   std::cerr << "Registering interface: " << Interface.name() << "\n";
441
442   InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
443   if (InterfaceInfo == 0) {   // First reference to Interface, add it now.
444     InterfaceInfo =   // Create the new PassInfo for the interface...
445       new PassInfo("", "", Interface, PassInfo::AnalysisGroup, 0, 0);
446     registerPass(InterfaceInfo);
447     PIObj = 0;
448   }
449   assert(InterfaceInfo->getPassType() == PassInfo::AnalysisGroup &&
450          "Trying to join an analysis group that is a normal pass!");
451
452   if (Pass) {
453   std::cerr << "Registering interface impl: " << Pass->name() << "\n";
454
455     ImplementationInfo = Pass::lookupPassInfo(*Pass);
456     assert(ImplementationInfo &&
457            "Must register pass before adding to AnalysisGroup!");
458
459     // Lazily allocate to avoid nasty initialization order dependencies
460     if (AnalysisGroupInfoMap == 0)
461       AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
462
463     AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
464     assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
465            "Cannot add a pass to the same analysis group more than once!");
466     AGI.Implementations.insert(ImplementationInfo);
467     if (isDefault) {
468       assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
469              "Default implementation for analysis group already specified!");
470       assert(ImplementationInfo->getNormalCtor() &&
471            "Cannot specify pass as default if it does not have a default ctor");
472       AGI.DefaultImpl = ImplementationInfo;
473       InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
474     }
475   }
476 }
477
478 void RegisterAGBase::setGroupName(const char *Name) {
479   assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
480   InterfaceInfo->setPassName(Name);
481 }
482
483 RegisterAGBase::~RegisterAGBase() {
484   if (ImplementationInfo) {
485     assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
486     AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
487
488     assert(AGI.Implementations.count(ImplementationInfo) &&
489            "Pass not a member of analysis group?");
490
491     if (AGI.DefaultImpl == ImplementationInfo)
492       AGI.DefaultImpl = 0;
493     
494     AGI.Implementations.erase(ImplementationInfo);
495
496     // Last member of this analysis group? Unregister PassInfo, delete map entry
497     if (AGI.Implementations.empty()) {
498       assert(AGI.DefaultImpl == 0 &&
499              "Default implementation didn't unregister?");
500       AnalysisGroupInfoMap->erase(InterfaceInfo);
501       if (AnalysisGroupInfoMap->empty()) {  // Delete map if empty
502         delete AnalysisGroupInfoMap;
503         AnalysisGroupInfoMap = 0;
504       }
505
506       unregisterPass(InterfaceInfo);
507     }
508   }
509 }
510
511
512 // findAnalysisGroupMember - Return an iterator pointing to one of the elements
513 // of Map if there is a pass in Map that is a member of the analysis group for
514 // the specified AnalysisGroupID.
515 //
516 static std::map<const PassInfo*, Pass*>::const_iterator
517 findAnalysisGroupMember(const PassInfo *AnalysisGroupID,
518                         const std::map<const PassInfo*, Pass*> &Map) {
519   assert(AnalysisGroupID->getPassType() == PassInfo::AnalysisGroup &&
520          "AnalysisGroupID is not an analysis group!");
521   assert(AnalysisGroupInfoMap && AnalysisGroupInfoMap->count(AnalysisGroupID) &&
522          "Analysis Group does not have any registered members!");
523
524   // Get the set of all known implementations of this analysis group...
525   std::set<const PassInfo *> &Impls = 
526     (*AnalysisGroupInfoMap)[AnalysisGroupID].Implementations;
527
528   // Scan over available passes, checking to see if any is a valid analysis
529   for (std::map<const PassInfo*, Pass*>::const_iterator I = Map.begin(),
530          E = Map.end(); I != E; ++I)
531     if (Impls.count(I->first))  // This is a valid analysis, return it.
532       return I;
533
534   return Map.end();  // Nothing of use found.
535 }
536
537
538
539
540 //===----------------------------------------------------------------------===//
541 // PassRegistrationListener implementation
542 //
543
544 // PassRegistrationListener ctor - Add the current object to the list of
545 // PassRegistrationListeners...
546 PassRegistrationListener::PassRegistrationListener() {
547   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
548   Listeners->push_back(this);
549 }
550
551 // dtor - Remove object from list of listeners...
552 PassRegistrationListener::~PassRegistrationListener() {
553   std::vector<PassRegistrationListener*>::iterator I =
554     std::find(Listeners->begin(), Listeners->end(), this);
555   assert(Listeners && I != Listeners->end() &&
556          "PassRegistrationListener not registered!");
557   Listeners->erase(I);
558
559   if (Listeners->empty()) {
560     delete Listeners;
561     Listeners = 0;
562   }
563 }
564
565 // enumeratePasses - Iterate over the registered passes, calling the
566 // passEnumerate callback on each PassInfo object.
567 //
568 void PassRegistrationListener::enumeratePasses() {
569   if (PassInfoMap)
570     for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
571            E = PassInfoMap->end(); I != E; ++I)
572       passEnumerate(I->second);
573 }