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 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
16 #include "llvm-c/Transforms/PassManagerBuilder.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/BasicAliasAnalysis.h"
19 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
20 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
21 #include "llvm/Analysis/GlobalsModRef.h"
22 #include "llvm/Analysis/InlineCost.h"
23 #include "llvm/Analysis/Passes.h"
24 #include "llvm/Analysis/ScopedNoAliasAA.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/LegacyPassManager.h"
29 #include "llvm/IR/ModuleSummaryIndex.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Transforms/IPO.h"
35 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
36 #include "llvm/Transforms/IPO/FunctionAttrs.h"
37 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
38 #include "llvm/Transforms/Instrumentation.h"
39 #include "llvm/Transforms/Scalar.h"
40 #include "llvm/Transforms/Scalar/GVN.h"
41 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
42 #include "llvm/Transforms/Vectorize.h"
47 RunPartialInlining("enable-partial-inlining", cl::init(false), cl::Hidden,
48 cl::ZeroOrMore, cl::desc("Run Partial inlinining pass"));
51 RunLoopVectorization("vectorize-loops", cl::Hidden,
52 cl::desc("Run the Loop vectorization passes"));
55 RunSLPVectorization("vectorize-slp", cl::Hidden,
56 cl::desc("Run the SLP vectorization passes"));
59 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
60 cl::desc("Run the BB vectorization passes"));
63 UseGVNAfterVectorization("use-gvn-after-vectorization",
64 cl::init(false), cl::Hidden,
65 cl::desc("Run GVN instead of Early CSE after vectorization passes"));
67 static cl::opt<bool> ExtraVectorizerPasses(
68 "extra-vectorizer-passes", cl::init(false), cl::Hidden,
69 cl::desc("Run cleanup optimization passes after vectorization."));
72 RunLoopRerolling("reroll-loops", cl::Hidden,
73 cl::desc("Run the loop rerolling pass"));
75 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
77 cl::desc("Run the load combining pass"));
79 static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
80 cl::desc("Run the NewGVN pass"));
83 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
84 cl::init(true), cl::Hidden,
85 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
86 "vectorizer instead of before"));
88 // Experimental option to use CFL-AA
89 enum class CFLAAType { None, Steensgaard, Andersen, Both };
90 static cl::opt<CFLAAType>
91 UseCFLAA("use-cfl-aa", cl::init(CFLAAType::None), cl::Hidden,
92 cl::desc("Enable the new, experimental CFL alias analysis"),
93 cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
94 clEnumValN(CFLAAType::Steensgaard, "steens",
95 "Enable unification-based CFL-AA"),
96 clEnumValN(CFLAAType::Andersen, "anders",
97 "Enable inclusion-based CFL-AA"),
98 clEnumValN(CFLAAType::Both, "both",
99 "Enable both variants of CFL-AA")));
101 static cl::opt<bool> EnableLoopInterchange(
102 "enable-loopinterchange", cl::init(false), cl::Hidden,
103 cl::desc("Enable the new, experimental LoopInterchange Pass"));
105 static cl::opt<bool> EnableNonLTOGlobalsModRef(
106 "enable-non-lto-gmr", cl::init(true), cl::Hidden,
108 "Enable the GlobalsModRef AliasAnalysis outside of the LTO pipeline."));
110 static cl::opt<bool> EnableLoopLoadElim(
111 "enable-loop-load-elim", cl::init(true), cl::Hidden,
112 cl::desc("Enable the LoopLoadElimination Pass"));
115 EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden,
116 cl::desc("Enable preparation for ThinLTO."));
118 static cl::opt<bool> RunPGOInstrGen(
119 "profile-generate", cl::init(false), cl::Hidden,
120 cl::desc("Enable PGO instrumentation."));
122 static cl::opt<std::string>
123 PGOOutputFile("profile-generate-file", cl::init(""), cl::Hidden,
124 cl::desc("Specify the path of profile data file."));
126 static cl::opt<std::string> RunPGOInstrUse(
127 "profile-use", cl::init(""), cl::Hidden, cl::value_desc("filename"),
128 cl::desc("Enable use phase of PGO instrumentation and specify the path "
129 "of profile data file"));
131 static cl::opt<bool> UseLoopVersioningLICM(
132 "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
133 cl::desc("Enable the experimental Loop Versioning LICM pass"));
136 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
137 cl::desc("Disable pre-instrumentation inliner"));
139 static cl::opt<int> PreInlineThreshold(
140 "preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore,
141 cl::desc("Control the amount of inlining in pre-instrumentation inliner "
144 static cl::opt<bool> EnableGVNHoist(
145 "enable-gvn-hoist", cl::init(false), cl::Hidden,
146 cl::desc("Enable the GVN hoisting pass (default = off)"));
149 DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false),
151 cl::desc("Disable shrink-wrap library calls"));
154 EnableSimpleLoopUnswitch("enable-simple-loop-unswitch", cl::init(false),
156 cl::desc("Enable the simple loop unswitch pass."));
158 PassManagerBuilder::PassManagerBuilder() {
161 LibraryInfo = nullptr;
163 DisableUnitAtATime = false;
164 DisableUnrollLoops = false;
165 BBVectorize = RunBBVectorization;
166 SLPVectorize = RunSLPVectorization;
167 LoopVectorize = RunLoopVectorization;
168 RerollLoops = RunLoopRerolling;
169 LoadCombine = RunLoadCombine;
171 DisableGVNLoadPRE = false;
173 VerifyOutput = false;
174 MergeFunctions = false;
175 PrepareForLTO = false;
176 EnablePGOInstrGen = RunPGOInstrGen;
177 PGOInstrGen = PGOOutputFile;
178 PGOInstrUse = RunPGOInstrUse;
179 PrepareForThinLTO = EnablePrepareForThinLTO;
180 PerformThinLTO = false;
181 DivergentTarget = false;
184 PassManagerBuilder::~PassManagerBuilder() {
189 /// Set of global extensions, automatically added as part of the standard set.
190 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
191 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
193 void PassManagerBuilder::addGlobalExtension(
194 PassManagerBuilder::ExtensionPointTy Ty,
195 PassManagerBuilder::ExtensionFn Fn) {
196 GlobalExtensions->push_back(std::make_pair(Ty, std::move(Fn)));
199 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
200 Extensions.push_back(std::make_pair(Ty, std::move(Fn)));
203 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
204 legacy::PassManagerBase &PM) const {
205 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
206 if ((*GlobalExtensions)[i].first == ETy)
207 (*GlobalExtensions)[i].second(*this, PM);
208 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
209 if (Extensions[i].first == ETy)
210 Extensions[i].second(*this, PM);
213 void PassManagerBuilder::addInitialAliasAnalysisPasses(
214 legacy::PassManagerBase &PM) const {
216 case CFLAAType::Steensgaard:
217 PM.add(createCFLSteensAAWrapperPass());
219 case CFLAAType::Andersen:
220 PM.add(createCFLAndersAAWrapperPass());
222 case CFLAAType::Both:
223 PM.add(createCFLSteensAAWrapperPass());
224 PM.add(createCFLAndersAAWrapperPass());
230 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
231 // BasicAliasAnalysis wins if they disagree. This is intended to help
232 // support "obvious" type-punning idioms.
233 PM.add(createTypeBasedAAWrapperPass());
234 PM.add(createScopedNoAliasAAWrapperPass());
237 void PassManagerBuilder::addInstructionCombiningPass(
238 legacy::PassManagerBase &PM) const {
239 bool ExpensiveCombines = OptLevel > 2;
240 PM.add(createInstructionCombiningPass(ExpensiveCombines));
243 void PassManagerBuilder::populateFunctionPassManager(
244 legacy::FunctionPassManager &FPM) {
245 addExtensionsToPM(EP_EarlyAsPossible, FPM);
247 // Add LibraryInfo if we have some.
249 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
251 if (OptLevel == 0) return;
253 addInitialAliasAnalysisPasses(FPM);
255 FPM.add(createCFGSimplificationPass());
256 FPM.add(createSROAPass());
257 FPM.add(createEarlyCSEPass());
258 FPM.add(createLowerExpectIntrinsicPass());
261 // Do PGO instrumentation generation or use pass as the option specified.
262 void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM) {
263 if (!EnablePGOInstrGen && PGOInstrUse.empty())
265 // Perform the preinline and cleanup passes for O1 and above.
266 // And avoid doing them if optimizing for size.
267 if (OptLevel > 0 && SizeLevel == 0 && !DisablePreInliner) {
268 // Create preinline pass. We construct an InlineParams object and specify
269 // the threshold here to avoid the command line options of the regular
270 // inliner to influence pre-inlining. The only fields of InlineParams we
271 // care about are DefaultThreshold and HintThreshold.
273 IP.DefaultThreshold = PreInlineThreshold;
274 // FIXME: The hint threshold has the same value used by the regular inliner.
275 // This should probably be lowered after performance testing.
276 IP.HintThreshold = 325;
278 MPM.add(createFunctionInliningPass(IP));
279 MPM.add(createSROAPass());
280 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
281 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
282 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
283 addExtensionsToPM(EP_Peephole, MPM);
285 if (EnablePGOInstrGen) {
286 MPM.add(createPGOInstrumentationGenLegacyPass());
287 // Add the profile lowering pass.
288 InstrProfOptions Options;
289 if (!PGOInstrGen.empty())
290 Options.InstrProfileOutput = PGOInstrGen;
291 MPM.add(createInstrProfilingLegacyPass(Options));
293 if (!PGOInstrUse.empty())
294 MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse));
295 // Indirect call promotion that promotes intra-module targets only.
296 // For ThinLTO this is done earlier due to interactions with globalopt
297 // for imported functions. We don't run this at -O0.
300 createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty()));
302 void PassManagerBuilder::addFunctionSimplificationPasses(
303 legacy::PassManagerBase &MPM) {
304 // Start of function pass.
305 // Break up aggregate allocas, using SSAUpdater.
306 MPM.add(createSROAPass());
307 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
309 MPM.add(createGVNHoistPass());
310 // Speculative execution if the target has divergent branches; otherwise nop.
311 MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass());
312 MPM.add(createJumpThreadingPass()); // Thread jumps.
313 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
314 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
315 // Combine silly seq's
316 addInstructionCombiningPass(MPM);
317 if (SizeLevel == 0 && !DisableLibCallsShrinkWrap)
318 MPM.add(createLibCallsShrinkWrapPass());
319 addExtensionsToPM(EP_Peephole, MPM);
321 // Optimize memory intrinsic calls based on the profiled size information.
323 MPM.add(createPGOMemOPSizeOptLegacyPass());
325 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
326 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
327 MPM.add(createReassociatePass()); // Reassociate expressions
328 // Rotate Loop - disable header duplication at -Oz
329 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
330 MPM.add(createLICMPass()); // Hoist loop invariants
331 if (EnableSimpleLoopUnswitch)
332 MPM.add(createSimpleLoopUnswitchLegacyPass());
334 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
335 MPM.add(createCFGSimplificationPass());
336 addInstructionCombiningPass(MPM);
337 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
338 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
339 addExtensionsToPM(EP_LateLoopOptimizations, MPM);
340 MPM.add(createLoopDeletionPass()); // Delete dead loops
342 if (EnableLoopInterchange) {
343 MPM.add(createLoopInterchangePass()); // Interchange loops
344 MPM.add(createCFGSimplificationPass());
346 if (!DisableUnrollLoops)
347 MPM.add(createSimpleLoopUnrollPass(OptLevel)); // Unroll small loops
348 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
351 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
352 MPM.add(NewGVN ? createNewGVNPass()
353 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
355 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
356 MPM.add(createSCCPPass()); // Constant prop with SCCP
358 // Delete dead bit computations (instcombine runs after to fold away the dead
359 // computations, and then ADCE will run later to exploit any new DCE
360 // opportunities that creates).
361 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
363 // Run instcombine after redundancy elimination to exploit opportunities
364 // opened up by them.
365 addInstructionCombiningPass(MPM);
366 addExtensionsToPM(EP_Peephole, MPM);
367 MPM.add(createJumpThreadingPass()); // Thread jumps
368 MPM.add(createCorrelatedValuePropagationPass());
369 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
370 MPM.add(createLICMPass());
372 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
375 MPM.add(createLoopRerollPass());
376 if (!RunSLPAfterLoopVectorization) {
378 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
381 MPM.add(createBBVectorizePass());
382 addInstructionCombiningPass(MPM);
383 addExtensionsToPM(EP_Peephole, MPM);
384 if (OptLevel > 1 && UseGVNAfterVectorization)
387 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
389 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
391 // BBVectorize may have significantly shortened a loop body; unroll again.
392 if (!DisableUnrollLoops)
393 MPM.add(createLoopUnrollPass(OptLevel));
398 MPM.add(createLoadCombinePass());
400 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
401 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
402 // Clean up after everything.
403 addInstructionCombiningPass(MPM);
404 addExtensionsToPM(EP_Peephole, MPM);
407 void PassManagerBuilder::populateModulePassManager(
408 legacy::PassManagerBase &MPM) {
409 if (!PGOSampleUse.empty()) {
410 MPM.add(createPruneEHPass());
411 MPM.add(createSampleProfileLoaderPass(PGOSampleUse));
414 // Allow forcing function attributes as a debugging and tuning aid.
415 MPM.add(createForceFunctionAttrsLegacyPass());
417 // If all optimizations are disabled, just run the always-inline pass and,
418 // if enabled, the function merging pass.
420 addPGOInstrPasses(MPM);
426 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
427 // creates a CGSCC pass manager, but we don't want to add extensions into
428 // that pass manager. To prevent this we insert a no-op module pass to reset
429 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
430 // builds. The function merging pass is
432 MPM.add(createMergeFunctionsPass());
433 else if (!GlobalExtensions->empty() || !Extensions.empty())
434 MPM.add(createBarrierNoopPass());
436 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
438 // Rename anon globals to be able to export them in the summary.
439 // This has to be done after we add the extensions to the pass manager
440 // as there could be passes (e.g. Adddress sanitizer) which introduce
441 // new unnamed globals.
442 if (PrepareForThinLTO)
443 MPM.add(createNameAnonGlobalPass());
447 // Add LibraryInfo if we have some.
449 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
451 addInitialAliasAnalysisPasses(MPM);
453 // For ThinLTO there are two passes of indirect call promotion. The
454 // first is during the compile phase when PerformThinLTO=false and
455 // intra-module indirect call targets are promoted. The second is during
456 // the ThinLTO backend when PerformThinLTO=true, when we promote imported
457 // inter-module indirect calls. For that we perform indirect call promotion
458 // earlier in the pass pipeline, here before globalopt. Otherwise imported
459 // available_externally functions look unreferenced and are removed.
461 MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true,
462 !PGOSampleUse.empty()));
464 // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops
465 // as it will change the CFG too much to make the 2nd profile annotation
466 // in backend more difficult.
467 bool PrepareForThinLTOUsingPGOSampleProfile =
468 PrepareForThinLTO && !PGOSampleUse.empty();
469 if (PrepareForThinLTOUsingPGOSampleProfile)
470 DisableUnrollLoops = true;
472 if (!DisableUnitAtATime) {
473 // Infer attributes about declarations if possible.
474 MPM.add(createInferFunctionAttrsLegacyPass());
476 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
478 MPM.add(createIPSCCPPass()); // IP SCCP
479 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
480 // Promote any localized global vars.
481 MPM.add(createPromoteMemoryToRegisterPass());
483 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
485 addInstructionCombiningPass(MPM); // Clean up after IPCP & DAE
486 addExtensionsToPM(EP_Peephole, MPM);
487 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
490 // For SamplePGO in ThinLTO compile phase, we do not want to do indirect
491 // call promotion as it will change the CFG too much to make the 2nd
492 // profile annotation in backend more difficult.
493 // PGO instrumentation is added during the compile phase for ThinLTO, do
494 // not run it a second time
495 if (!PerformThinLTO && !PrepareForThinLTOUsingPGOSampleProfile)
496 addPGOInstrPasses(MPM);
498 if (EnableNonLTOGlobalsModRef)
499 // We add a module alias analysis pass here. In part due to bugs in the
500 // analysis infrastructure this "works" in that the analysis stays alive
501 // for the entire SCC pass run below.
502 MPM.add(createGlobalsAAWrapperPass());
504 // Start of CallGraph SCC passes.
505 if (!DisableUnitAtATime)
506 MPM.add(createPruneEHPass()); // Remove dead EH info
511 if (!DisableUnitAtATime)
512 MPM.add(createPostOrderFunctionAttrsLegacyPass());
514 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
516 addExtensionsToPM(EP_CGSCCOptimizerLate, MPM);
517 addFunctionSimplificationPasses(MPM);
519 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
520 // pass manager that we are specifically trying to avoid. To prevent this
521 // we must insert a no-op module pass to reset the pass manager.
522 MPM.add(createBarrierNoopPass());
523 if (RunPartialInlining)
524 MPM.add(createPartialInliningPass());
526 if (!DisableUnitAtATime && OptLevel > 1 && !PrepareForLTO &&
528 // Remove avail extern fns and globals definitions if we aren't
529 // compiling an object file for later LTO. For LTO we want to preserve
530 // these so they are eligible for inlining at link-time. Note if they
531 // are unreferenced they will be removed by GlobalDCE later, so
532 // this only impacts referenced available externally globals.
533 // Eventually they will be suppressed during codegen, but eliminating
534 // here enables more opportunity for GlobalDCE as it may make
535 // globals referenced by available external functions dead
536 // and saves running remaining passes on the eliminated functions.
537 MPM.add(createEliminateAvailableExternallyPass());
539 if (!DisableUnitAtATime)
540 MPM.add(createReversePostOrderFunctionAttrsPass());
542 // If we are planning to perform ThinLTO later, let's not bloat the code with
543 // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes
544 // during ThinLTO and perform the rest of the optimizations afterward.
545 if (PrepareForThinLTO) {
546 // Reduce the size of the IR as much as possible.
547 MPM.add(createGlobalOptimizerPass());
548 // Rename anon globals to be able to export them in the summary.
549 MPM.add(createNameAnonGlobalPass());
554 // Optimize globals now when performing ThinLTO, this enables more
555 // optimizations later.
556 MPM.add(createGlobalOptimizerPass());
558 // Scheduling LoopVersioningLICM when inlining is over, because after that
559 // we may see more accurate aliasing. Reason to run this late is that too
560 // early versioning may prevent further inlining due to increase of code
561 // size. By placing it just after inlining other optimizations which runs
562 // later might get benefit of no-alias assumption in clone loop.
563 if (UseLoopVersioningLICM) {
564 MPM.add(createLoopVersioningLICMPass()); // Do LoopVersioningLICM
565 MPM.add(createLICMPass()); // Hoist loop invariants
568 if (EnableNonLTOGlobalsModRef)
569 // We add a fresh GlobalsModRef run at this point. This is particularly
570 // useful as the above will have inlined, DCE'ed, and function-attr
571 // propagated everything. We should at this point have a reasonably minimal
572 // and richly annotated call graph. By computing aliasing and mod/ref
573 // information for all local globals here, the late loop passes and notably
574 // the vectorizer will be able to use them to help recognize vectorizable
575 // memory operations.
577 // Note that this relies on a bug in the pass manager which preserves
578 // a module analysis into a function pass pipeline (and throughout it) so
579 // long as the first function pass doesn't invalidate the module analysis.
580 // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
581 // this to work. Fortunately, it is trivial to preserve AliasAnalysis
582 // (doing nothing preserves it as it is required to be conservatively
583 // correct in the face of IR changes).
584 MPM.add(createGlobalsAAWrapperPass());
586 MPM.add(createFloat2IntPass());
588 addExtensionsToPM(EP_VectorizerStart, MPM);
590 // Re-rotate loops in all our loop nests. These may have fallout out of
591 // rotated form due to GVN or other transformations, and the vectorizer relies
592 // on the rotated form. Disable header duplication at -Oz.
593 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
595 // Distribute loops to allow partial vectorization. I.e. isolate dependences
596 // into separate loop that would otherwise inhibit vectorization. This is
597 // currently only performed for loops marked with the metadata
598 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
599 MPM.add(createLoopDistributePass());
601 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
603 // Eliminate loads by forwarding stores from the previous iteration to loads
604 // of the current iteration.
605 if (EnableLoopLoadElim)
606 MPM.add(createLoopLoadEliminationPass());
608 // FIXME: Because of #pragma vectorize enable, the passes below are always
609 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
610 // on -O1 and no #pragma is found). Would be good to have these two passes
611 // as function calls, so that we can only pass them when the vectorizer
613 addInstructionCombiningPass(MPM);
614 if (OptLevel > 1 && ExtraVectorizerPasses) {
615 // At higher optimization levels, try to clean up any runtime overlap and
616 // alignment checks inserted by the vectorizer. We want to track correllated
617 // runtime checks for two inner loops in the same outer loop, fold any
618 // common computations, hoist loop-invariant aspects out of any outer loop,
619 // and unswitch the runtime checks if possible. Once hoisted, we may have
620 // dead (or speculatable) control flows or more combining opportunities.
621 MPM.add(createEarlyCSEPass());
622 MPM.add(createCorrelatedValuePropagationPass());
623 addInstructionCombiningPass(MPM);
624 MPM.add(createLICMPass());
625 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
626 MPM.add(createCFGSimplificationPass());
627 addInstructionCombiningPass(MPM);
630 if (RunSLPAfterLoopVectorization) {
632 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
633 if (OptLevel > 1 && ExtraVectorizerPasses) {
634 MPM.add(createEarlyCSEPass());
639 MPM.add(createBBVectorizePass());
640 addInstructionCombiningPass(MPM);
641 addExtensionsToPM(EP_Peephole, MPM);
642 if (OptLevel > 1 && UseGVNAfterVectorization)
645 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
647 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
649 // BBVectorize may have significantly shortened a loop body; unroll again.
650 if (!DisableUnrollLoops)
651 MPM.add(createLoopUnrollPass(OptLevel));
655 addExtensionsToPM(EP_Peephole, MPM);
656 MPM.add(createLateCFGSimplificationPass()); // Switches to lookup tables
657 addInstructionCombiningPass(MPM);
659 if (!DisableUnrollLoops) {
660 MPM.add(createLoopUnrollPass(OptLevel)); // Unroll small loops
662 // LoopUnroll may generate some redundency to cleanup.
663 addInstructionCombiningPass(MPM);
665 // Runtime unrolling will introduce runtime check in loop prologue. If the
666 // unrolled loop is a inner loop, then the prologue will be inside the
667 // outer loop. LICM pass can help to promote the runtime check out if the
668 // checked value is loop invariant.
669 MPM.add(createLICMPass());
672 // After vectorization and unrolling, assume intrinsics may tell us more
673 // about pointer alignments.
674 MPM.add(createAlignmentFromAssumptionsPass());
676 if (!DisableUnitAtATime) {
677 // FIXME: We shouldn't bother with this anymore.
678 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
680 // GlobalOpt already deletes dead functions and globals, at -O2 try a
681 // late pass of GlobalDCE. It is capable of deleting dead cycles.
683 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
684 MPM.add(createConstantMergePass()); // Merge dup global constants
689 MPM.add(createMergeFunctionsPass());
691 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
692 // canonicalization pass that enables other optimizations. As a result,
693 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
695 MPM.add(createLoopSinkPass());
696 // Get rid of LCSSA nodes.
697 MPM.add(createInstructionSimplifierPass());
699 // LoopSink (and other loop passes since the last simplifyCFG) might have
700 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
701 MPM.add(createCFGSimplificationPass());
703 addExtensionsToPM(EP_OptimizerLast, MPM);
706 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
707 // Remove unused virtual tables to improve the quality of code generated by
708 // whole-program devirtualization and bitset lowering.
709 PM.add(createGlobalDCEPass());
711 // Provide AliasAnalysis services for optimizations.
712 addInitialAliasAnalysisPasses(PM);
714 // Allow forcing function attributes as a debugging and tuning aid.
715 PM.add(createForceFunctionAttrsLegacyPass());
717 // Infer attributes about declarations if possible.
718 PM.add(createInferFunctionAttrsLegacyPass());
721 // Indirect call promotion. This should promote all the targets that are
722 // left by the earlier promotion pass that promotes intra-module targets.
723 // This two-step promotion is to save the compile time. For LTO, it should
724 // produce the same result as if we only do promotion here.
726 createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty()));
728 // Propagate constants at call sites into the functions they call. This
729 // opens opportunities for globalopt (and inlining) by substituting function
730 // pointers passed as arguments to direct uses of functions.
731 PM.add(createIPSCCPPass());
734 // Infer attributes about definitions. The readnone attribute in particular is
735 // required for virtual constant propagation.
736 PM.add(createPostOrderFunctionAttrsLegacyPass());
737 PM.add(createReversePostOrderFunctionAttrsPass());
739 // Split globals using inrange annotations on GEP indices. This can help
740 // improve the quality of generated code when virtual constant propagation or
741 // control flow integrity are enabled.
742 PM.add(createGlobalSplitPass());
744 // Apply whole-program devirtualization and virtual constant propagation.
745 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
747 // That's all we need at opt level 1.
751 // Now that we internalized some globals, see if we can hack on them!
752 PM.add(createGlobalOptimizerPass());
753 // Promote any localized global vars.
754 PM.add(createPromoteMemoryToRegisterPass());
756 // Linking modules together can lead to duplicated global constants, only
757 // keep one copy of each constant.
758 PM.add(createConstantMergePass());
760 // Remove unused arguments from functions.
761 PM.add(createDeadArgEliminationPass());
763 // Reduce the code after globalopt and ipsccp. Both can open up significant
764 // simplification opportunities, and both can propagate functions through
765 // function pointers. When this happens, we often have to resolve varargs
766 // calls, etc, so let instcombine do this.
767 addInstructionCombiningPass(PM);
768 addExtensionsToPM(EP_Peephole, PM);
770 // Inline small functions
771 bool RunInliner = Inliner;
777 PM.add(createPruneEHPass()); // Remove dead EH info.
779 // Optimize globals again if we ran the inliner.
781 PM.add(createGlobalOptimizerPass());
782 PM.add(createGlobalDCEPass()); // Remove dead functions.
784 // If we didn't decide to inline a function, check to see if we can
785 // transform it to pass arguments by value instead of by reference.
786 PM.add(createArgumentPromotionPass());
788 // The IPO passes may leave cruft around. Clean up after them.
789 addInstructionCombiningPass(PM);
790 addExtensionsToPM(EP_Peephole, PM);
791 PM.add(createJumpThreadingPass());
794 PM.add(createSROAPass());
796 // Run a few AA driven optimizations here and now, to cleanup the code.
797 PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture.
798 PM.add(createGlobalsAAWrapperPass()); // IP alias analysis.
800 PM.add(createLICMPass()); // Hoist loop invariants.
801 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
802 PM.add(NewGVN ? createNewGVNPass()
803 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
804 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
807 PM.add(createDeadStoreEliminationPass());
809 // More loops are countable; try to optimize them.
810 PM.add(createIndVarSimplifyPass());
811 PM.add(createLoopDeletionPass());
812 if (EnableLoopInterchange)
813 PM.add(createLoopInterchangePass());
815 if (!DisableUnrollLoops)
816 PM.add(createSimpleLoopUnrollPass(OptLevel)); // Unroll small loops
817 PM.add(createLoopVectorizePass(true, LoopVectorize));
818 // The vectorizer may have significantly shortened a loop body; unroll again.
819 if (!DisableUnrollLoops)
820 PM.add(createLoopUnrollPass(OptLevel));
822 // Now that we've optimized loops (in particular loop induction variables),
823 // we may have exposed more scalar opportunities. Run parts of the scalar
824 // optimizer again at this point.
825 addInstructionCombiningPass(PM); // Initial cleanup
826 PM.add(createCFGSimplificationPass()); // if-convert
827 PM.add(createSCCPPass()); // Propagate exposed constants
828 addInstructionCombiningPass(PM); // Clean up again
829 PM.add(createBitTrackingDCEPass());
831 // More scalar chains could be vectorized due to more alias information
832 if (RunSLPAfterLoopVectorization)
834 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
836 // After vectorization, assume intrinsics may tell us more about pointer
838 PM.add(createAlignmentFromAssumptionsPass());
841 PM.add(createLoadCombinePass());
843 // Cleanup and simplify the code after the scalar optimizations.
844 addInstructionCombiningPass(PM);
845 addExtensionsToPM(EP_Peephole, PM);
847 PM.add(createJumpThreadingPass());
850 void PassManagerBuilder::addLateLTOOptimizationPasses(
851 legacy::PassManagerBase &PM) {
852 // Delete basic blocks, which optimization passes may have killed.
853 PM.add(createCFGSimplificationPass());
855 // Drop bodies of available externally objects to improve GlobalDCE.
856 PM.add(createEliminateAvailableExternallyPass());
858 // Now that we have optimized the program, discard unreachable functions.
859 PM.add(createGlobalDCEPass());
861 // FIXME: this is profitable (for compiler time) to do at -O0 too, but
862 // currently it damages debug info.
864 PM.add(createMergeFunctionsPass());
867 void PassManagerBuilder::populateThinLTOPassManager(
868 legacy::PassManagerBase &PM) {
869 PerformThinLTO = true;
872 PM.add(createVerifierPass());
875 // These passes import type identifier resolutions for whole-program
876 // devirtualization and CFI. They must run early because other passes may
877 // disturb the specific instruction patterns that these passes look for,
878 // creating dependencies on resolutions that may not appear in the summary.
880 // For example, GVN may transform the pattern assume(type.test) appearing in
881 // two basic blocks into assume(phi(type.test, type.test)), which would
882 // transform a dependency on a WPD resolution into a dependency on a type
883 // identifier resolution for CFI.
885 // Also, WPD has access to more precise information than ICP and can
886 // devirtualize more effectively, so it should operate on the IR first.
887 PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary));
888 PM.add(createLowerTypeTestsPass(nullptr, ImportSummary));
891 populateModulePassManager(PM);
894 PM.add(createVerifierPass());
895 PerformThinLTO = false;
898 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
900 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
903 PM.add(createVerifierPass());
906 addLTOOptimizationPasses(PM);
908 // Create a function that performs CFI checks for cross-DSO calls with targets
909 // in the current module.
910 PM.add(createCrossDSOCFIPass());
912 // Lower type metadata and the type.test intrinsic. This pass supports Clang's
913 // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at
914 // link time if CFI is enabled. The pass does nothing if CFI is disabled.
915 PM.add(createLowerTypeTestsPass(ExportSummary, nullptr));
918 addLateLTOOptimizationPasses(PM);
921 PM.add(createVerifierPass());
924 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
925 return reinterpret_cast<PassManagerBuilder*>(P);
928 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
929 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
932 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
933 PassManagerBuilder *PMB = new PassManagerBuilder();
937 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
938 PassManagerBuilder *Builder = unwrap(PMB);
943 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
945 PassManagerBuilder *Builder = unwrap(PMB);
946 Builder->OptLevel = OptLevel;
950 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
951 unsigned SizeLevel) {
952 PassManagerBuilder *Builder = unwrap(PMB);
953 Builder->SizeLevel = SizeLevel;
957 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
959 PassManagerBuilder *Builder = unwrap(PMB);
960 Builder->DisableUnitAtATime = Value;
964 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
966 PassManagerBuilder *Builder = unwrap(PMB);
967 Builder->DisableUnrollLoops = Value;
971 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
973 // NOTE: The simplify-libcalls pass has been removed.
977 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
978 unsigned Threshold) {
979 PassManagerBuilder *Builder = unwrap(PMB);
980 Builder->Inliner = createFunctionInliningPass(Threshold);
984 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
985 LLVMPassManagerRef PM) {
986 PassManagerBuilder *Builder = unwrap(PMB);
987 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
988 Builder->populateFunctionPassManager(*FPM);
992 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
993 LLVMPassManagerRef PM) {
994 PassManagerBuilder *Builder = unwrap(PMB);
995 legacy::PassManagerBase *MPM = unwrap(PM);
996 Builder->populateModulePassManager(*MPM);
999 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
1000 LLVMPassManagerRef PM,
1001 LLVMBool Internalize,
1002 LLVMBool RunInliner) {
1003 PassManagerBuilder *Builder = unwrap(PMB);
1004 legacy::PassManagerBase *LPM = unwrap(PM);
1006 // A small backwards compatibility hack. populateLTOPassManager used to take
1007 // an RunInliner option.
1008 if (RunInliner && !Builder->Inliner)
1009 Builder->Inliner = createFunctionInliningPass();
1011 Builder->populateLTOPassManager(*LPM);