llvm.org GIT mirror llvm / 49837ef
Move the old pass manager infrastructure into a legacy namespace and give the files a legacy prefix in the right directory. Use forwarding headers in the old locations to paper over the name change for most clients during the transitional period. No functionality changed here! This is just clearing some space to reduce renaming churn later on with a new system. Even when the new stuff starts to go in, it is going to be hidden behind a flag and off-by-default as it is still WIP and under development. This patch is specifically designed so that very little out-of-tree code has to change. I'm going to work as hard as I can to keep that the case. Only direct forward declarations of the PassManager class are impacted by this change. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@194324 91177308-0d34-0410-b5e6-96231b3b80d8 Chandler Carruth 6 years ago
16 changed file(s) with 3106 addition(s) and 3032 deletion(s). Raw diff Collapse all Expand all
1515 #define LLVM_ANALYSIS_LOOPPASS_H
1616
1717 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/IR/LegacyPassManagers.h"
1819 #include "llvm/Pass.h"
19 #include "llvm/PassManagers.h"
2020 #include
2121
2222 namespace llvm {
1717
1818 #include "llvm/Analysis/RegionInfo.h"
1919 #include "llvm/IR/Function.h"
20 #include "llvm/IR/LegacyPassManagers.h"
2021 #include "llvm/Pass.h"
21 #include "llvm/PassManagers.h"
2222 #include
2323
2424 namespace llvm {
2424 class MachineFunctionPass;
2525 class PassConfigImpl;
2626 class PassInfo;
27 class PassManagerBase;
2827 class ScheduleDAGInstrs;
2928 class TargetLowering;
3029 class TargetLoweringBase;
3130 class TargetRegisterClass;
3231 class raw_ostream;
3332 struct MachineSchedContext;
33
34 // The old pass manager infrastructure is hidden in a legacy namespace now.
35 namespace legacy {
36 class PassManagerBase;
37 }
38 using legacy::PassManagerBase;
3439
3540 /// Discriminated union of Pass ID types.
3641 ///
0 //===- LegacyPassManager.h - Legacy Container for Passes --------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the legacy PassManager class. This class is used to hold,
10 // maintain, and optimize execution of Passes. The PassManager class ensures
11 // that analysis results are available before a pass runs, and that Pass's are
12 // destroyed when the PassManager is destroyed.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_IR_LEGACYPASSMANAGER_H
17 #define LLVM_IR_LEGACYPASSMANAGER_H
18
19 #include "llvm/Pass.h"
20 #include "llvm/Support/CBindingWrapping.h"
21
22 namespace llvm {
23
24 class Pass;
25 class Module;
26
27 namespace legacy {
28
29 class PassManagerImpl;
30 class FunctionPassManagerImpl;
31
32 /// PassManagerBase - An abstract interface to allow code to add passes to
33 /// a pass manager without having to hard-code what kind of pass manager
34 /// it is.
35 class PassManagerBase {
36 public:
37 virtual ~PassManagerBase();
38
39 /// add - Add a pass to the queue of passes to run. This passes ownership of
40 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
41 /// will be destroyed as well, so there is no need to delete the pass. This
42 /// implies that all passes MUST be allocated with 'new'.
43 virtual void add(Pass *P) = 0;
44 };
45
46 /// PassManager manages ModulePassManagers
47 class PassManager : public PassManagerBase {
48 public:
49
50 PassManager();
51 ~PassManager();
52
53 /// add - Add a pass to the queue of passes to run. This passes ownership of
54 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
55 /// will be destroyed as well, so there is no need to delete the pass. This
56 /// implies that all passes MUST be allocated with 'new'.
57 void add(Pass *P);
58
59 /// run - Execute all of the passes scheduled for execution. Keep track of
60 /// whether any of the passes modifies the module, and if so, return true.
61 bool run(Module &M);
62
63 private:
64 /// PassManagerImpl_New is the actual class. PassManager is just the
65 /// wraper to publish simple pass manager interface
66 PassManagerImpl *PM;
67 };
68
69 /// FunctionPassManager manages FunctionPasses and BasicBlockPassManagers.
70 class FunctionPassManager : public PassManagerBase {
71 public:
72 /// FunctionPassManager ctor - This initializes the pass manager. It needs,
73 /// but does not take ownership of, the specified Module.
74 explicit FunctionPassManager(Module *M);
75 ~FunctionPassManager();
76
77 /// add - Add a pass to the queue of passes to run. This passes
78 /// ownership of the Pass to the PassManager. When the
79 /// PassManager_X is destroyed, the pass will be destroyed as well, so
80 /// there is no need to delete the pass.
81 /// This implies that all passes MUST be allocated with 'new'.
82 void add(Pass *P);
83
84 /// run - Execute all of the passes scheduled for execution. Keep
85 /// track of whether any of the passes modifies the function, and if
86 /// so, return true.
87 ///
88 bool run(Function &F);
89
90 /// doInitialization - Run all of the initializers for the function passes.
91 ///
92 bool doInitialization();
93
94 /// doFinalization - Run all of the finalizers for the function passes.
95 ///
96 bool doFinalization();
97
98 private:
99 FunctionPassManagerImpl *FPM;
100 Module *M;
101 };
102
103 } // End legacy namespace
104
105 // Create wrappers for C Binding types (see CBindingWrapping.h).
106 DEFINE_STDCXX_CONVERSION_FUNCTIONS(legacy::PassManagerBase, LLVMPassManagerRef)
107
108 } // End llvm namespace
109
110 #endif
0 //===- LegacyPassManagers.h - Legacy Pass Infrastructure --------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the LLVM Pass Manager infrastructure.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_PASSMANAGERS_H
14 #define LLVM_PASSMANAGERS_H
15
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Pass.h"
21 #include
22 #include
23
24 //===----------------------------------------------------------------------===//
25 // Overview:
26 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
27 //
28 // o Manage optimization pass execution order
29 // o Make required Analysis information available before pass P is run
30 // o Release memory occupied by dead passes
31 // o If Analysis information is dirtied by a pass then regenerate Analysis
32 // information before it is consumed by another pass.
33 //
34 // Pass Manager Infrastructure uses multiple pass managers. They are
35 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
36 // This class hierarchy uses multiple inheritance but pass managers do not
37 // derive from another pass manager.
38 //
39 // PassManager and FunctionPassManager are two top-level pass manager that
40 // represents the external interface of this entire pass manager infrastucture.
41 //
42 // Important classes :
43 //
44 // [o] class PMTopLevelManager;
45 //
46 // Two top level managers, PassManager and FunctionPassManager, derive from
47 // PMTopLevelManager. PMTopLevelManager manages information used by top level
48 // managers such as last user info.
49 //
50 // [o] class PMDataManager;
51 //
52 // PMDataManager manages information, e.g. list of available analysis info,
53 // used by a pass manager to manage execution order of passes. It also provides
54 // a place to implement common pass manager APIs. All pass managers derive from
55 // PMDataManager.
56 //
57 // [o] class BBPassManager : public FunctionPass, public PMDataManager;
58 //
59 // BBPassManager manages BasicBlockPasses.
60 //
61 // [o] class FunctionPassManager;
62 //
63 // This is a external interface used by JIT to manage FunctionPasses. This
64 // interface relies on FunctionPassManagerImpl to do all the tasks.
65 //
66 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
67 // public PMTopLevelManager;
68 //
69 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
70 //
71 // [o] class FPPassManager : public ModulePass, public PMDataManager;
72 //
73 // FPPassManager manages FunctionPasses and BBPassManagers
74 //
75 // [o] class MPPassManager : public Pass, public PMDataManager;
76 //
77 // MPPassManager manages ModulePasses and FPPassManagers
78 //
79 // [o] class PassManager;
80 //
81 // This is a external interface used by various tools to manages passes. It
82 // relies on PassManagerImpl to do all the tasks.
83 //
84 // [o] class PassManagerImpl : public Pass, public PMDataManager,
85 // public PMTopLevelManager
86 //
87 // PassManagerImpl is a top level pass manager responsible for managing
88 // MPPassManagers.
89 //===----------------------------------------------------------------------===//
90
91 #include "llvm/Support/PrettyStackTrace.h"
92
93 namespace llvm {
94 class Module;
95 class Pass;
96 class StringRef;
97 class Value;
98 class Timer;
99 class PMDataManager;
100
101 // enums for debugging strings
102 enum PassDebuggingString {
103 EXECUTION_MSG, // "Executing Pass '"
104 MODIFICATION_MSG, // "' Made Modification '"
105 FREEING_MSG, // " Freeing Pass '"
106 ON_BASICBLOCK_MSG, // "' on BasicBlock '" + PassName + "'...\n"
107 ON_FUNCTION_MSG, // "' on Function '" + FunctionName + "'...\n"
108 ON_MODULE_MSG, // "' on Module '" + ModuleName + "'...\n"
109 ON_REGION_MSG, // " 'on Region ...\n'"
110 ON_LOOP_MSG, // " 'on Loop ...\n'"
111 ON_CG_MSG // "' on Call Graph ...\n'"
112 };
113
114 /// PassManagerPrettyStackEntry - This is used to print informative information
115 /// about what pass is running when/if a stack trace is generated.
116 class PassManagerPrettyStackEntry : public PrettyStackTraceEntry {
117 Pass *P;
118 Value *V;
119 Module *M;
120 public:
121 explicit PassManagerPrettyStackEntry(Pass *p)
122 : P(p), V(0), M(0) {} // When P is releaseMemory'd.
123 PassManagerPrettyStackEntry(Pass *p, Value &v)
124 : P(p), V(&v), M(0) {} // When P is run on V
125 PassManagerPrettyStackEntry(Pass *p, Module &m)
126 : P(p), V(0), M(&m) {} // When P is run on M
127
128 /// print - Emit information about this stack frame to OS.
129 virtual void print(raw_ostream &OS) const;
130 };
131
132
133 //===----------------------------------------------------------------------===//
134 // PMStack
135 //
136 /// PMStack - This class implements a stack data structure of PMDataManager
137 /// pointers.
138 ///
139 /// Top level pass managers (see PassManager.cpp) maintain active Pass Managers
140 /// using PMStack. Each Pass implements assignPassManager() to connect itself
141 /// with appropriate manager. assignPassManager() walks PMStack to find
142 /// suitable manager.
143 class PMStack {
144 public:
145 typedef std::vector::const_reverse_iterator iterator;
146 iterator begin() const { return S.rbegin(); }
147 iterator end() const { return S.rend(); }
148
149 void pop();
150 PMDataManager *top() const { return S.back(); }
151 void push(PMDataManager *PM);
152 bool empty() const { return S.empty(); }
153
154 void dump() const;
155
156 private:
157 std::vector S;
158 };
159
160
161 //===----------------------------------------------------------------------===//
162 // PMTopLevelManager
163 //
164 /// PMTopLevelManager manages LastUser info and collects common APIs used by
165 /// top level pass managers.
166 class PMTopLevelManager {
167 protected:
168 explicit PMTopLevelManager(PMDataManager *PMDM);
169
170 unsigned getNumContainedManagers() const {
171 return (unsigned)PassManagers.size();
172 }
173
174 void initializeAllAnalysisInfo();
175
176 private:
177 virtual PMDataManager *getAsPMDataManager() = 0;
178 virtual PassManagerType getTopLevelPassManagerType() = 0;
179
180 public:
181 /// Schedule pass P for execution. Make sure that passes required by
182 /// P are run before P is run. Update analysis info maintained by
183 /// the manager. Remove dead passes. This is a recursive function.
184 void schedulePass(Pass *P);
185
186 /// Set pass P as the last user of the given analysis passes.
187 void setLastUser(ArrayRef AnalysisPasses, Pass *P);
188
189 /// Collect passes whose last user is P
190 void collectLastUses(SmallVectorImpl &LastUses, Pass *P);
191
192 /// Find the pass that implements Analysis AID. Search immutable
193 /// passes and all pass managers. If desired pass is not found
194 /// then return NULL.
195 Pass *findAnalysisPass(AnalysisID AID);
196
197 /// Find analysis usage information for the pass P.
198 AnalysisUsage *findAnalysisUsage(Pass *P);
199
200 virtual ~PMTopLevelManager();
201
202 /// Add immutable pass and initialize it.
203 inline void addImmutablePass(ImmutablePass *P) {
204 P->initializePass();
205 ImmutablePasses.push_back(P);
206 }
207
208 inline SmallVectorImpl& getImmutablePasses() {
209 return ImmutablePasses;
210 }
211
212 void addPassManager(PMDataManager *Manager) {
213 PassManagers.push_back(Manager);
214 }
215
216 // Add Manager into the list of managers that are not directly
217 // maintained by this top level pass manager
218 inline void addIndirectPassManager(PMDataManager *Manager) {
219 IndirectPassManagers.push_back(Manager);
220 }
221
222 // Print passes managed by this top level manager.
223 void dumpPasses() const;
224 void dumpArguments() const;
225
226 // Active Pass Managers
227 PMStack activeStack;
228
229 protected:
230
231 /// Collection of pass managers
232 SmallVector PassManagers;
233
234 private:
235
236 /// Collection of pass managers that are not directly maintained
237 /// by this pass manager
238 SmallVector IndirectPassManagers;
239
240 // Map to keep track of last user of the analysis pass.
241 // LastUser->second is the last user of Lastuser->first.
242 DenseMap LastUser;
243
244 // Map to keep track of passes that are last used by a pass.
245 // This inverse map is initialized at PM->run() based on
246 // LastUser map.
247 DenseMap > InversedLastUser;
248
249 /// Immutable passes are managed by top level manager.
250 SmallVector ImmutablePasses;
251
252 DenseMap AnUsageMap;
253 };
254
255
256
257 //===----------------------------------------------------------------------===//
258 // PMDataManager
259
260 /// PMDataManager provides the common place to manage the analysis data
261 /// used by pass managers.
262 class PMDataManager {
263 public:
264
265 explicit PMDataManager() : TPM(NULL), Depth(0) {
266 initializeAnalysisInfo();
267 }
268
269 virtual ~PMDataManager();
270
271 virtual Pass *getAsPass() = 0;
272
273 /// Augment AvailableAnalysis by adding analysis made available by pass P.
274 void recordAvailableAnalysis(Pass *P);
275
276 /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
277 void verifyPreservedAnalysis(Pass *P);
278
279 /// Remove Analysis that is not preserved by the pass
280 void removeNotPreservedAnalysis(Pass *P);
281
282 /// Remove dead passes used by P.
283 void removeDeadPasses(Pass *P, StringRef Msg,
284 enum PassDebuggingString);
285
286 /// Remove P.
287 void freePass(Pass *P, StringRef Msg,
288 enum PassDebuggingString);
289
290 /// Add pass P into the PassVector. Update
291 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
292 void add(Pass *P, bool ProcessAnalysis = true);
293
294 /// Add RequiredPass into list of lower level passes required by pass P.
295 /// RequiredPass is run on the fly by Pass Manager when P requests it
296 /// through getAnalysis interface.
297 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
298
299 virtual Pass *getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F);
300
301 /// Initialize available analysis information.
302 void initializeAnalysisInfo() {
303 AvailableAnalysis.clear();
304 for (unsigned i = 0; i < PMT_Last; ++i)
305 InheritedAnalysis[i] = NULL;
306 }
307
308 // Return true if P preserves high level analysis used by other
309 // passes that are managed by this manager.
310 bool preserveHigherLevelAnalysis(Pass *P);
311
312
313 /// Populate RequiredPasses with analysis pass that are required by
314 /// pass P and are available. Populate ReqPassNotAvailable with analysis
315 /// pass that are required by pass P but are not available.
316 void collectRequiredAnalysis(SmallVectorImpl &RequiredPasses,
317 SmallVectorImpl &ReqPassNotAvailable,
318 Pass *P);
319
320 /// All Required analyses should be available to the pass as it runs! Here
321 /// we fill in the AnalysisImpls member of the pass so that it can
322 /// successfully use the getAnalysis() method to retrieve the
323 /// implementations it needs.
324 void initializeAnalysisImpl(Pass *P);
325
326 /// Find the pass that implements Analysis AID. If desired pass is not found
327 /// then return NULL.
328 Pass *findAnalysisPass(AnalysisID AID, bool Direction);
329
330 // Access toplevel manager
331 PMTopLevelManager *getTopLevelManager() { return TPM; }
332 void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
333
334 unsigned getDepth() const { return Depth; }
335 void setDepth(unsigned newDepth) { Depth = newDepth; }
336
337 // Print routines used by debug-pass
338 void dumpLastUses(Pass *P, unsigned Offset) const;
339 void dumpPassArguments() const;
340 void dumpPassInfo(Pass *P, enum PassDebuggingString S1,
341 enum PassDebuggingString S2, StringRef Msg);
342 void dumpRequiredSet(const Pass *P) const;
343 void dumpPreservedSet(const Pass *P) const;
344
345 unsigned getNumContainedPasses() const {
346 return (unsigned)PassVector.size();
347 }
348
349 virtual PassManagerType getPassManagerType() const {
350 assert ( 0 && "Invalid use of getPassManagerType");
351 return PMT_Unknown;
352 }
353
354 DenseMap *getAvailableAnalysis() {
355 return &AvailableAnalysis;
356 }
357
358 // Collect AvailableAnalysis from all the active Pass Managers.
359 void populateInheritedAnalysis(PMStack &PMS) {
360 unsigned Index = 0;
361 for (PMStack::iterator I = PMS.begin(), E = PMS.end();
362 I != E; ++I)
363 InheritedAnalysis[Index++] = (*I)->getAvailableAnalysis();
364 }
365
366 protected:
367
368 // Top level manager.
369 PMTopLevelManager *TPM;
370
371 // Collection of pass that are managed by this manager
372 SmallVector PassVector;
373
374 // Collection of Analysis provided by Parent pass manager and
375 // used by current pass manager. At at time there can not be more
376 // then PMT_Last active pass mangers.
377 DenseMap *InheritedAnalysis[PMT_Last];
378
379 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
380 /// or higher is specified.
381 bool isPassDebuggingExecutionsOrMore() const;
382
383 private:
384 void dumpAnalysisUsage(StringRef Msg, const Pass *P,
385 const AnalysisUsage::VectorType &Set) const;
386
387 // Set of available Analysis. This information is used while scheduling
388 // pass. If a pass requires an analysis which is not available then
389 // the required analysis pass is scheduled to run before the pass itself is
390 // scheduled to run.
391 DenseMap AvailableAnalysis;
392
393 // Collection of higher level analysis used by the pass managed by
394 // this manager.
395 SmallVector HigherLevelAnalysis;
396
397 unsigned Depth;
398 };
399
400 //===----------------------------------------------------------------------===//
401 // FPPassManager
402 //
403 /// FPPassManager manages BBPassManagers and FunctionPasses.
404 /// It batches all function passes and basic block pass managers together and
405 /// sequence them to process one function at a time before processing next
406 /// function.
407 class FPPassManager : public ModulePass, public PMDataManager {
408 public:
409 static char ID;
410 explicit FPPassManager()
411 : ModulePass(ID), PMDataManager() { }
412
413 /// run - Execute all of the passes scheduled for execution. Keep track of
414 /// whether any of the passes modifies the module, and if so, return true.
415 bool runOnFunction(Function &F);
416 bool runOnModule(Module &M);
417
418 /// cleanup - After running all passes, clean up pass manager cache.
419 void cleanup();
420
421 /// doInitialization - Overrides ModulePass doInitialization for global
422 /// initialization tasks
423 ///
424 using ModulePass::doInitialization;
425
426 /// doInitialization - Run all of the initializers for the function passes.
427 ///
428 bool doInitialization(Module &M);
429
430 /// doFinalization - Overrides ModulePass doFinalization for global
431 /// finalization tasks
432 ///
433 using ModulePass::doFinalization;
434
435 /// doFinalization - Run all of the finalizers for the function passes.
436 ///
437 bool doFinalization(Module &M);
438
439 virtual PMDataManager *getAsPMDataManager() { return this; }
440 virtual Pass *getAsPass() { return this; }
441
442 /// Pass Manager itself does not invalidate any analysis info.
443 void getAnalysisUsage(AnalysisUsage &Info) const {
444 Info.setPreservesAll();
445 }
446
447 // Print passes managed by this manager
448 void dumpPassStructure(unsigned Offset);
449
450 virtual const char *getPassName() const {
451 return "Function Pass Manager";
452 }
453
454 FunctionPass *getContainedPass(unsigned N) {
455 assert ( N < PassVector.size() && "Pass number out of range!");
456 FunctionPass *FP = static_cast(PassVector[N]);
457 return FP;
458 }
459
460 virtual PassManagerType getPassManagerType() const {
461 return PMT_FunctionPassManager;
462 }
463 };
464
465 Timer *getPassTimer(Pass *);
466
467 }
468
469 #endif
66 //
77 //===----------------------------------------------------------------------===//
88 //
9 // This file defines the PassManager class. This class is used to hold,
10 // maintain, and optimize execution of Passes. The PassManager class ensures
11 // that analysis results are available before a pass runs, and that Pass's are
12 // destroyed when the PassManager is destroyed.
9 // This is a legacy redirect header for the old PassManager. It is intended to
10 // be used by clients that have not been converted to be aware of the new pass
11 // management infrastructure being built for LLVM, which is every client
12 // initially. Eventually this header (and the legacy management layer) will go
13 // away, but we want to minimize changes to out-of-tree users of LLVM in the
14 // interim.
15 //
16 // Note that this header *must not* be included into the same file as the new
17 // pass management infrastructure is included. Things will break spectacularly.
18 // If you are starting that conversion, you should switch to explicitly
19 // including LegacyPassManager.h and using the legacy namespace.
1320 //
1421 //===----------------------------------------------------------------------===//
1522
1623 #ifndef LLVM_PASSMANAGER_H
1724 #define LLVM_PASSMANAGER_H
1825
19 #include "llvm/Pass.h"
20 #include "llvm/Support/CBindingWrapping.h"
26 #include "llvm/IR/LegacyPassManager.h"
2127
2228 namespace llvm {
2329
24 class Pass;
25 class Module;
30 // Pull these into the llvm namespace so that existing code that expects it
31 // there can find it.
32 using legacy::PassManagerBase;
33 using legacy::PassManager;
34 using legacy::FunctionPassManager;
2635
27 class PassManagerImpl;
28 class FunctionPassManagerImpl;
29
30 /// PassManagerBase - An abstract interface to allow code to add passes to
31 /// a pass manager without having to hard-code what kind of pass manager
32 /// it is.
33 class PassManagerBase {
34 public:
35 virtual ~PassManagerBase();
36
37 /// add - Add a pass to the queue of passes to run. This passes ownership of
38 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
39 /// will be destroyed as well, so there is no need to delete the pass. This
40 /// implies that all passes MUST be allocated with 'new'.
41 virtual void add(Pass *P) = 0;
42 };
43
44 /// PassManager manages ModulePassManagers
45 class PassManager : public PassManagerBase {
46 public:
47
48 PassManager();
49 ~PassManager();
50
51 /// add - Add a pass to the queue of passes to run. This passes ownership of
52 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
53 /// will be destroyed as well, so there is no need to delete the pass. This
54 /// implies that all passes MUST be allocated with 'new'.
55 void add(Pass *P);
56
57 /// run - Execute all of the passes scheduled for execution. Keep track of
58 /// whether any of the passes modifies the module, and if so, return true.
59 bool run(Module &M);
60
61 private:
62 /// PassManagerImpl_New is the actual class. PassManager is just the
63 /// wraper to publish simple pass manager interface
64 PassManagerImpl *PM;
65 };
66
67 /// FunctionPassManager manages FunctionPasses and BasicBlockPassManagers.
68 class FunctionPassManager : public PassManagerBase {
69 public:
70 /// FunctionPassManager ctor - This initializes the pass manager. It needs,
71 /// but does not take ownership of, the specified Module.
72 explicit FunctionPassManager(Module *M);
73 ~FunctionPassManager();
74
75 /// add - Add a pass to the queue of passes to run. This passes
76 /// ownership of the Pass to the PassManager. When the
77 /// PassManager_X is destroyed, the pass will be destroyed as well, so
78 /// there is no need to delete the pass.
79 /// This implies that all passes MUST be allocated with 'new'.
80 void add(Pass *P);
81
82 /// run - Execute all of the passes scheduled for execution. Keep
83 /// track of whether any of the passes modifies the function, and if
84 /// so, return true.
85 ///
86 bool run(Function &F);
87
88 /// doInitialization - Run all of the initializers for the function passes.
89 ///
90 bool doInitialization();
91
92 /// doFinalization - Run all of the finalizers for the function passes.
93 ///
94 bool doFinalization();
95
96 private:
97 FunctionPassManagerImpl *FPM;
98 Module *M;
99 };
100
101 // Create wrappers for C Binding types (see CBindingWrapping.h).
102 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBase, LLVMPassManagerRef)
103
104 } // End llvm namespace
36 }
10537
10638 #endif
+0
-470
include/llvm/PassManagers.h less more
None //===- llvm/PassManagers.h - Pass Infrastructure classes -------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the LLVM Pass Manager infrastructure.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_PASSMANAGERS_H
14 #define LLVM_PASSMANAGERS_H
15
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Pass.h"
21 #include
22 #include
23
24 //===----------------------------------------------------------------------===//
25 // Overview:
26 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
27 //
28 // o Manage optimization pass execution order
29 // o Make required Analysis information available before pass P is run
30 // o Release memory occupied by dead passes
31 // o If Analysis information is dirtied by a pass then regenerate Analysis
32 // information before it is consumed by another pass.
33 //
34 // Pass Manager Infrastructure uses multiple pass managers. They are
35 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
36 // This class hierarchy uses multiple inheritance but pass managers do not
37 // derive from another pass manager.
38 //
39 // PassManager and FunctionPassManager are two top-level pass manager that
40 // represents the external interface of this entire pass manager infrastucture.
41 //
42 // Important classes :
43 //
44 // [o] class PMTopLevelManager;
45 //
46 // Two top level managers, PassManager and FunctionPassManager, derive from
47 // PMTopLevelManager. PMTopLevelManager manages information used by top level
48 // managers such as last user info.
49 //
50 // [o] class PMDataManager;
51 //
52 // PMDataManager manages information, e.g. list of available analysis info,
53 // used by a pass manager to manage execution order of passes. It also provides
54 // a place to implement common pass manager APIs. All pass managers derive from
55 // PMDataManager.
56 //
57 // [o] class BBPassManager : public FunctionPass, public PMDataManager;
58 //
59 // BBPassManager manages BasicBlockPasses.
60 //
61 // [o] class FunctionPassManager;
62 //
63 // This is a external interface used by JIT to manage FunctionPasses. This
64 // interface relies on FunctionPassManagerImpl to do all the tasks.
65 //
66 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
67 // public PMTopLevelManager;
68 //
69 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
70 //
71 // [o] class FPPassManager : public ModulePass, public PMDataManager;
72 //
73 // FPPassManager manages FunctionPasses and BBPassManagers
74 //
75 // [o] class MPPassManager : public Pass, public PMDataManager;
76 //
77 // MPPassManager manages ModulePasses and FPPassManagers
78 //
79 // [o] class PassManager;
80 //
81 // This is a external interface used by various tools to manages passes. It
82 // relies on PassManagerImpl to do all the tasks.
83 //
84 // [o] class PassManagerImpl : public Pass, public PMDataManager,
85 // public PMTopLevelManager
86 //
87 // PassManagerImpl is a top level pass manager responsible for managing
88 // MPPassManagers.
89 //===----------------------------------------------------------------------===//
90
91 #include "llvm/Support/PrettyStackTrace.h"
92
93 namespace llvm {
94 class Module;
95 class Pass;
96 class StringRef;
97 class Value;
98 class Timer;
99 class PMDataManager;
100
101 // enums for debugging strings
102 enum PassDebuggingString {
103 EXECUTION_MSG, // "Executing Pass '"
104 MODIFICATION_MSG, // "' Made Modification '"
105 FREEING_MSG, // " Freeing Pass '"
106 ON_BASICBLOCK_MSG, // "' on BasicBlock '" + PassName + "'...\n"
107 ON_FUNCTION_MSG, // "' on Function '" + FunctionName + "'...\n"
108 ON_MODULE_MSG, // "' on Module '" + ModuleName + "'...\n"
109 ON_REGION_MSG, // " 'on Region ...\n'"
110 ON_LOOP_MSG, // " 'on Loop ...\n'"
111 ON_CG_MSG // "' on Call Graph ...\n'"
112 };
113
114 /// PassManagerPrettyStackEntry - This is used to print informative information
115 /// about what pass is running when/if a stack trace is generated.
116 class PassManagerPrettyStackEntry : public PrettyStackTraceEntry {
117 Pass *P;
118 Value *V;
119 Module *M;
120 public:
121 explicit PassManagerPrettyStackEntry(Pass *p)
122 : P(p), V(0), M(0) {} // When P is releaseMemory'd.
123 PassManagerPrettyStackEntry(Pass *p, Value &v)
124 : P(p), V(&v), M(0) {} // When P is run on V
125 PassManagerPrettyStackEntry(Pass *p, Module &m)
126 : P(p), V(0), M(&m) {} // When P is run on M
127
128 /// print - Emit information about this stack frame to OS.
129 virtual void print(raw_ostream &OS) const;
130 };
131
132
133 //===----------------------------------------------------------------------===//
134 // PMStack
135 //
136 /// PMStack - This class implements a stack data structure of PMDataManager
137 /// pointers.
138 ///
139 /// Top level pass managers (see PassManager.cpp) maintain active Pass Managers
140 /// using PMStack. Each Pass implements assignPassManager() to connect itself
141 /// with appropriate manager. assignPassManager() walks PMStack to find
142 /// suitable manager.
143 class PMStack {
144 public:
145 typedef std::vector::const_reverse_iterator iterator;
146 iterator begin() const { return S.rbegin(); }
147 iterator end() const { return S.rend(); }
148
149 void pop();
150 PMDataManager *top() const { return S.back(); }
151 void push(PMDataManager *PM);
152 bool empty() const { return S.empty(); }
153
154 void dump() const;
155
156 private:
157 std::vector S;
158 };
159
160
161 //===----------------------------------------------------------------------===//
162 // PMTopLevelManager
163 //
164 /// PMTopLevelManager manages LastUser info and collects common APIs used by
165 /// top level pass managers.
166 class PMTopLevelManager {
167 protected:
168 explicit PMTopLevelManager(PMDataManager *PMDM);
169
170 unsigned getNumContainedManagers() const {
171 return (unsigned)PassManagers.size();
172 }
173
174 void initializeAllAnalysisInfo();
175
176 private:
177 virtual PMDataManager *getAsPMDataManager() = 0;
178 virtual PassManagerType getTopLevelPassManagerType() = 0;
179
180 public:
181 /// Schedule pass P for execution. Make sure that passes required by
182 /// P are run before P is run. Update analysis info maintained by
183 /// the manager. Remove dead passes. This is a recursive function.
184 void schedulePass(Pass *P);
185
186 /// Set pass P as the last user of the given analysis passes.
187 void setLastUser(ArrayRef AnalysisPasses, Pass *P);
188
189 /// Collect passes whose last user is P
190 void collectLastUses(SmallVectorImpl &LastUses, Pass *P);
191
192 /// Find the pass that implements Analysis AID. Search immutable
193 /// passes and all pass managers. If desired pass is not found
194 /// then return NULL.
195 Pass *findAnalysisPass(AnalysisID AID);
196
197 /// Find analysis usage information for the pass P.
198 AnalysisUsage *findAnalysisUsage(Pass *P);
199
200 virtual ~PMTopLevelManager();
201
202 /// Add immutable pass and initialize it.
203 inline void addImmutablePass(ImmutablePass *P) {
204 P->initializePass();
205 ImmutablePasses.push_back(P);
206 }
207
208 inline SmallVectorImpl& getImmutablePasses() {
209 return ImmutablePasses;
210 }
211
212 void addPassManager(PMDataManager *Manager) {
213 PassManagers.push_back(Manager);
214 }
215
216 // Add Manager into the list of managers that are not directly
217 // maintained by this top level pass manager
218 inline void addIndirectPassManager(PMDataManager *Manager) {
219 IndirectPassManagers.push_back(Manager);
220 }
221
222 // Print passes managed by this top level manager.
223 void dumpPasses() const;
224 void dumpArguments() const;
225
226 // Active Pass Managers
227 PMStack activeStack;
228
229 protected:
230
231 /// Collection of pass managers
232 SmallVector PassManagers;
233
234 private:
235
236 /// Collection of pass managers that are not directly maintained
237 /// by this pass manager
238 SmallVector IndirectPassManagers;
239
240 // Map to keep track of last user of the analysis pass.
241 // LastUser->second is the last user of Lastuser->first.
242 DenseMap LastUser;
243
244 // Map to keep track of passes that are last used by a pass.
245 // This inverse map is initialized at PM->run() based on
246 // LastUser map.
247 DenseMap > InversedLastUser;
248
249 /// Immutable passes are managed by top level manager.
250 SmallVector ImmutablePasses;
251
252 DenseMap AnUsageMap;
253 };
254
255
256
257 //===----------------------------------------------------------------------===//
258 // PMDataManager
259
260 /// PMDataManager provides the common place to manage the analysis data
261 /// used by pass managers.
262 class PMDataManager {
263 public:
264
265 explicit PMDataManager() : TPM(NULL), Depth(0) {
266 initializeAnalysisInfo();
267 }
268
269 virtual ~PMDataManager();
270
271 virtual Pass *getAsPass() = 0;
272
273 /// Augment AvailableAnalysis by adding analysis made available by pass P.
274 void recordAvailableAnalysis(Pass *P);
275
276 /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
277 void verifyPreservedAnalysis(Pass *P);
278
279 /// Remove Analysis that is not preserved by the pass
280 void removeNotPreservedAnalysis(Pass *P);
281
282 /// Remove dead passes used by P.
283 void removeDeadPasses(Pass *P, StringRef Msg,
284 enum PassDebuggingString);
285
286 /// Remove P.
287 void freePass(Pass *P, StringRef Msg,
288 enum PassDebuggingString);
289
290 /// Add pass P into the PassVector. Update
291 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
292 void add(Pass *P, bool ProcessAnalysis = true);
293
294 /// Add RequiredPass into list of lower level passes required by pass P.
295 /// RequiredPass is run on the fly by Pass Manager when P requests it
296 /// through getAnalysis interface.
297 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
298
299 virtual Pass *getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F);
300
301 /// Initialize available analysis information.
302 void initializeAnalysisInfo() {
303 AvailableAnalysis.clear();
304 for (unsigned i = 0; i < PMT_Last; ++i)
305 InheritedAnalysis[i] = NULL;
306 }
307
308 // Return true if P preserves high level analysis used by other
309 // passes that are managed by this manager.
310 bool preserveHigherLevelAnalysis(Pass *P);
311
312
313 /// Populate RequiredPasses with analysis pass that are required by
314 /// pass P and are available. Populate ReqPassNotAvailable with analysis
315 /// pass that are required by pass P but are not available.
316 void collectRequiredAnalysis(SmallVectorImpl &RequiredPasses,
317 SmallVectorImpl &ReqPassNotAvailable,
318 Pass *P);
319
320 /// All Required analyses should be available to the pass as it runs! Here
321 /// we fill in the AnalysisImpls member of the pass so that it can
322 /// successfully use the getAnalysis() method to retrieve the
323 /// implementations it needs.
324 void initializeAnalysisImpl(Pass *P);
325
326 /// Find the pass that implements Analysis AID. If desired pass is not found
327 /// then return NULL.
328 Pass *findAnalysisPass(AnalysisID AID, bool Direction);
329
330 // Access toplevel manager
331 PMTopLevelManager *getTopLevelManager() { return TPM; }
332 void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
333
334 unsigned getDepth() const { return Depth; }
335 void setDepth(unsigned newDepth) { Depth = newDepth; }
336
337 // Print routines used by debug-pass
338 void dumpLastUses(Pass *P, unsigned Offset) const;
339 void dumpPassArguments() const;
340 void dumpPassInfo(Pass *P, enum PassDebuggingString S1,
341 enum PassDebuggingString S2, StringRef Msg);
342 void dumpRequiredSet(const Pass *P) const;
343 void dumpPreservedSet(const Pass *P) const;
344
345 unsigned getNumContainedPasses() const {
346 return (unsigned)PassVector.size();
347 }
348
349 virtual PassManagerType getPassManagerType() const {
350 assert ( 0 && "Invalid use of getPassManagerType");
351 return PMT_Unknown;
352 }
353
354 DenseMap *getAvailableAnalysis() {
355 return &AvailableAnalysis;
356 }
357
358 // Collect AvailableAnalysis from all the active Pass Managers.
359 void populateInheritedAnalysis(PMStack &PMS) {
360 unsigned Index = 0;
361 for (PMStack::iterator I = PMS.begin(), E = PMS.end();
362 I != E; ++I)
363 InheritedAnalysis[Index++] = (*I)->getAvailableAnalysis();
364 }
365
366 protected:
367
368 // Top level manager.
369 PMTopLevelManager *TPM;
370
371 // Collection of pass that are managed by this manager
372 SmallVector PassVector;
373
374 // Collection of Analysis provided by Parent pass manager and
375 // used by current pass manager. At at time there can not be more
376 // then PMT_Last active pass mangers.
377 DenseMap *InheritedAnalysis[PMT_Last];
378
379 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
380 /// or higher is specified.
381 bool isPassDebuggingExecutionsOrMore() const;
382
383 private:
384 void dumpAnalysisUsage(StringRef Msg, const Pass *P,
385 const AnalysisUsage::VectorType &Set) const;
386
387 // Set of available Analysis. This information is used while scheduling
388 // pass. If a pass requires an analysis which is not available then
389 // the required analysis pass is scheduled to run before the pass itself is
390 // scheduled to run.
391 DenseMap AvailableAnalysis;
392
393 // Collection of higher level analysis used by the pass managed by
394 // this manager.
395 SmallVector HigherLevelAnalysis;
396
397 unsigned Depth;
398 };
399
400 //===----------------------------------------------------------------------===//
401 // FPPassManager
402 //
403 /// FPPassManager manages BBPassManagers and FunctionPasses.
404 /// It batches all function passes and basic block pass managers together and
405 /// sequence them to process one function at a time before processing next
406 /// function.
407 class FPPassManager : public ModulePass, public PMDataManager {
408 public:
409 static char ID;
410 explicit FPPassManager()
411 : ModulePass(ID), PMDataManager() { }
412
413 /// run - Execute all of the passes scheduled for execution. Keep track of
414 /// whether any of the passes modifies the module, and if so, return true.
415 bool runOnFunction(Function &F);
416 bool runOnModule(Module &M);
417
418 /// cleanup - After running all passes, clean up pass manager cache.
419 void cleanup();
420
421 /// doInitialization - Overrides ModulePass doInitialization for global
422 /// initialization tasks
423 ///
424 using ModulePass::doInitialization;
425
426 /// doInitialization - Run all of the initializers for the function passes.
427 ///
428 bool doInitialization(Module &M);
429
430 /// doFinalization - Overrides ModulePass doFinalization for global
431 /// finalization tasks
432 ///
433 using ModulePass::doFinalization;
434
435 /// doFinalization - Run all of the finalizers for the function passes.
436 ///
437 bool doFinalization(Module &M);
438
439 virtual PMDataManager *getAsPMDataManager() { return this; }
440 virtual Pass *getAsPass() { return this; }
441
442 /// Pass Manager itself does not invalidate any analysis info.
443 void getAnalysisUsage(AnalysisUsage &Info) const {
444 Info.setPreservesAll();
445 }
446
447 // Print passes managed by this manager
448 void dumpPassStructure(unsigned Offset);
449
450 virtual const char *getPassName() const {
451 return "Function Pass Manager";
452 }
453
454 FunctionPass *getContainedPass(unsigned N) {
455 assert ( N < PassVector.size() && "Pass number out of range!");
456 FunctionPass *FP = static_cast(PassVector[N]);
457 return FP;
458 }
459
460 virtual PassManagerType getPassManagerType() const {
461 return PMT_FunctionPassManager;
462 }
463 };
464
465 Timer *getPassTimer(Pass *);
466
467 }
468
469 #endif
2828 class MCAsmInfo;
2929 class MCCodeGenInfo;
3030 class MCContext;
31 class PassManagerBase;
3231 class Target;
3332 class DataLayout;
3433 class TargetLibraryInfo;
4645 class formatted_raw_ostream;
4746 class raw_ostream;
4847
48 // The old pass manager infrastructure is hidden in a legacy namespace now.
49 namespace legacy {
50 class PassManagerBase;
51 }
52 using legacy::PassManagerBase;
53
4954 //===----------------------------------------------------------------------===//
5055 ///
5156 /// TargetMachine - Primary interface to the complete machine description for
1717 #include
1818
1919 namespace llvm {
20 class TargetLibraryInfo;
21 class PassManagerBase;
22 class Pass;
23 class FunctionPassManager;
20 class TargetLibraryInfo;
21 class Pass;
22
23 // The old pass manager infrastructure is hidden in a legacy namespace now.
24 namespace legacy {
25 class PassManagerBase;
26 class FunctionPassManager;
27 }
28 using legacy::PassManagerBase;
29 using legacy::FunctionPassManager;
2430
2531 /// PassManagerBuilder - This class is used to set up a standard optimization
2632 /// sequence for languages like C and C++, allowing some APIs to customize the
2121 #include "llvm/Analysis/CallGraph.h"
2222 #include "llvm/IR/Function.h"
2323 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/PassManagers.h"
24 #include "llvm/IR/LegacyPassManagers.h"
2525 #include "llvm/Support/CommandLine.h"
2626 #include "llvm/Support/Debug.h"
2727 #include "llvm/Support/Timer.h"
55 ConstantFold.cpp
66 Constants.cpp
77 Core.cpp
8 DIBuilder.cpp
89 DataLayout.cpp
910 DebugInfo.cpp
1011 DebugLoc.cpp
11 DIBuilder.cpp
1212 Dominators.cpp
1313 Function.cpp
1414 GCOV.cpp
2222 LLVMContext.cpp
2323 LLVMContextImpl.cpp
2424 LeakDetector.cpp
25 LegacyPassManager.cpp
2526 Metadata.cpp
2627 Module.cpp
2728 Pass.cpp
28 PassManager.cpp
2929 PassRegistry.cpp
3030 PrintModulePass.cpp
3131 Type.cpp
0 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the legacy LLVM Pass Manager infrastructure.
10 //
11 //===----------------------------------------------------------------------===//
12
13
14 #include "llvm/Assembly/PrintModulePass.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/IR/LegacyPassManager.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/IR/LegacyPassManagers.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/Mutex.h"
24 #include "llvm/Support/PassNameParser.h"
25 #include "llvm/Support/Timer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include
28 #include
29 using namespace llvm;
30 using namespace llvm::legacy;
31
32 // See PassManagers.h for Pass Manager infrastructure overview.
33
34 //===----------------------------------------------------------------------===//
35 // Pass debugging information. Often it is useful to find out what pass is
36 // running when a crash occurs in a utility. When this library is compiled with
37 // debugging on, a command line option (--debug-pass) is enabled that causes the
38 // pass name to be printed before it executes.
39 //
40
41 namespace {
42 // Different debug levels that can be enabled...
43 enum PassDebugLevel {
44 Disabled, Arguments, Structure, Executions, Details
45 };
46 }
47
48 static cl::opt
49 PassDebugging("debug-pass", cl::Hidden,
50 cl::desc("Print PassManager debugging information"),
51 cl::values(
52 clEnumVal(Disabled , "disable debug output"),
53 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
54 clEnumVal(Structure , "print pass structure before run()"),
55 clEnumVal(Executions, "print pass name before it is executed"),
56 clEnumVal(Details , "print pass details when it is executed"),
57 clEnumValEnd));
58
59 namespace {
60 typedef llvm::cl::list
61 PassOptionList;
62 }
63
64 // Print IR out before/after specified passes.
65 static PassOptionList
66 PrintBefore("print-before",
67 llvm::cl::desc("Print IR before specified passes"),
68 cl::Hidden);
69
70 static PassOptionList
71 PrintAfter("print-after",
72 llvm::cl::desc("Print IR after specified passes"),
73 cl::Hidden);
74
75 static cl::opt
76 PrintBeforeAll("print-before-all",
77 llvm::cl::desc("Print IR before each pass"),
78 cl::init(false));
79 static cl::opt
80 PrintAfterAll("print-after-all",
81 llvm::cl::desc("Print IR after each pass"),
82 cl::init(false));
83
84 /// This is a helper to determine whether to print IR before or
85 /// after a pass.
86
87 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
88 PassOptionList &PassesToPrint) {
89 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
90 const llvm::PassInfo *PassInf = PassesToPrint[i];
91 if (PassInf)
92 if (PassInf->getPassArgument() == PI->getPassArgument()) {
93 return true;
94 }
95 }
96 return false;
97 }
98
99 /// This is a utility to check whether a pass should have IR dumped
100 /// before it.
101 static bool ShouldPrintBeforePass(const PassInfo *PI) {
102 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
103 }
104
105 /// This is a utility to check whether a pass should have IR dumped
106 /// after it.
107 static bool ShouldPrintAfterPass(const PassInfo *PI) {
108 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
109 }
110
111 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
112 /// or higher is specified.
113 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
114 return PassDebugging >= Executions;
115 }
116
117
118
119
120 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
121 if (V == 0 && M == 0)
122 OS << "Releasing pass '";
123 else
124 OS << "Running pass '";
125
126 OS << P->getPassName() << "'";
127
128 if (M) {
129 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
130 return;
131 }
132 if (V == 0) {
133 OS << '\n';
134 return;
135 }
136
137 OS << " on ";
138 if (isa(V))
139 OS << "function";
140 else if (isa(V))
141 OS << "basic block";
142 else
143 OS << "value";
144
145 OS << " '";
146 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
147 OS << "'\n";
148 }
149
150
151 namespace {
152 //===----------------------------------------------------------------------===//
153 // BBPassManager
154 //
155 /// BBPassManager manages BasicBlockPass. It batches all the
156 /// pass together and sequence them to process one basic block before
157 /// processing next basic block.
158 class BBPassManager : public PMDataManager, public FunctionPass {
159
160 public:
161 static char ID;
162 explicit BBPassManager()
163 : PMDataManager(), FunctionPass(ID) {}
164
165 /// Execute all of the passes scheduled for execution. Keep track of
166 /// whether any of the passes modifies the function, and if so, return true.
167 bool runOnFunction(Function &F);
168
169 /// Pass Manager itself does not invalidate any analysis info.
170 void getAnalysisUsage(AnalysisUsage &Info) const {
171 Info.setPreservesAll();
172 }
173
174 bool doInitialization(Module &M);
175 bool doInitialization(Function &F);
176 bool doFinalization(Module &M);
177 bool doFinalization(Function &F);
178
179 virtual PMDataManager *getAsPMDataManager() { return this; }
180 virtual Pass *getAsPass() { return this; }
181
182 virtual const char *getPassName() const {
183 return "BasicBlock Pass Manager";
184 }
185
186 // Print passes managed by this manager
187 void dumpPassStructure(unsigned Offset) {
188 llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
189 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
190 BasicBlockPass *BP = getContainedPass(Index);
191 BP->dumpPassStructure(Offset + 1);
192 dumpLastUses(BP, Offset+1);
193 }
194 }
195
196 BasicBlockPass *getContainedPass(unsigned N) {
197 assert(N < PassVector.size() && "Pass number out of range!");
198 BasicBlockPass *BP = static_cast(PassVector[N]);
199 return BP;
200 }
201
202 virtual PassManagerType getPassManagerType() const {
203 return PMT_BasicBlockPassManager;
204 }
205 };
206
207 char BBPassManager::ID = 0;
208 } // End anonymous namespace
209
210 namespace llvm {
211 namespace legacy {
212 //===----------------------------------------------------------------------===//
213 // FunctionPassManagerImpl
214 //
215 /// FunctionPassManagerImpl manages FPPassManagers
216 class FunctionPassManagerImpl : public Pass,
217 public PMDataManager,
218 public PMTopLevelManager {
219 virtual void anchor();
220 private:
221 bool wasRun;
222 public:
223 static char ID;
224 explicit FunctionPassManagerImpl() :
225 Pass(PT_PassManager, ID), PMDataManager(),
226 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
227
228 /// add - Add a pass to the queue of passes to run. This passes ownership of
229 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
230 /// will be destroyed as well, so there is no need to delete the pass. This
231 /// implies that all passes MUST be allocated with 'new'.
232 void add(Pass *P) {
233 schedulePass(P);
234 }
235
236 /// createPrinterPass - Get a function printer pass.
237 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
238 return createPrintFunctionPass(Banner, &O);
239 }
240
241 // Prepare for running an on the fly pass, freeing memory if needed
242 // from a previous run.
243 void releaseMemoryOnTheFly();
244
245 /// run - Execute all of the passes scheduled for execution. Keep track of
246 /// whether any of the passes modifies the module, and if so, return true.
247 bool run(Function &F);
248
249 /// doInitialization - Run all of the initializers for the function passes.
250 ///
251 bool doInitialization(Module &M);
252
253 /// doFinalization - Run all of the finalizers for the function passes.
254 ///
255 bool doFinalization(Module &M);
256
257
258 virtual PMDataManager *getAsPMDataManager() { return this; }
259 virtual Pass *getAsPass() { return this; }
260 virtual PassManagerType getTopLevelPassManagerType() {
261 return PMT_FunctionPassManager;
262 }
263
264 /// Pass Manager itself does not invalidate any analysis info.
265 void getAnalysisUsage(AnalysisUsage &Info) const {
266 Info.setPreservesAll();
267 }
268
269 FPPassManager *getContainedManager(unsigned N) {
270 assert(N < PassManagers.size() && "Pass number out of range!");
271 FPPassManager *FP = static_cast(PassManagers[N]);
272 return FP;
273 }
274 };
275
276 void FunctionPassManagerImpl::anchor() {}
277
278 char FunctionPassManagerImpl::ID = 0;
279 } // End of legacy namespace
280 } // End of llvm namespace
281
282 namespace {
283 //===----------------------------------------------------------------------===//
284 // MPPassManager
285 //
286 /// MPPassManager manages ModulePasses and function pass managers.
287 /// It batches all Module passes and function pass managers together and
288 /// sequences them to process one module.
289 class MPPassManager : public Pass, public PMDataManager {
290 public:
291 static char ID;
292 explicit MPPassManager() :
293 Pass(PT_PassManager, ID), PMDataManager() { }
294
295 // Delete on the fly managers.
296 virtual ~MPPassManager() {
297 for (std::map::iterator
298 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
299 I != E; ++I) {
300 FunctionPassManagerImpl *FPP = I->second;
301 delete FPP;
302 }
303 }
304
305 /// createPrinterPass - Get a module printer pass.
306 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
307 return createPrintModulePass(&O, false, Banner);
308 }
309
310 /// run - Execute all of the passes scheduled for execution. Keep track of
311 /// whether any of the passes modifies the module, and if so, return true.
312 bool runOnModule(Module &M);
313
314 using llvm::Pass::doInitialization;
315 using llvm::Pass::doFinalization;
316
317 /// doInitialization - Run all of the initializers for the module passes.
318 ///
319 bool doInitialization();
320
321 /// doFinalization - Run all of the finalizers for the module passes.
322 ///
323 bool doFinalization();
324
325 /// Pass Manager itself does not invalidate any analysis info.
326 void getAnalysisUsage(AnalysisUsage &Info) const {
327 Info.setPreservesAll();
328 }
329
330 /// Add RequiredPass into list of lower level passes required by pass P.
331 /// RequiredPass is run on the fly by Pass Manager when P requests it
332 /// through getAnalysis interface.
333 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
334
335 /// Return function pass corresponding to PassInfo PI, that is
336 /// required by module pass MP. Instantiate analysis pass, by using
337 /// its runOnFunction() for function F.
338 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
339
340 virtual const char *getPassName() const {
341 return "Module Pass Manager";
342 }
343
344 virtual PMDataManager *getAsPMDataManager() { return this; }
345 virtual Pass *getAsPass() { return this; }
346
347 // Print passes managed by this manager
348 void dumpPassStructure(unsigned Offset) {
349 llvm::dbgs().indent(Offset*2) << "ModulePass Manager\n";
350 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
351 ModulePass *MP = getContainedPass(Index);
352 MP->dumpPassStructure(Offset + 1);
353 std::map::const_iterator I =
354 OnTheFlyManagers.find(MP);
355 if (I != OnTheFlyManagers.end())
356 I->second->dumpPassStructure(Offset + 2);
357 dumpLastUses(MP, Offset+1);
358 }
359 }
360
361 ModulePass *getContainedPass(unsigned N) {
362 assert(N < PassVector.size() && "Pass number out of range!");
363 return static_cast(PassVector[N]);
364 }
365
366 virtual PassManagerType getPassManagerType() const {
367 return PMT_ModulePassManager;
368 }
369
370 private:
371 /// Collection of on the fly FPPassManagers. These managers manage
372 /// function passes that are required by module passes.
373 std::map OnTheFlyManagers;
374 };
375
376 char MPPassManager::ID = 0;
377 } // End anonymous namespace
378
379 namespace llvm {
380 namespace legacy {
381 //===----------------------------------------------------------------------===//
382 // PassManagerImpl
383 //
384
385 /// PassManagerImpl manages MPPassManagers
386 class PassManagerImpl : public Pass,
387 public PMDataManager,
388 public PMTopLevelManager {
389 virtual void anchor();
390
391 public:
392 static char ID;
393 explicit PassManagerImpl() :
394 Pass(PT_PassManager, ID), PMDataManager(),
395 PMTopLevelManager(new MPPassManager()) {}
396
397 /// add - Add a pass to the queue of passes to run. This passes ownership of
398 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
399 /// will be destroyed as well, so there is no need to delete the pass. This
400 /// implies that all passes MUST be allocated with 'new'.
401 void add(Pass *P) {
402 schedulePass(P);
403 }
404
405 /// createPrinterPass - Get a module printer pass.
406 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
407 return createPrintModulePass(&O, false, Banner);
408 }
409
410 /// run - Execute all of the passes scheduled for execution. Keep track of
411 /// whether any of the passes modifies the module, and if so, return true.
412 bool run(Module &M);
413
414 using llvm::Pass::doInitialization;
415 using llvm::Pass::doFinalization;
416
417 /// doInitialization - Run all of the initializers for the module passes.
418 ///
419 bool doInitialization();
420
421 /// doFinalization - Run all of the finalizers for the module passes.
422 ///
423 bool doFinalization();
424
425 /// Pass Manager itself does not invalidate any analysis info.
426 void getAnalysisUsage(AnalysisUsage &Info) const {
427 Info.setPreservesAll();
428 }
429
430 virtual PMDataManager *getAsPMDataManager() { return this; }
431 virtual Pass *getAsPass() { return this; }
432 virtual PassManagerType getTopLevelPassManagerType() {
433 return PMT_ModulePassManager;
434 }
435
436 MPPassManager *getContainedManager(unsigned N) {
437 assert(N < PassManagers.size() && "Pass number out of range!");
438 MPPassManager *MP = static_cast(PassManagers[N]);
439 return MP;
440 }
441 };
442
443 void PassManagerImpl::anchor() {}
444
445 char PassManagerImpl::ID = 0;
446 } // End of legacy namespace
447 } // End of llvm namespace
448
449 namespace {
450
451 //===----------------------------------------------------------------------===//
452 /// TimingInfo Class - This class is used to calculate information about the
453 /// amount of time each pass takes to execute. This only happens when
454 /// -time-passes is enabled on the command line.
455 ///
456
457 static ManagedStatic > TimingInfoMutex;
458
459 class TimingInfo {
460 DenseMap TimingData;
461 TimerGroup TG;
462 public:
463 // Use 'create' member to get this.
464 TimingInfo() : TG("... Pass execution timing report ...") {}
465
466 // TimingDtor - Print out information about timing information
467 ~TimingInfo() {
468 // Delete all of the timers, which accumulate their info into the
469 // TimerGroup.
470 for (DenseMap::iterator I = TimingData.begin(),
471 E = TimingData.end(); I != E; ++I)
472 delete I->second;
473 // TimerGroup is deleted next, printing the report.
474 }
475
476 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
477 // to a non null value (if the -time-passes option is enabled) or it leaves it
478 // null. It may be called multiple times.
479 static void createTheTimeInfo();
480
481 /// getPassTimer - Return the timer for the specified pass if it exists.
482 Timer *getPassTimer(Pass *P) {
483 if (P->getAsPMDataManager())
484 return 0;
485
486 sys::SmartScopedLock Lock(*TimingInfoMutex);
487 Timer *&T = TimingData[P];
488 if (T == 0)
489 T = new Timer(P->getPassName(), TG);
490 return T;
491 }
492 };
493
494 } // End of anon namespace
495
496 static TimingInfo *TheTimeInfo;
497
498 //===----------------------------------------------------------------------===//
499 // PMTopLevelManager implementation
500
501 /// Initialize top level manager. Create first pass manager.
502 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
503 PMDM->setTopLevelManager(this);
504 addPassManager(PMDM);
505 activeStack.push(PMDM);
506 }
507
508 /// Set pass P as the last user of the given analysis passes.
509 void
510 PMTopLevelManager::setLastUser(ArrayRef AnalysisPasses, Pass *P) {
511 unsigned PDepth = 0;
512 if (P->getResolver())
513 PDepth = P->getResolver()->getPMDataManager().getDepth();
514
515 for (SmallVectorImpl::const_iterator I = AnalysisPasses.begin(),
516 E = AnalysisPasses.end(); I != E; ++I) {
517 Pass *AP = *I;
518 LastUser[AP] = P;
519
520 if (P == AP)
521 continue;
522
523 // Update the last users of passes that are required transitive by AP.
524 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
525 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
526 SmallVector LastUses;
527 SmallVector LastPMUses;
528 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
529 E = IDs.end(); I != E; ++I) {
530 Pass *AnalysisPass = findAnalysisPass(*I);
531 assert(AnalysisPass && "Expected analysis pass to exist.");
532 AnalysisResolver *AR = AnalysisPass->getResolver();
533 assert(AR && "Expected analysis resolver to exist.");
534 unsigned APDepth = AR->getPMDataManager().getDepth();
535
536 if (PDepth == APDepth)
537 LastUses.push_back(AnalysisPass);
538 else if (PDepth > APDepth)
539 LastPMUses.push_back(AnalysisPass);
540 }
541
542 setLastUser(LastUses, P);
543
544 // If this pass has a corresponding pass manager, push higher level
545 // analysis to this pass manager.
546 if (P->getResolver())
547 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
548
549
550 // If AP is the last user of other passes then make P last user of
551 // such passes.
552 for (DenseMap::iterator LUI = LastUser.begin(),
553 LUE = LastUser.end(); LUI != LUE; ++LUI) {
554 if (LUI->second == AP)
555 // DenseMap iterator is not invalidated here because
556 // this is just updating existing entries.
557 LastUser[LUI->first] = P;
558 }
559 }
560 }
561
562 /// Collect passes whose last user is P
563 void PMTopLevelManager::collectLastUses(SmallVectorImpl &LastUses,
564 Pass *P) {
565 DenseMap >::iterator DMI =
566 InversedLastUser.find(P);
567 if (DMI == InversedLastUser.end())
568 return;
569
570 SmallPtrSet &LU = DMI->second;
571 for (SmallPtrSet::iterator I = LU.begin(),
572 E = LU.end(); I != E; ++I) {
573 LastUses.push_back(*I);
574 }
575
576 }
577
578 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
579 AnalysisUsage *AnUsage = NULL;
580 DenseMap::iterator DMI = AnUsageMap.find(P);
581 if (DMI != AnUsageMap.end())
582 AnUsage = DMI->second;
583 else {
584 AnUsage = new AnalysisUsage();
585 P->getAnalysisUsage(*AnUsage);
586 AnUsageMap[P] = AnUsage;
587 }
588 return AnUsage;
589 }
590
591 /// Schedule pass P for execution. Make sure that passes required by
592 /// P are run before P is run. Update analysis info maintained by
593 /// the manager. Remove dead passes. This is a recursive function.
594 void PMTopLevelManager::schedulePass(Pass *P) {
595
596 // TODO : Allocate function manager for this pass, other wise required set
597 // may be inserted into previous function manager
598
599 // Give pass a chance to prepare the stage.
600 P->preparePassManager(activeStack);
601
602 // If P is an analysis pass and it is available then do not
603 // generate the analysis again. Stale analysis info should not be
604 // available at this point.
605 const PassInfo *PI =
606 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
607 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
608 delete P;
609 return;
610 }
611
612 AnalysisUsage *AnUsage = findAnalysisUsage(P);
613
614 bool checkAnalysis = true;
615 while (checkAnalysis) {
616 checkAnalysis = false;
617
618 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
619 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
620 E = RequiredSet.end(); I != E; ++I) {
621
622 Pass *AnalysisPass = findAnalysisPass(*I);
623 if (!AnalysisPass) {
624 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
625
626 if (PI == NULL) {
627 // Pass P is not in the global PassRegistry
628 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
629 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
630 dbgs() << "Required Passes:" << "\n";
631 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
632 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
633 Pass *AnalysisPass2 = findAnalysisPass(*I2);
634 if (AnalysisPass2) {
635 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
636 } else {
637 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
638 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
639 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
640 }
641 }
642 }
643
644 assert(PI && "Expected required passes to be initialized");
645 AnalysisPass = PI->createPass();
646 if (P->getPotentialPassManagerType () ==
647 AnalysisPass->getPotentialPassManagerType())
648 // Schedule analysis pass that is managed by the same pass manager.
649 schedulePass(AnalysisPass);
650 else if (P->getPotentialPassManagerType () >
651 AnalysisPass->getPotentialPassManagerType()) {
652 // Schedule analysis pass that is managed by a new manager.
653 schedulePass(AnalysisPass);
654 // Recheck analysis passes to ensure that required analyses that
655 // are already checked are still available.
656 checkAnalysis = true;
657 } else
658 // Do not schedule this analysis. Lower level analsyis
659 // passes are run on the fly.
660 delete AnalysisPass;
661 }
662 }
663 }
664
665 // Now all required passes are available.
666 if (ImmutablePass *IP = P->getAsImmutablePass()) {
667 // P is a immutable pass and it will be managed by this
668 // top level manager. Set up analysis resolver to connect them.
669 PMDataManager *DM = getAsPMDataManager();
670 AnalysisResolver *AR = new AnalysisResolver(*DM);
671 P->setResolver(AR);
672 DM->initializeAnalysisImpl(P);
673 addImmutablePass(IP);
674 DM->recordAvailableAnalysis(IP);
675 return;
676 }
677
678 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
679 Pass *PP = P->createPrinterPass(
680 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
681 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
682 }
683
684 // Add the requested pass to the best available pass manager.
685 P->assignPassManager(activeStack, getTopLevelPassManagerType());
686
687 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
688 Pass *PP = P->createPrinterPass(
689 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
690 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
691 }
692 }
693
694 /// Find the pass that implements Analysis AID. Search immutable
695 /// passes and all pass managers. If desired pass is not found
696 /// then return NULL.
697 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
698
699 // Check pass managers
700 for (SmallVectorImpl::iterator I = PassManagers.begin(),
701 E = PassManagers.end(); I != E; ++I)
702 if (Pass *P = (*I)->findAnalysisPass(AID, false))
703 return P;
704
705 // Check other pass managers
706 for (SmallVectorImpl::iterator
707 I = IndirectPassManagers.begin(),
708 E = IndirectPassManagers.end(); I != E; ++I)
709 if (Pass *P = (*I)->findAnalysisPass(AID, false))
710 return P;
711
712 // Check the immutable passes. Iterate in reverse order so that we find
713 // the most recently registered passes first.
714 for (SmallVectorImpl::reverse_iterator I =
715 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
716 AnalysisID PI = (*I)->getPassID();
717 if (PI == AID)
718 return *I;
719
720 // If Pass not found then check the interfaces implemented by Immutable Pass
721 const PassInfo *PassInf =
722 PassRegistry::getPassRegistry()->getPassInfo(PI);
723 assert(PassInf && "Expected all immutable passes to be initialized");
724 const std::vector &ImmPI =
725 PassInf->getInterfacesImplemented();
726 for (std::vector::const_iterator II = ImmPI.begin(),
727 EE = ImmPI.end(); II != EE; ++II) {
728 if ((*II)->getTypeInfo() == AID)
729 return *I;
730 }
731 }
732
733 return 0;
734 }
735
736 // Print passes managed by this top level manager.
737 void PMTopLevelManager::dumpPasses() const {
738
739 if (PassDebugging < Structure)
740 return;
741
742 // Print out the immutable passes
743 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
744 ImmutablePasses[i]->dumpPassStructure(0);
745 }
746
747 // Every class that derives from PMDataManager also derives from Pass
748 // (sometimes indirectly), but there's no inheritance relationship
749 // between PMDataManager and Pass, so we have to getAsPass to get
750 // from a PMDataManager* to a Pass*.
751 for (SmallVectorImpl::const_iterator I =
752 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
753 (*I)->getAsPass()->dumpPassStructure(1);
754 }
755
756 void PMTopLevelManager::dumpArguments() const {
757
758 if (PassDebugging < Arguments)
759 return;
760
761 dbgs() << "Pass Arguments: ";
762 for (SmallVectorImpl::const_iterator I =
763 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
764 if (const PassInfo *PI =
765 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
766 assert(PI && "Expected all immutable passes to be initialized");
767 if (!PI->isAnalysisGroup())
768 dbgs() << " -" << PI->getPassArgument();
769 }
770 for (SmallVectorImpl::const_iterator I =
771 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
772 (*I)->dumpPassArguments();
773 dbgs() << "\n";
774 }
775
776 void PMTopLevelManager::initializeAllAnalysisInfo() {
777 for (SmallVectorImpl::iterator I = PassManagers.begin(),
778 E = PassManagers.end(); I != E; ++I)
779 (*I)->initializeAnalysisInfo();
780
781 // Initailize other pass managers
782 for (SmallVectorImpl::iterator
783 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
784 I != E; ++I)
785 (*I)->initializeAnalysisInfo();
786
787 for (DenseMap::iterator DMI = LastUser.begin(),
788 DME = LastUser.end(); DMI != DME; ++DMI) {
789 DenseMap >::iterator InvDMI =
790 InversedLastUser.find(DMI->second);
791 if (InvDMI != InversedLastUser.end()) {
792 SmallPtrSet &L = InvDMI->second;
793 L.insert(DMI->first);
794 } else {
795 SmallPtrSet L; L.insert(DMI->first);
796 InversedLastUser[DMI->second] = L;
797 }
798 }
799 }
800
801 /// Destructor
802 PMTopLevelManager::~PMTopLevelManager() {
803 for (SmallVectorImpl::iterator I = PassManagers.begin(),
804 E = PassManagers.end(); I != E; ++I)
805 delete *I;
806
807 for (SmallVectorImpl::iterator
808 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
809 delete *I;
810
811 for (DenseMap::iterator DMI = AnUsageMap.begin(),
812 DME = AnUsageMap.end(); DMI != DME; ++DMI)
813 delete DMI->second;
814 }
815
816 //===----------------------------------------------------------------------===//
817 // PMDataManager implementation
818
819 /// Augement AvailableAnalysis by adding analysis made available by pass P.
820 void PMDataManager::recordAvailableAnalysis(Pass *P) {
821 AnalysisID PI = P->getPassID();
822
823 AvailableAnalysis[PI] = P;
824
825 assert(!AvailableAnalysis.empty());
826
827 // This pass is the current implementation of all of the interfaces it
828 // implements as well.
829 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
830 if (PInf == 0) return;
831 const std::vector &II = PInf->getInterfacesImplemented();
832 for (unsigned i = 0, e = II.size(); i != e; ++i)
833 AvailableAnalysis[II[i]->getTypeInfo()] = P;
834 }
835
836 // Return true if P preserves high level analysis used by other
837 // passes managed by this manager
838 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
839 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
840 if (AnUsage->getPreservesAll())
841 return true;
842
843 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
844 for (SmallVectorImpl::iterator I = HigherLevelAnalysis.begin(),
845 E = HigherLevelAnalysis.end(); I != E; ++I) {
846 Pass *P1 = *I;
847 if (P1->getAsImmutablePass() == 0 &&
848 std::find(PreservedSet.begin(), PreservedSet.end(),
849 P1->getPassID()) ==
850 PreservedSet.end())
851 return false;
852 }
853
854 return true;
855 }
856
857 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
858 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
859 // Don't do this unless assertions are enabled.
860 #ifdef NDEBUG
861 return;
862 #endif
863 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
864 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
865
866 // Verify preserved analysis
867 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
868 E = PreservedSet.end(); I != E; ++I) {
869 AnalysisID AID = *I;
870 if (Pass *AP = findAnalysisPass(AID, true)) {
871 TimeRegion PassTimer(getPassTimer(AP));
872 AP->verifyAnalysis();
873 }
874 }
875 }
876
877 /// Remove Analysis not preserved by Pass P
878 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
879 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
880 if (AnUsage->getPreservesAll())
881 return;
882
883 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
884 for (DenseMap::iterator I = AvailableAnalysis.begin(),
885 E = AvailableAnalysis.end(); I != E; ) {
886 DenseMap::iterator Info = I++;
887 if (Info->second->getAsImmutablePass() == 0 &&
888 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
889 PreservedSet.end()) {
890 // Remove this analysis
891 if (PassDebugging >= Details) {
892 Pass *S = Info->second;
893 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
894 dbgs() << S->getPassName() << "'\n";
895 }
896 AvailableAnalysis.erase(Info);
897 }
898 }
899
900 // Check inherited analysis also. If P is not preserving analysis
901 // provided by parent manager then remove it here.
902 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
903
904 if (!InheritedAnalysis[Index])
905 continue;
906
907 for (DenseMap::iterator
908 I = InheritedAnalysis[Index]->begin(),
909 E = InheritedAnalysis[Index]->end(); I != E; ) {
910 DenseMap::iterator Info = I++;
911 if (Info->second->getAsImmutablePass() == 0 &&
912 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
913 PreservedSet.end()) {
914 // Remove this analysis
915 if (PassDebugging >= Details) {
916 Pass *S = Info->second;
917 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
918 dbgs() << S->getPassName() << "'\n";
919 }
920 InheritedAnalysis[Index]->erase(Info);
921 }
922 }
923 }
924 }
925
926 /// Remove analysis passes that are not used any longer
927 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
928 enum PassDebuggingString DBG_STR) {
929
930 SmallVector DeadPasses;
931
932 // If this is a on the fly manager then it does not have TPM.
933 if (!TPM)
934 return;
935
936 TPM->collectLastUses(DeadPasses, P);
937
938 if (PassDebugging >= Details && !DeadPasses.empty()) {
939 dbgs() << " -*- '" << P->getPassName();
940 dbgs() << "' is the last user of following pass instances.";
941 dbgs() << " Free these instances\n";
942 }
943
944 for (SmallVectorImpl::iterator I = DeadPasses.begin(),
945 E = DeadPasses.end(); I != E; ++I)
946 freePass(*I, Msg, DBG_STR);
947 }
948
949 void PMDataManager::freePass(Pass *P, StringRef Msg,
950 enum PassDebuggingString DBG_STR) {
951 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
952
953 {
954 // If the pass crashes releasing memory, remember this.
955 PassManagerPrettyStackEntry X(P);
956 TimeRegion PassTimer(getPassTimer(P));
957
958 P->releaseMemory();
959 }
960
961 AnalysisID PI = P->getPassID();
962 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
963 // Remove the pass itself (if it is not already removed).
964 AvailableAnalysis.erase(PI);
965
966 // Remove all interfaces this pass implements, for which it is also
967 // listed as the available implementation.
968 const std::vector &II = PInf->getInterfacesImplemented();
969 for (unsigned i = 0, e = II.size(); i != e; ++i) {
970 DenseMap::iterator Pos =
971 AvailableAnalysis.find(II[i]->getTypeInfo());
972 if (Pos != AvailableAnalysis.end() && Pos->second == P)
973 AvailableAnalysis.erase(Pos);
974 }
975 }
976 }
977
978 /// Add pass P into the PassVector. Update
979 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
980 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
981 // This manager is going to manage pass P. Set up analysis resolver
982 // to connect them.
983 AnalysisResolver *AR = new AnalysisResolver(*this);
984 P->setResolver(AR);
985
986 // If a FunctionPass F is the last user of ModulePass info M
987 // then the F's manager, not F, records itself as a last user of M.
988 SmallVector TransferLastUses;
989
990 if (!ProcessAnalysis) {
991 // Add pass
992 PassVector.push_back(P);
993 return;
994 }
995
996 // At the moment, this pass is the last user of all required passes.
997 SmallVector LastUses;
998 SmallVector RequiredPasses;
999 SmallVector ReqAnalysisNotAvailable;
1000
1001 unsigned PDepth = this->getDepth();
1002
1003 collectRequiredAnalysis(RequiredPasses,
1004 ReqAnalysisNotAvailable, P);
1005 for (SmallVectorImpl::iterator I = RequiredPasses.begin(),
1006 E = RequiredPasses.end(); I != E; ++I) {
1007 Pass *PRequired = *I;
1008 unsigned RDepth = 0;
1009
1010 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1011 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1012 RDepth = DM.getDepth();
1013
1014 if (PDepth == RDepth)
1015 LastUses.push_back(PRequired);
1016 else if (PDepth > RDepth) {
1017 // Let the parent claim responsibility of last use
1018 TransferLastUses.push_back(PRequired);
1019 // Keep track of higher level analysis used by this manager.
1020 HigherLevelAnalysis.push_back(PRequired);
1021 } else
1022 llvm_unreachable("Unable to accommodate Required Pass");
1023 }
1024
1025 // Set P as P's last user until someone starts using P.
1026 // However, if P is a Pass Manager then it does not need
1027 // to record its last user.
1028 if (P->getAsPMDataManager() == 0)
1029 LastUses.push_back(P);
1030 TPM->setLastUser(LastUses, P);
1031
1032 if (!TransferLastUses.empty()) {
1033 Pass *My_PM = getAsPass();
1034 TPM->setLastUser(TransferLastUses, My_PM);
1035 TransferLastUses.clear();
1036 }
1037
1038 // Now, take care of required analyses that are not available.
1039 for (SmallVectorImpl::iterator
1040 I = ReqAnalysisNotAvailable.begin(),
1041 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1042 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1043 Pass *AnalysisPass = PI->createPass();
1044 this->addLowerLevelRequiredPass(P, AnalysisPass);
1045 }
1046
1047 // Take a note of analysis required and made available by this pass.
1048 // Remove the analysis not preserved by this pass
1049 removeNotPreservedAnalysis(P);
1050 recordAvailableAnalysis(P);
1051
1052 // Add pass
1053 PassVector.push_back(P);
1054 }
1055
1056
1057 /// Populate RP with analysis pass that are required by
1058 /// pass P and are available. Populate RP_NotAvail with analysis
1059 /// pass that are required by pass P but are not available.
1060 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl &RP,
1061 SmallVectorImpl &RP_NotAvail,
1062 Pass *P) {
1063 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1064 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1065 for (AnalysisUsage::VectorType::const_iterator
1066 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1067 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1068 RP.push_back(AnalysisPass);
1069 else
1070 RP_NotAvail.push_back(*I);
1071 }
1072
1073 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1074 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1075 E = IDs.end(); I != E; ++I) {
1076 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1077 RP.push_back(AnalysisPass);
1078 else
1079 RP_NotAvail.push_back(*I);
1080 }
1081 }
1082
1083 // All Required analyses should be available to the pass as it runs! Here
1084 // we fill in the AnalysisImpls member of the pass so that it can
1085 // successfully use the getAnalysis() method to retrieve the
1086 // implementations it needs.
1087 //
1088 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1089 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1090
1091 for (AnalysisUsage::VectorType::const_iterator
1092 I = AnUsage->getRequiredSet().begin(),
1093 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1094 Pass *Impl = findAnalysisPass(*I, true);
1095 if (Impl == 0)
1096 // This may be analysis pass that is initialized on the fly.
1097 // If that is not the case then it will raise an assert when it is used.
1098 continue;
1099 AnalysisResolver *AR = P->getResolver();
1100 assert(AR && "Analysis Resolver is not set");
1101 AR->addAnalysisImplsPair(*I, Impl);
1102 }
1103 }
1104
1105 /// Find the pass that implements Analysis AID. If desired pass is not found
1106 /// then return NULL.
1107 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1108
1109 // Check if AvailableAnalysis map has one entry.
1110 DenseMap::const_iterator I = AvailableAnalysis.find(AID);
1111
1112 if (I != AvailableAnalysis.end())
1113 return I->second;
1114
1115 // Search Parents through TopLevelManager
1116 if (SearchParent)
1117 return TPM->findAnalysisPass(AID);
1118
1119 return NULL;
1120 }
1121
1122 // Print list of passes that are last used by P.
1123 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1124
1125 SmallVector LUses;
1126
1127 // If this is a on the fly manager then it does not have TPM.
1128 if (!TPM)
1129 return;
1130
1131 TPM->collectLastUses(LUses, P);
1132
1133 for (SmallVectorImpl::iterator I = LUses.begin(),
1134 E = LUses.end(); I != E; ++I) {
1135 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1136 (*I)->dumpPassStructure(0);
1137 }
1138 }
1139
1140 void PMDataManager::dumpPassArguments() const {
1141 for (SmallVectorImpl::const_iterator I = PassVector.begin(),
1142 E = PassVector.end(); I != E; ++I) {
1143 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1144 PMD->dumpPassArguments();
1145 else
1146 if (const PassInfo *PI =
1147 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1148 if (!PI->isAnalysisGroup())
1149 dbgs() << " -" << PI->getPassArgument();
1150 }
1151 }
1152
1153 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1154 enum PassDebuggingString S2,
1155 StringRef Msg) {
1156 if (PassDebugging < Executions)
1157 return;
1158 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1159 switch (S1) {
1160 case EXECUTION_MSG:
1161 dbgs() << "Executing Pass '" << P->getPassName();
1162 break;
1163 case MODIFICATION_MSG:
1164 dbgs() << "Made Modification '" << P->getPassName();
1165 break;
1166 case FREEING_MSG:
1167 dbgs() << " Freeing Pass '" << P->getPassName();
1168 break;
1169 default:
1170 break;
1171 }
1172 switch (S2) {
1173 case ON_BASICBLOCK_MSG:
1174 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1175 break;
1176 case ON_FUNCTION_MSG:
1177 dbgs() << "' on Function '" << Msg << "'...\n";
1178 break;
1179 case ON_MODULE_MSG:
1180 dbgs() << "' on Module '" << Msg << "'...\n";
1181 break;
1182 case ON_REGION_MSG:
1183 dbgs() << "' on Region '" << Msg << "'...\n";
1184 break;
1185 case ON_LOOP_MSG:
1186 dbgs() << "' on Loop '" << Msg << "'...\n";
1187 break;
1188 case ON_CG_MSG:
1189 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1190 break;
1191 default:
1192 break;
1193 }
1194 }
1195
1196 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1197 if (PassDebugging < Details)
1198 return;
1199
1200 AnalysisUsage analysisUsage;
1201 P->getAnalysisUsage(analysisUsage);
1202 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1203 }
1204
1205 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1206 if (PassDebugging < Details)
1207 return;
1208
1209 AnalysisUsage analysisUsage;
1210 P->getAnalysisUsage(analysisUsage);
1211 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1212 }
1213
1214 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1215 const AnalysisUsage::VectorType &Set) const {
1216 assert(PassDebugging >= Details);
1217 if (Set.empty())
1218 return;
1219 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1220 for (unsigned i = 0; i != Set.size(); ++i) {
1221 if (i) dbgs() << ',';
1222 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1223 if (!PInf) {
1224 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1225 // all drivers.
1226 dbgs() << " Uninitialized Pass";
1227 continue;
1228 }
1229 dbgs() << ' ' << PInf->getPassName();
1230 }
1231 dbgs() << '\n';
1232 }
1233
1234 /// Add RequiredPass into list of lower level passes required by pass P.
1235 /// RequiredPass is run on the fly by Pass Manager when P requests it
1236 /// through getAnalysis interface.
1237 /// This should be handled by specific pass manager.
1238 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1239 if (TPM) {
1240 TPM->dumpArguments();
1241 TPM->dumpPasses();
1242 }
1243
1244 // Module Level pass may required Function Level analysis info
1245 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1246 // to provide this on demand. In that case, in Pass manager terminology,
1247 // module level pass is requiring lower level analysis info managed by
1248 // lower level pass manager.
1249
1250 // When Pass manager is not able to order required analysis info, Pass manager
1251 // checks whether any lower level manager will be able to provide this
1252 // analysis info on demand or not.
1253 #ifndef NDEBUG
1254 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1255 dbgs() << "' required by '" << P->getPassName() << "'\n";
1256 #endif
1257 llvm_unreachable("Unable to schedule pass");
1258 }
1259
1260 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1261 llvm_unreachable("Unable to find on the fly pass");
1262 }
1263
1264 // Destructor
1265 PMDataManager::~PMDataManager() {
1266 for (SmallVectorImpl::iterator I = PassVector.begin(),
1267 E = PassVector.end(); I != E; ++I)
1268 delete *I;
1269 }
1270
1271 //===----------------------------------------------------------------------===//
1272 // NOTE: Is this the right place to define this method ?
1273 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1274 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1275 return PM.findAnalysisPass(ID, dir);
1276 }
1277
1278 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1279 Function &F) {
1280 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1281 }
1282
1283 //===----------------------------------------------------------------------===//
1284 // BBPassManager implementation
1285
1286 /// Execute all of the passes scheduled for execution by invoking
1287 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1288 /// the function, and if so, return true.
1289 bool BBPassManager::runOnFunction(Function &F) {
1290 if (F.isDeclaration())
1291 return false;
1292
1293 bool Changed = doInitialization(F);
1294
1295 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1296 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1297 BasicBlockPass *BP = getContainedPass(Index);
1298 bool LocalChanged = false;
1299
1300 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1301 dumpRequiredSet(BP);
1302
1303 initializeAnalysisImpl(BP);
1304
1305 {
1306 // If the pass crashes, remember this.
1307 PassManagerPrettyStackEntry X(BP, *I);
1308 TimeRegion PassTimer(getPassTimer(BP));
1309
1310 LocalChanged |= BP->runOnBasicBlock(*I);
1311 }
1312
1313 Changed |= LocalChanged;
1314 if (LocalChanged)
1315 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1316 I->getName());
1317 dumpPreservedSet(BP);
1318
1319 verifyPreservedAnalysis(BP);
1320 removeNotPreservedAnalysis(BP);
1321 recordAvailableAnalysis(BP);
1322 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1323 }
1324
1325 return doFinalization(F) || Changed;
1326 }
1327
1328 // Implement doInitialization and doFinalization
1329 bool BBPassManager::doInitialization(Module &M) {
1330 bool Changed = false;
1331
1332 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1333 Changed |= getContainedPass(Index)->doInitialization(M);
1334
1335 return Changed;
1336 }
1337
1338 bool BBPassManager::doFinalization(Module &M) {
1339 bool Changed = false;
1340
1341 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1342 Changed |= getContainedPass(Index)->doFinalization(M);
1343
1344 return Changed;
1345 }
1346
1347 bool BBPassManager::doInitialization(Function &F) {
1348 bool Changed = false;
1349
1350 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1351 BasicBlockPass *BP = getContainedPass(Index);
1352 Changed |= BP->doInitialization(F);
1353 }
1354
1355 return Changed;
1356 }
1357
1358 bool BBPassManager::doFinalization(Function &F) {
1359 bool Changed = false;
1360
1361 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1362 BasicBlockPass *BP = getContainedPass(Index);
1363 Changed |= BP->doFinalization(F);
1364 }
1365
1366 return Changed;
1367 }
1368
1369
1370 //===----------------------------------------------------------------------===//
1371 // FunctionPassManager implementation
1372
1373 /// Create new Function pass manager
1374 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1375 FPM = new FunctionPassManagerImpl();
1376 // FPM is the top level manager.
1377 FPM->setTopLevelManager(FPM);
1378
1379 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1380 FPM->setResolver(AR);
1381 }
1382
1383 FunctionPassManager::~FunctionPassManager() {
1384 delete FPM;
1385 }
1386
1387 /// add - Add a pass to the queue of passes to run. This passes
1388 /// ownership of the Pass to the PassManager. When the
1389 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1390 /// there is no need to delete the pass. (TODO delete passes.)
1391 /// This implies that all passes MUST be allocated with 'new'.
1392 void FunctionPassManager::add(Pass *P) {
1393 FPM->add(P);
1394 }
1395
1396 /// run - Execute all of the passes scheduled for execution. Keep
1397 /// track of whether any of the passes modifies the function, and if
1398 /// so, return true.
1399 ///
1400 bool FunctionPassManager::run(Function &F) {
1401 if (F.isMaterializable()) {
1402 std::string errstr;
1403 if (F.Materialize(&errstr))
1404 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1405 }
1406 return FPM->run(F);
1407 }
1408
1409
1410 /// doInitialization - Run all of the initializers for the function passes.
1411 ///
1412 bool FunctionPassManager::doInitialization() {
1413 return FPM->doInitialization(*M);
1414 }
1415
1416 /// doFinalization - Run all of the finalizers for the function passes.
1417 ///
1418 bool FunctionPassManager::doFinalization() {
1419 return FPM->doFinalization(*M);
1420 }
1421
1422 //===----------------------------------------------------------------------===//
1423 // FunctionPassManagerImpl implementation
1424 //
1425 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1426 bool Changed = false;
1427
1428 dumpArguments();
1429 dumpPasses();
1430
1431 SmallVectorImpl& IPV = getImmutablePasses();
1432 for (SmallVectorImpl::const_iterator I = IPV.begin(),
1433 E = IPV.end(); I != E; ++I) {
1434 Changed |= (*I)->doInitialization(M);
1435 }
1436
1437 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1438 Changed |= getContainedManager(Index)->doInitialization(M);
1439
1440 return Changed;
1441 }
1442
1443 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1444 bool Changed = false;
1445
1446 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1447 Changed |= getContainedManager(Index)->doFinalization(M);
1448
1449 SmallVectorImpl& IPV = getImmutablePasses();
1450 for (SmallVectorImpl::const_iterator I = IPV.begin(),
1451 E = IPV.end(); I != E; ++I) {
1452 Changed |= (*I)->doFinalization(M);
1453 }
1454
1455 return Changed;
1456 }
1457
1458 /// cleanup - After running all passes, clean up pass manager cache.
1459 void FPPassManager::cleanup() {
1460 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1461 FunctionPass *FP = getContainedPass(Index);
1462 AnalysisResolver *AR = FP->getResolver();
1463 assert(AR && "Analysis Resolver is not set");
1464 AR->clearAnalysisImpls();
1465 }
1466 }
1467
1468 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1469 if (!wasRun)
1470 return;
1471 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1472 FPPassManager *FPPM = getContainedManager(Index);
1473 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1474 FPPM->getContainedPass(Index)->releaseMemory();
1475 }
1476 }
1477 wasRun = false;
1478 }
1479
1480 // Execute all the passes managed by this top level manager.
1481 // Return true if any function is modified by a pass.
1482 bool FunctionPassManagerImpl::run(Function &F) {
1483 bool Changed = false;
1484 TimingInfo::createTheTimeInfo();
1485
1486 initializeAllAnalysisInfo();
1487 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1488 Changed |= getContainedManager(Index)->runOnFunction(F);
1489
1490 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1491 getContainedManager(Index)->cleanup();
1492
1493 wasRun = true;
1494 return Changed;
1495 }
1496
1497 //===----------------------------------------------------------------------===//
1498 // FPPassManager implementation
1499
1500 char FPPassManager::ID = 0;
1501 /// Print passes managed by this manager
1502 void FPPassManager::dumpPassStructure(unsigned Offset) {
1503 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1504 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1505 FunctionPass *FP = getContainedPass(Index);
1506 FP->dumpPassStructure(Offset + 1);
1507 dumpLastUses(FP, Offset+1);
1508 }
1509 }
1510
1511
1512 /// Execute all of the passes scheduled for execution by invoking
1513 /// runOnFunction method. Keep track of whether any of the passes modifies
1514 /// the function, and if so, return true.
1515 bool FPPassManager::runOnFunction(Function &F) {
1516 if (F.isDeclaration())
1517 return false;
1518
1519 bool Changed = false;
1520
1521 // Collect inherited analysis from Module level pass manager.
1522 populateInheritedAnalysis(TPM->activeStack);
1523
1524 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1525 FunctionPass *FP = getContainedPass(Index);
1526 bool LocalChanged = false;
1527
1528 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1529 dumpRequiredSet(FP);
1530
1531 initializeAnalysisImpl(FP);
1532
1533 {
1534 PassManagerPrettyStackEntry X(FP, F);
1535 TimeRegion PassTimer(getPassTimer(FP));
1536
1537 LocalChanged |= FP->runOnFunction(F);
1538 }
1539
1540 Changed |= LocalChanged;
1541 if (LocalChanged)
1542 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1543 dumpPreservedSet(FP);
1544
1545 verifyPreservedAnalysis(FP);
1546 removeNotPreservedAnalysis(FP);
1547 recordAvailableAnalysis(FP);
1548 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1549 }
1550 return Changed;
1551 }
1552
1553 bool FPPassManager::runOnModule(Module &M) {
1554 bool Changed = false;
1555
1556 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1557 Changed |= runOnFunction(*I);
1558
1559 return Changed;
1560 }
1561
1562 bool FPPassManager::doInitialization(Module &M) {
1563 bool Changed = false;
1564
1565 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1566 Changed |= getContainedPass(Index)->doInitialization(M);
1567
1568 return Changed;
1569 }
1570
1571 bool FPPassManager::doFinalization(Module &M) {
1572 bool Changed = false;
1573
1574 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1575 Changed |= getContainedPass(Index)->doFinalization(M);
1576
1577 return Changed;
1578 }
1579
1580 //===----------------------------------------------------------------------===//
1581 // MPPassManager implementation
1582
1583 /// Execute all of the passes scheduled for execution by invoking
1584 /// runOnModule method. Keep track of whether any of the passes modifies
1585 /// the module, and if so, return true.
1586 bool
1587 MPPassManager::runOnModule(Module &M) {
1588 bool Changed = false;
1589
1590 // Initialize on-the-fly passes
1591 for (std::map::iterator
1592 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1593 I != E; ++I) {
1594 FunctionPassManagerImpl *FPP = I->second;
1595 Changed |= FPP->doInitialization(M);
1596 }
1597
1598 // Initialize module passes
1599 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1600 Changed |= getContainedPass(Index)->doInitialization(M);
1601
1602 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1603 ModulePass *MP = getContainedPass(Index);
1604 bool LocalChanged = false;
1605
1606 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1607 dumpRequiredSet(MP);
1608
1609 initializeAnalysisImpl(MP);
1610
1611 {
1612 PassManagerPrettyStackEntry X(MP, M);
1613 TimeRegion PassTimer(getPassTimer(MP));
1614
1615 LocalChanged |= MP->runOnModule(M);
1616 }
1617
1618 Changed |= LocalChanged;
1619 if (LocalChanged)
1620 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1621 M.getModuleIdentifier());
1622 dumpPreservedSet(MP);
1623
1624 verifyPreservedAnalysis(MP);
1625 removeNotPreservedAnalysis(MP);
1626 recordAvailableAnalysis(MP);
1627 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1628 }
1629
1630 // Finalize module passes
1631 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1632 Changed |= getContainedPass(Index)->doFinalization(M);
1633
1634 // Finalize on-the-fly passes
1635 for (std::map::iterator
1636 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1637 I != E; ++I) {
1638 FunctionPassManagerImpl *FPP = I->second;
1639 // We don't know when is the last time an on-the-fly pass is run,
1640 // so we need to releaseMemory / finalize here
1641 FPP->releaseMemoryOnTheFly();
1642 Changed |= FPP->doFinalization(M);
1643 }
1644
1645 return Changed;
1646 }
1647
1648 /// Add RequiredPass into list of lower level passes required by pass P.
1649 /// RequiredPass is run on the fly by Pass Manager when P requests it
1650 /// through getAnalysis interface.
1651 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1652 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1653 "Unable to handle Pass that requires lower level Analysis pass");
1654 assert((P->getPotentialPassManagerType() <
1655 RequiredPass->getPotentialPassManagerType()) &&
1656 "Unable to handle Pass that requires lower level Analysis pass");
1657
1658 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1659 if (!FPP) {
1660 FPP = new FunctionPassManagerImpl();
1661 // FPP is the top level manager.
1662 FPP->setTopLevelManager(FPP);
1663
1664 OnTheFlyManagers[P] = FPP;
1665 }
1666 FPP->add(RequiredPass);
1667
1668 // Register P as the last user of RequiredPass.
1669 if (RequiredPass) {
1670 SmallVector LU;
1671 LU.push_back(RequiredPass);
1672 FPP->setLastUser(LU, P);
1673 }
1674 }
1675
1676 /// Return function pass corresponding to PassInfo PI, that is
1677 /// required by module pass MP. Instantiate analysis pass, by using
1678 /// its runOnFunction() for function F.
1679 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1680 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1681 assert(FPP && "Unable to find on the fly pass");
1682
1683 FPP->releaseMemoryOnTheFly();
1684 FPP->run(F);
1685 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1686 }
1687
1688
1689 //===----------------------------------------------------------------------===//
1690 // PassManagerImpl implementation
1691
1692 //
1693 /// run - Execute all of the passes scheduled for execution. Keep track of
1694 /// whether any of the passes modifies the module, and if so, return true.
1695 bool PassManagerImpl::run(Module &M) {
1696 bool Changed = false;
1697 TimingInfo::createTheTimeInfo();
1698
1699 dumpArguments();
1700 dumpPasses();
1701
1702 SmallVectorImpl& IPV = getImmutablePasses();
1703 for (SmallVectorImpl::const_iterator I = IPV.begin(),
1704 E = IPV.end(); I != E; ++I) {
1705 Changed |= (*I)->doInitialization(M);
1706 }
1707
1708 initializeAllAnalysisInfo();
1709 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1710 Changed |= getContainedManager(Index)->runOnModule(M);
1711
1712 for (SmallVectorImpl::const_iterator I = IPV.begin(),
1713 E = IPV.end(); I != E; ++I) {
1714 Changed |= (*I)->doFinalization(M);
1715 }
1716
1717 return Changed;
1718 }
1719
1720 //===----------------------------------------------------------------------===//
1721 // PassManager implementation
1722
1723 /// Create new pass manager
1724 PassManager::PassManager() {
1725 PM = new PassManagerImpl();
1726 // PM is the top level manager
1727 PM->setTopLevelManager(PM);
1728 }
1729
1730 PassManager::~PassManager() {
1731 delete PM;
1732 }
1733
1734 /// add - Add a pass to the queue of passes to run. This passes ownership of
1735 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1736 /// will be destroyed as well, so there is no need to delete the pass. This
1737 /// implies that all passes MUST be allocated with 'new'.
1738 void PassManager::add(Pass *P) {
1739 PM->add(P);
1740 }
1741
1742 /// run - Execute all of the passes scheduled for execution. Keep track of
1743 /// whether any of the passes modifies the module, and if so, return true.
1744 bool PassManager::run(Module &M) {
1745 return PM->run(M);
1746 }
1747
1748 //===----------------------------------------------------------------------===//
1749 // TimingInfo implementation
1750
1751 bool llvm::TimePassesIsEnabled = false;
1752 static cl::opt
1753 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1754 cl::desc("Time each pass, printing elapsed time for each on exit"));
1755
1756 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1757 // a non null value (if the -time-passes option is enabled) or it leaves it
1758 // null. It may be called multiple times.
1759 void TimingInfo::createTheTimeInfo() {
1760 if (!TimePassesIsEnabled || TheTimeInfo) return;
1761
1762 // Constructed the first time this is called, iff -time-passes is enabled.
1763 // This guarantees that the object will be constructed before static globals,
1764 // thus it will be destroyed before them.
1765 static ManagedStatic TTI;
1766 TheTimeInfo = &*TTI;
1767 }
1768
1769 /// If TimingInfo is enabled then start pass timer.
1770 Timer *llvm::getPassTimer(Pass *P) {
1771 if (TheTimeInfo)
1772 return TheTimeInfo->getPassTimer(P);
1773 return 0;
1774 }
1775
1776 //===----------------------------------------------------------------------===//
1777 // PMStack implementation
1778 //
1779
1780 // Pop Pass Manager from the stack and clear its analysis info.
1781 void PMStack::pop() {
1782
1783 PMDataManager *Top = this->top();
1784 Top->initializeAnalysisInfo();
1785
1786 S.pop_back();
1787 }
1788
1789 // Push PM on the stack and set its top level manager.
1790 void PMStack::push(PMDataManager *PM) {
1791 assert(PM && "Unable to push. Pass Manager expected");
1792 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1793
1794 if (!this->empty()) {
1795 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1796 && "pushing bad pass manager to PMStack");
1797 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1798
1799 assert(TPM && "Unable to find top level manager");
1800 TPM->addIndirectPassManager(PM);
1801 PM->setTopLevelManager(TPM);
1802 PM->setDepth(this->top()->getDepth()+1);
1803 } else {
1804 assert((PM->getPassManagerType() == PMT_ModulePassManager
1805 || PM->getPassManagerType() == PMT_FunctionPassManager)
1806 && "pushing bad pass manager to PMStack");
1807 PM->setDepth(1);
1808 }
1809
1810 S.push_back(PM);
1811 }
1812
1813 // Dump content of the pass manager stack.
1814 void PMStack::dump() const {
1815 for (std::vector::const_iterator I = S.begin(),
1816 E = S.end(); I != E; ++I)
1817 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1818
1819 if (!S.empty())
1820 dbgs() << '\n';
1821 }
1822
1823 /// Find appropriate Module Pass Manager in the PM Stack and
1824 /// add self into that manager.
1825 void ModulePass::assignPassManager(PMStack &PMS,
1826 PassManagerType PreferredType) {
1827 // Find Module Pass Manager
1828 while (!PMS.empty()) {
1829 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1830 if (TopPMType == PreferredType)
1831 break; // We found desired pass manager
1832 else if (TopPMType > PMT_ModulePassManager)
1833 PMS.pop(); // Pop children pass managers
1834 else
1835 break;
1836 }
1837 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1838 PMS.top()->add(this);
1839 }
1840
1841 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1842 /// in the PM Stack and add self into that manager.
1843 void FunctionPass::assignPassManager(PMStack &PMS,
1844 PassManagerType PreferredType) {
1845
1846 // Find Function Pass Manager
1847 while (!PMS.empty()) {
1848 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1849 PMS.pop();
1850 else
1851 break;
1852 }
1853
1854 // Create new Function Pass Manager if needed.
1855 FPPassManager *FPP;
1856 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1857 FPP = (FPPassManager *)PMS.top();
1858 } else {
1859 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1860 PMDataManager *PMD = PMS.top();
1861
1862 // [1] Create new Function Pass Manager
1863 FPP = new FPPassManager();
1864 FPP->populateInheritedAnalysis(PMS);
1865
1866 // [2] Set up new manager's top level manager
1867 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1868 TPM->addIndirectPassManager(FPP);
1869
1870 // [3] Assign manager to manage this new manager. This may create
1871 // and push new managers into PMS
1872 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1873
1874 // [4] Push new manager into PMS
1875 PMS.push(FPP);
1876 }
1877
1878 // Assign FPP as the manager of this pass.
1879 FPP->add(this);
1880 }
1881
1882 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1883 /// in the PM Stack and add self into that manager.
1884 void BasicBlockPass::assignPassManager(PMStack &PMS,
1885 PassManagerType PreferredType) {
1886 BBPassManager *BBP;
1887
1888 // Basic Pass Manager is a leaf pass manager. It does not handle
1889 // any other pass manager.
1890 if (!PMS.empty() &&
1891 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1892 BBP = (BBPassManager *)PMS.top();
1893 } else {
1894 // If leaf manager is not Basic Block Pass manager then create new
1895 // basic Block Pass manager.
1896 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1897 PMDataManager *PMD = PMS.top();
1898
1899 // [1] Create new Basic Block Manager
1900 BBP = new BBPassManager();
1901
1902 // [2] Set up new manager's top level manager
1903 // Basic Block Pass Manager does not live by itself
1904 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1905 TPM->addIndirectPassManager(BBP);
1906
1907 // [3] Assign manager to manage this new manager. This may create
1908 // and push new managers into PMS
1909 BBP->assignPassManager(PMS, PreferredType);
1910
1911 // [4] Push new manager into PMS
1912 PMS.push(BBP);
1913 }
1914
1915 // Assign BBP as the manager of this pass.
1916 BBP->add(this);
1917 }
1918
1919 PassManagerBase::~PassManagerBase() {}
+0
-1912
lib/IR/PassManager.cpp less more
None //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the LLVM Pass Manager infrastructure.
10 //
11 //===----------------------------------------------------------------------===//
12
13
14 #include "llvm/PassManagers.h"
15 #include "llvm/Assembly/PrintModulePass.h"
16 #include "llvm/Assembly/Writer.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/Mutex.h"
24 #include "llvm/Support/PassNameParser.h"
25 #include "llvm/Support/Timer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include
28 #include
29 using namespace llvm;
30
31 // See PassManagers.h for Pass Manager infrastructure overview.
32
33 namespace llvm {
34
35 //===----------------------------------------------------------------------===//
36 // Pass debugging information. Often it is useful to find out what pass is
37 // running when a crash occurs in a utility. When this library is compiled with
38 // debugging on, a command line option (--debug-pass) is enabled that causes the
39 // pass name to be printed before it executes.
40 //
41
42 // Different debug levels that can be enabled...
43 enum PassDebugLevel {
44 Disabled, Arguments, Structure, Executions, Details
45 };
46
47 static cl::opt
48 PassDebugging("debug-pass", cl::Hidden,
49 cl::desc("Print PassManager debugging information"),
50 cl::values(
51 clEnumVal(Disabled , "disable debug output"),
52 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
53 clEnumVal(Structure , "print pass structure before run()"),
54 clEnumVal(Executions, "print pass name before it is executed"),
55 clEnumVal(Details , "print pass details when it is executed"),
56 clEnumValEnd));
57
58 typedef llvm::cl::list
59 PassOptionList;
60
61 // Print IR out before/after specified passes.
62 static PassOptionList
63 PrintBefore("print-before",
64 llvm::cl::desc("Print IR before specified passes"),
65 cl::Hidden);
66
67 static PassOptionList
68 PrintAfter("print-after",
69 llvm::cl::desc("Print IR after specified passes"),
70 cl::Hidden);
71
72 static cl::opt
73 PrintBeforeAll("print-before-all",
74 llvm::cl::desc("Print IR before each pass"),
75 cl::init(false));
76 static cl::opt
77 PrintAfterAll("print-after-all",
78 llvm::cl::desc("Print IR after each pass"),
79 cl::init(false));
80
81 /// This is a helper to determine whether to print IR before or
82 /// after a pass.
83
84 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
85 PassOptionList &PassesToPrint) {
86 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
87 const llvm::PassInfo *PassInf = PassesToPrint[i];
88 if (PassInf)
89 if (PassInf->getPassArgument() == PI->getPassArgument()) {
90 return true;
91 }
92 }
93 return false;
94 }
95
96 /// This is a utility to check whether a pass should have IR dumped
97 /// before it.
98 static bool ShouldPrintBeforePass(const PassInfo *PI) {
99 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
100 }
101
102 /// This is a utility to check whether a pass should have IR dumped
103 /// after it.
104 static bool ShouldPrintAfterPass(const PassInfo *PI) {
105 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
106 }
107
108 } // End of llvm namespace
109
110 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
111 /// or higher is specified.
112 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
113 return PassDebugging >= Executions;
114 }
115
116
117
118
119 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
120 if (V == 0 && M == 0)
121 OS << "Releasing pass '";
122 else
123 OS << "Running pass '";
124
125 OS << P->getPassName() << "'";
126
127 if (M) {
128 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
129 return;
130 }
131 if (V == 0) {
132 OS << '\n';
133 return;
134 }
135
136 OS << " on ";
137 if (isa(V))
138 OS << "function";
139 else if (isa(V))
140 OS << "basic block";
141 else
142 OS << "value";
143
144 OS << " '";
145 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
146 OS << "'\n";
147 }
148
149
150 namespace {
151
152 //===----------------------------------------------------------------------===//
153 // BBPassManager
154 //
155 /// BBPassManager manages BasicBlockPass. It batches all the
156 /// pass together and sequence them to process one basic block before
157 /// processing next basic block.
158 class BBPassManager : public PMDataManager, public FunctionPass {
159
160 public:
161 static char ID;
162 explicit BBPassManager()
163 : PMDataManager(), FunctionPass(ID) {}
164
165 /// Execute all of the passes scheduled for execution. Keep track of
166 /// whether any of the passes modifies the function, and if so, return true.
167 bool runOnFunction(Function &F);
168
169 /// Pass Manager itself does not invalidate any analysis info.
170 void getAnalysisUsage(AnalysisUsage &Info) const {
171 Info.setPreservesAll();
172 }
173
174 bool doInitialization(Module &M);
175 bool doInitialization(Function &F);
176 bool doFinalization(Module &M);
177 bool doFinalization(Function &F);
178
179 virtual PMDataManager *getAsPMDataManager() { return this; }
180 virtual Pass *getAsPass() { return this; }
181
182 virtual const char *getPassName() const {
183 return "BasicBlock Pass Manager";
184 }
185
186 // Print passes managed by this manager
187 void dumpPassStructure(unsigned Offset) {
188 llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
189 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
190 BasicBlockPass *BP = getContainedPass(Index);
191 BP->dumpPassStructure(Offset + 1);
192 dumpLastUses(BP, Offset+1);
193 }
194 }
195
196 BasicBlockPass *getContainedPass(unsigned N) {
197 assert(N < PassVector.size() && "Pass number out of range!");
198 BasicBlockPass *BP = static_cast(PassVector[N]);
199 return BP;
200 }
201
202 virtual PassManagerType getPassManagerType() const {
203 return PMT_BasicBlockPassManager;
204 }
205 };
206
207 char BBPassManager::ID = 0;
208 }
209
210 namespace llvm {
211
212 //===----------------------------------------------------------------------===//
213 // FunctionPassManagerImpl
214 //
215 /// FunctionPassManagerImpl manages FPPassManagers
216 class FunctionPassManagerImpl : public Pass,
217 public PMDataManager,
218 public PMTopLevelManager {
219 virtual void anchor();
220 private:
221 bool wasRun;
222 public:
223 static char ID;
224 explicit FunctionPassManagerImpl() :
225 Pass(PT_PassManager, ID), PMDataManager(),
226 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
227
228 /// add - Add a pass to the queue of passes to run. This passes ownership of
229 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
230 /// will be destroyed as well, so there is no need to delete the pass. This
231 /// implies that all passes MUST be allocated with 'new'.
232 void add(Pass *P) {
233 schedulePass(P);
234 }
235
236 /// createPrinterPass - Get a function printer pass.
237 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
238 return createPrintFunctionPass(Banner, &O);
239 }
240
241 // Prepare for running an on the fly pass, freeing memory if needed
242 // from a previous run.
243 void releaseMemoryOnTheFly();
244
245 /// run - Execute all of the passes scheduled for execution. Keep track of
246 /// whether any of the passes modifies the module, and if so, return true.
247 bool run(Function &F);
248
249 /// doInitialization - Run all of the initializers for the function passes.
250 ///
251 bool doInitialization(Module &M);
252
253 /// doFinalization - Run all of the finalizers for the function passes.
254 ///
255 bool doFinalization(Module &M);
256
257
258 virtual PMDataManager *getAsPMDataManager() { return this; }
259 virtual Pass *getAsPass() { return this; }
260 virtual PassManagerType getTopLevelPassManagerType() {
261 return PMT_FunctionPassManager;
262 }
263
264 /// Pass Manager itself does not invalidate any analysis info.
265 void getAnalysisUsage(AnalysisUsage &Info) const {
266 Info.setPreservesAll();
267 }
268
269 FPPassManager *getContainedManager(unsigned N) {
270 assert(N < PassManagers.size() && "Pass number out of range!");
271 FPPassManager *FP = static_cast(PassManagers[N]);
272 return FP;
273 }
274 };
275
276 void FunctionPassManagerImpl::anchor() {}
277
278 char FunctionPassManagerImpl::ID = 0;
279
280 //===----------------------------------------------------------------------===//
281 // MPPassManager
282 //
283 /// MPPassManager manages ModulePasses and function pass managers.
284 /// It batches all Module passes and function pass managers together and
285 /// sequences them to process one module.
286 class MPPassManager : public Pass, public PMDataManager {
287 public:
288 static char ID;
289 explicit MPPassManager() :
290 Pass(PT_PassManager, ID), PMDataManager() { }
291
292 // Delete on the fly managers.
293 virtual ~MPPassManager() {
294 for (std::map::iterator
295 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
296 I != E; ++I) {
297 FunctionPassManagerImpl *FPP = I->second;
298 delete FPP;
299 }
300 }
301
302 /// createPrinterPass - Get a module printer pass.
303 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
304 return createPrintModulePass(&O, false, Banner);
305 }
306
307 /// run - Execute all of the passes scheduled for execution. Keep track of
308 /// whether any of the passes modifies the module, and if so, return true.
309 bool runOnModule(Module &M);
310
311 using llvm::Pass::doInitialization;
312 using llvm::Pass::doFinalization;
313
314 /// doInitialization - Run all of the initializers for the module passes.
315 ///
316 bool doInitialization();
317
318 /// doFinalization - Run all of the finalizers for the module passes.
319 ///
320 bool doFinalization();
321
322 /// Pass Manager itself does not invalidate any analysis info.
323 void getAnalysisUsage(AnalysisUsage &Info) const {
324 Info.setPreservesAll();
325 }
326
327 /// Add RequiredPass into list of lower level passes required by pass P.
328 /// RequiredPass is run on the fly by Pass Manager when P requests it
329 /// through getAnalysis interface.
330 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
331
332 /// Return function pass corresponding to PassInfo PI, that is
333 /// required by module pass MP. Instantiate analysis pass, by using