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