0c6ff19f9ff5e3ffed47ca887604a7213e67ae2e
[oota-llvm.git] / include / llvm / PassManagers.h
1 //===- llvm/PassManager.h - Pass Inftrastructre classes  --------*- C++ -*-===//
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 declares the LLVM Pass Manager infrastructure. 
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/PassManager.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include <deque>
17 #include <map>
18
19 //===----------------------------------------------------------------------===//
20 // Overview:
21 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
22 // 
23 //   o Manage optimization pass execution order
24 //   o Make required Analysis information available before pass P is run
25 //   o Release memory occupied by dead passes
26 //   o If Analysis information is dirtied by a pass then regenerate Analysis 
27 //     information before it is consumed by another pass.
28 //
29 // Pass Manager Infrastructure uses multiple pass managers.  They are
30 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
31 // This class hierarcy uses multiple inheritance but pass managers do not derive
32 // from another pass manager.
33 //
34 // PassManager and FunctionPassManager are two top-level pass manager that
35 // represents the external interface of this entire pass manager infrastucture.
36 //
37 // Important classes :
38 //
39 // [o] class PMTopLevelManager;
40 //
41 // Two top level managers, PassManager and FunctionPassManager, derive from 
42 // PMTopLevelManager. PMTopLevelManager manages information used by top level 
43 // managers such as last user info.
44 //
45 // [o] class PMDataManager;
46 //
47 // PMDataManager manages information, e.g. list of available analysis info, 
48 // used by a pass manager to manage execution order of passes. It also provides
49 // a place to implement common pass manager APIs. All pass managers derive from
50 // PMDataManager.
51 //
52 // [o] class BBPassManager : public FunctionPass, public PMDataManager;
53 //
54 // BBPassManager manages BasicBlockPasses.
55 //
56 // [o] class FunctionPassManager;
57 //
58 // This is a external interface used by JIT to manage FunctionPasses. This
59 // interface relies on FunctionPassManagerImpl to do all the tasks.
60 //
61 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
62 //                                     public PMTopLevelManager;
63 //
64 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
65 //
66 // [o] class FPPassManager : public ModulePass, public PMDataManager;
67 //
68 // FPPassManager manages FunctionPasses and BBPassManagers
69 //
70 // [o] class MPPassManager : public Pass, public PMDataManager;
71 //
72 // MPPassManager manages ModulePasses and FPPassManagers
73 //
74 // [o] class PassManager;
75 //
76 // This is a external interface used by various tools to manages passes. It
77 // relies on PassManagerImpl to do all the tasks.
78 //
79 // [o] class PassManagerImpl : public Pass, public PMDataManager,
80 //                             public PMDTopLevelManager
81 //
82 // PassManagerImpl is a top level pass manager responsible for managing
83 // MPPassManagers.
84 //===----------------------------------------------------------------------===//
85
86 #ifndef PASSMANAGERS_H
87 #define PASSMANAGERS_H
88
89 namespace llvm {
90
91 /// FunctionPassManager and PassManager, two top level managers, serve 
92 /// as the public interface of pass manager infrastructure.
93 enum TopLevelManagerType {
94   TLM_Function,  // FunctionPassManager
95   TLM_Pass       // PassManager
96 };
97     
98 // enums for debugging strings
99 enum PassDebuggingString {
100   EXECUTION_MSG, // "Executing Pass '"
101   MODIFICATION_MSG, // "' Made Modification '"
102   FREEING_MSG, // " Freeing Pass '"
103   ON_BASICBLOCK_MSG, // "'  on BasicBlock '" + PassName + "'...\n"
104   ON_FUNCTION_MSG, // "' on Function '" + FunctionName + "'...\n"
105   ON_MODULE_MSG, // "' on Module '" + ModuleName + "'...\n"
106   ON_LOOP_MSG, // " 'on Loop ...\n'"
107   ON_CG_MSG // "' on Call Graph ...\n'"
108 };  
109
110 //===----------------------------------------------------------------------===//
111 // PMStack
112 //
113 /// PMStack
114 /// Top level pass managers (see PassManager.cpp) maintain active Pass Managers 
115 /// using PMStack. Each Pass implements assignPassManager() to connect itself
116 /// with appropriate manager. assignPassManager() walks PMStack to find
117 /// suitable manager.
118 ///
119 /// PMStack is just a wrapper around standard deque that overrides pop() and
120 /// push() methods.
121 class PMStack {
122 public:
123   typedef std::deque<PMDataManager *>::reverse_iterator iterator;
124   iterator begin() { return S.rbegin(); }
125   iterator end() { return S.rend(); }
126
127   void handleLastUserOverflow();
128
129   void pop();
130   inline PMDataManager *top() { return S.back(); }
131   void push(PMDataManager *PM);
132   inline bool empty() { return S.empty(); }
133
134   void dump();
135 private:
136   std::deque<PMDataManager *> S;
137 };
138
139
140 //===----------------------------------------------------------------------===//
141 // PMTopLevelManager
142 //
143 /// PMTopLevelManager manages LastUser info and collects common APIs used by
144 /// top level pass managers.
145 class PMTopLevelManager {
146 public:
147
148   virtual unsigned getNumContainedManagers() const {
149     return (unsigned)PassManagers.size();
150   }
151
152   /// Schedule pass P for execution. Make sure that passes required by
153   /// P are run before P is run. Update analysis info maintained by
154   /// the manager. Remove dead passes. This is a recursive function.
155   void schedulePass(Pass *P);
156
157   /// This is implemented by top level pass manager and used by 
158   /// schedulePass() to add analysis info passes that are not available.
159   virtual void addTopLevelPass(Pass  *P) = 0;
160
161   /// Set pass P as the last user of the given analysis passes.
162   void setLastUser(SmallVector<Pass *, 12> &AnalysisPasses, Pass *P);
163
164   /// Collect passes whose last user is P
165   void collectLastUses(SmallVector<Pass *, 12> &LastUses, Pass *P);
166
167   /// Find the pass that implements Analysis AID. Search immutable
168   /// passes and all pass managers. If desired pass is not found
169   /// then return NULL.
170   Pass *findAnalysisPass(AnalysisID AID);
171
172   explicit PMTopLevelManager(enum TopLevelManagerType t);
173   virtual ~PMTopLevelManager(); 
174
175   /// Add immutable pass and initialize it.
176   inline void addImmutablePass(ImmutablePass *P) {
177     P->initializePass();
178     ImmutablePasses.push_back(P);
179   }
180
181   inline std::vector<ImmutablePass *>& getImmutablePasses() {
182     return ImmutablePasses;
183   }
184
185   void addPassManager(PMDataManager *Manager) {
186     PassManagers.push_back(Manager);
187   }
188
189   // Add Manager into the list of managers that are not directly
190   // maintained by this top level pass manager
191   inline void addIndirectPassManager(PMDataManager *Manager) {
192     IndirectPassManagers.push_back(Manager);
193   }
194
195   // Print passes managed by this top level manager.
196   void dumpPasses() const;
197   void dumpArguments() const;
198
199   void initializeAllAnalysisInfo();
200
201   // Active Pass Managers
202   PMStack activeStack;
203
204 protected:
205   
206   /// Collection of pass managers
207   std::vector<PMDataManager *> PassManagers;
208
209 private:
210
211   /// Collection of pass managers that are not directly maintained
212   /// by this pass manager
213   std::vector<PMDataManager *> IndirectPassManagers;
214
215   // Map to keep track of last user of the analysis pass.
216   // LastUser->second is the last user of Lastuser->first.
217   std::map<Pass *, Pass *> LastUser;
218
219   /// Immutable passes are managed by top level manager.
220   std::vector<ImmutablePass *> ImmutablePasses;
221 };
222
223
224   
225 //===----------------------------------------------------------------------===//
226 // PMDataManager
227
228 /// PMDataManager provides the common place to manage the analysis data
229 /// used by pass managers.
230 class PMDataManager {
231 public:
232
233   explicit PMDataManager(int Depth) : TPM(NULL), Depth(Depth) {
234     initializeAnalysisInfo();
235   }
236
237   virtual ~PMDataManager();
238
239   /// Augment AvailableAnalysis by adding analysis made available by pass P.
240   void recordAvailableAnalysis(Pass *P);
241
242   /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
243   void verifyPreservedAnalysis(Pass *P);
244
245   /// Remove Analysis that is not preserved by the pass
246   void removeNotPreservedAnalysis(Pass *P);
247   
248   /// Remove dead passes
249   void removeDeadPasses(Pass *P, const char *Msg, enum PassDebuggingString);
250
251   /// Add pass P into the PassVector. Update 
252   /// AvailableAnalysis appropriately if ProcessAnalysis is true.
253   void add(Pass *P, bool ProcessAnalysis = true);
254
255   /// Add RequiredPass into list of lower level passes required by pass P.
256   /// RequiredPass is run on the fly by Pass Manager when P requests it
257   /// through getAnalysis interface.
258   virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
259
260   virtual Pass * getOnTheFlyPass(Pass *P, const PassInfo *PI, Function &F) {
261     assert (0 && "Unable to find on the fly pass");
262     return NULL;
263   }
264
265   /// Initialize available analysis information.
266   void initializeAnalysisInfo() { 
267     AvailableAnalysis.clear();
268     for (unsigned i = 0; i < PMT_Last; ++i)
269       InheritedAnalysis[i] = NULL;
270   }
271
272   // Return true if P preserves high level analysis used by other
273   // passes that are managed by this manager.
274   bool preserveHigherLevelAnalysis(Pass *P);
275
276
277   /// Populate RequiredPasses with analysis pass that are required by
278   /// pass P and are available. Populate ReqPassNotAvailable with analysis
279   /// pass that are required by pass P but are not available.
280   void collectRequiredAnalysis(SmallVector<Pass *, 8> &RequiredPasses,
281                                SmallVector<AnalysisID, 8> &ReqPassNotAvailable,
282                                Pass *P);
283
284   /// All Required analyses should be available to the pass as it runs!  Here
285   /// we fill in the AnalysisImpls member of the pass so that it can
286   /// successfully use the getAnalysis() method to retrieve the
287   /// implementations it needs.
288   void initializeAnalysisImpl(Pass *P);
289
290   /// Find the pass that implements Analysis AID. If desired pass is not found
291   /// then return NULL.
292   Pass *findAnalysisPass(AnalysisID AID, bool Direction);
293
294   // Access toplevel manager
295   PMTopLevelManager *getTopLevelManager() { return TPM; }
296   void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
297
298   unsigned getDepth() const { return Depth; }
299
300   // Print routines used by debug-pass
301   void dumpLastUses(Pass *P, unsigned Offset) const;
302   void dumpPassArguments() const;
303   void dumpPassInfo(Pass *P, enum PassDebuggingString S1,
304                     enum PassDebuggingString S2, const char *Msg);
305   void dumpAnalysisSetInfo(const char *Msg, Pass *P,
306                            const std::vector<AnalysisID> &Set) const;
307
308   virtual unsigned getNumContainedPasses() const {
309     return (unsigned)PassVector.size();
310   }
311
312   virtual PassManagerType getPassManagerType() const { 
313     assert ( 0 && "Invalid use of getPassManagerType");
314     return PMT_Unknown; 
315   }
316
317   std::map<AnalysisID, Pass*> *getAvailableAnalysis() {
318     return &AvailableAnalysis;
319   }
320
321   // Collect AvailableAnalysis from all the active Pass Managers.
322   void populateInheritedAnalysis(PMStack &PMS) {
323     unsigned Index = 0;
324     for (PMStack::iterator I = PMS.begin(), E = PMS.end();
325          I != E; ++I)
326       InheritedAnalysis[Index++] = (*I)->getAvailableAnalysis();
327   }
328
329 protected:
330
331   // Top level manager.
332   PMTopLevelManager *TPM;
333
334   // Collection of pass that are managed by this manager
335   std::vector<Pass *> PassVector;
336
337   // Collection of Analysis provided by Parent pass manager and
338   // used by current pass manager. At at time there can not be more
339   // then PMT_Last active pass mangers.
340   std::map<AnalysisID, Pass *> *InheritedAnalysis[PMT_Last];
341
342 private:
343   // Set of available Analysis. This information is used while scheduling 
344   // pass. If a pass requires an analysis which is not not available then 
345   // equired analysis pass is scheduled to run before the pass itself is 
346   // scheduled to run.
347   std::map<AnalysisID, Pass*> AvailableAnalysis;
348
349   // Collection of higher level analysis used by the pass managed by
350   // this manager.
351   std::vector<Pass *> HigherLevelAnalysis;
352
353   unsigned Depth;
354 };
355
356 //===----------------------------------------------------------------------===//
357 // FPPassManager
358 //
359 /// FPPassManager manages BBPassManagers and FunctionPasses.
360 /// It batches all function passes and basic block pass managers together and 
361 /// sequence them to process one function at a time before processing next 
362 /// function.
363
364 class FPPassManager : public ModulePass, public PMDataManager {
365  
366 public:
367   static char ID;
368   explicit FPPassManager(int Depth) 
369   : ModulePass(intptr_t(&ID)), PMDataManager(Depth) { }
370   
371   /// run - Execute all of the passes scheduled for execution.  Keep track of
372   /// whether any of the passes modifies the module, and if so, return true.
373   bool runOnFunction(Function &F);
374   bool runOnModule(Module &M);
375
376   /// doInitialization - Run all of the initializers for the function passes.
377   ///
378   bool doInitialization(Module &M);
379   
380   /// doFinalization - Run all of the finalizers for the function passes.
381   ///
382   bool doFinalization(Module &M);
383
384   /// Pass Manager itself does not invalidate any analysis info.
385   void getAnalysisUsage(AnalysisUsage &Info) const {
386     Info.setPreservesAll();
387   }
388
389   // Print passes managed by this manager
390   void dumpPassStructure(unsigned Offset);
391
392   virtual const char *getPassName() const {
393     return "Function Pass Manager";
394   }
395
396   FunctionPass *getContainedPass(unsigned N) {
397     assert ( N < PassVector.size() && "Pass number out of range!");
398     FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
399     return FP;
400   }
401
402   virtual PassManagerType getPassManagerType() const { 
403     return PMT_FunctionPassManager; 
404   }
405 };
406
407 }
408
409 extern void StartPassTimer(llvm::Pass *);
410 extern void StopPassTimer(llvm::Pass *);
411
412 #endif
413