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/PassManager.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 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);
130 PassManagerBuilder::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.
135 PM.add(createCFLAliasAnalysisPass());
136 PM.add(createTypeBasedAliasAnalysisPass());
137 PM.add(createScopedNoAliasAAPass());
138 PM.add(createBasicAliasAnalysisPass());
141 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
142 addExtensionsToPM(EP_EarlyAsPossible, FPM);
144 // Add LibraryInfo if we have some.
146 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
148 if (OptLevel == 0) return;
150 addInitialAliasAnalysisPasses(FPM);
152 FPM.add(createCFGSimplificationPass());
154 FPM.add(createSROAPass());
156 FPM.add(createScalarReplAggregatesPass());
157 FPM.add(createEarlyCSEPass());
158 FPM.add(createLowerExpectIntrinsicPass());
161 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
162 // If all optimizations are disabled, just run the always-inline pass and,
163 // if enabled, the function merging pass.
170 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
171 // creates a CGSCC pass manager, but we don't want to add extensions into
172 // that pass manager. To prevent this we insert a no-op module pass to reset
173 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
174 // builds. The function merging pass is
176 MPM.add(createMergeFunctionsPass());
177 else if (!GlobalExtensions->empty() || !Extensions.empty())
178 MPM.add(createBarrierNoopPass());
180 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
184 // Add LibraryInfo if we have some.
186 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
188 addInitialAliasAnalysisPasses(MPM);
190 if (!DisableUnitAtATime) {
191 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
193 MPM.add(createIPSCCPPass()); // IP SCCP
194 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
196 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
198 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
199 addExtensionsToPM(EP_Peephole, MPM);
200 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
203 // Start of CallGraph SCC passes.
204 if (!DisableUnitAtATime)
205 MPM.add(createPruneEHPass()); // Remove dead EH info
210 if (!DisableUnitAtATime)
211 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
213 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
215 // Start of function pass.
216 // Break up aggregate allocas, using SSAUpdater.
218 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
220 MPM.add(createScalarReplAggregatesPass(-1, false));
221 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
222 MPM.add(createJumpThreadingPass()); // Thread jumps.
223 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
224 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
225 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
226 addExtensionsToPM(EP_Peephole, MPM);
228 if (!DisableTailCalls)
229 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
230 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
231 MPM.add(createReassociatePass()); // Reassociate expressions
232 // Rotate Loop - disable header duplication at -Oz
233 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
234 MPM.add(createLICMPass()); // Hoist loop invariants
235 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
236 MPM.add(createInstructionCombiningPass());
237 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
238 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
239 MPM.add(createLoopDeletionPass()); // Delete dead loops
241 if (!DisableUnrollLoops)
242 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
243 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
247 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
248 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
250 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
251 MPM.add(createSCCPPass()); // Constant prop with SCCP
253 // Run instcombine after redundancy elimination to exploit opportunities
254 // opened up by them.
255 MPM.add(createInstructionCombiningPass());
256 addExtensionsToPM(EP_Peephole, MPM);
257 MPM.add(createJumpThreadingPass()); // Thread jumps
258 MPM.add(createCorrelatedValuePropagationPass());
259 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
261 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
264 MPM.add(createLoopRerollPass());
265 if (!RunSLPAfterLoopVectorization) {
267 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
270 MPM.add(createBBVectorizePass());
271 MPM.add(createInstructionCombiningPass());
272 addExtensionsToPM(EP_Peephole, MPM);
273 if (OptLevel > 1 && UseGVNAfterVectorization)
274 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
276 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
278 // BBVectorize may have significantly shortened a loop body; unroll again.
279 if (!DisableUnrollLoops)
280 MPM.add(createLoopUnrollPass());
285 MPM.add(createLoadCombinePass());
287 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
288 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
289 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
290 addExtensionsToPM(EP_Peephole, MPM);
292 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
293 // pass manager that we are specifically trying to avoid. To prevent this
294 // we must insert a no-op module pass to reset the pass manager.
295 MPM.add(createBarrierNoopPass());
297 // Re-rotate loops in all our loop nests. These may have fallout out of
298 // rotated form due to GVN or other transformations, and the vectorizer relies
299 // on the rotated form.
300 if (ExtraVectorizerPasses)
301 MPM.add(createLoopRotatePass());
303 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
304 // FIXME: Because of #pragma vectorize enable, the passes below are always
305 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
306 // on -O1 and no #pragma is found). Would be good to have these two passes
307 // as function calls, so that we can only pass them when the vectorizer
309 MPM.add(createInstructionCombiningPass());
310 if (OptLevel > 1 && ExtraVectorizerPasses) {
311 // At higher optimization levels, try to clean up any runtime overlap and
312 // alignment checks inserted by the vectorizer. We want to track correllated
313 // runtime checks for two inner loops in the same outer loop, fold any
314 // common computations, hoist loop-invariant aspects out of any outer loop,
315 // and unswitch the runtime checks if possible. Once hoisted, we may have
316 // dead (or speculatable) control flows or more combining opportunities.
317 MPM.add(createEarlyCSEPass());
318 MPM.add(createCorrelatedValuePropagationPass());
319 MPM.add(createInstructionCombiningPass());
320 MPM.add(createLICMPass());
321 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
322 MPM.add(createCFGSimplificationPass());
323 MPM.add(createInstructionCombiningPass());
326 if (RunSLPAfterLoopVectorization) {
328 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
329 if (OptLevel > 1 && ExtraVectorizerPasses) {
330 MPM.add(createEarlyCSEPass());
335 MPM.add(createBBVectorizePass());
336 MPM.add(createInstructionCombiningPass());
337 addExtensionsToPM(EP_Peephole, MPM);
338 if (OptLevel > 1 && UseGVNAfterVectorization)
339 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
341 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
343 // BBVectorize may have significantly shortened a loop body; unroll again.
344 if (!DisableUnrollLoops)
345 MPM.add(createLoopUnrollPass());
349 addExtensionsToPM(EP_Peephole, MPM);
350 MPM.add(createCFGSimplificationPass());
351 MPM.add(createInstructionCombiningPass());
353 if (!DisableUnrollLoops)
354 MPM.add(createLoopUnrollPass()); // Unroll small loops
356 // After vectorization and unrolling, assume intrinsics may tell us more
357 // about pointer alignments.
358 MPM.add(createAlignmentFromAssumptionsPass());
360 if (!DisableUnitAtATime) {
361 // FIXME: We shouldn't bother with this anymore.
362 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
364 // GlobalOpt already deletes dead functions and globals, at -O2 try a
365 // late pass of GlobalDCE. It is capable of deleting dead cycles.
367 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
368 MPM.add(createConstantMergePass()); // Merge dup global constants
373 MPM.add(createMergeFunctionsPass());
375 addExtensionsToPM(EP_OptimizerLast, MPM);
378 void PassManagerBuilder::addLTOOptimizationPasses(PassManagerBase &PM) {
379 // Provide AliasAnalysis services for optimizations.
380 addInitialAliasAnalysisPasses(PM);
382 // Propagate constants at call sites into the functions they call. This
383 // opens opportunities for globalopt (and inlining) by substituting function
384 // pointers passed as arguments to direct uses of functions.
385 PM.add(createIPSCCPPass());
387 // Now that we internalized some globals, see if we can hack on them!
388 PM.add(createGlobalOptimizerPass());
390 // Linking modules together can lead to duplicated global constants, only
391 // keep one copy of each constant.
392 PM.add(createConstantMergePass());
394 // Remove unused arguments from functions.
395 PM.add(createDeadArgEliminationPass());
397 // Reduce the code after globalopt and ipsccp. Both can open up significant
398 // simplification opportunities, and both can propagate functions through
399 // function pointers. When this happens, we often have to resolve varargs
400 // calls, etc, so let instcombine do this.
401 PM.add(createInstructionCombiningPass());
402 addExtensionsToPM(EP_Peephole, PM);
404 // Inline small functions
405 bool RunInliner = Inliner;
411 PM.add(createPruneEHPass()); // Remove dead EH info.
413 // Optimize globals again if we ran the inliner.
415 PM.add(createGlobalOptimizerPass());
416 PM.add(createGlobalDCEPass()); // Remove dead functions.
418 // If we didn't decide to inline a function, check to see if we can
419 // transform it to pass arguments by value instead of by reference.
420 PM.add(createArgumentPromotionPass());
422 // The IPO passes may leave cruft around. Clean up after them.
423 PM.add(createInstructionCombiningPass());
424 addExtensionsToPM(EP_Peephole, PM);
425 PM.add(createJumpThreadingPass());
429 PM.add(createSROAPass());
431 PM.add(createScalarReplAggregatesPass());
433 // Run a few AA driven optimizations here and now, to cleanup the code.
434 PM.add(createFunctionAttrsPass()); // Add nocapture.
435 PM.add(createGlobalsModRefPass()); // IP alias analysis.
437 PM.add(createLICMPass()); // Hoist loop invariants.
439 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
440 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
441 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
444 PM.add(createDeadStoreEliminationPass());
446 // More loops are countable; try to optimize them.
447 PM.add(createIndVarSimplifyPass());
448 PM.add(createLoopDeletionPass());
449 PM.add(createLoopVectorizePass(true, LoopVectorize));
451 // More scalar chains could be vectorized due to more alias information
452 if (RunSLPAfterLoopVectorization)
454 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
456 // After vectorization, assume intrinsics may tell us more about pointer
458 PM.add(createAlignmentFromAssumptionsPass());
461 PM.add(createLoadCombinePass());
463 // Cleanup and simplify the code after the scalar optimizations.
464 PM.add(createInstructionCombiningPass());
465 addExtensionsToPM(EP_Peephole, PM);
467 PM.add(createJumpThreadingPass());
469 // Delete basic blocks, which optimization passes may have killed.
470 PM.add(createCFGSimplificationPass());
472 // Now that we have optimized the program, discard unreachable functions.
473 PM.add(createGlobalDCEPass());
475 // FIXME: this is profitable (for compiler time) to do at -O0 too, but
476 // currently it damages debug info.
478 PM.add(createMergeFunctionsPass());
481 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM) {
483 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
486 PM.add(createVerifierPass());
489 PM.add(createStripSymbolsPass(true));
492 PM.add(createDebugInfoVerifierPass());
495 addLTOOptimizationPasses(PM);
498 PM.add(createVerifierPass());
499 PM.add(createDebugInfoVerifierPass());
503 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
504 return reinterpret_cast<PassManagerBuilder*>(P);
507 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
508 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
511 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
512 PassManagerBuilder *PMB = new PassManagerBuilder();
516 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
517 PassManagerBuilder *Builder = unwrap(PMB);
522 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
524 PassManagerBuilder *Builder = unwrap(PMB);
525 Builder->OptLevel = OptLevel;
529 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
530 unsigned SizeLevel) {
531 PassManagerBuilder *Builder = unwrap(PMB);
532 Builder->SizeLevel = SizeLevel;
536 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
538 PassManagerBuilder *Builder = unwrap(PMB);
539 Builder->DisableUnitAtATime = Value;
543 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
545 PassManagerBuilder *Builder = unwrap(PMB);
546 Builder->DisableUnrollLoops = Value;
550 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
552 // NOTE: The simplify-libcalls pass has been removed.
556 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
557 unsigned Threshold) {
558 PassManagerBuilder *Builder = unwrap(PMB);
559 Builder->Inliner = createFunctionInliningPass(Threshold);
563 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
564 LLVMPassManagerRef PM) {
565 PassManagerBuilder *Builder = unwrap(PMB);
566 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
567 Builder->populateFunctionPassManager(*FPM);
571 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
572 LLVMPassManagerRef PM) {
573 PassManagerBuilder *Builder = unwrap(PMB);
574 PassManagerBase *MPM = unwrap(PM);
575 Builder->populateModulePassManager(*MPM);
578 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
579 LLVMPassManagerRef PM,
580 LLVMBool Internalize,
581 LLVMBool RunInliner) {
582 PassManagerBuilder *Builder = unwrap(PMB);
583 PassManagerBase *LPM = unwrap(PM);
585 // A small backwards compatibility hack. populateLTOPassManager used to take
586 // an RunInliner option.
587 if (RunInliner && !Builder->Inliner)
588 Builder->Inliner = createFunctionInliningPass();
590 Builder->populateLTOPassManager(*LPM);