*** empty log message ***
[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 "llvm/Function.h"
13 #include "llvm/BasicBlock.h"
14 #include "Support/STLExtras.h"
15 #include "Support/CommandLine.h"
16 #include <typeinfo>
17 #include <iostream>
18 #include <sys/time.h>
19 #include <stdio.h>
20
21 //===----------------------------------------------------------------------===//
22 //   AnalysisID Class Implementation
23 //
24
25 static std::vector<AnalysisID> CFGOnlyAnalyses;
26
27 // Source of unique analysis ID #'s.
28 unsigned AnalysisID::NextID = 0;
29
30 AnalysisID::AnalysisID(const AnalysisID &AID, bool DependsOnlyOnCFG) {
31   ID = AID.ID;                    // Implement the copy ctor part...
32   Constructor = AID.Constructor;
33   
34   // If this analysis only depends on the CFG of the function, add it to the CFG
35   // only list...
36   if (DependsOnlyOnCFG)
37     CFGOnlyAnalyses.push_back(AID);
38 }
39
40 //===----------------------------------------------------------------------===//
41 //   AnalysisResolver Class Implementation
42 //
43
44 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
45   assert(P->Resolver == 0 && "Pass already in a PassManager!");
46   P->Resolver = AR;
47 }
48
49 //===----------------------------------------------------------------------===//
50 //   AnalysisUsage Class Implementation
51 //
52
53 // preservesCFG - This function should be called to by the pass, iff they do
54 // not:
55 //
56 //  1. Add or remove basic blocks from the function
57 //  2. Modify terminator instructions in any way.
58 //
59 // This function annotates the AnalysisUsage info object to say that analyses
60 // that only depend on the CFG are preserved by this pass.
61 //
62 void AnalysisUsage::preservesCFG() {
63   // Since this transformation doesn't modify the CFG, it preserves all analyses
64   // that only depend on the CFG (like dominators, loop info, etc...)
65   //
66   Preserved.insert(Preserved.end(),
67                    CFGOnlyAnalyses.begin(), CFGOnlyAnalyses.end());
68 }
69
70
71 //===----------------------------------------------------------------------===//
72 // PassManager implementation - The PassManager class is a simple Pimpl class
73 // that wraps the PassManagerT template.
74 //
75 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
76 PassManager::~PassManager() { delete PM; }
77 void PassManager::add(Pass *P) { PM->add(P); }
78 bool PassManager::run(Module *M) { return PM->run(M); }
79
80
81 //===----------------------------------------------------------------------===//
82 // TimingInfo Class - This class is used to calculate information about the
83 // amount of time each pass takes to execute.  This only happens with
84 // -time-passes is enabled on the command line.
85 //
86 static cl::Flag EnableTiming("time-passes", "Time each pass, printing elapsed"
87                              " time for each on exit");
88
89 static double getTime() {
90   struct timeval T;
91   gettimeofday(&T, 0);
92   return T.tv_sec + T.tv_usec/1000000.0;
93 }
94
95 // Create method.  If Timing is enabled, this creates and returns a new timing
96 // object, otherwise it returns null.
97 //
98 TimingInfo *TimingInfo::create() {
99   return EnableTiming ? new TimingInfo() : 0;
100 }
101
102 void TimingInfo::passStarted(Pass *P) { TimingData[P] -= getTime(); }
103 void TimingInfo::passEnded(Pass *P) { TimingData[P] += getTime(); }
104
105 // TimingDtor - Print out information about timing information
106 TimingInfo::~TimingInfo() {
107   // Iterate over all of the data, converting it into the dual of the data map,
108   // so that the data is sorted by amount of time taken, instead of pointer.
109   //
110   std::vector<pair<double, Pass*> > Data;
111   double TotalTime = 0;
112   for (std::map<Pass*, double>::iterator I = TimingData.begin(),
113          E = TimingData.end(); I != E; ++I)
114     // Throw out results for "grouping" pass managers...
115     if (!dynamic_cast<AnalysisResolver*>(I->first)) {
116       Data.push_back(std::make_pair(I->second, I->first));
117       TotalTime += I->second;
118     }
119   
120   // Sort the data by time as the primary key, in reverse order...
121   std::sort(Data.begin(), Data.end(), greater<pair<double, Pass*> >());
122
123   // Print out timing header...
124   cerr << std::string(79, '=') << "\n"
125        << "                      ... Pass execution timing report ...\n"
126        << std::string(79, '=') << "\n  Total Execution Time: " << TotalTime
127        << " seconds\n\n  % Time: Seconds:\tPass Name:\n";
128
129   // Loop through all of the timing data, printing it out...
130   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
131     fprintf(stderr, "  %6.2f%% %fs\t%s\n", Data[i].first*100 / TotalTime,
132             Data[i].first, Data[i].second->getPassName());
133   }
134   cerr << "  100.00% " << TotalTime << "s\tTOTAL\n"
135        << std::string(79, '=') << "\n";
136 }
137
138
139 //===----------------------------------------------------------------------===//
140 // Pass debugging information.  Often it is useful to find out what pass is
141 // running when a crash occurs in a utility.  When this library is compiled with
142 // debugging on, a command line option (--debug-pass) is enabled that causes the
143 // pass name to be printed before it executes.
144 //
145
146 // Different debug levels that can be enabled...
147 enum PassDebugLevel {
148   None, PassStructure, PassExecutions, PassDetails
149 };
150
151 static cl::Enum<enum PassDebugLevel> PassDebugging("debug-pass", cl::Hidden,
152   "Print PassManager debugging information",
153   clEnumVal(None          , "disable debug output"),
154   clEnumVal(PassStructure , "print pass structure before run()"),
155   clEnumVal(PassExecutions, "print pass name before it is executed"),
156   clEnumVal(PassDetails   , "print pass details when it is executed"), 0); 
157
158 void PMDebug::PrintPassStructure(Pass *P) {
159   if (PassDebugging >= PassStructure)
160     P->dumpPassStructure();
161 }
162
163 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
164                                    Pass *P, Annotable *V) {
165   if (PassDebugging >= PassExecutions) {
166     std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '" 
167               << P->getPassName();
168     if (V) {
169       std::cerr << "' on ";
170
171       if (dynamic_cast<Module*>(V)) {
172         std::cerr << "Module\n"; return;
173       } else if (Function *F = dynamic_cast<Function*>(V))
174         std::cerr << "Function '" << F->getName();
175       else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
176         std::cerr << "BasicBlock '" << BB->getName();
177       else if (Value *Val = dynamic_cast<Value*>(V))
178         std::cerr << typeid(*Val).name() << " '" << Val->getName();
179     }
180     std::cerr << "'...\n";
181   }
182 }
183
184 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
185                                    Pass *P, const std::vector<AnalysisID> &Set){
186   if (PassDebugging >= PassDetails && !Set.empty()) {
187     std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
188     for (unsigned i = 0; i != Set.size(); ++i) {
189       Pass *P = Set[i].createPass();   // Good thing this is just debug code...
190       std::cerr << "  " << P->getPassName();
191       delete P;
192     }
193     std::cerr << "\n";
194   }
195 }
196
197 // dumpPassStructure - Implement the -debug-passes=PassStructure option
198 void Pass::dumpPassStructure(unsigned Offset = 0) {
199   std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
200 }
201
202
203 //===----------------------------------------------------------------------===//
204 // Pass Implementation
205 //
206
207 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
208   PM->addPass(this, AU);
209 }
210
211
212 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
213 //
214 const char *Pass::getPassName() const { return typeid(*this).name(); }
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 = false;
261   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
262     Changed |= runOnBasicBlock(*I);
263   return Changed;
264 }
265
266 // To run directly on the basic block, we initialize, runOnBasicBlock, then
267 // finalize.
268 //
269 bool BasicBlockPass::run(BasicBlock *BB) {
270   Module *M = BB->getParent()->getParent();
271   return doInitialization(M) | runOnBasicBlock(BB) | doFinalization(M);
272 }
273
274 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
275                                       AnalysisUsage &AU) {
276   PM->addPass(this, AU);
277 }
278
279 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
280                                       AnalysisUsage &AU) {
281   PM->addPass(this, AU);
282 }
283