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