LLVM API Documentation

PassManagerBuilder.cpp
Go to the documentation of this file.
00001 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the PassManagerBuilder class, which is used to set up a
00011 // "standard" optimization sequence suitable for languages like C and C++.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 
00016 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
00017 #include "llvm-c/Transforms/PassManagerBuilder.h"
00018 #include "llvm/ADT/SmallVector.h"
00019 #include "llvm/Analysis/Passes.h"
00020 #include "llvm/IR/Verifier.h"
00021 #include "llvm/PassManager.h"
00022 #include "llvm/Support/CommandLine.h"
00023 #include "llvm/Support/ManagedStatic.h"
00024 #include "llvm/Target/TargetLibraryInfo.h"
00025 #include "llvm/Transforms/IPO.h"
00026 #include "llvm/Transforms/Scalar.h"
00027 #include "llvm/Transforms/Vectorize.h"
00028 
00029 using namespace llvm;
00030 
00031 static cl::opt<bool>
00032 RunLoopVectorization("vectorize-loops", cl::Hidden,
00033                      cl::desc("Run the Loop vectorization passes"));
00034 
00035 static cl::opt<bool>
00036 RunSLPVectorization("vectorize-slp", cl::Hidden,
00037                     cl::desc("Run the SLP vectorization passes"));
00038 
00039 static cl::opt<bool>
00040 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
00041                     cl::desc("Run the BB vectorization passes"));
00042 
00043 static cl::opt<bool>
00044 UseGVNAfterVectorization("use-gvn-after-vectorization",
00045   cl::init(false), cl::Hidden,
00046   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
00047 
00048 static cl::opt<bool> UseNewSROA("use-new-sroa",
00049   cl::init(true), cl::Hidden,
00050   cl::desc("Enable the new, experimental SROA pass"));
00051 
00052 static cl::opt<bool>
00053 RunLoopRerolling("reroll-loops", cl::Hidden,
00054                  cl::desc("Run the loop rerolling pass"));
00055 
00056 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
00057                                     cl::Hidden,
00058                                     cl::desc("Run the load combining pass"));
00059 
00060 PassManagerBuilder::PassManagerBuilder() {
00061     OptLevel = 2;
00062     SizeLevel = 0;
00063     LibraryInfo = nullptr;
00064     Inliner = nullptr;
00065     DisableTailCalls = false;
00066     DisableUnitAtATime = false;
00067     DisableUnrollLoops = false;
00068     BBVectorize = RunBBVectorization;
00069     SLPVectorize = RunSLPVectorization;
00070     LoopVectorize = RunLoopVectorization;
00071     RerollLoops = RunLoopRerolling;
00072     LoadCombine = RunLoadCombine;
00073 }
00074 
00075 PassManagerBuilder::~PassManagerBuilder() {
00076   delete LibraryInfo;
00077   delete Inliner;
00078 }
00079 
00080 /// Set of global extensions, automatically added as part of the standard set.
00081 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
00082    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
00083 
00084 void PassManagerBuilder::addGlobalExtension(
00085     PassManagerBuilder::ExtensionPointTy Ty,
00086     PassManagerBuilder::ExtensionFn Fn) {
00087   GlobalExtensions->push_back(std::make_pair(Ty, Fn));
00088 }
00089 
00090 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
00091   Extensions.push_back(std::make_pair(Ty, Fn));
00092 }
00093 
00094 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
00095                                            PassManagerBase &PM) const {
00096   for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
00097     if ((*GlobalExtensions)[i].first == ETy)
00098       (*GlobalExtensions)[i].second(*this, PM);
00099   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
00100     if (Extensions[i].first == ETy)
00101       Extensions[i].second(*this, PM);
00102 }
00103 
00104 void
00105 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
00106   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
00107   // BasicAliasAnalysis wins if they disagree. This is intended to help
00108   // support "obvious" type-punning idioms.
00109   PM.add(createTypeBasedAliasAnalysisPass());
00110   PM.add(createBasicAliasAnalysisPass());
00111 }
00112 
00113 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
00114   addExtensionsToPM(EP_EarlyAsPossible, FPM);
00115 
00116   // Add LibraryInfo if we have some.
00117   if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
00118 
00119   if (OptLevel == 0) return;
00120 
00121   addInitialAliasAnalysisPasses(FPM);
00122 
00123   FPM.add(createCFGSimplificationPass());
00124   if (UseNewSROA)
00125     FPM.add(createSROAPass());
00126   else
00127     FPM.add(createScalarReplAggregatesPass());
00128   FPM.add(createEarlyCSEPass());
00129   FPM.add(createLowerExpectIntrinsicPass());
00130 }
00131 
00132 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
00133   // If all optimizations are disabled, just run the always-inline pass.
00134   if (OptLevel == 0) {
00135     if (Inliner) {
00136       MPM.add(Inliner);
00137       Inliner = nullptr;
00138     }
00139 
00140     // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
00141     // pass manager, but we don't want to add extensions into that pass manager.
00142     // To prevent this we must insert a no-op module pass to reset the pass
00143     // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
00144     if (!GlobalExtensions->empty() || !Extensions.empty())
00145       MPM.add(createBarrierNoopPass());
00146 
00147     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
00148     return;
00149   }
00150 
00151   // Add LibraryInfo if we have some.
00152   if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
00153 
00154   addInitialAliasAnalysisPasses(MPM);
00155 
00156   if (!DisableUnitAtATime) {
00157     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
00158 
00159     MPM.add(createIPSCCPPass());              // IP SCCP
00160     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
00161 
00162     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
00163 
00164     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
00165     addExtensionsToPM(EP_Peephole, MPM);
00166     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
00167   }
00168 
00169   // Start of CallGraph SCC passes.
00170   if (!DisableUnitAtATime)
00171     MPM.add(createPruneEHPass());             // Remove dead EH info
00172   if (Inliner) {
00173     MPM.add(Inliner);
00174     Inliner = nullptr;
00175   }
00176   if (!DisableUnitAtATime)
00177     MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
00178   if (OptLevel > 2)
00179     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
00180 
00181   // Start of function pass.
00182   // Break up aggregate allocas, using SSAUpdater.
00183   if (UseNewSROA)
00184     MPM.add(createSROAPass(/*RequiresDomTree*/ false));
00185   else
00186     MPM.add(createScalarReplAggregatesPass(-1, false));
00187   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
00188   MPM.add(createJumpThreadingPass());         // Thread jumps.
00189   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
00190   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
00191   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
00192   addExtensionsToPM(EP_Peephole, MPM);
00193 
00194   if (!DisableTailCalls)
00195     MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
00196   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
00197   MPM.add(createReassociatePass());           // Reassociate expressions
00198   MPM.add(createLoopRotatePass());            // Rotate Loop
00199   MPM.add(createLICMPass());                  // Hoist loop invariants
00200   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
00201   MPM.add(createInstructionCombiningPass());
00202   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
00203   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
00204   MPM.add(createLoopDeletionPass());          // Delete dead loops
00205 
00206   if (!DisableUnrollLoops)
00207     MPM.add(createSimpleLoopUnrollPass());    // Unroll small loops
00208   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
00209 
00210   if (OptLevel > 1) {
00211     MPM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamond
00212     MPM.add(createGVNPass());                 // Remove redundancies
00213   }
00214   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
00215   MPM.add(createSCCPPass());                  // Constant prop with SCCP
00216 
00217   // Run instcombine after redundancy elimination to exploit opportunities
00218   // opened up by them.
00219   MPM.add(createInstructionCombiningPass());
00220   addExtensionsToPM(EP_Peephole, MPM);
00221   MPM.add(createJumpThreadingPass());         // Thread jumps
00222   MPM.add(createCorrelatedValuePropagationPass());
00223   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
00224 
00225   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
00226 
00227   if (RerollLoops)
00228     MPM.add(createLoopRerollPass());
00229   if (SLPVectorize)
00230     MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
00231 
00232   if (BBVectorize) {
00233     MPM.add(createBBVectorizePass());
00234     MPM.add(createInstructionCombiningPass());
00235     addExtensionsToPM(EP_Peephole, MPM);
00236     if (OptLevel > 1 && UseGVNAfterVectorization)
00237       MPM.add(createGVNPass());           // Remove redundancies
00238     else
00239       MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
00240 
00241     // BBVectorize may have significantly shortened a loop body; unroll again.
00242     if (!DisableUnrollLoops)
00243       MPM.add(createLoopUnrollPass());
00244   }
00245 
00246   if (LoadCombine)
00247     MPM.add(createLoadCombinePass());
00248 
00249   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
00250   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
00251   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
00252   addExtensionsToPM(EP_Peephole, MPM);
00253 
00254   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
00255   // pass manager that we are specifically trying to avoid. To prevent this
00256   // we must insert a no-op module pass to reset the pass manager.
00257   MPM.add(createBarrierNoopPass());
00258   MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
00259   // FIXME: Because of #pragma vectorize enable, the passes below are always
00260   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
00261   // on -O1 and no #pragma is found). Would be good to have these two passes
00262   // as function calls, so that we can only pass them when the vectorizer
00263   // changed the code.
00264   MPM.add(createInstructionCombiningPass());
00265   addExtensionsToPM(EP_Peephole, MPM);
00266   MPM.add(createCFGSimplificationPass());
00267 
00268   if (!DisableUnrollLoops)
00269     MPM.add(createLoopUnrollPass());    // Unroll small loops
00270 
00271   if (!DisableUnitAtATime) {
00272     // FIXME: We shouldn't bother with this anymore.
00273     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
00274 
00275     // GlobalOpt already deletes dead functions and globals, at -O2 try a
00276     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
00277     if (OptLevel > 1) {
00278       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
00279       MPM.add(createConstantMergePass());     // Merge dup global constants
00280     }
00281   }
00282   addExtensionsToPM(EP_OptimizerLast, MPM);
00283 }
00284 
00285 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
00286                                                 bool Internalize,
00287                                                 bool RunInliner,
00288                                                 bool DisableGVNLoadPRE) {
00289   // Provide AliasAnalysis services for optimizations.
00290   addInitialAliasAnalysisPasses(PM);
00291 
00292   // Now that composite has been compiled, scan through the module, looking
00293   // for a main function.  If main is defined, mark all other functions
00294   // internal.
00295   if (Internalize)
00296     PM.add(createInternalizePass("main"));
00297 
00298   // Propagate constants at call sites into the functions they call.  This
00299   // opens opportunities for globalopt (and inlining) by substituting function
00300   // pointers passed as arguments to direct uses of functions.
00301   PM.add(createIPSCCPPass());
00302 
00303   // Now that we internalized some globals, see if we can hack on them!
00304   PM.add(createGlobalOptimizerPass());
00305 
00306   // Linking modules together can lead to duplicated global constants, only
00307   // keep one copy of each constant.
00308   PM.add(createConstantMergePass());
00309 
00310   // Remove unused arguments from functions.
00311   PM.add(createDeadArgEliminationPass());
00312 
00313   // Reduce the code after globalopt and ipsccp.  Both can open up significant
00314   // simplification opportunities, and both can propagate functions through
00315   // function pointers.  When this happens, we often have to resolve varargs
00316   // calls, etc, so let instcombine do this.
00317   PM.add(createInstructionCombiningPass());
00318   addExtensionsToPM(EP_Peephole, PM);
00319 
00320   // Inline small functions
00321   if (RunInliner)
00322     PM.add(createFunctionInliningPass());
00323 
00324   PM.add(createPruneEHPass());   // Remove dead EH info.
00325 
00326   // Optimize globals again if we ran the inliner.
00327   if (RunInliner)
00328     PM.add(createGlobalOptimizerPass());
00329   PM.add(createGlobalDCEPass()); // Remove dead functions.
00330 
00331   // If we didn't decide to inline a function, check to see if we can
00332   // transform it to pass arguments by value instead of by reference.
00333   PM.add(createArgumentPromotionPass());
00334 
00335   // The IPO passes may leave cruft around.  Clean up after them.
00336   PM.add(createInstructionCombiningPass());
00337   addExtensionsToPM(EP_Peephole, PM);
00338   PM.add(createJumpThreadingPass());
00339 
00340   // Break up allocas
00341   if (UseNewSROA)
00342     PM.add(createSROAPass());
00343   else
00344     PM.add(createScalarReplAggregatesPass());
00345 
00346   // Run a few AA driven optimizations here and now, to cleanup the code.
00347   PM.add(createFunctionAttrsPass()); // Add nocapture.
00348   PM.add(createGlobalsModRefPass()); // IP alias analysis.
00349 
00350   PM.add(createLICMPass());                 // Hoist loop invariants.
00351   PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds
00352   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
00353   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
00354 
00355   // Nuke dead stores.
00356   PM.add(createDeadStoreEliminationPass());
00357 
00358   // More loops are countable; try to optimize them.
00359   PM.add(createIndVarSimplifyPass());
00360   PM.add(createLoopDeletionPass());
00361   PM.add(createLoopVectorizePass(true, true));
00362 
00363   // More scalar chains could be vectorized due to more alias information
00364   PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
00365 
00366   if (LoadCombine)
00367     PM.add(createLoadCombinePass());
00368 
00369   // Cleanup and simplify the code after the scalar optimizations.
00370   PM.add(createInstructionCombiningPass());
00371   addExtensionsToPM(EP_Peephole, PM);
00372 
00373   PM.add(createJumpThreadingPass());
00374 
00375   // Delete basic blocks, which optimization passes may have killed.
00376   PM.add(createCFGSimplificationPass());
00377 
00378   // Now that we have optimized the program, discard unreachable functions.
00379   PM.add(createGlobalDCEPass());
00380 }
00381 
00382 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
00383     return reinterpret_cast<PassManagerBuilder*>(P);
00384 }
00385 
00386 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
00387   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
00388 }
00389 
00390 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
00391   PassManagerBuilder *PMB = new PassManagerBuilder();
00392   return wrap(PMB);
00393 }
00394 
00395 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
00396   PassManagerBuilder *Builder = unwrap(PMB);
00397   delete Builder;
00398 }
00399 
00400 void
00401 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
00402                                   unsigned OptLevel) {
00403   PassManagerBuilder *Builder = unwrap(PMB);
00404   Builder->OptLevel = OptLevel;
00405 }
00406 
00407 void
00408 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
00409                                    unsigned SizeLevel) {
00410   PassManagerBuilder *Builder = unwrap(PMB);
00411   Builder->SizeLevel = SizeLevel;
00412 }
00413 
00414 void
00415 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
00416                                             LLVMBool Value) {
00417   PassManagerBuilder *Builder = unwrap(PMB);
00418   Builder->DisableUnitAtATime = Value;
00419 }
00420 
00421 void
00422 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
00423                                             LLVMBool Value) {
00424   PassManagerBuilder *Builder = unwrap(PMB);
00425   Builder->DisableUnrollLoops = Value;
00426 }
00427 
00428 void
00429 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
00430                                                  LLVMBool Value) {
00431   // NOTE: The simplify-libcalls pass has been removed.
00432 }
00433 
00434 void
00435 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
00436                                               unsigned Threshold) {
00437   PassManagerBuilder *Builder = unwrap(PMB);
00438   Builder->Inliner = createFunctionInliningPass(Threshold);
00439 }
00440 
00441 void
00442 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
00443                                                   LLVMPassManagerRef PM) {
00444   PassManagerBuilder *Builder = unwrap(PMB);
00445   FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
00446   Builder->populateFunctionPassManager(*FPM);
00447 }
00448 
00449 void
00450 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
00451                                                 LLVMPassManagerRef PM) {
00452   PassManagerBuilder *Builder = unwrap(PMB);
00453   PassManagerBase *MPM = unwrap(PM);
00454   Builder->populateModulePassManager(*MPM);
00455 }
00456 
00457 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
00458                                                   LLVMPassManagerRef PM,
00459                                                   LLVMBool Internalize,
00460                                                   LLVMBool RunInliner) {
00461   PassManagerBuilder *Builder = unwrap(PMB);
00462   PassManagerBase *LPM = unwrap(PM);
00463   Builder->populateLTOPassManager(*LPM, Internalize != 0, RunInliner != 0);
00464 }