Add support for plugins add passes to the default set of passes. The standard set...
[oota-llvm.git] / include / llvm / PassSupport.h
1 //===- llvm/PassSupport.h - Pass Support code -------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines stuff that is used to define and "use" Passes.  This file
11 // is automatically #included by Pass.h, so:
12 //
13 //           NO .CPP FILES SHOULD INCLUDE THIS FILE DIRECTLY
14 //
15 // Instead, #include Pass.h.
16 //
17 // This file defines Pass registration code and classes used for it.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_PASS_SUPPORT_H
22 #define LLVM_PASS_SUPPORT_H
23
24 #include "Pass.h"
25 #include "llvm/PassRegistry.h"
26 #include "llvm/InitializePasses.h"
27 #include "llvm/Support/Atomic.h"
28 #include <vector>
29
30 namespace llvm {
31
32   class PassManagerBase;
33
34 //===---------------------------------------------------------------------------
35 /// PassInfo class - An instance of this class exists for every pass known by
36 /// the system, and can be obtained from a live Pass by calling its
37 /// getPassInfo() method.  These objects are set up by the RegisterPass<>
38 /// template, defined below.
39 ///
40 class PassInfo {
41 public:
42   typedef Pass* (*NormalCtor_t)();
43
44 private:
45   const char      *const PassName;     // Nice name for Pass
46   const char      *const PassArgument; // Command Line argument to run this pass
47   const void *PassID;      
48   const bool IsCFGOnlyPass;            // Pass only looks at the CFG.
49   const bool IsAnalysis;               // True if an analysis pass.
50   const bool IsAnalysisGroup;          // True if an analysis group.
51   std::vector<const PassInfo*> ItfImpl;// Interfaces implemented by this pass
52
53   NormalCtor_t NormalCtor;
54
55 public:
56   /// PassInfo ctor - Do not call this directly, this should only be invoked
57   /// through RegisterPass.
58   PassInfo(const char *name, const char *arg, const void *pi,
59            NormalCtor_t normal, bool isCFGOnly, bool is_analysis)
60     : PassName(name), PassArgument(arg), PassID(pi), 
61       IsCFGOnlyPass(isCFGOnly), 
62       IsAnalysis(is_analysis), IsAnalysisGroup(false), NormalCtor(normal) { }
63   /// PassInfo ctor - Do not call this directly, this should only be invoked
64   /// through RegisterPass. This version is for use by analysis groups; it
65   /// does not auto-register the pass.
66   PassInfo(const char *name, const void *pi)
67     : PassName(name), PassArgument(""), PassID(pi), 
68       IsCFGOnlyPass(false), 
69       IsAnalysis(false), IsAnalysisGroup(true), NormalCtor(0) { }
70
71   /// getPassName - Return the friendly name for the pass, never returns null
72   ///
73   const char *getPassName() const { return PassName; }
74
75   /// getPassArgument - Return the command line option that may be passed to
76   /// 'opt' that will cause this pass to be run.  This will return null if there
77   /// is no argument.
78   ///
79   const char *getPassArgument() const { return PassArgument; }
80
81   /// getTypeInfo - Return the id object for the pass...
82   /// TODO : Rename
83   const void *getTypeInfo() const { return PassID; }
84
85   /// Return true if this PassID implements the specified ID pointer.
86   bool isPassID(const void *IDPtr) const {
87     return PassID == IDPtr;
88   }
89   
90   /// isAnalysisGroup - Return true if this is an analysis group, not a normal
91   /// pass.
92   ///
93   bool isAnalysisGroup() const { return IsAnalysisGroup; }
94   bool isAnalysis() const { return IsAnalysis; }
95
96   /// isCFGOnlyPass - return true if this pass only looks at the CFG for the
97   /// function.
98   bool isCFGOnlyPass() const { return IsCFGOnlyPass; }
99   
100   /// getNormalCtor - Return a pointer to a function, that when called, creates
101   /// an instance of the pass and returns it.  This pointer may be null if there
102   /// is no default constructor for the pass.
103   ///
104   NormalCtor_t getNormalCtor() const {
105     return NormalCtor;
106   }
107   void setNormalCtor(NormalCtor_t Ctor) {
108     NormalCtor = Ctor;
109   }
110
111   /// createPass() - Use this method to create an instance of this pass.
112   Pass *createPass() const;
113
114   /// addInterfaceImplemented - This method is called when this pass is
115   /// registered as a member of an analysis group with the RegisterAnalysisGroup
116   /// template.
117   ///
118   void addInterfaceImplemented(const PassInfo *ItfPI) {
119     ItfImpl.push_back(ItfPI);
120   }
121
122   /// getInterfacesImplemented - Return a list of all of the analysis group
123   /// interfaces implemented by this pass.
124   ///
125   const std::vector<const PassInfo*> &getInterfacesImplemented() const {
126     return ItfImpl;
127   }
128
129 private:
130   void operator=(const PassInfo &); // do not implement
131   PassInfo(const PassInfo &);       // do not implement
132 };
133
134 #define CALL_ONCE_INITIALIZATION(function) \
135   static volatile sys::cas_flag initialized = 0; \
136   sys::cas_flag old_val = sys::CompareAndSwap(&initialized, 1, 0); \
137   if (old_val == 0) { \
138     function(Registry); \
139     sys::MemoryFence(); \
140     initialized = 2; \
141   } else { \
142     sys::cas_flag tmp = initialized; \
143     sys::MemoryFence(); \
144     while (tmp != 2) { \
145       tmp = initialized; \
146       sys::MemoryFence(); \
147     } \
148   }
149
150 #define INITIALIZE_PASS(passName, arg, name, cfg, analysis) \
151   static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
152     PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
153       PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
154     Registry.registerPass(*PI, true); \
155     return PI; \
156   } \
157   void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
158     CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
159   }
160
161 #define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis) \
162   static void* initialize##passName##PassOnce(PassRegistry &Registry) {
163
164 #define INITIALIZE_PASS_DEPENDENCY(depName) \
165     initialize##depName##Pass(Registry);
166 #define INITIALIZE_AG_DEPENDENCY(depName) \
167     initialize##depName##AnalysisGroup(Registry);
168
169 #define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis) \
170     PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
171       PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
172     Registry.registerPass(*PI, true); \
173     return PI; \
174   } \
175   void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
176     CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
177   }
178
179 template<typename PassName>
180 Pass *callDefaultCtor() { return new PassName(); }
181
182 //===---------------------------------------------------------------------------
183 /// RegisterPass<t> template - This template class is used to notify the system
184 /// that a Pass is available for use, and registers it into the internal
185 /// database maintained by the PassManager.  Unless this template is used, opt,
186 /// for example will not be able to see the pass and attempts to create the pass
187 /// will fail. This template is used in the follow manner (at global scope, in
188 /// your .cpp file):
189 ///
190 /// static RegisterPass<YourPassClassName> tmp("passopt", "My Pass Name");
191 ///
192 /// This statement will cause your pass to be created by calling the default
193 /// constructor exposed by the pass.  If you have a different constructor that
194 /// must be called, create a global constructor function (which takes the
195 /// arguments you need and returns a Pass*) and register your pass like this:
196 ///
197 /// static RegisterPass<PassClassName> tmp("passopt", "My Name");
198 ///
199 template<typename passName>
200 struct RegisterPass : public PassInfo {
201
202   // Register Pass using default constructor...
203   RegisterPass(const char *PassArg, const char *Name, bool CFGOnly = false,
204                bool is_analysis = false)
205     : PassInfo(Name, PassArg, &passName::ID,
206                PassInfo::NormalCtor_t(callDefaultCtor<passName>),
207                CFGOnly, is_analysis) {
208     PassRegistry::getPassRegistry()->registerPass(*this);
209   }
210 };
211
212   /// Unique identifiers for the default standard passes.  The addresses of
213   /// these symbols are used to uniquely identify passes from the default list.
214   namespace DefaultStandardPasses {
215     extern unsigned char AggressiveDCEID;
216     extern unsigned char ArgumentPromotionID;
217     extern unsigned char BasicAliasAnalysisID;
218     extern unsigned char CFGSimplificationID;
219     extern unsigned char ConstantMergeID;
220     extern unsigned char CorrelatedValuePropagationID;
221     extern unsigned char DeadArgEliminationID;
222     extern unsigned char DeadStoreEliminationID;
223     extern unsigned char DeadTypeEliminationID;
224     extern unsigned char EarlyCSEID;
225     extern unsigned char FunctionAttrsID;
226     extern unsigned char FunctionInliningID;
227     extern unsigned char GVNID;
228     extern unsigned char GlobalDCEID;
229     extern unsigned char GlobalOptimizerID;
230     extern unsigned char GlobalsModRefID;
231     extern unsigned char IPSCCPID;
232     extern unsigned char IndVarSimplifyID;
233     extern unsigned char InlinerPlaceholderID;
234     extern unsigned char InstructionCombiningID;
235     extern unsigned char JumpThreadingID;
236     extern unsigned char LICMID;
237     extern unsigned char LoopDeletionID;
238     extern unsigned char LoopIdiomID;
239     extern unsigned char LoopRotateID;
240     extern unsigned char LoopUnrollID;
241     extern unsigned char LoopUnswitchID;
242     extern unsigned char MemCpyOptID;
243     extern unsigned char PruneEHID;
244     extern unsigned char ReassociateID;
245     extern unsigned char SCCPID;
246     extern unsigned char ScalarReplAggregatesID;
247     extern unsigned char SimplifyLibCallsID;
248     extern unsigned char StripDeadPrototypesID;
249     extern unsigned char TailCallEliminationID;
250     extern unsigned char TypeBasedAliasAnalysisID;
251   }
252
253
254 class RegisterStandardPass;
255 /// RegisterStandardPass - Registers a pass as a member of a standard set.  
256 class StandardPass {
257   friend class RegisterStandardPassLists;
258   public:
259   /// Predefined standard sets of passes
260   enum StandardSet {
261     AliasAnalysis,
262     Function,
263     Module,
264     LTO
265   };
266   /// Flags to specify whether a pass should be enabled.  Passes registered
267   /// with the standard sets may specify a minimum optimization level and one
268   /// or more flags that must be set when constructing the set for the pass to
269   /// be used.
270   enum OptimizationFlags {
271     /// Optimize for size was requested.
272     OptimizeSize = 1<<0,
273     /// Allow passes which may make global module changes.
274     UnitAtATime = 1<<1,
275     /// UnrollLoops - Allow loop unrolling.
276     UnrollLoops = 1<<2,
277     /// Allow library calls to be simplified.
278     SimplifyLibCalls = 1<<3,
279     /// Whether the module may have code using exceptions.
280     HaveExceptions = 1<<4,
281     // Run an inliner pass as part of this set.
282     RunInliner = 1<<5
283   };
284   enum OptimizationFlagComponents {
285     /// The low bits are used to store the optimization level.  When requesting
286     /// passes, this should store the requested optimisation level.  When
287     /// setting passes, this should set the minimum optimization level at which
288     /// the pass will run.
289     OptimizationLevelMask = 0xf,
290     /// The maximum optimisation level at which the pass is run.
291     MaxOptimizationLevelMask = 0xf0,
292     // Flags that must be set
293     RequiredFlagMask = 0xff00,
294     // Flags that may not be set.
295     DisallowedFlagMask = 0xff0000,
296     MaxOptimizationLevelShift = 4,
297     RequiredFlagShift = 8,
298     DisallowedFlagShift = 16
299   };
300   /// Returns the optimisation level from a set of flags.
301   static unsigned OptimizationLevel(unsigned flags) {
302       return flags & OptimizationLevelMask;
303   }
304   /// Returns the maximum optimization level for this set of flags
305   static unsigned MaxOptimizationLevel(unsigned flags) {
306       return (flags & MaxOptimizationLevelMask) >> 4;
307   }
308   /// Constructs a set of flags from the specified minimum and maximum
309   /// optimisation level
310   static unsigned OptimizationFlags(unsigned minLevel=0, unsigned maxLevel=0xf,
311                                     unsigned requiredFlags=0,
312                                     unsigned disallowedFlags=0) {
313     return ((minLevel & OptimizationLevelMask) |
314             ((maxLevel<<MaxOptimizationLevelShift) & MaxOptimizationLevelMask)
315             | ((requiredFlags<<RequiredFlagShift) & RequiredFlagMask)
316             | ((disallowedFlags<<DisallowedFlagShift) & DisallowedFlagMask));
317   }
318   /// Returns the flags that must be set for this to match
319   static unsigned RequiredFlags(unsigned flags) {
320       return (flags & RequiredFlagMask) >> RequiredFlagShift;
321   }
322   /// Returns the flags that must not be set for this to match
323   static unsigned DisallowedFlags(unsigned flags) {
324       return (flags & DisallowedFlagMask) >> RequiredFlagShift;
325   }
326   /// Register a standard pass in the specified set.  If flags is non-zero,
327   /// then the pass will only be returned when the specified flags are set.
328   template<typename passName>
329   class RegisterStandardPass {
330     RegisterStandardPass(StandardSet set, unsigned char *runBefore=0,
331                          unsigned flags=0, unsigned char *ID=0) {
332       // Use the pass's ID if one is not specified
333       RegisterDefaultPass(PassInfo::NormalCtor_t(callDefaultCtor<passName>),
334                           ID ? ID : &passName::ID, runBefore, set, flags);
335     };
336   };
337   /// Adds the passes from the specified set to a pass manager.
338   static void AddPassesFromSet(PassManagerBase *PM,
339                                StandardSet Set,
340                                unsigned Flags=0,
341                                bool VerifyEach=false,
342                                Pass *Inliner=0);
343   private:
344   /// Registers the default passes.  This is set by RegisterStandardPassLists
345   /// and is called lazily.
346   static void (*RegisterDefaultPasses)(void);
347   /// Registers the pass
348   static void RegisterDefaultPass(PassInfo::NormalCtor_t constructor,
349                                   unsigned char *newPass,
350                                   unsigned char *oldPass,
351                                   StandardSet set,
352                                   unsigned flags=0);
353 };
354
355
356 /// RegisterAnalysisGroup - Register a Pass as a member of an analysis _group_.
357 /// Analysis groups are used to define an interface (which need not derive from
358 /// Pass) that is required by passes to do their job.  Analysis Groups differ
359 /// from normal analyses because any available implementation of the group will
360 /// be used if it is available.
361 ///
362 /// If no analysis implementing the interface is available, a default
363 /// implementation is created and added.  A pass registers itself as the default
364 /// implementation by specifying 'true' as the second template argument of this
365 /// class.
366 ///
367 /// In addition to registering itself as an analysis group member, a pass must
368 /// register itself normally as well.  Passes may be members of multiple groups
369 /// and may still be "required" specifically by name.
370 ///
371 /// The actual interface may also be registered as well (by not specifying the
372 /// second template argument).  The interface should be registered to associate
373 /// a nice name with the interface.
374 ///
375 class RegisterAGBase : public PassInfo {
376 public:
377   RegisterAGBase(const char *Name,
378                  const void *InterfaceID,
379                  const void *PassID = 0,
380                  bool isDefault = false);
381 };
382
383 template<typename Interface, bool Default = false>
384 struct RegisterAnalysisGroup : public RegisterAGBase {
385   explicit RegisterAnalysisGroup(PassInfo &RPB)
386     : RegisterAGBase(RPB.getPassName(),
387                      &Interface::ID, RPB.getTypeInfo(),
388                      Default) {
389   }
390
391   explicit RegisterAnalysisGroup(const char *Name)
392     : RegisterAGBase(Name, &Interface::ID) {
393   }
394 };
395
396 #define INITIALIZE_ANALYSIS_GROUP(agName, name, defaultPass) \
397   static void* initialize##agName##AnalysisGroupOnce(PassRegistry &Registry) { \
398     initialize##defaultPass##Pass(Registry); \
399     PassInfo *AI = new PassInfo(name, & agName :: ID); \
400     Registry.registerAnalysisGroup(& agName ::ID, 0, *AI, false, true); \
401     return AI; \
402   } \
403   void llvm::initialize##agName##AnalysisGroup(PassRegistry &Registry) { \
404     CALL_ONCE_INITIALIZATION(initialize##agName##AnalysisGroupOnce) \
405   }
406
407
408 #define INITIALIZE_AG_PASS(passName, agName, arg, name, cfg, analysis, def) \
409   static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
410     if (!def) initialize##agName##AnalysisGroup(Registry); \
411     PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
412       PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
413     Registry.registerPass(*PI, true); \
414     \
415     PassInfo *AI = new PassInfo(name, & agName :: ID); \
416     Registry.registerAnalysisGroup(& agName ::ID, & passName ::ID, \
417                                    *AI, def, true); \
418     return AI; \
419   } \
420   void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
421     CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
422   }
423
424
425 #define INITIALIZE_AG_PASS_BEGIN(passName, agName, arg, n, cfg, analysis, def) \
426   static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
427     if (!def) initialize##agName##AnalysisGroup(Registry);
428
429 #define INITIALIZE_AG_PASS_END(passName, agName, arg, n, cfg, analysis, def) \
430     PassInfo *PI = new PassInfo(n, arg, & passName ::ID, \
431       PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
432     Registry.registerPass(*PI, true); \
433     \
434     PassInfo *AI = new PassInfo(n, & agName :: ID); \
435     Registry.registerAnalysisGroup(& agName ::ID, & passName ::ID, \
436                                    *AI, def, true); \
437     return AI; \
438   } \
439   void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
440     CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
441   }
442
443 //===---------------------------------------------------------------------------
444 /// PassRegistrationListener class - This class is meant to be derived from by
445 /// clients that are interested in which passes get registered and unregistered
446 /// at runtime (which can be because of the RegisterPass constructors being run
447 /// as the program starts up, or may be because a shared object just got
448 /// loaded).  Deriving from the PassRegistationListener class automatically
449 /// registers your object to receive callbacks indicating when passes are loaded
450 /// and removed.
451 ///
452 struct PassRegistrationListener {
453
454   /// PassRegistrationListener ctor - Add the current object to the list of
455   /// PassRegistrationListeners...
456   PassRegistrationListener();
457
458   /// dtor - Remove object from list of listeners...
459   ///
460   virtual ~PassRegistrationListener();
461
462   /// Callback functions - These functions are invoked whenever a pass is loaded
463   /// or removed from the current executable.
464   ///
465   virtual void passRegistered(const PassInfo *) {}
466
467   /// enumeratePasses - Iterate over the registered passes, calling the
468   /// passEnumerate callback on each PassInfo object.
469   ///
470   void enumeratePasses();
471
472   /// passEnumerate - Callback function invoked when someone calls
473   /// enumeratePasses on this PassRegistrationListener object.
474   ///
475   virtual void passEnumerate(const PassInfo *) {}
476 };
477
478
479 } // End llvm namespace
480
481 #endif