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