efd98af0f443ce4acfc56b53af0c5f3e0f4ff953
[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/Module.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/Assembly/PrintModulePass.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/PassNameParser.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/System/Atomic.h"
27 #include "llvm/System/Mutex.h"
28 #include "llvm/System/Threading.h"
29 #include <algorithm>
30 #include <map>
31 #include <set>
32 using namespace llvm;
33
34 //===----------------------------------------------------------------------===//
35 // Pass Implementation
36 //
37
38 Pass::Pass(PassKind K, intptr_t pid) : Resolver(0), PassID(pid), Kind(K) {
39   assert(pid && "pid cannot be 0");
40 }
41
42 Pass::Pass(PassKind K, const void *pid)
43   : Resolver(0), PassID((intptr_t)pid), Kind(K) {
44   assert(pid && "pid cannot be 0");
45 }
46
47 // Force out-of-line virtual method.
48 Pass::~Pass() { 
49   delete Resolver; 
50 }
51
52 // Force out-of-line virtual method.
53 ModulePass::~ModulePass() { }
54
55 Pass *ModulePass::createPrinterPass(raw_ostream &O,
56                                     const std::string &Banner) const {
57   return createPrintModulePass(&O, false, Banner);
58 }
59
60 PassManagerType ModulePass::getPotentialPassManagerType() const {
61   return PMT_ModulePassManager;
62 }
63
64 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
65   return Resolver->getAnalysisIfAvailable(AnalysisID, true) != 0;
66 }
67
68 // dumpPassStructure - Implement the -debug-passes=Structure option
69 void Pass::dumpPassStructure(unsigned Offset) {
70   dbgs().indent(Offset*2) << getPassName() << "\n";
71 }
72
73 /// getPassName - Return a nice clean name for a pass.  This usually
74 /// implemented in terms of the name that is registered by one of the
75 /// Registration templates, but can be overloaded directly.
76 ///
77 const char *Pass::getPassName() const {
78   if (const PassInfo *PI = getPassInfo())
79     return PI->getPassName();
80   return "Unnamed pass: implement Pass::getPassName()";
81 }
82
83 void Pass::preparePassManager(PMStack &) {
84   // By default, don't do anything.
85 }
86
87 PassManagerType Pass::getPotentialPassManagerType() const {
88   // Default implementation.
89   return PMT_Unknown; 
90 }
91
92 void Pass::getAnalysisUsage(AnalysisUsage &) const {
93   // By default, no analysis results are used, all are invalidated.
94 }
95
96 void Pass::releaseMemory() {
97   // By default, don't do anything.
98 }
99
100 void Pass::verifyAnalysis() const {
101   // By default, don't do anything.
102 }
103
104 void *Pass::getAdjustedAnalysisPointer(const PassInfo *) {
105   return this;
106 }
107
108 ImmutablePass *Pass::getAsImmutablePass() {
109   return 0;
110 }
111
112 PMDataManager *Pass::getAsPMDataManager() {
113   return 0;
114 }
115
116 void Pass::setResolver(AnalysisResolver *AR) {
117   assert(!Resolver && "Resolver is already set");
118   Resolver = AR;
119 }
120
121 // print - Print out the internal state of the pass.  This is called by Analyze
122 // to print out the contents of an analysis.  Otherwise it is not necessary to
123 // implement this method.
124 //
125 void Pass::print(raw_ostream &O,const Module*) const {
126   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
127 }
128
129 // dump - call print(cerr);
130 void Pass::dump() const {
131   print(dbgs(), 0);
132 }
133
134 //===----------------------------------------------------------------------===//
135 // ImmutablePass Implementation
136 //
137 // Force out-of-line virtual method.
138 ImmutablePass::~ImmutablePass() { }
139
140 void ImmutablePass::initializePass() {
141   // By default, don't do anything.
142 }
143
144 //===----------------------------------------------------------------------===//
145 // FunctionPass Implementation
146 //
147
148 Pass *FunctionPass::createPrinterPass(raw_ostream &O,
149                                       const std::string &Banner) const {
150   return createPrintFunctionPass(Banner, &O);
151 }
152
153 // run - On a module, we run this pass by initializing, runOnFunction'ing once
154 // for every function in the module, then by finalizing.
155 //
156 bool FunctionPass::runOnModule(Module &M) {
157   bool Changed = doInitialization(M);
158
159   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
160     if (!I->isDeclaration())      // Passes are not run on external functions!
161     Changed |= runOnFunction(*I);
162
163   return Changed | doFinalization(M);
164 }
165
166 // run - On a function, we simply initialize, run the function, then finalize.
167 //
168 bool FunctionPass::run(Function &F) {
169   // Passes are not run on external functions!
170   if (F.isDeclaration()) return false;
171
172   bool Changed = doInitialization(*F.getParent());
173   Changed |= runOnFunction(F);
174   return Changed | doFinalization(*F.getParent());
175 }
176
177 bool FunctionPass::doInitialization(Module &) {
178   // By default, don't do anything.
179   return false;
180 }
181
182 bool FunctionPass::doFinalization(Module &) {
183   // By default, don't do anything.
184   return false;
185 }
186
187 PassManagerType FunctionPass::getPotentialPassManagerType() const {
188   return PMT_FunctionPassManager;
189 }
190
191 //===----------------------------------------------------------------------===//
192 // BasicBlockPass Implementation
193 //
194
195 Pass *BasicBlockPass::createPrinterPass(raw_ostream &O,
196                                         const std::string &Banner) const {
197   
198   llvm_unreachable("BasicBlockPass printing unsupported.");
199   return 0;
200 }
201
202 // To run this pass on a function, we simply call runOnBasicBlock once for each
203 // function.
204 //
205 bool BasicBlockPass::runOnFunction(Function &F) {
206   bool Changed = doInitialization(F);
207   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
208     Changed |= runOnBasicBlock(*I);
209   return Changed | doFinalization(F);
210 }
211
212 bool BasicBlockPass::doInitialization(Module &) {
213   // By default, don't do anything.
214   return false;
215 }
216
217 bool BasicBlockPass::doInitialization(Function &) {
218   // By default, don't do anything.
219   return false;
220 }
221
222 bool BasicBlockPass::doFinalization(Function &) {
223   // By default, don't do anything.
224   return false;
225 }
226
227 bool BasicBlockPass::doFinalization(Module &) {
228   // By default, don't do anything.
229   return false;
230 }
231
232 PassManagerType BasicBlockPass::getPotentialPassManagerType() const {
233   return PMT_BasicBlockPassManager; 
234 }
235
236 //===----------------------------------------------------------------------===//
237 // Pass Registration mechanism
238 //
239 namespace {
240 class PassRegistrar {
241   /// Guards the contents of this class.
242   mutable sys::SmartMutex<true> Lock;
243
244   /// PassInfoMap - Keep track of the passinfo object for each registered llvm
245   /// pass.
246   typedef std::map<intptr_t, const PassInfo*> MapType;
247   MapType PassInfoMap;
248
249   typedef StringMap<const PassInfo*> StringMapType;
250   StringMapType PassInfoStringMap;
251   
252   /// AnalysisGroupInfo - Keep track of information for each analysis group.
253   struct AnalysisGroupInfo {
254     std::set<const PassInfo *> Implementations;
255   };
256   
257   /// AnalysisGroupInfoMap - Information for each analysis group.
258   std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap;
259
260 public:
261   
262   const PassInfo *GetPassInfo(intptr_t TI) const {
263     sys::SmartScopedLock<true> Guard(Lock);
264     MapType::const_iterator I = PassInfoMap.find(TI);
265     return I != PassInfoMap.end() ? I->second : 0;
266   }
267   
268   const PassInfo *GetPassInfo(StringRef Arg) const {
269     sys::SmartScopedLock<true> Guard(Lock);
270     StringMapType::const_iterator I = PassInfoStringMap.find(Arg);
271     return I != PassInfoStringMap.end() ? I->second : 0;
272   }
273   
274   void RegisterPass(const PassInfo &PI) {
275     sys::SmartScopedLock<true> Guard(Lock);
276     bool Inserted =
277       PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;
278     assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted;
279     PassInfoStringMap[PI.getPassArgument()] = &PI;
280   }
281   
282   void UnregisterPass(const PassInfo &PI) {
283     sys::SmartScopedLock<true> Guard(Lock);
284     MapType::iterator I = PassInfoMap.find(PI.getTypeInfo());
285     assert(I != PassInfoMap.end() && "Pass registered but not in map!");
286     
287     // Remove pass from the map.
288     PassInfoMap.erase(I);
289     PassInfoStringMap.erase(PI.getPassArgument());
290   }
291   
292   void EnumerateWith(PassRegistrationListener *L) {
293     sys::SmartScopedLock<true> Guard(Lock);
294     for (MapType::const_iterator I = PassInfoMap.begin(),
295          E = PassInfoMap.end(); I != E; ++I)
296       L->passEnumerate(I->second);
297   }
298   
299   
300   /// Analysis Group Mechanisms.
301   void RegisterAnalysisGroup(PassInfo *InterfaceInfo,
302                              const PassInfo *ImplementationInfo,
303                              bool isDefault) {
304     sys::SmartScopedLock<true> Guard(Lock);
305     AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];
306     assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
307            "Cannot add a pass to the same analysis group more than once!");
308     AGI.Implementations.insert(ImplementationInfo);
309     if (isDefault) {
310       assert(InterfaceInfo->getNormalCtor() == 0 &&
311              "Default implementation for analysis group already specified!");
312       assert(ImplementationInfo->getNormalCtor() &&
313            "Cannot specify pass as default if it does not have a default ctor");
314       InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
315     }
316   }
317 };
318 }
319
320 static std::vector<PassRegistrationListener*> *Listeners = 0;
321 static sys::SmartMutex<true> ListenersLock;
322
323 static PassRegistrar *PassRegistrarObj = 0;
324 static PassRegistrar *getPassRegistrar() {
325   // Use double-checked locking to safely initialize the registrar when
326   // we're running in multithreaded mode.
327   PassRegistrar* tmp = PassRegistrarObj;
328   if (llvm_is_multithreaded()) {
329     sys::MemoryFence();
330     if (!tmp) {
331       llvm_acquire_global_lock();
332       tmp = PassRegistrarObj;
333       if (!tmp) {
334         tmp = new PassRegistrar();
335         sys::MemoryFence();
336         PassRegistrarObj = tmp;
337       }
338       llvm_release_global_lock();
339     }
340   } else if (!tmp) {
341     PassRegistrarObj = new PassRegistrar();
342   }
343   
344   return PassRegistrarObj;
345 }
346
347 namespace {
348
349 // FIXME: We use ManagedCleanup to erase the pass registrar on shutdown.
350 // Unfortunately, passes are registered with static ctors, and having
351 // llvm_shutdown clear this map prevents successful ressurection after 
352 // llvm_shutdown is run.  Ideally we should find a solution so that we don't
353 // leak the map, AND can still resurrect after shutdown.
354 void cleanupPassRegistrar(void*) {
355   if (PassRegistrarObj) {
356     delete PassRegistrarObj;
357     PassRegistrarObj = 0;
358   }
359 }
360 ManagedCleanup<&cleanupPassRegistrar> registrarCleanup ATTRIBUTE_USED;
361
362 }
363
364 // getPassInfo - Return the PassInfo data structure that corresponds to this
365 // pass...
366 const PassInfo *Pass::getPassInfo() const {
367   return lookupPassInfo(PassID);
368 }
369
370 const PassInfo *Pass::lookupPassInfo(intptr_t TI) {
371   return getPassRegistrar()->GetPassInfo(TI);
372 }
373
374 const PassInfo *Pass::lookupPassInfo(StringRef Arg) {
375   return getPassRegistrar()->GetPassInfo(Arg);
376 }
377
378 void PassInfo::registerPass() {
379   getPassRegistrar()->RegisterPass(*this);
380
381   // Notify any listeners.
382   sys::SmartScopedLock<true> Lock(ListenersLock);
383   if (Listeners)
384     for (std::vector<PassRegistrationListener*>::iterator
385            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
386       (*I)->passRegistered(this);
387 }
388
389 void PassInfo::unregisterPass() {
390   getPassRegistrar()->UnregisterPass(*this);
391 }
392
393 Pass *PassInfo::createPass() const {
394   assert((!isAnalysisGroup() || NormalCtor) &&
395          "No default implementation found for analysis group!");
396   assert(NormalCtor &&
397          "Cannot call createPass on PassInfo without default ctor!");
398   return NormalCtor();
399 }
400
401 //===----------------------------------------------------------------------===//
402 //                  Analysis Group Implementation Code
403 //===----------------------------------------------------------------------===//
404
405 // RegisterAGBase implementation
406 //
407 RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID,
408                                intptr_t PassID, bool isDefault)
409   : PassInfo(Name, InterfaceID) {
410
411   PassInfo *InterfaceInfo =
412     const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID));
413   if (InterfaceInfo == 0) {
414     // First reference to Interface, register it now.
415     registerPass();
416     InterfaceInfo = this;
417   }
418   assert(isAnalysisGroup() &&
419          "Trying to join an analysis group that is a normal pass!");
420
421   if (PassID) {
422     const PassInfo *ImplementationInfo = Pass::lookupPassInfo(PassID);
423     assert(ImplementationInfo &&
424            "Must register pass before adding to AnalysisGroup!");
425
426     // Make sure we keep track of the fact that the implementation implements
427     // the interface.
428     PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
429     IIPI->addInterfaceImplemented(InterfaceInfo);
430     
431     getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
432   }
433 }
434
435
436 //===----------------------------------------------------------------------===//
437 // PassRegistrationListener implementation
438 //
439
440 // PassRegistrationListener ctor - Add the current object to the list of
441 // PassRegistrationListeners...
442 PassRegistrationListener::PassRegistrationListener() {
443   sys::SmartScopedLock<true> Lock(ListenersLock);
444   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
445   Listeners->push_back(this);
446 }
447
448 // dtor - Remove object from list of listeners...
449 PassRegistrationListener::~PassRegistrationListener() {
450   sys::SmartScopedLock<true> Lock(ListenersLock);
451   std::vector<PassRegistrationListener*>::iterator I =
452     std::find(Listeners->begin(), Listeners->end(), this);
453   assert(Listeners && I != Listeners->end() &&
454          "PassRegistrationListener not registered!");
455   Listeners->erase(I);
456
457   if (Listeners->empty()) {
458     delete Listeners;
459     Listeners = 0;
460   }
461 }
462
463 // enumeratePasses - Iterate over the registered passes, calling the
464 // passEnumerate callback on each PassInfo object.
465 //
466 void PassRegistrationListener::enumeratePasses() {
467   getPassRegistrar()->EnumerateWith(this);
468 }
469
470 PassNameParser::~PassNameParser() {}
471
472 //===----------------------------------------------------------------------===//
473 //   AnalysisUsage Class Implementation
474 //
475
476 namespace {
477   struct GetCFGOnlyPasses : public PassRegistrationListener {
478     typedef AnalysisUsage::VectorType VectorType;
479     VectorType &CFGOnlyList;
480     GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {}
481     
482     void passEnumerate(const PassInfo *P) {
483       if (P->isCFGOnlyPass())
484         CFGOnlyList.push_back(P);
485     }
486   };
487 }
488
489 // setPreservesCFG - This function should be called to by the pass, iff they do
490 // not:
491 //
492 //  1. Add or remove basic blocks from the function
493 //  2. Modify terminator instructions in any way.
494 //
495 // This function annotates the AnalysisUsage info object to say that analyses
496 // that only depend on the CFG are preserved by this pass.
497 //
498 void AnalysisUsage::setPreservesCFG() {
499   // Since this transformation doesn't modify the CFG, it preserves all analyses
500   // that only depend on the CFG (like dominators, loop info, etc...)
501   GetCFGOnlyPasses(Preserved).enumeratePasses();
502 }
503
504 AnalysisUsage &AnalysisUsage::addRequiredID(AnalysisID ID) {
505   assert(ID && "Pass class not registered!");
506   Required.push_back(ID);
507   return *this;
508 }
509
510 AnalysisUsage &AnalysisUsage::addRequiredTransitiveID(AnalysisID ID) {
511   assert(ID && "Pass class not registered!");
512   Required.push_back(ID);
513   RequiredTransitive.push_back(ID);
514   return *this;
515 }