255be38cd6d4cd31c19f7bd031872b3c5d0f4798
[oota-llvm.git] / lib / VMCore / Pass.cpp
1 //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Pass.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/PassRegistry.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/Assembly/PrintModulePass.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/PassNameParser.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/System/Atomic.h"
28 #include "llvm/System/Mutex.h"
29 #include "llvm/System/Threading.h"
30 #include <algorithm>
31 #include <map>
32 #include <set>
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 // Pass Implementation
37 //
38
39 Pass::Pass(PassKind K, intptr_t pid) : Resolver(0), PassID(pid), Kind(K) {
40   assert(pid && "pid cannot be 0");
41 }
42
43 Pass::Pass(PassKind K, const void *pid)
44   : Resolver(0), PassID((intptr_t)pid), Kind(K) {
45   assert(pid && "pid cannot be 0");
46 }
47
48 // Force out-of-line virtual method.
49 Pass::~Pass() { 
50   delete Resolver; 
51 }
52
53 // Force out-of-line virtual method.
54 ModulePass::~ModulePass() { }
55
56 Pass *ModulePass::createPrinterPass(raw_ostream &O,
57                                     const std::string &Banner) const {
58   return createPrintModulePass(&O, false, Banner);
59 }
60
61 PassManagerType ModulePass::getPotentialPassManagerType() const {
62   return PMT_ModulePassManager;
63 }
64
65 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
66   return Resolver->getAnalysisIfAvailable(AnalysisID, true) != 0;
67 }
68
69 // dumpPassStructure - Implement the -debug-passes=Structure option
70 void Pass::dumpPassStructure(unsigned Offset) {
71   dbgs().indent(Offset*2) << getPassName() << "\n";
72 }
73
74 /// getPassName - Return a nice clean name for a pass.  This usually
75 /// implemented in terms of the name that is registered by one of the
76 /// Registration templates, but can be overloaded directly.
77 ///
78 const char *Pass::getPassName() const {
79   if (const PassInfo *PI = getPassInfo())
80     return PI->getPassName();
81   return "Unnamed pass: implement Pass::getPassName()";
82 }
83
84 void Pass::preparePassManager(PMStack &) {
85   // By default, don't do anything.
86 }
87
88 PassManagerType Pass::getPotentialPassManagerType() const {
89   // Default implementation.
90   return PMT_Unknown; 
91 }
92
93 void Pass::getAnalysisUsage(AnalysisUsage &) const {
94   // By default, no analysis results are used, all are invalidated.
95 }
96
97 void Pass::releaseMemory() {
98   // By default, don't do anything.
99 }
100
101 void Pass::verifyAnalysis() const {
102   // By default, don't do anything.
103 }
104
105 void *Pass::getAdjustedAnalysisPointer(const PassInfo *) {
106   return this;
107 }
108
109 ImmutablePass *Pass::getAsImmutablePass() {
110   return 0;
111 }
112
113 PMDataManager *Pass::getAsPMDataManager() {
114   return 0;
115 }
116
117 void Pass::setResolver(AnalysisResolver *AR) {
118   assert(!Resolver && "Resolver is already set");
119   Resolver = AR;
120 }
121
122 // print - Print out the internal state of the pass.  This is called by Analyze
123 // to print out the contents of an analysis.  Otherwise it is not necessary to
124 // implement this method.
125 //
126 void Pass::print(raw_ostream &O,const Module*) const {
127   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
128 }
129
130 // dump - call print(cerr);
131 void Pass::dump() const {
132   print(dbgs(), 0);
133 }
134
135 //===----------------------------------------------------------------------===//
136 // ImmutablePass Implementation
137 //
138 // Force out-of-line virtual method.
139 ImmutablePass::~ImmutablePass() { }
140
141 void ImmutablePass::initializePass() {
142   // By default, don't do anything.
143 }
144
145 //===----------------------------------------------------------------------===//
146 // FunctionPass Implementation
147 //
148
149 Pass *FunctionPass::createPrinterPass(raw_ostream &O,
150                                       const std::string &Banner) const {
151   return createPrintFunctionPass(Banner, &O);
152 }
153
154 // run - On a module, we run this pass by initializing, runOnFunction'ing once
155 // for every function in the module, then by finalizing.
156 //
157 bool FunctionPass::runOnModule(Module &M) {
158   bool Changed = doInitialization(M);
159
160   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
161     if (!I->isDeclaration())      // Passes are not run on external functions!
162     Changed |= runOnFunction(*I);
163
164   return Changed | doFinalization(M);
165 }
166
167 // run - On a function, we simply initialize, run the function, then finalize.
168 //
169 bool FunctionPass::run(Function &F) {
170   // Passes are not run on external functions!
171   if (F.isDeclaration()) return false;
172
173   bool Changed = doInitialization(*F.getParent());
174   Changed |= runOnFunction(F);
175   return Changed | doFinalization(*F.getParent());
176 }
177
178 bool FunctionPass::doInitialization(Module &) {
179   // By default, don't do anything.
180   return false;
181 }
182
183 bool FunctionPass::doFinalization(Module &) {
184   // By default, don't do anything.
185   return false;
186 }
187
188 PassManagerType FunctionPass::getPotentialPassManagerType() const {
189   return PMT_FunctionPassManager;
190 }
191
192 //===----------------------------------------------------------------------===//
193 // BasicBlockPass Implementation
194 //
195
196 Pass *BasicBlockPass::createPrinterPass(raw_ostream &O,
197                                         const std::string &Banner) const {
198   
199   llvm_unreachable("BasicBlockPass printing unsupported.");
200   return 0;
201 }
202
203 // To run this pass on a function, we simply call runOnBasicBlock once for each
204 // function.
205 //
206 bool BasicBlockPass::runOnFunction(Function &F) {
207   bool Changed = doInitialization(F);
208   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
209     Changed |= runOnBasicBlock(*I);
210   return Changed | doFinalization(F);
211 }
212
213 bool BasicBlockPass::doInitialization(Module &) {
214   // By default, don't do anything.
215   return false;
216 }
217
218 bool BasicBlockPass::doInitialization(Function &) {
219   // By default, don't do anything.
220   return false;
221 }
222
223 bool BasicBlockPass::doFinalization(Function &) {
224   // By default, don't do anything.
225   return false;
226 }
227
228 bool BasicBlockPass::doFinalization(Module &) {
229   // By default, don't do anything.
230   return false;
231 }
232
233 PassManagerType BasicBlockPass::getPotentialPassManagerType() const {
234   return PMT_BasicBlockPassManager; 
235 }
236
237 //===----------------------------------------------------------------------===//
238 // Pass Registration mechanism
239 //
240
241 static std::vector<PassRegistrationListener*> *Listeners = 0;
242 static sys::SmartMutex<true> ListenersLock;
243
244 // getPassInfo - Return the PassInfo data structure that corresponds to this
245 // pass...
246 const PassInfo *Pass::getPassInfo() const {
247   return lookupPassInfo(PassID);
248 }
249
250 const PassInfo *Pass::lookupPassInfo(intptr_t TI) {
251   return PassRegistry::getPassRegistry()->getPassInfo(TI);
252 }
253
254 const PassInfo *Pass::lookupPassInfo(StringRef Arg) {
255   return PassRegistry::getPassRegistry()->getPassInfo(Arg);
256 }
257
258 void PassInfo::registerPass() {
259   PassRegistry::getPassRegistry()->registerPass(*this);
260
261   // Notify any listeners.
262   sys::SmartScopedLock<true> Lock(ListenersLock);
263   if (Listeners)
264     for (std::vector<PassRegistrationListener*>::iterator
265            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
266       (*I)->passRegistered(this);
267 }
268
269 void PassInfo::unregisterPass() {
270   PassRegistry::getPassRegistry()->unregisterPass(*this);
271 }
272
273 Pass *PassInfo::createPass() const {
274   assert((!isAnalysisGroup() || NormalCtor) &&
275          "No default implementation found for analysis group!");
276   assert(NormalCtor &&
277          "Cannot call createPass on PassInfo without default ctor!");
278   return NormalCtor();
279 }
280
281 //===----------------------------------------------------------------------===//
282 //                  Analysis Group Implementation Code
283 //===----------------------------------------------------------------------===//
284
285 // RegisterAGBase implementation
286 //
287 RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID,
288                                intptr_t PassID, bool isDefault)
289   : PassInfo(Name, InterfaceID) {
290
291   PassInfo *InterfaceInfo =
292     const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID));
293   if (InterfaceInfo == 0) {
294     // First reference to Interface, register it now.
295     registerPass();
296     InterfaceInfo = this;
297   }
298   assert(isAnalysisGroup() &&
299          "Trying to join an analysis group that is a normal pass!");
300
301   if (PassID) {
302     const PassInfo *ImplementationInfo = Pass::lookupPassInfo(PassID);
303     assert(ImplementationInfo &&
304            "Must register pass before adding to AnalysisGroup!");
305
306     // Make sure we keep track of the fact that the implementation implements
307     // the interface.
308     PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
309     IIPI->addInterfaceImplemented(InterfaceInfo);
310     
311     PassRegistry::getPassRegistry()->registerAnalysisGroup(InterfaceInfo, IIPI, isDefault);
312   }
313 }
314
315
316 //===----------------------------------------------------------------------===//
317 // PassRegistrationListener implementation
318 //
319
320 // PassRegistrationListener ctor - Add the current object to the list of
321 // PassRegistrationListeners...
322 PassRegistrationListener::PassRegistrationListener() {
323   sys::SmartScopedLock<true> Lock(ListenersLock);
324   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
325   Listeners->push_back(this);
326 }
327
328 // dtor - Remove object from list of listeners...
329 PassRegistrationListener::~PassRegistrationListener() {
330   sys::SmartScopedLock<true> Lock(ListenersLock);
331   std::vector<PassRegistrationListener*>::iterator I =
332     std::find(Listeners->begin(), Listeners->end(), this);
333   assert(Listeners && I != Listeners->end() &&
334          "PassRegistrationListener not registered!");
335   Listeners->erase(I);
336
337   if (Listeners->empty()) {
338     delete Listeners;
339     Listeners = 0;
340   }
341 }
342
343 // enumeratePasses - Iterate over the registered passes, calling the
344 // passEnumerate callback on each PassInfo object.
345 //
346 void PassRegistrationListener::enumeratePasses() {
347   PassRegistry::getPassRegistry()->enumerateWith(this);
348 }
349
350 PassNameParser::~PassNameParser() {}
351
352 //===----------------------------------------------------------------------===//
353 //   AnalysisUsage Class Implementation
354 //
355
356 namespace {
357   struct GetCFGOnlyPasses : public PassRegistrationListener {
358     typedef AnalysisUsage::VectorType VectorType;
359     VectorType &CFGOnlyList;
360     GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {}
361     
362     void passEnumerate(const PassInfo *P) {
363       if (P->isCFGOnlyPass())
364         CFGOnlyList.push_back(P);
365     }
366   };
367 }
368
369 // setPreservesCFG - This function should be called to by the pass, iff they do
370 // not:
371 //
372 //  1. Add or remove basic blocks from the function
373 //  2. Modify terminator instructions in any way.
374 //
375 // This function annotates the AnalysisUsage info object to say that analyses
376 // that only depend on the CFG are preserved by this pass.
377 //
378 void AnalysisUsage::setPreservesCFG() {
379   // Since this transformation doesn't modify the CFG, it preserves all analyses
380   // that only depend on the CFG (like dominators, loop info, etc...)
381   GetCFGOnlyPasses(Preserved).enumeratePasses();
382 }
383
384 AnalysisUsage &AnalysisUsage::addRequiredID(AnalysisID ID) {
385   assert(ID && "Pass class not registered!");
386   Required.push_back(ID);
387   return *this;
388 }
389
390 AnalysisUsage &AnalysisUsage::addRequiredTransitiveID(AnalysisID ID) {
391   assert(ID && "Pass class not registered!");
392   Required.push_back(ID);
393   RequiredTransitive.push_back(ID);
394   return *this;
395 }