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