Home | History | Annotate | Download | only in CodeGen
      1 //===-- Passes.h - Target independent code generation passes ----*- 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 interfaces to access the target independent code generation
     11 // passes provided by the LLVM backend.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_CODEGEN_PASSES_H
     16 #define LLVM_CODEGEN_PASSES_H
     17 
     18 #include "llvm/Pass.h"
     19 #include "llvm/Target/TargetMachine.h"
     20 #include <string>
     21 
     22 namespace llvm {
     23 
     24   class FunctionPass;
     25   class MachineFunctionPass;
     26   class PassInfo;
     27   class PassManagerBase;
     28   class TargetLoweringBase;
     29   class TargetLowering;
     30   class TargetRegisterClass;
     31   class raw_ostream;
     32 }
     33 
     34 namespace llvm {
     35 
     36 class PassConfigImpl;
     37 
     38 /// Discriminated union of Pass ID types.
     39 ///
     40 /// The PassConfig API prefers dealing with IDs because they are safer and more
     41 /// efficient. IDs decouple configuration from instantiation. This way, when a
     42 /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to
     43 /// refer to a Pass pointer after adding it to a pass manager, which deletes
     44 /// redundant pass instances.
     45 ///
     46 /// However, it is convient to directly instantiate target passes with
     47 /// non-default ctors. These often don't have a registered PassInfo. Rather than
     48 /// force all target passes to implement the pass registry boilerplate, allow
     49 /// the PassConfig API to handle either type.
     50 ///
     51 /// AnalysisID is sadly char*, so PointerIntPair won't work.
     52 class IdentifyingPassPtr {
     53   union {
     54     AnalysisID ID;
     55     Pass *P;
     56   };
     57   bool IsInstance;
     58 public:
     59   IdentifyingPassPtr() : P(0), IsInstance(false) {}
     60   IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr), IsInstance(false) {}
     61   IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
     62 
     63   bool isValid() const { return P; }
     64   bool isInstance() const { return IsInstance; }
     65 
     66   AnalysisID getID() const {
     67     assert(!IsInstance && "Not a Pass ID");
     68     return ID;
     69   }
     70   Pass *getInstance() const {
     71     assert(IsInstance && "Not a Pass Instance");
     72     return P;
     73   }
     74 };
     75 
     76 template <> struct isPodLike<IdentifyingPassPtr> {
     77   static const bool value = true;
     78 };
     79 
     80 /// Target-Independent Code Generator Pass Configuration Options.
     81 ///
     82 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options
     83 /// to the internals of other CodeGen passes.
     84 class TargetPassConfig : public ImmutablePass {
     85 public:
     86   /// Pseudo Pass IDs. These are defined within TargetPassConfig because they
     87   /// are unregistered pass IDs. They are only useful for use with
     88   /// TargetPassConfig APIs to identify multiple occurrences of the same pass.
     89   ///
     90 
     91   /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
     92   /// during codegen, on SSA form.
     93   static char EarlyTailDuplicateID;
     94 
     95   /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
     96   /// optimization after regalloc.
     97   static char PostRAMachineLICMID;
     98 
     99 private:
    100   PassManagerBase *PM;
    101   AnalysisID StartAfter;
    102   AnalysisID StopAfter;
    103   bool Started;
    104   bool Stopped;
    105 
    106 protected:
    107   TargetMachine *TM;
    108   PassConfigImpl *Impl; // Internal data structures
    109   bool Initialized;     // Flagged after all passes are configured.
    110 
    111   // Target Pass Options
    112   // Targets provide a default setting, user flags override.
    113   //
    114   bool DisableVerify;
    115 
    116   /// Default setting for -enable-tail-merge on this target.
    117   bool EnableTailMerge;
    118 
    119 public:
    120   TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
    121   // Dummy constructor.
    122   TargetPassConfig();
    123 
    124   virtual ~TargetPassConfig();
    125 
    126   static char ID;
    127 
    128   /// Get the right type of TargetMachine for this target.
    129   template<typename TMC> TMC &getTM() const {
    130     return *static_cast<TMC*>(TM);
    131   }
    132 
    133   const TargetLowering *getTargetLowering() const {
    134     return TM->getTargetLowering();
    135   }
    136 
    137   //
    138   void setInitialized() { Initialized = true; }
    139 
    140   CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
    141 
    142   /// setStartStopPasses - Set the StartAfter and StopAfter passes to allow
    143   /// running only a portion of the normal code-gen pass sequence.  If the
    144   /// Start pass ID is zero, then compilation will begin at the normal point;
    145   /// otherwise, clear the Started flag to indicate that passes should not be
    146   /// added until the starting pass is seen.  If the Stop pass ID is zero,
    147   /// then compilation will continue to the end.
    148   void setStartStopPasses(AnalysisID Start, AnalysisID Stop) {
    149     StartAfter = Start;
    150     StopAfter = Stop;
    151     Started = (StartAfter == 0);
    152   }
    153 
    154   void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
    155 
    156   bool getEnableTailMerge() const { return EnableTailMerge; }
    157   void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
    158 
    159   /// Allow the target to override a specific pass without overriding the pass
    160   /// pipeline. When passes are added to the standard pipeline at the
    161   /// point where StandardID is expected, add TargetID in its place.
    162   void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
    163 
    164   /// Insert InsertedPassID pass after TargetPassID pass.
    165   void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
    166 
    167   /// Allow the target to enable a specific standard pass by default.
    168   void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
    169 
    170   /// Allow the target to disable a specific standard pass by default.
    171   void disablePass(AnalysisID PassID) {
    172     substitutePass(PassID, IdentifyingPassPtr());
    173   }
    174 
    175   /// Return the pass substituted for StandardID by the target.
    176   /// If no substitution exists, return StandardID.
    177   IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
    178 
    179   /// Return true if the optimized regalloc pipeline is enabled.
    180   bool getOptimizeRegAlloc() const;
    181 
    182   /// Add common target configurable passes that perform LLVM IR to IR
    183   /// transforms following machine independent optimization.
    184   virtual void addIRPasses();
    185 
    186   /// Add passes to lower exception handling for the code generator.
    187   void addPassesToHandleExceptions();
    188 
    189   /// Add pass to prepare the LLVM IR for code generation. This should be done
    190   /// before exception handling preparation passes.
    191   virtual void addCodeGenPrepare();
    192 
    193   /// Add common passes that perform LLVM IR to IR transforms in preparation for
    194   /// instruction selection.
    195   virtual void addISelPrepare();
    196 
    197   /// addInstSelector - This method should install an instruction selector pass,
    198   /// which converts from LLVM code to machine instructions.
    199   virtual bool addInstSelector() {
    200     return true;
    201   }
    202 
    203   /// Add the complete, standard set of LLVM CodeGen passes.
    204   /// Fully developed targets will not generally override this.
    205   virtual void addMachinePasses();
    206 
    207 protected:
    208   // Helper to verify the analysis is really immutable.
    209   void setOpt(bool &Opt, bool Val);
    210 
    211   /// Methods with trivial inline returns are convenient points in the common
    212   /// codegen pass pipeline where targets may insert passes. Methods with
    213   /// out-of-line standard implementations are major CodeGen stages called by
    214   /// addMachinePasses. Some targets may override major stages when inserting
    215   /// passes is insufficient, but maintaining overriden stages is more work.
    216   ///
    217 
    218   /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
    219   /// passes (which are run just before instruction selector).
    220   virtual bool addPreISel() {
    221     return true;
    222   }
    223 
    224   /// addMachineSSAOptimization - Add standard passes that optimize machine
    225   /// instructions in SSA form.
    226   virtual void addMachineSSAOptimization();
    227 
    228   /// Add passes that optimize instruction level parallelism for out-of-order
    229   /// targets. These passes are run while the machine code is still in SSA
    230   /// form, so they can use MachineTraceMetrics to control their heuristics.
    231   ///
    232   /// All passes added here should preserve the MachineDominatorTree,
    233   /// MachineLoopInfo, and MachineTraceMetrics analyses.
    234   virtual bool addILPOpts() {
    235     return false;
    236   }
    237 
    238   /// addPreRegAlloc - This method may be implemented by targets that want to
    239   /// run passes immediately before register allocation. This should return
    240   /// true if -print-machineinstrs should print after these passes.
    241   virtual bool addPreRegAlloc() {
    242     return false;
    243   }
    244 
    245   /// createTargetRegisterAllocator - Create the register allocator pass for
    246   /// this target at the current optimization level.
    247   virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
    248 
    249   /// addFastRegAlloc - Add the minimum set of target-independent passes that
    250   /// are required for fast register allocation.
    251   virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
    252 
    253   /// addOptimizedRegAlloc - Add passes related to register allocation.
    254   /// LLVMTargetMachine provides standard regalloc passes for most targets.
    255   virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
    256 
    257   /// addPreRewrite - Add passes to the optimized register allocation pipeline
    258   /// after register allocation is complete, but before virtual registers are
    259   /// rewritten to physical registers.
    260   ///
    261   /// These passes must preserve VirtRegMap and LiveIntervals, and when running
    262   /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
    263   /// When these passes run, VirtRegMap contains legal physreg assignments for
    264   /// all virtual registers.
    265   virtual bool addPreRewrite() {
    266     return false;
    267   }
    268 
    269   /// addPostRegAlloc - This method may be implemented by targets that want to
    270   /// run passes after register allocation pass pipeline but before
    271   /// prolog-epilog insertion.  This should return true if -print-machineinstrs
    272   /// should print after these passes.
    273   virtual bool addPostRegAlloc() {
    274     return false;
    275   }
    276 
    277   /// Add passes that optimize machine instructions after register allocation.
    278   virtual void addMachineLateOptimization();
    279 
    280   /// addPreSched2 - This method may be implemented by targets that want to
    281   /// run passes after prolog-epilog insertion and before the second instruction
    282   /// scheduling pass.  This should return true if -print-machineinstrs should
    283   /// print after these passes.
    284   virtual bool addPreSched2() {
    285     return false;
    286   }
    287 
    288   /// addGCPasses - Add late codegen passes that analyze code for garbage
    289   /// collection. This should return true if GC info should be printed after
    290   /// these passes.
    291   virtual bool addGCPasses();
    292 
    293   /// Add standard basic block placement passes.
    294   virtual void addBlockPlacement();
    295 
    296   /// addPreEmitPass - This pass may be implemented by targets that want to run
    297   /// passes immediately before machine code is emitted.  This should return
    298   /// true if -print-machineinstrs should print out the code after the passes.
    299   virtual bool addPreEmitPass() {
    300     return false;
    301   }
    302 
    303   /// Utilities for targets to add passes to the pass manager.
    304   ///
    305 
    306   /// Add a CodeGen pass at this point in the pipeline after checking overrides.
    307   /// Return the pass that was added, or zero if no pass was added.
    308   AnalysisID addPass(AnalysisID PassID);
    309 
    310   /// Add a pass to the PassManager if that pass is supposed to be run, as
    311   /// determined by the StartAfter and StopAfter options. Takes ownership of the
    312   /// pass.
    313   void addPass(Pass *P);
    314 
    315   /// addMachinePasses helper to create the target-selected or overriden
    316   /// regalloc pass.
    317   FunctionPass *createRegAllocPass(bool Optimized);
    318 
    319   /// printAndVerify - Add a pass to dump then verify the machine function, if
    320   /// those steps are enabled.
    321   ///
    322   void printAndVerify(const char *Banner);
    323 };
    324 } // namespace llvm
    325 
    326 /// List of target independent CodeGen pass IDs.
    327 namespace llvm {
    328   /// \brief Create a basic TargetTransformInfo analysis pass.
    329   ///
    330   /// This pass implements the target transform info analysis using the target
    331   /// independent information available to the LLVM code generator.
    332   ImmutablePass *
    333   createBasicTargetTransformInfoPass(const TargetMachine *TM);
    334 
    335   /// createUnreachableBlockEliminationPass - The LLVM code generator does not
    336   /// work well with unreachable basic blocks (what live ranges make sense for a
    337   /// block that cannot be reached?).  As such, a code generator should either
    338   /// not instruction select unreachable blocks, or run this pass as its
    339   /// last LLVM modifying pass to clean up blocks that are not reachable from
    340   /// the entry block.
    341   FunctionPass *createUnreachableBlockEliminationPass();
    342 
    343   /// MachineFunctionPrinter pass - This pass prints out the machine function to
    344   /// the given stream as a debugging tool.
    345   MachineFunctionPass *
    346   createMachineFunctionPrinterPass(raw_ostream &OS,
    347                                    const std::string &Banner ="");
    348 
    349   /// MachineLoopInfo - This pass is a loop analysis pass.
    350   extern char &MachineLoopInfoID;
    351 
    352   /// MachineDominators - This pass is a machine dominators analysis pass.
    353   extern char &MachineDominatorsID;
    354 
    355   /// EdgeBundles analysis - Bundle machine CFG edges.
    356   extern char &EdgeBundlesID;
    357 
    358   /// LiveVariables pass - This pass computes the set of blocks in which each
    359   /// variable is life and sets machine operand kill flags.
    360   extern char &LiveVariablesID;
    361 
    362   /// PHIElimination - This pass eliminates machine instruction PHI nodes
    363   /// by inserting copy instructions.  This destroys SSA information, but is the
    364   /// desired input for some register allocators.  This pass is "required" by
    365   /// these register allocator like this: AU.addRequiredID(PHIEliminationID);
    366   extern char &PHIEliminationID;
    367 
    368   /// StrongPHIElimination - This pass eliminates machine instruction PHI
    369   /// nodes by inserting copy instructions.  This destroys SSA information, but
    370   /// is the desired input for some register allocators.  This pass is
    371   /// "required" by these register allocator like this:
    372   ///    AU.addRequiredID(PHIEliminationID);
    373   ///  This pass is still in development
    374   extern char &StrongPHIEliminationID;
    375 
    376   /// LiveIntervals - This analysis keeps track of the live ranges of virtual
    377   /// and physical registers.
    378   extern char &LiveIntervalsID;
    379 
    380   /// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
    381   extern char &LiveStacksID;
    382 
    383   /// TwoAddressInstruction - This pass reduces two-address instructions to
    384   /// use two operands. This destroys SSA information but it is desired by
    385   /// register allocators.
    386   extern char &TwoAddressInstructionPassID;
    387 
    388   /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
    389   extern char &ProcessImplicitDefsID;
    390 
    391   /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
    392   extern char &RegisterCoalescerID;
    393 
    394   /// MachineScheduler - This pass schedules machine instructions.
    395   extern char &MachineSchedulerID;
    396 
    397   /// SpillPlacement analysis. Suggest optimal placement of spill code between
    398   /// basic blocks.
    399   extern char &SpillPlacementID;
    400 
    401   /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
    402   /// assigned in VirtRegMap.
    403   extern char &VirtRegRewriterID;
    404 
    405   /// UnreachableMachineBlockElimination - This pass removes unreachable
    406   /// machine basic blocks.
    407   extern char &UnreachableMachineBlockElimID;
    408 
    409   /// DeadMachineInstructionElim - This pass removes dead machine instructions.
    410   extern char &DeadMachineInstructionElimID;
    411 
    412   /// FastRegisterAllocation Pass - This pass register allocates as fast as
    413   /// possible. It is best suited for debug code where live ranges are short.
    414   ///
    415   FunctionPass *createFastRegisterAllocator();
    416 
    417   /// BasicRegisterAllocation Pass - This pass implements a degenerate global
    418   /// register allocator using the basic regalloc framework.
    419   ///
    420   FunctionPass *createBasicRegisterAllocator();
    421 
    422   /// Greedy register allocation pass - This pass implements a global register
    423   /// allocator for optimized builds.
    424   ///
    425   FunctionPass *createGreedyRegisterAllocator();
    426 
    427   /// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
    428   /// Quadratic Prograaming (PBQP) based register allocator.
    429   ///
    430   FunctionPass *createDefaultPBQPRegisterAllocator();
    431 
    432   /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
    433   /// and eliminates abstract frame references.
    434   extern char &PrologEpilogCodeInserterID;
    435 
    436   /// ExpandPostRAPseudos - This pass expands pseudo instructions after
    437   /// register allocation.
    438   extern char &ExpandPostRAPseudosID;
    439 
    440   /// createPostRAScheduler - This pass performs post register allocation
    441   /// scheduling.
    442   extern char &PostRASchedulerID;
    443 
    444   /// BranchFolding - This pass performs machine code CFG based
    445   /// optimizations to delete branches to branches, eliminate branches to
    446   /// successor blocks (creating fall throughs), and eliminating branches over
    447   /// branches.
    448   extern char &BranchFolderPassID;
    449 
    450   /// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
    451   extern char &MachineFunctionPrinterPassID;
    452 
    453   /// TailDuplicate - Duplicate blocks with unconditional branches
    454   /// into tails of their predecessors.
    455   extern char &TailDuplicateID;
    456 
    457   /// MachineTraceMetrics - This pass computes critical path and CPU resource
    458   /// usage in an ensemble of traces.
    459   extern char &MachineTraceMetricsID;
    460 
    461   /// EarlyIfConverter - This pass performs if-conversion on SSA form by
    462   /// inserting cmov instructions.
    463   extern char &EarlyIfConverterID;
    464 
    465   /// StackSlotColoring - This pass performs stack coloring and merging.
    466   /// It merges disjoint allocas to reduce the stack size.
    467   extern char &StackColoringID;
    468 
    469   /// IfConverter - This pass performs machine code if conversion.
    470   extern char &IfConverterID;
    471 
    472   /// MachineBlockPlacement - This pass places basic blocks based on branch
    473   /// probabilities.
    474   extern char &MachineBlockPlacementID;
    475 
    476   /// MachineBlockPlacementStats - This pass collects statistics about the
    477   /// basic block placement using branch probabilities and block frequency
    478   /// information.
    479   extern char &MachineBlockPlacementStatsID;
    480 
    481   /// GCLowering Pass - Performs target-independent LLVM IR transformations for
    482   /// highly portable strategies.
    483   ///
    484   FunctionPass *createGCLoweringPass();
    485 
    486   /// GCMachineCodeAnalysis - Target-independent pass to mark safe points
    487   /// in machine code. Must be added very late during code generation, just
    488   /// prior to output, and importantly after all CFG transformations (such as
    489   /// branch folding).
    490   extern char &GCMachineCodeAnalysisID;
    491 
    492   /// Creates a pass to print GC metadata.
    493   ///
    494   FunctionPass *createGCInfoPrinter(raw_ostream &OS);
    495 
    496   /// MachineCSE - This pass performs global CSE on machine instructions.
    497   extern char &MachineCSEID;
    498 
    499   /// MachineLICM - This pass performs LICM on machine instructions.
    500   extern char &MachineLICMID;
    501 
    502   /// MachineSinking - This pass performs sinking on machine instructions.
    503   extern char &MachineSinkingID;
    504 
    505   /// MachineCopyPropagation - This pass performs copy propagation on
    506   /// machine instructions.
    507   extern char &MachineCopyPropagationID;
    508 
    509   /// PeepholeOptimizer - This pass performs peephole optimizations -
    510   /// like extension and comparison eliminations.
    511   extern char &PeepholeOptimizerID;
    512 
    513   /// OptimizePHIs - This pass optimizes machine instruction PHIs
    514   /// to take advantage of opportunities created during DAG legalization.
    515   extern char &OptimizePHIsID;
    516 
    517   /// StackSlotColoring - This pass performs stack slot coloring.
    518   extern char &StackSlotColoringID;
    519 
    520   /// createStackProtectorPass - This pass adds stack protectors to functions.
    521   ///
    522   FunctionPass *createStackProtectorPass(const TargetMachine *TM);
    523 
    524   /// createMachineVerifierPass - This pass verifies cenerated machine code
    525   /// instructions for correctness.
    526   ///
    527   FunctionPass *createMachineVerifierPass(const char *Banner = 0);
    528 
    529   /// createDwarfEHPass - This pass mulches exception handling code into a form
    530   /// adapted to code generation.  Required if using dwarf exception handling.
    531   FunctionPass *createDwarfEHPass(const TargetMachine *TM);
    532 
    533   /// createSjLjEHPreparePass - This pass adapts exception handling code to use
    534   /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
    535   ///
    536   FunctionPass *createSjLjEHPreparePass(const TargetMachine *TM);
    537 
    538   /// LocalStackSlotAllocation - This pass assigns local frame indices to stack
    539   /// slots relative to one another and allocates base registers to access them
    540   /// when it is estimated by the target to be out of range of normal frame
    541   /// pointer or stack pointer index addressing.
    542   extern char &LocalStackSlotAllocationID;
    543 
    544   /// ExpandISelPseudos - This pass expands pseudo-instructions.
    545   extern char &ExpandISelPseudosID;
    546 
    547   /// createExecutionDependencyFixPass - This pass fixes execution time
    548   /// problems with dependent instructions, such as switching execution
    549   /// domains to match.
    550   ///
    551   /// The pass will examine instructions using and defining registers in RC.
    552   ///
    553   FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass *RC);
    554 
    555   /// UnpackMachineBundles - This pass unpack machine instruction bundles.
    556   extern char &UnpackMachineBundlesID;
    557 
    558   /// FinalizeMachineBundles - This pass finalize machine instruction
    559   /// bundles (created earlier, e.g. during pre-RA scheduling).
    560   extern char &FinalizeMachineBundlesID;
    561 
    562 } // End llvm namespace
    563 
    564 #endif
    565