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