Home | History | Annotate | Download | only in Support
      1 //===-- llvm/Support/PassManagerBuilder.h - Build Standard Pass -*- 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 the PassManagerBuilder class, which is used to set up a
     11 // "standard" optimization sequence suitable for languages like C and C++.
     12 //
     13 // These are implemented as inline functions so that we do not have to worry
     14 // about link issues.
     15 //
     16 //===----------------------------------------------------------------------===//
     17 
     18 #ifndef LLVM_SUPPORT_PASSMANAGERBUILDER_H
     19 #define LLVM_SUPPORT_PASSMANAGERBUILDER_H
     20 
     21 #include "llvm/PassManager.h"
     22 #include "llvm/DefaultPasses.h"
     23 #include "llvm/Analysis/Passes.h"
     24 #include "llvm/Analysis/Verifier.h"
     25 #include "llvm/Target/TargetLibraryInfo.h"
     26 #include "llvm/Transforms/Scalar.h"
     27 #include "llvm/Transforms/IPO.h"
     28 
     29 namespace llvm {
     30 
     31 /// PassManagerBuilder - This class is used to set up a standard optimization
     32 /// sequence for languages like C and C++, allowing some APIs to customize the
     33 /// pass sequence in various ways. A simple example of using it would be:
     34 ///
     35 ///  PassManagerBuilder Builder;
     36 ///  Builder.OptLevel = 2;
     37 ///  Builder.populateFunctionPassManager(FPM);
     38 ///  Builder.populateModulePassManager(MPM);
     39 ///
     40 /// In addition to setting up the basic passes, PassManagerBuilder allows
     41 /// frontends to vend a plugin API, where plugins are allowed to add extensions
     42 /// to the default pass manager.  They do this by specifying where in the pass
     43 /// pipeline they want to be added, along with a callback function that adds
     44 /// the pass(es).  For example, a plugin that wanted to add a loop optimization
     45 /// could do something like this:
     46 ///
     47 /// static void addMyLoopPass(const PMBuilder &Builder, PassManagerBase &PM) {
     48 ///   if (Builder.getOptLevel() > 2 && Builder.getOptSizeLevel() == 0)
     49 ///     PM.add(createMyAwesomePass());
     50 /// }
     51 ///   ...
     52 ///   Builder.addExtension(PassManagerBuilder::EP_LoopOptimizerEnd,
     53 ///                        addMyLoopPass);
     54 ///   ...
     55 class PassManagerBuilder {
     56 public:
     57 
     58   /// Extensions are passed the builder itself (so they can see how it is
     59   /// configured) as well as the pass manager to add stuff to.
     60   typedef void (*ExtensionFn)(const PassManagerBuilder &Builder,
     61                               PassManagerBase &PM);
     62   enum ExtensionPointTy {
     63     /// EP_EarlyAsPossible - This extension point allows adding passes before
     64     /// any other transformations, allowing them to see the code as it is coming
     65     /// out of the frontend.
     66     EP_EarlyAsPossible,
     67 
     68     /// EP_LoopOptimizerEnd - This extension point allows adding loop passes to
     69     /// the end of the loop optimizer.
     70     EP_LoopOptimizerEnd,
     71 
     72     /// EP_ScalarOptimizerLate - This extension point allows adding optimization
     73     /// passes after most of the main optimizations, but before the last
     74     /// cleanup-ish optimizations.
     75     EP_ScalarOptimizerLate
     76   };
     77 
     78   /// The Optimization Level - Specify the basic optimization level.
     79   ///    0 = -O0, 1 = -O1, 2 = -O2, 3 = -O3
     80   unsigned OptLevel;
     81 
     82   /// SizeLevel - How much we're optimizing for size.
     83   ///    0 = none, 1 = -Os, 2 = -Oz
     84   unsigned SizeLevel;
     85 
     86   /// LibraryInfo - Specifies information about the runtime library for the
     87   /// optimizer.  If this is non-null, it is added to both the function and
     88   /// per-module pass pipeline.
     89   TargetLibraryInfo *LibraryInfo;
     90 
     91   /// Inliner - Specifies the inliner to use.  If this is non-null, it is
     92   /// added to the per-module passes.
     93   Pass *Inliner;
     94 
     95   bool DisableSimplifyLibCalls;
     96   bool DisableUnitAtATime;
     97   bool DisableUnrollLoops;
     98 
     99 private:
    100   /// ExtensionList - This is list of all of the extensions that are registered.
    101   std::vector<std::pair<ExtensionPointTy, ExtensionFn> > Extensions;
    102 
    103 public:
    104   PassManagerBuilder() {
    105     OptLevel = 2;
    106     SizeLevel = 0;
    107     LibraryInfo = 0;
    108     Inliner = 0;
    109     DisableSimplifyLibCalls = false;
    110     DisableUnitAtATime = false;
    111     DisableUnrollLoops = false;
    112   }
    113 
    114   ~PassManagerBuilder() {
    115     delete LibraryInfo;
    116     delete Inliner;
    117   }
    118 
    119   void addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
    120     Extensions.push_back(std::make_pair(Ty, Fn));
    121   }
    122 
    123 private:
    124   void addExtensionsToPM(ExtensionPointTy ETy, PassManagerBase &PM) const {
    125     for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
    126       if (Extensions[i].first == ETy)
    127         Extensions[i].second(*this, PM);
    128   }
    129 
    130   void addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
    131     // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
    132     // BasicAliasAnalysis wins if they disagree. This is intended to help
    133     // support "obvious" type-punning idioms.
    134     PM.add(createTypeBasedAliasAnalysisPass());
    135     PM.add(createBasicAliasAnalysisPass());
    136   }
    137 public:
    138 
    139   /// populateFunctionPassManager - This fills in the function pass manager,
    140   /// which is expected to be run on each function immediately as it is
    141   /// generated.  The idea is to reduce the size of the IR in memory.
    142   void populateFunctionPassManager(FunctionPassManager &FPM) {
    143     addExtensionsToPM(EP_EarlyAsPossible, FPM);
    144 
    145     // Add LibraryInfo if we have some.
    146     if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
    147 
    148     if (OptLevel == 0) return;
    149 
    150     addInitialAliasAnalysisPasses(FPM);
    151 
    152     FPM.add(createCFGSimplificationPass());
    153     FPM.add(createScalarReplAggregatesPass());
    154     FPM.add(createEarlyCSEPass());
    155     FPM.add(createLowerExpectIntrinsicPass());
    156   }
    157 
    158   /// populateModulePassManager - This sets up the primary pass manager.
    159   void populateModulePassManager(PassManagerBase &MPM) {
    160     // If all optimizations are disabled, just run the always-inline pass.
    161     if (OptLevel == 0) {
    162       if (Inliner) {
    163         MPM.add(Inliner);
    164         Inliner = 0;
    165       }
    166       return;
    167     }
    168 
    169     // Add LibraryInfo if we have some.
    170     if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
    171 
    172     addInitialAliasAnalysisPasses(MPM);
    173 
    174     if (!DisableUnitAtATime) {
    175       MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
    176 
    177       MPM.add(createIPSCCPPass());              // IP SCCP
    178       MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
    179 
    180       MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
    181       MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
    182     }
    183 
    184     // Start of CallGraph SCC passes.
    185     if (!DisableUnitAtATime)
    186       MPM.add(createPruneEHPass());             // Remove dead EH info
    187     if (Inliner) {
    188       MPM.add(Inliner);
    189       Inliner = 0;
    190     }
    191     if (!DisableUnitAtATime)
    192       MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
    193     if (OptLevel > 2)
    194       MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
    195 
    196     // Start of function pass.
    197     // Break up aggregate allocas, using SSAUpdater.
    198     MPM.add(createScalarReplAggregatesPass(-1, false));
    199     MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
    200     if (!DisableSimplifyLibCalls)
    201       MPM.add(createSimplifyLibCallsPass());    // Library Call Optimizations
    202     MPM.add(createJumpThreadingPass());         // Thread jumps.
    203     MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
    204     MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
    205     MPM.add(createInstructionCombiningPass());  // Combine silly seq's
    206 
    207     MPM.add(createTailCallEliminationPass());   // Eliminate tail calls
    208     MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
    209     MPM.add(createReassociatePass());           // Reassociate expressions
    210     MPM.add(createLoopRotatePass());            // Rotate Loop
    211     MPM.add(createLICMPass());                  // Hoist loop invariants
    212     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
    213     MPM.add(createInstructionCombiningPass());
    214     MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
    215     MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
    216     MPM.add(createLoopDeletionPass());          // Delete dead loops
    217     if (!DisableUnrollLoops)
    218       MPM.add(createLoopUnrollPass());          // Unroll small loops
    219     addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
    220 
    221     if (OptLevel > 1)
    222       MPM.add(createGVNPass());                 // Remove redundancies
    223     MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
    224     MPM.add(createSCCPPass());                  // Constant prop with SCCP
    225 
    226     // Run instcombine after redundancy elimination to exploit opportunities
    227     // opened up by them.
    228     MPM.add(createInstructionCombiningPass());
    229     MPM.add(createJumpThreadingPass());         // Thread jumps
    230     MPM.add(createCorrelatedValuePropagationPass());
    231     MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
    232 
    233     addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
    234 
    235     MPM.add(createAggressiveDCEPass());         // Delete dead instructions
    236     MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
    237     MPM.add(createInstructionCombiningPass());  // Clean up after everything.
    238 
    239     if (!DisableUnitAtATime) {
    240       // FIXME: We shouldn't bother with this anymore.
    241       MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
    242 
    243       // GlobalOpt already deletes dead functions and globals, at -O3 try a
    244       // late pass of GlobalDCE.  It is capable of deleting dead cycles.
    245       if (OptLevel > 2)
    246         MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
    247 
    248       if (OptLevel > 1)
    249         MPM.add(createConstantMergePass());     // Merge dup global constants
    250     }
    251   }
    252 
    253   void populateLTOPassManager(PassManagerBase &PM, bool Internalize,
    254                               bool RunInliner) {
    255     // Provide AliasAnalysis services for optimizations.
    256     addInitialAliasAnalysisPasses(PM);
    257 
    258     // Now that composite has been compiled, scan through the module, looking
    259     // for a main function.  If main is defined, mark all other functions
    260     // internal.
    261     if (Internalize)
    262       PM.add(createInternalizePass(true));
    263 
    264     // Propagate constants at call sites into the functions they call.  This
    265     // opens opportunities for globalopt (and inlining) by substituting function
    266     // pointers passed as arguments to direct uses of functions.
    267     PM.add(createIPSCCPPass());
    268 
    269     // Now that we internalized some globals, see if we can hack on them!
    270     PM.add(createGlobalOptimizerPass());
    271 
    272     // Linking modules together can lead to duplicated global constants, only
    273     // keep one copy of each constant.
    274     PM.add(createConstantMergePass());
    275 
    276     // Remove unused arguments from functions.
    277     PM.add(createDeadArgEliminationPass());
    278 
    279     // Reduce the code after globalopt and ipsccp.  Both can open up significant
    280     // simplification opportunities, and both can propagate functions through
    281     // function pointers.  When this happens, we often have to resolve varargs
    282     // calls, etc, so let instcombine do this.
    283     PM.add(createInstructionCombiningPass());
    284 
    285     // Inline small functions
    286     if (RunInliner)
    287       PM.add(createFunctionInliningPass());
    288 
    289     PM.add(createPruneEHPass());   // Remove dead EH info.
    290 
    291     // Optimize globals again if we ran the inliner.
    292     if (RunInliner)
    293       PM.add(createGlobalOptimizerPass());
    294     PM.add(createGlobalDCEPass()); // Remove dead functions.
    295 
    296     // If we didn't decide to inline a function, check to see if we can
    297     // transform it to pass arguments by value instead of by reference.
    298     PM.add(createArgumentPromotionPass());
    299 
    300     // The IPO passes may leave cruft around.  Clean up after them.
    301     PM.add(createInstructionCombiningPass());
    302     PM.add(createJumpThreadingPass());
    303     // Break up allocas
    304     PM.add(createScalarReplAggregatesPass());
    305 
    306     // Run a few AA driven optimizations here and now, to cleanup the code.
    307     PM.add(createFunctionAttrsPass()); // Add nocapture.
    308     PM.add(createGlobalsModRefPass()); // IP alias analysis.
    309 
    310     PM.add(createLICMPass());      // Hoist loop invariants.
    311     PM.add(createGVNPass());       // Remove redundancies.
    312     PM.add(createMemCpyOptPass()); // Remove dead memcpys.
    313     // Nuke dead stores.
    314     PM.add(createDeadStoreEliminationPass());
    315 
    316     // Cleanup and simplify the code after the scalar optimizations.
    317     PM.add(createInstructionCombiningPass());
    318 
    319     PM.add(createJumpThreadingPass());
    320 
    321     // Delete basic blocks, which optimization passes may have killed.
    322     PM.add(createCFGSimplificationPass());
    323 
    324     // Now that we have optimized the program, discard unreachable functions.
    325     PM.add(createGlobalDCEPass());
    326   }
    327 };
    328 
    329 
    330 } // end namespace llvm
    331 #endif
    332