1 //===- Parsing, selection, and construction of pass pipelines -------------===//
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 //===----------------------------------------------------------------------===//
11 /// This file provides the implementation of the PassBuilder based on our
12 /// static pass registry as well as related functionality. It also provides
13 /// helpers to aid in analyzing, debugging, and testing passes and pass
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Passes/PassBuilder.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AliasAnalysisEvaluator.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/BasicAliasAnalysis.h"
24 #include "llvm/Analysis/BlockFrequencyInfo.h"
25 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
26 #include "llvm/Analysis/BranchProbabilityInfo.h"
27 #include "llvm/Analysis/CFGPrinter.h"
28 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
29 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
30 #include "llvm/Analysis/CGSCCPassManager.h"
31 #include "llvm/Analysis/CallGraph.h"
32 #include "llvm/Analysis/DemandedBits.h"
33 #include "llvm/Analysis/DependenceAnalysis.h"
34 #include "llvm/Analysis/DominanceFrontier.h"
35 #include "llvm/Analysis/GlobalsModRef.h"
36 #include "llvm/Analysis/IVUsers.h"
37 #include "llvm/Analysis/LazyCallGraph.h"
38 #include "llvm/Analysis/LazyValueInfo.h"
39 #include "llvm/Analysis/LoopAccessAnalysis.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
42 #include "llvm/Analysis/MemorySSA.h"
43 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
44 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
45 #include "llvm/Analysis/PostDominators.h"
46 #include "llvm/Analysis/ProfileSummaryInfo.h"
47 #include "llvm/Analysis/RegionInfo.h"
48 #include "llvm/Analysis/ScalarEvolution.h"
49 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
50 #include "llvm/Analysis/ScopedNoAliasAA.h"
51 #include "llvm/Analysis/TargetLibraryInfo.h"
52 #include "llvm/Analysis/TargetTransformInfo.h"
53 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
54 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
55 #include "llvm/CodeGen/UnreachableBlockElim.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/IRPrintingPasses.h"
58 #include "llvm/IR/PassManager.h"
59 #include "llvm/IR/Verifier.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/Regex.h"
62 #include "llvm/Target/TargetMachine.h"
63 #include "llvm/Transforms/GCOVProfiler.h"
64 #include "llvm/Transforms/IPO/AlwaysInliner.h"
65 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
66 #include "llvm/Transforms/IPO/ConstantMerge.h"
67 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
68 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
69 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
70 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
71 #include "llvm/Transforms/IPO/FunctionAttrs.h"
72 #include "llvm/Transforms/IPO/FunctionImport.h"
73 #include "llvm/Transforms/IPO/GlobalDCE.h"
74 #include "llvm/Transforms/IPO/GlobalOpt.h"
75 #include "llvm/Transforms/IPO/GlobalSplit.h"
76 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
77 #include "llvm/Transforms/IPO/Inliner.h"
78 #include "llvm/Transforms/IPO/Internalize.h"
79 #include "llvm/Transforms/IPO/LowerTypeTests.h"
80 #include "llvm/Transforms/IPO/PartialInlining.h"
81 #include "llvm/Transforms/IPO/SCCP.h"
82 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
83 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
84 #include "llvm/Transforms/InstCombine/InstCombine.h"
85 #include "llvm/Transforms/InstrProfiling.h"
86 #include "llvm/Transforms/PGOInstrumentation.h"
87 #include "llvm/Transforms/SampleProfile.h"
88 #include "llvm/Transforms/Scalar/ADCE.h"
89 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
90 #include "llvm/Transforms/Scalar/BDCE.h"
91 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
92 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
93 #include "llvm/Transforms/Scalar/DCE.h"
94 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
95 #include "llvm/Transforms/Scalar/EarlyCSE.h"
96 #include "llvm/Transforms/Scalar/Float2Int.h"
97 #include "llvm/Transforms/Scalar/GVN.h"
98 #include "llvm/Transforms/Scalar/GuardWidening.h"
99 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
100 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
101 #include "llvm/Transforms/Scalar/JumpThreading.h"
102 #include "llvm/Transforms/Scalar/LICM.h"
103 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
104 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
105 #include "llvm/Transforms/Scalar/LoopDeletion.h"
106 #include "llvm/Transforms/Scalar/LoopDistribute.h"
107 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
108 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
109 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
110 #include "llvm/Transforms/Scalar/LoopPassManager.h"
111 #include "llvm/Transforms/Scalar/LoopPredication.h"
112 #include "llvm/Transforms/Scalar/LoopRotation.h"
113 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
114 #include "llvm/Transforms/Scalar/LoopSink.h"
115 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
116 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
117 #include "llvm/Transforms/Scalar/LowerAtomic.h"
118 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
119 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
120 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
121 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
122 #include "llvm/Transforms/Scalar/NaryReassociate.h"
123 #include "llvm/Transforms/Scalar/NewGVN.h"
124 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
125 #include "llvm/Transforms/Scalar/Reassociate.h"
126 #include "llvm/Transforms/Scalar/SCCP.h"
127 #include "llvm/Transforms/Scalar/SROA.h"
128 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
129 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
130 #include "llvm/Transforms/Scalar/Sink.h"
131 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
132 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
133 #include "llvm/Transforms/Utils/AddDiscriminators.h"
134 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
135 #include "llvm/Transforms/Utils/LCSSA.h"
136 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
137 #include "llvm/Transforms/Utils/LoopSimplify.h"
138 #include "llvm/Transforms/Utils/LowerInvoke.h"
139 #include "llvm/Transforms/Utils/Mem2Reg.h"
140 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
141 #include "llvm/Transforms/Utils/PredicateInfo.h"
142 #include "llvm/Transforms/Utils/SimplifyInstructions.h"
143 #include "llvm/Transforms/Utils/SymbolRewriter.h"
144 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
145 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
147 #include <type_traits>
149 using namespace llvm;
151 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
152 cl::ReallyHidden, cl::init(4));
154 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
155 cl::Hidden, cl::ZeroOrMore,
156 cl::desc("Run Partial inlinining pass"));
159 RunNewGVN("enable-npm-newgvn", cl::init(false),
160 cl::Hidden, cl::ZeroOrMore,
161 cl::desc("Run NewGVN instead of GVN"));
163 static cl::opt<bool> EnableEarlyCSEMemSSA(
164 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
165 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
167 static cl::opt<bool> EnableGVNHoist(
168 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
169 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
171 static cl::opt<bool> EnableGVNSink(
172 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
173 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
175 static Regex DefaultAliasRegex(
176 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
178 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
180 case PassBuilder::O0:
181 case PassBuilder::O1:
182 case PassBuilder::O2:
183 case PassBuilder::O3:
186 case PassBuilder::Os:
187 case PassBuilder::Oz:
190 llvm_unreachable("Invalid optimization level!");
195 /// \brief No-op module pass which does nothing.
196 struct NoOpModulePass {
197 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
198 return PreservedAnalyses::all();
200 static StringRef name() { return "NoOpModulePass"; }
203 /// \brief No-op module analysis.
204 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
205 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
206 static AnalysisKey Key;
210 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
211 static StringRef name() { return "NoOpModuleAnalysis"; }
214 /// \brief No-op CGSCC pass which does nothing.
215 struct NoOpCGSCCPass {
216 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
217 LazyCallGraph &, CGSCCUpdateResult &UR) {
218 return PreservedAnalyses::all();
220 static StringRef name() { return "NoOpCGSCCPass"; }
223 /// \brief No-op CGSCC analysis.
224 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
225 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
226 static AnalysisKey Key;
230 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
233 static StringRef name() { return "NoOpCGSCCAnalysis"; }
236 /// \brief No-op function pass which does nothing.
237 struct NoOpFunctionPass {
238 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
239 return PreservedAnalyses::all();
241 static StringRef name() { return "NoOpFunctionPass"; }
244 /// \brief No-op function analysis.
245 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
246 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
247 static AnalysisKey Key;
251 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
252 static StringRef name() { return "NoOpFunctionAnalysis"; }
255 /// \brief No-op loop pass which does nothing.
256 struct NoOpLoopPass {
257 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
258 LoopStandardAnalysisResults &, LPMUpdater &) {
259 return PreservedAnalyses::all();
261 static StringRef name() { return "NoOpLoopPass"; }
264 /// \brief No-op loop analysis.
265 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
266 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
267 static AnalysisKey Key;
271 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
274 static StringRef name() { return "NoOpLoopAnalysis"; }
277 AnalysisKey NoOpModuleAnalysis::Key;
278 AnalysisKey NoOpCGSCCAnalysis::Key;
279 AnalysisKey NoOpFunctionAnalysis::Key;
280 AnalysisKey NoOpLoopAnalysis::Key;
282 } // End anonymous namespace.
284 void PassBuilder::invokePeepholeEPCallbacks(
285 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
286 for (auto &C : PeepholeEPCallbacks)
290 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
291 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
292 MAM.registerPass([&] { return CREATE_PASS; });
293 #include "PassRegistry.def"
295 for (auto &C : ModuleAnalysisRegistrationCallbacks)
299 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
300 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
301 CGAM.registerPass([&] { return CREATE_PASS; });
302 #include "PassRegistry.def"
304 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
308 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
309 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
310 FAM.registerPass([&] { return CREATE_PASS; });
311 #include "PassRegistry.def"
313 for (auto &C : FunctionAnalysisRegistrationCallbacks)
317 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
318 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
319 LAM.registerPass([&] { return CREATE_PASS; });
320 #include "PassRegistry.def"
322 for (auto &C : LoopAnalysisRegistrationCallbacks)
327 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
329 bool PrepareForThinLTO) {
330 assert(Level != O0 && "Must request optimizations!");
331 FunctionPassManager FPM(DebugLogging);
333 // Form SSA out of local memory accesses after breaking apart aggregates into
337 // Catch trivial redundancies
338 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
340 // Hoisting of scalars and load expressions.
342 FPM.addPass(GVNHoistPass());
344 // Global value numbering based sinking.
346 FPM.addPass(GVNSinkPass());
347 FPM.addPass(SimplifyCFGPass());
350 // Speculative execution if the target has divergent branches; otherwise nop.
351 FPM.addPass(SpeculativeExecutionPass());
353 // Optimize based on known information about branches, and cleanup afterward.
354 FPM.addPass(JumpThreadingPass());
355 FPM.addPass(CorrelatedValuePropagationPass());
356 FPM.addPass(SimplifyCFGPass());
357 FPM.addPass(InstCombinePass());
359 if (!isOptimizingForSize(Level))
360 FPM.addPass(LibCallsShrinkWrapPass());
362 invokePeepholeEPCallbacks(FPM, Level);
364 FPM.addPass(TailCallElimPass());
365 FPM.addPass(SimplifyCFGPass());
367 // Form canonically associated expression trees, and simplify the trees using
368 // basic mathematical properties. For example, this will form (nearly)
369 // minimal multiplication trees.
370 FPM.addPass(ReassociatePass());
372 // Add the primary loop simplification pipeline.
373 // FIXME: Currently this is split into two loop pass pipelines because we run
374 // some function passes in between them. These can and should be replaced by
375 // loop pass equivalenst but those aren't ready yet. Specifically,
376 // `SimplifyCFGPass` and `InstCombinePass` are used. We have
377 // `LoopSimplifyCFGPass` which isn't yet powerful enough, and the closest to
378 // the other we have is `LoopInstSimplify`.
379 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
381 // Rotate Loop - disable header duplication at -Oz
382 LPM1.addPass(LoopRotatePass(Level != Oz));
383 LPM1.addPass(LICMPass());
384 LPM1.addPass(SimpleLoopUnswitchPass());
385 LPM2.addPass(IndVarSimplifyPass());
386 LPM2.addPass(LoopIdiomRecognizePass());
388 for (auto &C : LateLoopOptimizationsEPCallbacks)
391 LPM2.addPass(LoopDeletionPass());
392 // Do not enable unrolling in PrepareForThinLTO phase during sample PGO
393 // because it changes IR to makes profile annotation in back compile
395 if (!PrepareForThinLTO || !PGOOpt || PGOOpt->SampleProfileFile.empty())
396 LPM2.addPass(LoopUnrollPass::createFull(Level));
398 for (auto &C : LoopOptimizerEndEPCallbacks)
401 // We provide the opt remark emitter pass for LICM to use. We only need to do
402 // this once as it is immutable.
403 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
404 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1)));
405 FPM.addPass(SimplifyCFGPass());
406 FPM.addPass(InstCombinePass());
407 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2)));
409 // Eliminate redundancies.
411 // These passes add substantial compile time so skip them at O1.
412 FPM.addPass(MergedLoadStoreMotionPass());
414 FPM.addPass(NewGVNPass());
419 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
420 FPM.addPass(MemCpyOptPass());
422 // Sparse conditional constant propagation.
423 // FIXME: It isn't clear why we do this *after* loop passes rather than
425 FPM.addPass(SCCPPass());
427 // Delete dead bit computations (instcombine runs after to fold away the dead
428 // computations, and then ADCE will run later to exploit any new DCE
429 // opportunities that creates).
430 FPM.addPass(BDCEPass());
432 // Run instcombine after redundancy and dead bit elimination to exploit
433 // opportunities opened up by them.
434 FPM.addPass(InstCombinePass());
435 invokePeepholeEPCallbacks(FPM, Level);
437 // Re-consider control flow based optimizations after redundancy elimination,
439 FPM.addPass(JumpThreadingPass());
440 FPM.addPass(CorrelatedValuePropagationPass());
441 FPM.addPass(DSEPass());
442 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
444 for (auto &C : ScalarOptimizerLateEPCallbacks)
447 // Finally, do an expensive DCE pass to catch all the dead code exposed by
448 // the simplifications and basic cleanup after all the simplifications.
449 FPM.addPass(ADCEPass());
450 FPM.addPass(SimplifyCFGPass());
451 FPM.addPass(InstCombinePass());
452 invokePeepholeEPCallbacks(FPM, Level);
457 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
458 PassBuilder::OptimizationLevel Level,
460 std::string ProfileGenFile,
461 std::string ProfileUseFile) {
462 // Generally running simplification passes and the inliner with an high
463 // threshold results in smaller executables, but there may be cases where
464 // the size grows, so let's be conservative here and skip this simplification
466 if (!isOptimizingForSize(Level)) {
469 // In the old pass manager, this is a cl::opt. Should still this be one?
470 IP.DefaultThreshold = 75;
472 // FIXME: The hint threshold has the same value used by the regular inliner.
473 // This should probably be lowered after performance testing.
474 // FIXME: this comment is cargo culted from the old pass manager, revisit).
475 IP.HintThreshold = 325;
477 CGSCCPassManager CGPipeline(DebugLogging);
479 CGPipeline.addPass(InlinerPass(IP));
481 FunctionPassManager FPM;
483 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
484 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
485 FPM.addPass(InstCombinePass()); // Combine silly sequences.
486 invokePeepholeEPCallbacks(FPM, Level);
488 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
490 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
493 // Delete anything that is now dead to make sure that we don't instrument
494 // dead code. Instrumentation can end up keeping dead code around and
495 // dramatically increase code size.
496 MPM.addPass(GlobalDCEPass());
499 MPM.addPass(PGOInstrumentationGen());
501 FunctionPassManager FPM;
502 FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
503 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
505 // Add the profile lowering pass.
506 InstrProfOptions Options;
507 if (!ProfileGenFile.empty())
508 Options.InstrProfileOutput = ProfileGenFile;
509 Options.DoCounterPromotion = true;
510 MPM.addPass(InstrProfiling(Options));
513 if (!ProfileUseFile.empty())
514 MPM.addPass(PGOInstrumentationUse(ProfileUseFile));
518 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
519 auto O3 = PassBuilder::O3;
520 unsigned OptLevel = Level > O3 ? 2 : Level;
521 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
522 return getInlineParams(OptLevel, SizeLevel);
526 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
528 bool PrepareForThinLTO) {
529 ModulePassManager MPM(DebugLogging);
531 // Do basic inference of function attributes from known properties of system
532 // libraries and other oracles.
533 MPM.addPass(InferFunctionAttrsPass());
535 // Create an early function pass manager to cleanup the output of the
537 FunctionPassManager EarlyFPM(DebugLogging);
538 EarlyFPM.addPass(SimplifyCFGPass());
539 EarlyFPM.addPass(SROA());
540 EarlyFPM.addPass(EarlyCSEPass());
541 EarlyFPM.addPass(LowerExpectIntrinsicPass());
542 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
544 // Interprocedural constant propagation now that basic cleanup has occured
545 // and prior to optimizing globals.
546 // FIXME: This position in the pipeline hasn't been carefully considered in
547 // years, it should be re-analyzed.
548 MPM.addPass(IPSCCPPass());
550 // Optimize globals to try and fold them into constants.
551 MPM.addPass(GlobalOptPass());
553 // Promote any localized globals to SSA registers.
554 // FIXME: Should this instead by a run of SROA?
555 // FIXME: We should probably run instcombine and simplify-cfg afterward to
556 // delete control flows that are dead once globals have been folded to
558 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
560 // Remove any dead arguments exposed by cleanups and constand folding
562 MPM.addPass(DeadArgumentEliminationPass());
564 // Create a small function pass pipeline to cleanup after all the global
566 FunctionPassManager GlobalCleanupPM(DebugLogging);
567 GlobalCleanupPM.addPass(InstCombinePass());
568 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
570 GlobalCleanupPM.addPass(SimplifyCFGPass());
571 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
573 // Add all the requested passes for PGO, if requested.
575 assert(PGOOpt->RunProfileGen || !PGOOpt->SampleProfileFile.empty() ||
576 !PGOOpt->ProfileUseFile.empty());
577 if (PGOOpt->SampleProfileFile.empty())
578 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
579 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile);
581 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile));
583 // Indirect call promotion that promotes intra-module targes only.
584 // Do not enable it in PrepareForThinLTO phase during sample PGO because
585 // it changes IR to makes profile annotation in back compile inaccurate.
586 if (!PrepareForThinLTO || PGOOpt->SampleProfileFile.empty())
587 MPM.addPass(PGOIndirectCallPromotion(
588 false, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
591 // Require the GlobalsAA analysis for the module so we can query it within
592 // the CGSCC pipeline.
593 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
595 // Require the ProfileSummaryAnalysis for the module so we can query it within
597 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
599 // Now begin the main postorder CGSCC pipeline.
600 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
601 // manager and trying to emulate its precise behavior. Much of this doesn't
602 // make a lot of sense and we should revisit the core CGSCC structure.
603 CGSCCPassManager MainCGPipeline(DebugLogging);
605 // Note: historically, the PruneEH pass was run first to deduce nounwind and
606 // generally clean up exception handling overhead. It isn't clear this is
607 // valuable as the inliner doesn't currently care whether it is inlining an
610 // Run the inliner first. The theory is that we are walking bottom-up and so
611 // the callees have already been fully optimized, and we want to inline them
612 // into the callers so that our optimizations can reflect that.
613 // For PrepareForThinLTO pass, we disable hot-caller heuristic for sample PGO
614 // because it makes profile annotation in the backend inaccurate.
615 InlineParams IP = getInlineParamsFromOptLevel(Level);
616 if (PrepareForThinLTO && PGOOpt && !PGOOpt->SampleProfileFile.empty())
617 IP.HotCallSiteThreshold = 0;
618 MainCGPipeline.addPass(InlinerPass(IP));
620 // Now deduce any function attributes based in the current code.
621 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
623 // When at O3 add argument promotion to the pass pipeline.
624 // FIXME: It isn't at all clear why this should be limited to O3.
626 MainCGPipeline.addPass(ArgumentPromotionPass());
628 // Lastly, add the core function simplification pipeline nested inside the
630 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
631 buildFunctionSimplificationPipeline(Level, DebugLogging,
632 PrepareForThinLTO)));
634 for (auto &C : CGSCCOptimizerLateEPCallbacks)
635 C(MainCGPipeline, Level);
637 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
638 // to detect when we devirtualize indirect calls and iterate the SCC passes
639 // in that case to try and catch knock-on inlining or function attrs
640 // opportunities. Then we add it to the module pipeline by walking the SCCs
641 // in postorder (or bottom-up).
643 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
644 std::move(MainCGPipeline), MaxDevirtIterations, DebugLogging)));
650 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
652 ModulePassManager MPM(DebugLogging);
654 // Optimize globals now that the module is fully simplified.
655 MPM.addPass(GlobalOptPass());
657 // Run partial inlining pass to partially inline functions that have
659 if (RunPartialInlining)
660 MPM.addPass(PartialInlinerPass());
662 // Remove avail extern fns and globals definitions since we aren't compiling
663 // an object file for later LTO. For LTO we want to preserve these so they
664 // are eligible for inlining at link-time. Note if they are unreferenced they
665 // will be removed by GlobalDCE later, so this only impacts referenced
666 // available externally globals. Eventually they will be suppressed during
667 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
668 // may make globals referenced by available external functions dead and saves
669 // running remaining passes on the eliminated functions.
670 MPM.addPass(EliminateAvailableExternallyPass());
672 // Do RPO function attribute inference across the module to forward-propagate
673 // attributes where applicable.
674 // FIXME: Is this really an optimization rather than a canonicalization?
675 MPM.addPass(ReversePostOrderFunctionAttrsPass());
677 // Re-require GloblasAA here prior to function passes. This is particularly
678 // useful as the above will have inlined, DCE'ed, and function-attr
679 // propagated everything. We should at this point have a reasonably minimal
680 // and richly annotated call graph. By computing aliasing and mod/ref
681 // information for all local globals here, the late loop passes and notably
682 // the vectorizer will be able to use them to help recognize vectorizable
683 // memory operations.
684 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
686 FunctionPassManager OptimizePM(DebugLogging);
687 OptimizePM.addPass(Float2IntPass());
688 // FIXME: We need to run some loop optimizations to re-rotate loops after
689 // simplify-cfg and others undo their rotation.
691 // Optimize the loop execution. These passes operate on entire loop nests
692 // rather than on each loop in an inside-out manner, and so they are actually
695 for (auto &C : VectorizerStartEPCallbacks)
696 C(OptimizePM, Level);
698 // First rotate loops that may have been un-rotated by prior passes.
699 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
701 // Distribute loops to allow partial vectorization. I.e. isolate dependences
702 // into separate loop that would otherwise inhibit vectorization. This is
703 // currently only performed for loops marked with the metadata
704 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
705 OptimizePM.addPass(LoopDistributePass());
707 // Now run the core loop vectorizer.
708 OptimizePM.addPass(LoopVectorizePass());
710 // Eliminate loads by forwarding stores from the previous iteration to loads
711 // of the current iteration.
712 OptimizePM.addPass(LoopLoadEliminationPass());
714 // Cleanup after the loop optimization passes.
715 OptimizePM.addPass(InstCombinePass());
718 // Now that we've formed fast to execute loop structures, we do further
719 // optimizations. These are run afterward as they might block doing complex
720 // analyses and transforms such as what are needed for loop vectorization.
722 // Optimize parallel scalar instruction chains into SIMD instructions.
723 OptimizePM.addPass(SLPVectorizerPass());
725 // Cleanup after all of the vectorizers.
726 OptimizePM.addPass(SimplifyCFGPass());
727 OptimizePM.addPass(InstCombinePass());
729 // Unroll small loops to hide loop backedge latency and saturate any parallel
730 // execution resources of an out-of-order processor. We also then need to
731 // clean up redundancies and loop invariant code.
732 // FIXME: It would be really good to use a loop-integrated instruction
733 // combiner for cleanup here so that the unrolling and LICM can be pipelined
734 // across the loop nests.
735 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopUnrollPass::create(Level)));
736 OptimizePM.addPass(InstCombinePass());
737 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
738 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
740 // Now that we've vectorized and unrolled loops, we may have more refined
741 // alignment information, try to re-derive it here.
742 OptimizePM.addPass(AlignmentFromAssumptionsPass());
744 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
745 // canonicalization pass that enables other optimizations. As a result,
746 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
748 OptimizePM.addPass(LoopSinkPass());
750 // And finally clean up LCSSA form before generating code.
751 OptimizePM.addPass(InstSimplifierPass());
753 // LoopSink (and other loop passes since the last simplifyCFG) might have
754 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
755 OptimizePM.addPass(SimplifyCFGPass());
757 // Add the core optimizing pipeline.
758 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
760 // Now we need to do some global optimization transforms.
761 // FIXME: It would seem like these should come first in the optimization
762 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
764 MPM.addPass(GlobalDCEPass());
765 MPM.addPass(ConstantMergePass());
771 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
773 assert(Level != O0 && "Must request optimizations for the default pipeline!");
775 ModulePassManager MPM(DebugLogging);
777 // Force any function attributes we want the rest of the pipeline to observe.
778 MPM.addPass(ForceFunctionAttrsPass());
780 // Add the core simplification pipeline.
781 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging,
782 /*PrepareForThinLTO=*/false));
784 // Now add the optimization pipeline.
785 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
791 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
793 assert(Level != O0 && "Must request optimizations for the default pipeline!");
795 ModulePassManager MPM(DebugLogging);
797 // Force any function attributes we want the rest of the pipeline to observe.
798 MPM.addPass(ForceFunctionAttrsPass());
800 // If we are planning to perform ThinLTO later, we don't bloat the code with
801 // unrolling/vectorization/... now. Just simplify the module as much as we
803 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging,
804 /*PrepareForThinLTO=*/true));
806 // Run partial inlining pass to partially inline functions that have
808 // FIXME: It isn't clear whether this is really the right place to run this
809 // in ThinLTO. Because there is another canonicalization and simplification
810 // phase that will run after the thin link, running this here ends up with
811 // less information than will be available later and it may grow functions in
812 // ways that aren't beneficial.
813 if (RunPartialInlining)
814 MPM.addPass(PartialInlinerPass());
816 // Reduce the size of the IR as much as possible.
817 MPM.addPass(GlobalOptPass());
823 PassBuilder::buildThinLTODefaultPipeline(OptimizationLevel Level,
825 // FIXME: The summary index is not hooked in the new pass manager yet.
826 // When it's going to be hooked, enable WholeProgramDevirt and LowerTypeTest
829 ModulePassManager MPM(DebugLogging);
831 // Force any function attributes we want the rest of the pipeline to observe.
832 MPM.addPass(ForceFunctionAttrsPass());
834 // During the ThinLTO backend phase we perform early indirect call promotion
835 // here, before globalopt. Otherwise imported available_externally functions
836 // look unreferenced and are removed.
837 MPM.addPass(PGOIndirectCallPromotion(
838 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
839 !PGOOpt->ProfileUseFile.empty()));
841 // Add the core simplification pipeline.
842 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging,
843 /*PrepareForThinLTO=*/false));
845 // Now add the optimization pipeline.
846 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
852 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
854 assert(Level != O0 && "Must request optimizations for the default pipeline!");
855 // FIXME: We should use a customized pre-link pipeline!
856 return buildPerModuleDefaultPipeline(Level, DebugLogging);
859 ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
861 assert(Level != O0 && "Must request optimizations for the default pipeline!");
862 ModulePassManager MPM(DebugLogging);
864 // Remove unused virtual tables to improve the quality of code generated by
865 // whole-program devirtualization and bitset lowering.
866 MPM.addPass(GlobalDCEPass());
868 // Force any function attributes we want the rest of the pipeline to observe.
869 MPM.addPass(ForceFunctionAttrsPass());
871 // Do basic inference of function attributes from known properties of system
872 // libraries and other oracles.
873 MPM.addPass(InferFunctionAttrsPass());
876 // Indirect call promotion. This should promote all the targets that are
877 // left by the earlier promotion pass that promotes intra-module targets.
878 // This two-step promotion is to save the compile time. For LTO, it should
879 // produce the same result as if we only do promotion here.
880 MPM.addPass(PGOIndirectCallPromotion(
881 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
883 // Propagate constants at call sites into the functions they call. This
884 // opens opportunities for globalopt (and inlining) by substituting function
885 // pointers passed as arguments to direct uses of functions.
886 MPM.addPass(IPSCCPPass());
889 // Now deduce any function attributes based in the current code.
890 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
891 PostOrderFunctionAttrsPass()));
893 // Do RPO function attribute inference across the module to forward-propagate
894 // attributes where applicable.
895 // FIXME: Is this really an optimization rather than a canonicalization?
896 MPM.addPass(ReversePostOrderFunctionAttrsPass());
898 // Use inragne annotations on GEP indices to split globals where beneficial.
899 MPM.addPass(GlobalSplitPass());
901 // Run whole program optimization of virtual call when the list of callees
903 MPM.addPass(WholeProgramDevirtPass());
909 // Optimize globals to try and fold them into constants.
910 MPM.addPass(GlobalOptPass());
912 // Promote any localized globals to SSA registers.
913 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
915 // Linking modules together can lead to duplicate global constant, only
916 // keep one copy of each constant.
917 MPM.addPass(ConstantMergePass());
919 // Remove unused arguments from functions.
920 MPM.addPass(DeadArgumentEliminationPass());
922 // Reduce the code after globalopt and ipsccp. Both can open up significant
923 // simplification opportunities, and both can propagate functions through
924 // function pointers. When this happens, we often have to resolve varargs
925 // calls, etc, so let instcombine do this.
926 FunctionPassManager PeepholeFPM(DebugLogging);
927 PeepholeFPM.addPass(InstCombinePass());
928 invokePeepholeEPCallbacks(PeepholeFPM, Level);
930 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
932 // Note: historically, the PruneEH pass was run first to deduce nounwind and
933 // generally clean up exception handling overhead. It isn't clear this is
934 // valuable as the inliner doesn't currently care whether it is inlining an
936 // Run the inliner now.
937 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
938 InlinerPass(getInlineParamsFromOptLevel(Level))));
940 // Optimize globals again after we ran the inliner.
941 MPM.addPass(GlobalOptPass());
943 // Garbage collect dead functions.
944 // FIXME: Add ArgumentPromotion pass after once it's ported.
945 MPM.addPass(GlobalDCEPass());
947 FunctionPassManager FPM(DebugLogging);
948 // The IPO Passes may leave cruft around. Clean up after them.
949 FPM.addPass(InstCombinePass());
950 invokePeepholeEPCallbacks(FPM, Level);
952 FPM.addPass(JumpThreadingPass());
957 // Run a few AA driver optimizations here and now to cleanup the code.
958 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
960 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
961 PostOrderFunctionAttrsPass()));
962 // FIXME: here we run IP alias analysis in the legacy PM.
964 FunctionPassManager MainFPM;
966 // FIXME: once we fix LoopPass Manager, add LICM here.
967 // FIXME: once we provide support for enabling MLSM, add it here.
968 // FIXME: once we provide support for enabling NewGVN, add it here.
970 MainFPM.addPass(NewGVNPass());
972 MainFPM.addPass(GVN());
974 // Remove dead memcpy()'s.
975 MainFPM.addPass(MemCpyOptPass());
978 MainFPM.addPass(DSEPass());
980 // FIXME: at this point, we run a bunch of loop passes:
981 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
982 // loopVectorize. Enable them once the remaining issue with LPM
985 MainFPM.addPass(InstCombinePass());
986 MainFPM.addPass(SimplifyCFGPass());
987 MainFPM.addPass(SCCPPass());
988 MainFPM.addPass(InstCombinePass());
989 MainFPM.addPass(BDCEPass());
991 // FIXME: We may want to run SLPVectorizer here.
992 // After vectorization, assume intrinsics may tell us more
993 // about pointer alignments.
995 MainFPM.add(AlignmentFromAssumptionsPass());
998 // FIXME: Conditionally run LoadCombine here, after it's ported
999 // (in case we still have this pass, given its questionable usefulness).
1001 MainFPM.addPass(InstCombinePass());
1002 invokePeepholeEPCallbacks(MainFPM, Level);
1003 MainFPM.addPass(JumpThreadingPass());
1004 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1006 // Create a function that performs CFI checks for cross-DSO calls with
1007 // targets in the current module.
1008 MPM.addPass(CrossDSOCFIPass());
1010 // Lower type metadata and the type.test intrinsic. This pass supports
1011 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1012 // to be run at link time if CFI is enabled. This pass does nothing if
1014 // Enable once we add support for the summary in the new PM.
1016 MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export :
1017 PassSummaryAction::None,
1021 // Add late LTO optimization passes.
1022 // Delete basic blocks, which optimization passes may have killed.
1023 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1025 // Drop bodies of available eternally objects to improve GlobalDCE.
1026 MPM.addPass(EliminateAvailableExternallyPass());
1028 // Now that we have optimized the program, discard unreachable functions.
1029 MPM.addPass(GlobalDCEPass());
1031 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
1035 AAManager PassBuilder::buildDefaultAAPipeline() {
1038 // The order in which these are registered determines their priority when
1041 // First we register the basic alias analysis that provides the majority of
1042 // per-function local AA logic. This is a stateless, on-demand local set of
1044 AA.registerFunctionAnalysis<BasicAA>();
1046 // Next we query fast, specialized alias analyses that wrap IR-embedded
1047 // information about aliasing.
1048 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1049 AA.registerFunctionAnalysis<TypeBasedAA>();
1051 // Add support for querying global aliasing information when available.
1052 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1053 // analysis, all that the `AAManager` can do is query for any *cached*
1054 // results from `GlobalsAA` through a readonly proxy.
1055 AA.registerModuleAnalysis<GlobalsAA>();
1060 static Optional<int> parseRepeatPassName(StringRef Name) {
1061 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1064 if (Name.getAsInteger(0, Count) || Count <= 0)
1069 static Optional<int> parseDevirtPassName(StringRef Name) {
1070 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1073 if (Name.getAsInteger(0, Count) || Count <= 0)
1078 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1080 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1081 return Name.startswith("default") || Name.startswith("thinlto") ||
1082 Name.startswith("lto");
1085 /// Tests whether registered callbacks will accept a given pass name.
1087 /// When parsing a pipeline text, the type of the outermost pipeline may be
1088 /// omitted, in which case the type is automatically determined from the first
1089 /// pass name in the text. This may be a name that is handled through one of the
1090 /// callbacks. We check this through the oridinary parsing callbacks by setting
1091 /// up a dummy PassManager in order to not force the client to also handle this
1093 template <typename PassManagerT, typename CallbacksT>
1094 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1095 if (!Callbacks.empty()) {
1096 PassManagerT DummyPM;
1097 for (auto &CB : Callbacks)
1098 if (CB(Name, DummyPM, {}))
1104 template <typename CallbacksT>
1105 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
1106 // Manually handle aliases for pre-configured pipeline fragments.
1107 if (startsWithDefaultPipelineAliasPrefix(Name))
1108 return DefaultAliasRegex.match(Name);
1110 // Explicitly handle pass manager names.
1111 if (Name == "module")
1113 if (Name == "cgscc")
1115 if (Name == "function")
1118 // Explicitly handle custom-parsed pass names.
1119 if (parseRepeatPassName(Name))
1122 #define MODULE_PASS(NAME, CREATE_PASS) \
1125 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1126 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1128 #include "PassRegistry.def"
1130 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
1133 template <typename CallbacksT>
1134 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
1135 // Explicitly handle pass manager names.
1136 if (Name == "cgscc")
1138 if (Name == "function")
1141 // Explicitly handle custom-parsed pass names.
1142 if (parseRepeatPassName(Name))
1144 if (parseDevirtPassName(Name))
1147 #define CGSCC_PASS(NAME, CREATE_PASS) \
1150 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1151 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1153 #include "PassRegistry.def"
1155 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
1158 template <typename CallbacksT>
1159 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
1160 // Explicitly handle pass manager names.
1161 if (Name == "function")
1166 // Explicitly handle custom-parsed pass names.
1167 if (parseRepeatPassName(Name))
1170 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1173 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1174 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1176 #include "PassRegistry.def"
1178 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
1181 template <typename CallbacksT>
1182 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
1183 // Explicitly handle pass manager names.
1187 // Explicitly handle custom-parsed pass names.
1188 if (parseRepeatPassName(Name))
1191 #define LOOP_PASS(NAME, CREATE_PASS) \
1194 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1195 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1197 #include "PassRegistry.def"
1199 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1202 Optional<std::vector<PassBuilder::PipelineElement>>
1203 PassBuilder::parsePipelineText(StringRef Text) {
1204 std::vector<PipelineElement> ResultPipeline;
1206 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1209 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1210 size_t Pos = Text.find_first_of(",()");
1211 Pipeline.push_back({Text.substr(0, Pos), {}});
1213 // If we have a single terminating name, we're done.
1214 if (Pos == Text.npos)
1217 char Sep = Text[Pos];
1218 Text = Text.substr(Pos + 1);
1220 // Just a name ending in a comma, continue.
1224 // Push the inner pipeline onto the stack to continue processing.
1225 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1229 assert(Sep == ')' && "Bogus separator!");
1230 // When handling the close parenthesis, we greedily consume them to avoid
1231 // empty strings in the pipeline.
1233 // If we try to pop the outer pipeline we have unbalanced parentheses.
1234 if (PipelineStack.size() == 1)
1237 PipelineStack.pop_back();
1238 } while (Text.consume_front(")"));
1240 // Check if we've finished parsing.
1244 // Otherwise, the end of an inner pipeline always has to be followed by
1245 // a comma, and then we can continue.
1246 if (!Text.consume_front(","))
1250 if (PipelineStack.size() > 1)
1251 // Unbalanced paretheses.
1254 assert(PipelineStack.back() == &ResultPipeline &&
1255 "Wrong pipeline at the bottom of the stack!");
1256 return {std::move(ResultPipeline)};
1259 bool PassBuilder::parseModulePass(ModulePassManager &MPM,
1260 const PipelineElement &E, bool VerifyEachPass,
1261 bool DebugLogging) {
1262 auto &Name = E.Name;
1263 auto &InnerPipeline = E.InnerPipeline;
1265 // First handle complex passes like the pass managers which carry pipelines.
1266 if (!InnerPipeline.empty()) {
1267 if (Name == "module") {
1268 ModulePassManager NestedMPM(DebugLogging);
1269 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1272 MPM.addPass(std::move(NestedMPM));
1275 if (Name == "cgscc") {
1276 CGSCCPassManager CGPM(DebugLogging);
1277 if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1280 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM),
1284 if (Name == "function") {
1285 FunctionPassManager FPM(DebugLogging);
1286 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1289 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1292 if (auto Count = parseRepeatPassName(Name)) {
1293 ModulePassManager NestedMPM(DebugLogging);
1294 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1297 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1301 for (auto &C : ModulePipelineParsingCallbacks)
1302 if (C(Name, MPM, InnerPipeline))
1305 // Normal passes can't have pipelines.
1309 // Manually handle aliases for pre-configured pipeline fragments.
1310 if (startsWithDefaultPipelineAliasPrefix(Name)) {
1311 SmallVector<StringRef, 3> Matches;
1312 if (!DefaultAliasRegex.match(Name, &Matches))
1314 assert(Matches.size() == 3 && "Must capture two matched strings!");
1316 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1324 // At O0 we do nothing at all!
1327 if (Matches[1] == "default") {
1328 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1329 } else if (Matches[1] == "thinlto-pre-link") {
1330 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1331 } else if (Matches[1] == "thinlto") {
1332 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging));
1333 } else if (Matches[1] == "lto-pre-link") {
1334 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1336 assert(Matches[1] == "lto" && "Not one of the matched options!");
1337 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging));
1342 // Finally expand the basic registered passes from the .inc file.
1343 #define MODULE_PASS(NAME, CREATE_PASS) \
1344 if (Name == NAME) { \
1345 MPM.addPass(CREATE_PASS); \
1348 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1349 if (Name == "require<" NAME ">") { \
1351 RequireAnalysisPass< \
1352 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
1355 if (Name == "invalidate<" NAME ">") { \
1356 MPM.addPass(InvalidateAnalysisPass< \
1357 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1360 #include "PassRegistry.def"
1362 for (auto &C : ModulePipelineParsingCallbacks)
1363 if (C(Name, MPM, InnerPipeline))
1368 bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1369 const PipelineElement &E, bool VerifyEachPass,
1370 bool DebugLogging) {
1371 auto &Name = E.Name;
1372 auto &InnerPipeline = E.InnerPipeline;
1374 // First handle complex passes like the pass managers which carry pipelines.
1375 if (!InnerPipeline.empty()) {
1376 if (Name == "cgscc") {
1377 CGSCCPassManager NestedCGPM(DebugLogging);
1378 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1381 // Add the nested pass manager with the appropriate adaptor.
1382 CGPM.addPass(std::move(NestedCGPM));
1385 if (Name == "function") {
1386 FunctionPassManager FPM(DebugLogging);
1387 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1390 // Add the nested pass manager with the appropriate adaptor.
1392 createCGSCCToFunctionPassAdaptor(std::move(FPM), DebugLogging));
1395 if (auto Count = parseRepeatPassName(Name)) {
1396 CGSCCPassManager NestedCGPM(DebugLogging);
1397 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1400 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1403 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1404 CGSCCPassManager NestedCGPM(DebugLogging);
1405 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1408 CGPM.addPass(createDevirtSCCRepeatedPass(std::move(NestedCGPM),
1409 *MaxRepetitions, DebugLogging));
1413 for (auto &C : CGSCCPipelineParsingCallbacks)
1414 if (C(Name, CGPM, InnerPipeline))
1417 // Normal passes can't have pipelines.
1421 // Now expand the basic registered passes from the .inc file.
1422 #define CGSCC_PASS(NAME, CREATE_PASS) \
1423 if (Name == NAME) { \
1424 CGPM.addPass(CREATE_PASS); \
1427 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1428 if (Name == "require<" NAME ">") { \
1429 CGPM.addPass(RequireAnalysisPass< \
1430 std::remove_reference<decltype(CREATE_PASS)>::type, \
1431 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1432 CGSCCUpdateResult &>()); \
1435 if (Name == "invalidate<" NAME ">") { \
1436 CGPM.addPass(InvalidateAnalysisPass< \
1437 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1440 #include "PassRegistry.def"
1442 for (auto &C : CGSCCPipelineParsingCallbacks)
1443 if (C(Name, CGPM, InnerPipeline))
1448 bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1449 const PipelineElement &E,
1450 bool VerifyEachPass, bool DebugLogging) {
1451 auto &Name = E.Name;
1452 auto &InnerPipeline = E.InnerPipeline;
1454 // First handle complex passes like the pass managers which carry pipelines.
1455 if (!InnerPipeline.empty()) {
1456 if (Name == "function") {
1457 FunctionPassManager NestedFPM(DebugLogging);
1458 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1461 // Add the nested pass manager with the appropriate adaptor.
1462 FPM.addPass(std::move(NestedFPM));
1465 if (Name == "loop") {
1466 LoopPassManager LPM(DebugLogging);
1467 if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1470 // Add the nested pass manager with the appropriate adaptor.
1471 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
1474 if (auto Count = parseRepeatPassName(Name)) {
1475 FunctionPassManager NestedFPM(DebugLogging);
1476 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1479 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1483 for (auto &C : FunctionPipelineParsingCallbacks)
1484 if (C(Name, FPM, InnerPipeline))
1487 // Normal passes can't have pipelines.
1491 // Now expand the basic registered passes from the .inc file.
1492 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1493 if (Name == NAME) { \
1494 FPM.addPass(CREATE_PASS); \
1497 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1498 if (Name == "require<" NAME ">") { \
1500 RequireAnalysisPass< \
1501 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
1504 if (Name == "invalidate<" NAME ">") { \
1505 FPM.addPass(InvalidateAnalysisPass< \
1506 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1509 #include "PassRegistry.def"
1511 for (auto &C : FunctionPipelineParsingCallbacks)
1512 if (C(Name, FPM, InnerPipeline))
1517 bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1518 bool VerifyEachPass, bool DebugLogging) {
1519 StringRef Name = E.Name;
1520 auto &InnerPipeline = E.InnerPipeline;
1522 // First handle complex passes like the pass managers which carry pipelines.
1523 if (!InnerPipeline.empty()) {
1524 if (Name == "loop") {
1525 LoopPassManager NestedLPM(DebugLogging);
1526 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1529 // Add the nested pass manager with the appropriate adaptor.
1530 LPM.addPass(std::move(NestedLPM));
1533 if (auto Count = parseRepeatPassName(Name)) {
1534 LoopPassManager NestedLPM(DebugLogging);
1535 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1538 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1542 for (auto &C : LoopPipelineParsingCallbacks)
1543 if (C(Name, LPM, InnerPipeline))
1546 // Normal passes can't have pipelines.
1550 // Now expand the basic registered passes from the .inc file.
1551 #define LOOP_PASS(NAME, CREATE_PASS) \
1552 if (Name == NAME) { \
1553 LPM.addPass(CREATE_PASS); \
1556 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1557 if (Name == "require<" NAME ">") { \
1558 LPM.addPass(RequireAnalysisPass< \
1559 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1560 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1564 if (Name == "invalidate<" NAME ">") { \
1565 LPM.addPass(InvalidateAnalysisPass< \
1566 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1569 #include "PassRegistry.def"
1571 for (auto &C : LoopPipelineParsingCallbacks)
1572 if (C(Name, LPM, InnerPipeline))
1577 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1578 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1579 if (Name == NAME) { \
1580 AA.registerModuleAnalysis< \
1581 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1584 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1585 if (Name == NAME) { \
1586 AA.registerFunctionAnalysis< \
1587 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1590 #include "PassRegistry.def"
1592 for (auto &C : AAParsingCallbacks)
1598 bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1599 ArrayRef<PipelineElement> Pipeline,
1600 bool VerifyEachPass,
1601 bool DebugLogging) {
1602 for (const auto &Element : Pipeline) {
1603 if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1605 // FIXME: No verifier support for Loop passes!
1610 bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1611 ArrayRef<PipelineElement> Pipeline,
1612 bool VerifyEachPass,
1613 bool DebugLogging) {
1614 for (const auto &Element : Pipeline) {
1615 if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1618 FPM.addPass(VerifierPass());
1623 bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1624 ArrayRef<PipelineElement> Pipeline,
1625 bool VerifyEachPass,
1626 bool DebugLogging) {
1627 for (const auto &Element : Pipeline) {
1628 if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1630 // FIXME: No verifier support for CGSCC passes!
1635 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1636 FunctionAnalysisManager &FAM,
1637 CGSCCAnalysisManager &CGAM,
1638 ModuleAnalysisManager &MAM) {
1639 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1640 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1641 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1642 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1643 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1644 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1645 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1648 bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1649 ArrayRef<PipelineElement> Pipeline,
1650 bool VerifyEachPass,
1651 bool DebugLogging) {
1652 for (const auto &Element : Pipeline) {
1653 if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1656 MPM.addPass(VerifierPass());
1661 // Primary pass pipeline description parsing routine for a \c ModulePassManager
1662 // FIXME: Should this routine accept a TargetMachine or require the caller to
1663 // pre-populate the analysis managers with target-specific stuff?
1664 bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1665 StringRef PipelineText, bool VerifyEachPass,
1666 bool DebugLogging) {
1667 auto Pipeline = parsePipelineText(PipelineText);
1668 if (!Pipeline || Pipeline->empty())
1671 // If the first name isn't at the module layer, wrap the pipeline up
1673 StringRef FirstName = Pipeline->front().Name;
1675 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1676 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
1677 Pipeline = {{"cgscc", std::move(*Pipeline)}};
1678 } else if (isFunctionPassName(FirstName,
1679 FunctionPipelineParsingCallbacks)) {
1680 Pipeline = {{"function", std::move(*Pipeline)}};
1681 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
1682 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
1684 for (auto &C : TopLevelPipelineParsingCallbacks)
1685 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1688 // Unknown pass name!
1693 return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
1696 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
1697 bool PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1698 StringRef PipelineText, bool VerifyEachPass,
1699 bool DebugLogging) {
1700 auto Pipeline = parsePipelineText(PipelineText);
1701 if (!Pipeline || Pipeline->empty())
1704 StringRef FirstName = Pipeline->front().Name;
1705 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
1708 return parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1711 // Primary pass pipeline description parsing routine for a \c
1712 // FunctionPassManager
1713 bool PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1714 StringRef PipelineText, bool VerifyEachPass,
1715 bool DebugLogging) {
1716 auto Pipeline = parsePipelineText(PipelineText);
1717 if (!Pipeline || Pipeline->empty())
1720 StringRef FirstName = Pipeline->front().Name;
1721 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
1724 return parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1728 // Primary pass pipeline description parsing routine for a \c LoopPassManager
1729 bool PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1730 StringRef PipelineText, bool VerifyEachPass,
1731 bool DebugLogging) {
1732 auto Pipeline = parsePipelineText(PipelineText);
1733 if (!Pipeline || Pipeline->empty())
1736 return parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1739 bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
1740 // If the pipeline just consists of the word 'default' just replace the AA
1741 // manager with our default one.
1742 if (PipelineText == "default") {
1743 AA = buildDefaultAAPipeline();
1747 while (!PipelineText.empty()) {
1749 std::tie(Name, PipelineText) = PipelineText.split(',');
1750 if (!parseAAPassName(AA, Name))