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