1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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++.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
17 #include "llvm-c/Transforms/PassManagerBuilder.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Transforms/IPO.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/Transforms/Vectorize.h"
34 RunLoopVectorization("vectorize-loops", cl::Hidden,
35 cl::desc("Run the Loop vectorization passes"));
38 RunSLPVectorization("vectorize-slp", cl::Hidden,
39 cl::desc("Run the SLP vectorization passes"));
42 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
43 cl::desc("Run the BB vectorization passes"));
46 UseGVNAfterVectorization("use-gvn-after-vectorization",
47 cl::init(false), cl::Hidden,
48 cl::desc("Run GVN instead of Early CSE after vectorization passes"));
50 static cl::opt<bool> ExtraVectorizerPasses(
51 "extra-vectorizer-passes", cl::init(false), cl::Hidden,
52 cl::desc("Run cleanup optimization passes after vectorization."));
54 static cl::opt<bool> UseNewSROA("use-new-sroa",
55 cl::init(true), cl::Hidden,
56 cl::desc("Enable the new, experimental SROA pass"));
59 RunLoopRerolling("reroll-loops", cl::Hidden,
60 cl::desc("Run the loop rerolling pass"));
62 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
64 cl::desc("Run the load combining pass"));
67 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
68 cl::init(true), cl::Hidden,
69 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
70 "vectorizer instead of before"));
72 static cl::opt<bool> UseCFLAA("use-cfl-aa",
73 cl::init(false), cl::Hidden,
74 cl::desc("Enable the new, experimental CFL alias analysis"));
77 EnableMLSM("mlsm", cl::init(true), cl::Hidden,
78 cl::desc("Enable motion of merged load and store"));
80 PassManagerBuilder::PassManagerBuilder() {
83 LibraryInfo = nullptr;
85 DisableTailCalls = false;
86 DisableUnitAtATime = false;
87 DisableUnrollLoops = false;
88 BBVectorize = RunBBVectorization;
89 SLPVectorize = RunSLPVectorization;
90 LoopVectorize = RunLoopVectorization;
91 RerollLoops = RunLoopRerolling;
92 LoadCombine = RunLoadCombine;
93 DisableGVNLoadPRE = false;
97 MergeFunctions = false;
100 PassManagerBuilder::~PassManagerBuilder() {
105 /// Set of global extensions, automatically added as part of the standard set.
106 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
107 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
109 void PassManagerBuilder::addGlobalExtension(
110 PassManagerBuilder::ExtensionPointTy Ty,
111 PassManagerBuilder::ExtensionFn Fn) {
112 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
115 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
116 Extensions.push_back(std::make_pair(Ty, Fn));
119 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
120 legacy::PassManagerBase &PM) const {
121 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
122 if ((*GlobalExtensions)[i].first == ETy)
123 (*GlobalExtensions)[i].second(*this, PM);
124 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
125 if (Extensions[i].first == ETy)
126 Extensions[i].second(*this, PM);
129 void PassManagerBuilder::addInitialAliasAnalysisPasses(
130 legacy::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.
135 PM.add(createCFLAliasAnalysisPass());
136 PM.add(createTypeBasedAliasAnalysisPass());
137 PM.add(createScopedNoAliasAAPass());
138 PM.add(createBasicAliasAnalysisPass());
141 void PassManagerBuilder::populateFunctionPassManager(
142 legacy::FunctionPassManager &FPM) {
143 addExtensionsToPM(EP_EarlyAsPossible, FPM);
145 // Add LibraryInfo if we have some.
147 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
149 if (OptLevel == 0) return;
151 addInitialAliasAnalysisPasses(FPM);
153 FPM.add(createCFGSimplificationPass());
155 FPM.add(createSROAPass());
157 FPM.add(createScalarReplAggregatesPass());
158 FPM.add(createEarlyCSEPass());
159 FPM.add(createLowerExpectIntrinsicPass());
162 void PassManagerBuilder::populateModulePassManager(
163 legacy::PassManagerBase &MPM) {
164 // If all optimizations are disabled, just run the always-inline pass and,
165 // if enabled, the function merging pass.
172 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
173 // creates a CGSCC pass manager, but we don't want to add extensions into
174 // that pass manager. To prevent this we insert a no-op module pass to reset
175 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
176 // builds. The function merging pass is
178 MPM.add(createMergeFunctionsPass());
179 else if (!GlobalExtensions->empty() || !Extensions.empty())
180 MPM.add(createBarrierNoopPass());
182 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
186 // Add LibraryInfo if we have some.
188 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
190 addInitialAliasAnalysisPasses(MPM);
192 if (!DisableUnitAtATime) {
193 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
195 MPM.add(createIPSCCPPass()); // IP SCCP
196 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
198 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
200 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
201 addExtensionsToPM(EP_Peephole, MPM);
202 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
205 // Start of CallGraph SCC passes.
206 if (!DisableUnitAtATime)
207 MPM.add(createPruneEHPass()); // Remove dead EH info
212 if (!DisableUnitAtATime)
213 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
215 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
217 // Start of function pass.
218 // Break up aggregate allocas, using SSAUpdater.
220 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
222 MPM.add(createScalarReplAggregatesPass(-1, false));
223 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
224 MPM.add(createJumpThreadingPass()); // Thread jumps.
225 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
226 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
227 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
228 addExtensionsToPM(EP_Peephole, MPM);
230 if (!DisableTailCalls)
231 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
232 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
233 MPM.add(createReassociatePass()); // Reassociate expressions
234 // Rotate Loop - disable header duplication at -Oz
235 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
236 MPM.add(createLICMPass()); // Hoist loop invariants
237 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
238 MPM.add(createInstructionCombiningPass());
239 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
240 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
241 MPM.add(createLoopDeletionPass()); // Delete dead loops
243 if (!DisableUnrollLoops)
244 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
245 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
249 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
250 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
252 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
253 MPM.add(createSCCPPass()); // Constant prop with SCCP
255 // Delete dead bit computations (instcombine runs after to fold away the dead
256 // computations, and then ADCE will run later to exploit any new DCE
257 // opportunities that creates).
258 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
260 // Run instcombine after redundancy elimination to exploit opportunities
261 // opened up by them.
262 MPM.add(createInstructionCombiningPass());
263 addExtensionsToPM(EP_Peephole, MPM);
264 MPM.add(createJumpThreadingPass()); // Thread jumps
265 MPM.add(createCorrelatedValuePropagationPass());
266 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
267 MPM.add(createLICMPass());
269 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
272 MPM.add(createLoopRerollPass());
273 if (!RunSLPAfterLoopVectorization) {
275 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
278 MPM.add(createBBVectorizePass());
279 MPM.add(createInstructionCombiningPass());
280 addExtensionsToPM(EP_Peephole, MPM);
281 if (OptLevel > 1 && UseGVNAfterVectorization)
282 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
284 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
286 // BBVectorize may have significantly shortened a loop body; unroll again.
287 if (!DisableUnrollLoops)
288 MPM.add(createLoopUnrollPass());
293 MPM.add(createLoadCombinePass());
295 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
296 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
297 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
298 addExtensionsToPM(EP_Peephole, MPM);
300 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
301 // pass manager that we are specifically trying to avoid. To prevent this
302 // we must insert a no-op module pass to reset the pass manager.
303 MPM.add(createBarrierNoopPass());
305 // Re-rotate loops in all our loop nests. These may have fallout out of
306 // rotated form due to GVN or other transformations, and the vectorizer relies
307 // on the rotated form.
308 if (ExtraVectorizerPasses)
309 MPM.add(createLoopRotatePass());
311 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
312 // FIXME: Because of #pragma vectorize enable, the passes below are always
313 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
314 // on -O1 and no #pragma is found). Would be good to have these two passes
315 // as function calls, so that we can only pass them when the vectorizer
317 MPM.add(createInstructionCombiningPass());
318 if (OptLevel > 1 && ExtraVectorizerPasses) {
319 // At higher optimization levels, try to clean up any runtime overlap and
320 // alignment checks inserted by the vectorizer. We want to track correllated
321 // runtime checks for two inner loops in the same outer loop, fold any
322 // common computations, hoist loop-invariant aspects out of any outer loop,
323 // and unswitch the runtime checks if possible. Once hoisted, we may have
324 // dead (or speculatable) control flows or more combining opportunities.
325 MPM.add(createEarlyCSEPass());
326 MPM.add(createCorrelatedValuePropagationPass());
327 MPM.add(createInstructionCombiningPass());
328 MPM.add(createLICMPass());
329 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
330 MPM.add(createCFGSimplificationPass());
331 MPM.add(createInstructionCombiningPass());
334 if (RunSLPAfterLoopVectorization) {
336 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
337 if (OptLevel > 1 && ExtraVectorizerPasses) {
338 MPM.add(createEarlyCSEPass());
343 MPM.add(createBBVectorizePass());
344 MPM.add(createInstructionCombiningPass());
345 addExtensionsToPM(EP_Peephole, MPM);
346 if (OptLevel > 1 && UseGVNAfterVectorization)
347 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
349 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
351 // BBVectorize may have significantly shortened a loop body; unroll again.
352 if (!DisableUnrollLoops)
353 MPM.add(createLoopUnrollPass());
357 addExtensionsToPM(EP_Peephole, MPM);
358 MPM.add(createCFGSimplificationPass());
359 MPM.add(createInstructionCombiningPass());
361 if (!DisableUnrollLoops)
362 MPM.add(createLoopUnrollPass()); // Unroll small loops
364 // After vectorization and unrolling, assume intrinsics may tell us more
365 // about pointer alignments.
366 MPM.add(createAlignmentFromAssumptionsPass());
368 if (!DisableUnitAtATime) {
369 // FIXME: We shouldn't bother with this anymore.
370 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
372 // GlobalOpt already deletes dead functions and globals, at -O2 try a
373 // late pass of GlobalDCE. It is capable of deleting dead cycles.
375 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
376 MPM.add(createConstantMergePass()); // Merge dup global constants
381 MPM.add(createMergeFunctionsPass());
383 addExtensionsToPM(EP_OptimizerLast, MPM);
386 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
387 // Provide AliasAnalysis services for optimizations.
388 addInitialAliasAnalysisPasses(PM);
390 // Propagate constants at call sites into the functions they call. This
391 // opens opportunities for globalopt (and inlining) by substituting function
392 // pointers passed as arguments to direct uses of functions.
393 PM.add(createIPSCCPPass());
395 // Now that we internalized some globals, see if we can hack on them!
396 PM.add(createGlobalOptimizerPass());
398 // Linking modules together can lead to duplicated global constants, only
399 // keep one copy of each constant.
400 PM.add(createConstantMergePass());
402 // Remove unused arguments from functions.
403 PM.add(createDeadArgEliminationPass());
405 // Reduce the code after globalopt and ipsccp. Both can open up significant
406 // simplification opportunities, and both can propagate functions through
407 // function pointers. When this happens, we often have to resolve varargs
408 // calls, etc, so let instcombine do this.
409 PM.add(createInstructionCombiningPass());
410 addExtensionsToPM(EP_Peephole, PM);
412 // Inline small functions
413 bool RunInliner = Inliner;
419 PM.add(createPruneEHPass()); // Remove dead EH info.
421 // Optimize globals again if we ran the inliner.
423 PM.add(createGlobalOptimizerPass());
424 PM.add(createGlobalDCEPass()); // Remove dead functions.
426 // If we didn't decide to inline a function, check to see if we can
427 // transform it to pass arguments by value instead of by reference.
428 PM.add(createArgumentPromotionPass());
430 // The IPO passes may leave cruft around. Clean up after them.
431 PM.add(createInstructionCombiningPass());
432 addExtensionsToPM(EP_Peephole, PM);
433 PM.add(createJumpThreadingPass());
437 PM.add(createSROAPass());
439 PM.add(createScalarReplAggregatesPass());
441 // Run a few AA driven optimizations here and now, to cleanup the code.
442 PM.add(createFunctionAttrsPass()); // Add nocapture.
443 PM.add(createGlobalsModRefPass()); // IP alias analysis.
445 PM.add(createLICMPass()); // Hoist loop invariants.
447 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
448 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
449 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
452 PM.add(createDeadStoreEliminationPass());
454 // More loops are countable; try to optimize them.
455 PM.add(createIndVarSimplifyPass());
456 PM.add(createLoopDeletionPass());
457 PM.add(createLoopVectorizePass(true, LoopVectorize));
459 // More scalar chains could be vectorized due to more alias information
460 if (RunSLPAfterLoopVectorization)
462 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
464 // After vectorization, assume intrinsics may tell us more about pointer
466 PM.add(createAlignmentFromAssumptionsPass());
469 PM.add(createLoadCombinePass());
471 // Cleanup and simplify the code after the scalar optimizations.
472 PM.add(createInstructionCombiningPass());
473 addExtensionsToPM(EP_Peephole, PM);
475 PM.add(createJumpThreadingPass());
477 // Delete basic blocks, which optimization passes may have killed.
478 PM.add(createCFGSimplificationPass());
480 // Now that we have optimized the program, discard unreachable functions.
481 PM.add(createGlobalDCEPass());
483 // FIXME: this is profitable (for compiler time) to do at -O0 too, but
484 // currently it damages debug info.
486 PM.add(createMergeFunctionsPass());
489 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
491 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
494 PM.add(createVerifierPass());
497 PM.add(createStripSymbolsPass(true));
500 PM.add(createDebugInfoVerifierPass());
503 addLTOOptimizationPasses(PM);
506 PM.add(createVerifierPass());
507 PM.add(createDebugInfoVerifierPass());
511 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
512 return reinterpret_cast<PassManagerBuilder*>(P);
515 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
516 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
519 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
520 PassManagerBuilder *PMB = new PassManagerBuilder();
524 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
525 PassManagerBuilder *Builder = unwrap(PMB);
530 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
532 PassManagerBuilder *Builder = unwrap(PMB);
533 Builder->OptLevel = OptLevel;
537 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
538 unsigned SizeLevel) {
539 PassManagerBuilder *Builder = unwrap(PMB);
540 Builder->SizeLevel = SizeLevel;
544 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
546 PassManagerBuilder *Builder = unwrap(PMB);
547 Builder->DisableUnitAtATime = Value;
551 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
553 PassManagerBuilder *Builder = unwrap(PMB);
554 Builder->DisableUnrollLoops = Value;
558 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
560 // NOTE: The simplify-libcalls pass has been removed.
564 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
565 unsigned Threshold) {
566 PassManagerBuilder *Builder = unwrap(PMB);
567 Builder->Inliner = createFunctionInliningPass(Threshold);
571 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
572 LLVMPassManagerRef PM) {
573 PassManagerBuilder *Builder = unwrap(PMB);
574 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
575 Builder->populateFunctionPassManager(*FPM);
579 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
580 LLVMPassManagerRef PM) {
581 PassManagerBuilder *Builder = unwrap(PMB);
582 legacy::PassManagerBase *MPM = unwrap(PM);
583 Builder->populateModulePassManager(*MPM);
586 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
587 LLVMPassManagerRef PM,
588 LLVMBool Internalize,
589 LLVMBool RunInliner) {
590 PassManagerBuilder *Builder = unwrap(PMB);
591 legacy::PassManagerBase *LPM = unwrap(PM);
593 // A small backwards compatibility hack. populateLTOPassManager used to take
594 // an RunInliner option.
595 if (RunInliner && !Builder->Inliner)
596 Builder->Inliner = createFunctionInliningPass();
598 Builder->populateLTOPassManager(*LPM);