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"));
63 RunFloat2Int("float-to-int", cl::Hidden, cl::init(true),
64 cl::desc("Run the float2int (float demotion) pass"));
66 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
68 cl::desc("Run the load combining pass"));
71 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
72 cl::init(true), cl::Hidden,
73 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
74 "vectorizer instead of before"));
76 static cl::opt<bool> UseCFLAA("use-cfl-aa",
77 cl::init(false), cl::Hidden,
78 cl::desc("Enable the new, experimental CFL alias analysis"));
81 EnableMLSM("mlsm", cl::init(true), cl::Hidden,
82 cl::desc("Enable motion of merged load and store"));
84 static cl::opt<bool> EnableLoopInterchange(
85 "enable-loopinterchange", cl::init(false), cl::Hidden,
86 cl::desc("Enable the new, experimental LoopInterchange Pass"));
88 PassManagerBuilder::PassManagerBuilder() {
91 LibraryInfo = nullptr;
93 DisableTailCalls = false;
94 DisableUnitAtATime = false;
95 DisableUnrollLoops = false;
96 BBVectorize = RunBBVectorization;
97 SLPVectorize = RunSLPVectorization;
98 LoopVectorize = RunLoopVectorization;
99 RerollLoops = RunLoopRerolling;
100 LoadCombine = RunLoadCombine;
101 DisableGVNLoadPRE = false;
103 VerifyOutput = false;
104 MergeFunctions = false;
107 PassManagerBuilder::~PassManagerBuilder() {
112 /// Set of global extensions, automatically added as part of the standard set.
113 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
114 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
116 void PassManagerBuilder::addGlobalExtension(
117 PassManagerBuilder::ExtensionPointTy Ty,
118 PassManagerBuilder::ExtensionFn Fn) {
119 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
122 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
123 Extensions.push_back(std::make_pair(Ty, Fn));
126 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
127 legacy::PassManagerBase &PM) const {
128 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
129 if ((*GlobalExtensions)[i].first == ETy)
130 (*GlobalExtensions)[i].second(*this, PM);
131 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
132 if (Extensions[i].first == ETy)
133 Extensions[i].second(*this, PM);
136 void PassManagerBuilder::addInitialAliasAnalysisPasses(
137 legacy::PassManagerBase &PM) const {
138 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
139 // BasicAliasAnalysis wins if they disagree. This is intended to help
140 // support "obvious" type-punning idioms.
142 PM.add(createCFLAliasAnalysisPass());
143 PM.add(createTypeBasedAliasAnalysisPass());
144 PM.add(createScopedNoAliasAAPass());
145 PM.add(createBasicAliasAnalysisPass());
148 void PassManagerBuilder::populateFunctionPassManager(
149 legacy::FunctionPassManager &FPM) {
150 addExtensionsToPM(EP_EarlyAsPossible, FPM);
152 // Add LibraryInfo if we have some.
154 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
156 if (OptLevel == 0) return;
158 addInitialAliasAnalysisPasses(FPM);
160 FPM.add(createCFGSimplificationPass());
162 FPM.add(createSROAPass());
164 FPM.add(createScalarReplAggregatesPass());
165 FPM.add(createEarlyCSEPass());
166 FPM.add(createLowerExpectIntrinsicPass());
169 void PassManagerBuilder::populateModulePassManager(
170 legacy::PassManagerBase &MPM) {
171 // If all optimizations are disabled, just run the always-inline pass and,
172 // if enabled, the function merging pass.
179 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
180 // creates a CGSCC pass manager, but we don't want to add extensions into
181 // that pass manager. To prevent this we insert a no-op module pass to reset
182 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
183 // builds. The function merging pass is
185 MPM.add(createMergeFunctionsPass());
186 else if (!GlobalExtensions->empty() || !Extensions.empty())
187 MPM.add(createBarrierNoopPass());
189 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
193 // Add LibraryInfo if we have some.
195 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
197 addInitialAliasAnalysisPasses(MPM);
199 if (!DisableUnitAtATime) {
200 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
202 MPM.add(createIPSCCPPass()); // IP SCCP
203 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
205 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
207 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
208 addExtensionsToPM(EP_Peephole, MPM);
209 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
212 // Start of CallGraph SCC passes.
213 if (!DisableUnitAtATime)
214 MPM.add(createPruneEHPass()); // Remove dead EH info
219 if (!DisableUnitAtATime)
220 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
222 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
224 // Start of function pass.
225 // Break up aggregate allocas, using SSAUpdater.
227 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
229 MPM.add(createScalarReplAggregatesPass(-1, false));
230 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
231 MPM.add(createJumpThreadingPass()); // Thread jumps.
232 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
233 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
234 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
235 addExtensionsToPM(EP_Peephole, MPM);
237 if (!DisableTailCalls)
238 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
239 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
240 MPM.add(createReassociatePass()); // Reassociate expressions
241 // Rotate Loop - disable header duplication at -Oz
242 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
243 MPM.add(createLICMPass()); // Hoist loop invariants
244 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
245 MPM.add(createInstructionCombiningPass());
246 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
247 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
248 MPM.add(createLoopDeletionPass()); // Delete dead loops
249 if (EnableLoopInterchange) {
250 MPM.add(createLoopInterchangePass()); // Interchange loops
251 MPM.add(createCFGSimplificationPass());
253 if (!DisableUnrollLoops)
254 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
255 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
259 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
260 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
262 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
263 MPM.add(createSCCPPass()); // Constant prop with SCCP
265 // Delete dead bit computations (instcombine runs after to fold away the dead
266 // computations, and then ADCE will run later to exploit any new DCE
267 // opportunities that creates).
268 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
270 // Run instcombine after redundancy elimination to exploit opportunities
271 // opened up by them.
272 MPM.add(createInstructionCombiningPass());
273 addExtensionsToPM(EP_Peephole, MPM);
274 MPM.add(createJumpThreadingPass()); // Thread jumps
275 MPM.add(createCorrelatedValuePropagationPass());
276 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
277 MPM.add(createLICMPass());
279 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
282 MPM.add(createLoopRerollPass());
283 if (!RunSLPAfterLoopVectorization) {
285 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
288 MPM.add(createBBVectorizePass());
289 MPM.add(createInstructionCombiningPass());
290 addExtensionsToPM(EP_Peephole, MPM);
291 if (OptLevel > 1 && UseGVNAfterVectorization)
292 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
294 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
296 // BBVectorize may have significantly shortened a loop body; unroll again.
297 if (!DisableUnrollLoops)
298 MPM.add(createLoopUnrollPass());
303 MPM.add(createLoadCombinePass());
305 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
306 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
307 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
308 addExtensionsToPM(EP_Peephole, MPM);
310 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
311 // pass manager that we are specifically trying to avoid. To prevent this
312 // we must insert a no-op module pass to reset the pass manager.
313 MPM.add(createBarrierNoopPass());
316 MPM.add(createFloat2IntPass());
318 // Re-rotate loops in all our loop nests. These may have fallout out of
319 // rotated form due to GVN or other transformations, and the vectorizer relies
320 // on the rotated form.
321 MPM.add(createLoopRotatePass());
323 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
324 // FIXME: Because of #pragma vectorize enable, the passes below are always
325 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
326 // on -O1 and no #pragma is found). Would be good to have these two passes
327 // as function calls, so that we can only pass them when the vectorizer
329 MPM.add(createInstructionCombiningPass());
330 if (OptLevel > 1 && ExtraVectorizerPasses) {
331 // At higher optimization levels, try to clean up any runtime overlap and
332 // alignment checks inserted by the vectorizer. We want to track correllated
333 // runtime checks for two inner loops in the same outer loop, fold any
334 // common computations, hoist loop-invariant aspects out of any outer loop,
335 // and unswitch the runtime checks if possible. Once hoisted, we may have
336 // dead (or speculatable) control flows or more combining opportunities.
337 MPM.add(createEarlyCSEPass());
338 MPM.add(createCorrelatedValuePropagationPass());
339 MPM.add(createInstructionCombiningPass());
340 MPM.add(createLICMPass());
341 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
342 MPM.add(createCFGSimplificationPass());
343 MPM.add(createInstructionCombiningPass());
346 if (RunSLPAfterLoopVectorization) {
348 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
349 if (OptLevel > 1 && ExtraVectorizerPasses) {
350 MPM.add(createEarlyCSEPass());
355 MPM.add(createBBVectorizePass());
356 MPM.add(createInstructionCombiningPass());
357 addExtensionsToPM(EP_Peephole, MPM);
358 if (OptLevel > 1 && UseGVNAfterVectorization)
359 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
361 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
363 // BBVectorize may have significantly shortened a loop body; unroll again.
364 if (!DisableUnrollLoops)
365 MPM.add(createLoopUnrollPass());
369 addExtensionsToPM(EP_Peephole, MPM);
370 MPM.add(createCFGSimplificationPass());
371 MPM.add(createInstructionCombiningPass());
373 if (!DisableUnrollLoops) {
374 MPM.add(createLoopUnrollPass()); // Unroll small loops
376 // This is a barrier pass to avoid combine LICM pass and loop unroll pass
377 // within same loop pass manager.
378 MPM.add(createInstructionSimplifierPass());
380 // Runtime unrolling will introduce runtime check in loop prologue. If the
381 // unrolled loop is a inner loop, then the prologue will be inside the
382 // outer loop. LICM pass can help to promote the runtime check out if the
383 // checked value is loop invariant.
384 MPM.add(createLICMPass());
387 // After vectorization and unrolling, assume intrinsics may tell us more
388 // about pointer alignments.
389 MPM.add(createAlignmentFromAssumptionsPass());
391 if (!DisableUnitAtATime) {
392 // FIXME: We shouldn't bother with this anymore.
393 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
395 // GlobalOpt already deletes dead functions and globals, at -O2 try a
396 // late pass of GlobalDCE. It is capable of deleting dead cycles.
398 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
399 MPM.add(createConstantMergePass()); // Merge dup global constants
404 MPM.add(createMergeFunctionsPass());
406 addExtensionsToPM(EP_OptimizerLast, MPM);
409 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
410 // Provide AliasAnalysis services for optimizations.
411 addInitialAliasAnalysisPasses(PM);
413 // Propagate constants at call sites into the functions they call. This
414 // opens opportunities for globalopt (and inlining) by substituting function
415 // pointers passed as arguments to direct uses of functions.
416 PM.add(createIPSCCPPass());
418 // Now that we internalized some globals, see if we can hack on them!
419 PM.add(createGlobalOptimizerPass());
421 // Linking modules together can lead to duplicated global constants, only
422 // keep one copy of each constant.
423 PM.add(createConstantMergePass());
425 // Remove unused arguments from functions.
426 PM.add(createDeadArgEliminationPass());
428 // Reduce the code after globalopt and ipsccp. Both can open up significant
429 // simplification opportunities, and both can propagate functions through
430 // function pointers. When this happens, we often have to resolve varargs
431 // calls, etc, so let instcombine do this.
432 PM.add(createInstructionCombiningPass());
433 addExtensionsToPM(EP_Peephole, PM);
435 // Inline small functions
436 bool RunInliner = Inliner;
442 PM.add(createPruneEHPass()); // Remove dead EH info.
444 // Optimize globals again if we ran the inliner.
446 PM.add(createGlobalOptimizerPass());
447 PM.add(createGlobalDCEPass()); // Remove dead functions.
449 // If we didn't decide to inline a function, check to see if we can
450 // transform it to pass arguments by value instead of by reference.
451 PM.add(createArgumentPromotionPass());
453 // The IPO passes may leave cruft around. Clean up after them.
454 PM.add(createInstructionCombiningPass());
455 addExtensionsToPM(EP_Peephole, PM);
456 PM.add(createJumpThreadingPass());
460 PM.add(createSROAPass());
462 PM.add(createScalarReplAggregatesPass());
464 // Run a few AA driven optimizations here and now, to cleanup the code.
465 PM.add(createFunctionAttrsPass()); // Add nocapture.
466 PM.add(createGlobalsModRefPass()); // IP alias analysis.
468 PM.add(createLICMPass()); // Hoist loop invariants.
470 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
471 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
472 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
475 PM.add(createDeadStoreEliminationPass());
477 // More loops are countable; try to optimize them.
478 PM.add(createIndVarSimplifyPass());
479 PM.add(createLoopDeletionPass());
480 if (EnableLoopInterchange)
481 PM.add(createLoopInterchangePass());
483 PM.add(createLoopVectorizePass(true, LoopVectorize));
485 // More scalar chains could be vectorized due to more alias information
486 if (RunSLPAfterLoopVectorization)
488 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
490 // After vectorization, assume intrinsics may tell us more about pointer
492 PM.add(createAlignmentFromAssumptionsPass());
495 PM.add(createLoadCombinePass());
497 // Cleanup and simplify the code after the scalar optimizations.
498 PM.add(createInstructionCombiningPass());
499 addExtensionsToPM(EP_Peephole, PM);
501 PM.add(createJumpThreadingPass());
504 void PassManagerBuilder::addLateLTOOptimizationPasses(
505 legacy::PassManagerBase &PM) {
506 // Delete basic blocks, which optimization passes may have killed.
507 PM.add(createCFGSimplificationPass());
509 // Now that we have optimized the program, discard unreachable functions.
510 PM.add(createGlobalDCEPass());
512 // FIXME: this is profitable (for compiler time) to do at -O0 too, but
513 // currently it damages debug info.
515 PM.add(createMergeFunctionsPass());
518 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
520 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
523 PM.add(createVerifierPass());
526 addLTOOptimizationPasses(PM);
528 // Lower bit sets to globals. This pass supports Clang's control flow
529 // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
530 // is enabled. The pass does nothing if CFI is disabled.
531 PM.add(createLowerBitSetsPass());
534 addLateLTOOptimizationPasses(PM);
537 PM.add(createVerifierPass());
540 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
541 return reinterpret_cast<PassManagerBuilder*>(P);
544 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
545 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
548 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
549 PassManagerBuilder *PMB = new PassManagerBuilder();
553 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
554 PassManagerBuilder *Builder = unwrap(PMB);
559 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
561 PassManagerBuilder *Builder = unwrap(PMB);
562 Builder->OptLevel = OptLevel;
566 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
567 unsigned SizeLevel) {
568 PassManagerBuilder *Builder = unwrap(PMB);
569 Builder->SizeLevel = SizeLevel;
573 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
575 PassManagerBuilder *Builder = unwrap(PMB);
576 Builder->DisableUnitAtATime = Value;
580 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
582 PassManagerBuilder *Builder = unwrap(PMB);
583 Builder->DisableUnrollLoops = Value;
587 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
589 // NOTE: The simplify-libcalls pass has been removed.
593 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
594 unsigned Threshold) {
595 PassManagerBuilder *Builder = unwrap(PMB);
596 Builder->Inliner = createFunctionInliningPass(Threshold);
600 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
601 LLVMPassManagerRef PM) {
602 PassManagerBuilder *Builder = unwrap(PMB);
603 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
604 Builder->populateFunctionPassManager(*FPM);
608 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
609 LLVMPassManagerRef PM) {
610 PassManagerBuilder *Builder = unwrap(PMB);
611 legacy::PassManagerBase *MPM = unwrap(PM);
612 Builder->populateModulePassManager(*MPM);
615 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
616 LLVMPassManagerRef PM,
617 LLVMBool Internalize,
618 LLVMBool RunInliner) {
619 PassManagerBuilder *Builder = unwrap(PMB);
620 legacy::PassManagerBase *LPM = unwrap(PM);
622 // A small backwards compatibility hack. populateLTOPassManager used to take
623 // an RunInliner option.
624 if (RunInliner && !Builder->Inliner)
625 Builder->Inliner = createFunctionInliningPass();
627 Builder->populateLTOPassManager(*LPM);