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::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
285 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
286 MAM.registerPass([&] { return CREATE_PASS; });
287 #include "PassRegistry.def"
290 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
291 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
292 CGAM.registerPass([&] { return CREATE_PASS; });
293 #include "PassRegistry.def"
296 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
297 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
298 FAM.registerPass([&] { return CREATE_PASS; });
299 #include "PassRegistry.def"
302 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
303 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
304 LAM.registerPass([&] { return CREATE_PASS; });
305 #include "PassRegistry.def"
309 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
311 assert(Level != O0 && "Must request optimizations!");
312 FunctionPassManager FPM(DebugLogging);
314 // Form SSA out of local memory accesses after breaking apart aggregates into
318 // Catch trivial redundancies
319 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
321 // Hoisting of scalars and load expressions.
323 FPM.addPass(GVNHoistPass());
325 // Global value numbering based sinking.
327 FPM.addPass(GVNSinkPass());
328 FPM.addPass(SimplifyCFGPass());
331 // Speculative execution if the target has divergent branches; otherwise nop.
332 FPM.addPass(SpeculativeExecutionPass());
334 // Optimize based on known information about branches, and cleanup afterward.
335 FPM.addPass(JumpThreadingPass());
336 FPM.addPass(CorrelatedValuePropagationPass());
337 FPM.addPass(SimplifyCFGPass());
338 FPM.addPass(InstCombinePass());
340 if (!isOptimizingForSize(Level))
341 FPM.addPass(LibCallsShrinkWrapPass());
343 FPM.addPass(TailCallElimPass());
344 FPM.addPass(SimplifyCFGPass());
346 // Form canonically associated expression trees, and simplify the trees using
347 // basic mathematical properties. For example, this will form (nearly)
348 // minimal multiplication trees.
349 FPM.addPass(ReassociatePass());
351 // Add the primary loop simplification pipeline.
352 // FIXME: Currently this is split into two loop pass pipelines because we run
353 // some function passes in between them. These can and should be replaced by
354 // loop pass equivalenst but those aren't ready yet. Specifically,
355 // `SimplifyCFGPass` and `InstCombinePass` are used. We have
356 // `LoopSimplifyCFGPass` which isn't yet powerful enough, and the closest to
357 // the other we have is `LoopInstSimplify`.
358 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
360 // Rotate Loop - disable header duplication at -Oz
361 LPM1.addPass(LoopRotatePass(Level != Oz));
362 LPM1.addPass(LICMPass());
363 LPM1.addPass(SimpleLoopUnswitchPass());
364 LPM2.addPass(IndVarSimplifyPass());
365 LPM2.addPass(LoopIdiomRecognizePass());
366 LPM2.addPass(LoopDeletionPass());
367 // FIXME: The old pass manager has a hack to disable loop unrolling during
368 // ThinLTO when using sample PGO. Need to either fix it or port some
370 LPM2.addPass(LoopUnrollPass::createFull(Level));
372 // We provide the opt remark emitter pass for LICM to use. We only need to do
373 // this once as it is immutable.
374 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
375 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1)));
376 FPM.addPass(SimplifyCFGPass());
377 FPM.addPass(InstCombinePass());
378 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2)));
380 // Eliminate redundancies.
382 // These passes add substantial compile time so skip them at O1.
383 FPM.addPass(MergedLoadStoreMotionPass());
385 FPM.addPass(NewGVNPass());
390 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
391 FPM.addPass(MemCpyOptPass());
393 // Sparse conditional constant propagation.
394 // FIXME: It isn't clear why we do this *after* loop passes rather than
396 FPM.addPass(SCCPPass());
398 // Delete dead bit computations (instcombine runs after to fold away the dead
399 // computations, and then ADCE will run later to exploit any new DCE
400 // opportunities that creates).
401 FPM.addPass(BDCEPass());
403 // Run instcombine after redundancy and dead bit elimination to exploit
404 // opportunities opened up by them.
405 FPM.addPass(InstCombinePass());
407 // Re-consider control flow based optimizations after redundancy elimination,
409 FPM.addPass(JumpThreadingPass());
410 FPM.addPass(CorrelatedValuePropagationPass());
411 FPM.addPass(DSEPass());
412 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
414 // Finally, do an expensive DCE pass to catch all the dead code exposed by
415 // the simplifications and basic cleanup after all the simplifications.
416 FPM.addPass(ADCEPass());
417 FPM.addPass(SimplifyCFGPass());
418 FPM.addPass(InstCombinePass());
423 static void addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
424 PassBuilder::OptimizationLevel Level,
425 bool RunProfileGen, std::string ProfileGenFile,
426 std::string ProfileUseFile) {
427 // Generally running simplification passes and the inliner with an high
428 // threshold results in smaller executables, but there may be cases where
429 // the size grows, so let's be conservative here and skip this simplification
431 if (!isOptimizingForSize(Level)) {
434 // In the old pass manager, this is a cl::opt. Should still this be one?
435 IP.DefaultThreshold = 75;
437 // FIXME: The hint threshold has the same value used by the regular inliner.
438 // This should probably be lowered after performance testing.
439 // FIXME: this comment is cargo culted from the old pass manager, revisit).
440 IP.HintThreshold = 325;
442 CGSCCPassManager CGPipeline(DebugLogging);
444 CGPipeline.addPass(InlinerPass(IP));
446 FunctionPassManager FPM;
448 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
449 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
450 FPM.addPass(InstCombinePass()); // Combine silly sequences.
452 // FIXME: Here the old pass manager inserts peephole extensions.
453 // Add them when they're supported.
454 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
456 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
459 // Delete anything that is now dead to make sure that we don't instrument
460 // dead code. Instrumentation can end up keeping dead code around and
461 // dramatically increase code size.
462 MPM.addPass(GlobalDCEPass());
465 MPM.addPass(PGOInstrumentationGen());
467 FunctionPassManager FPM;
468 FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
469 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
471 // Add the profile lowering pass.
472 InstrProfOptions Options;
473 if (!ProfileGenFile.empty())
474 Options.InstrProfileOutput = ProfileGenFile;
475 Options.DoCounterPromotion = true;
476 MPM.addPass(InstrProfiling(Options));
479 if (!ProfileUseFile.empty())
480 MPM.addPass(PGOInstrumentationUse(ProfileUseFile));
484 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
485 auto O3 = PassBuilder::O3;
486 unsigned OptLevel = Level > O3 ? 2 : Level;
487 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
488 return getInlineParams(OptLevel, SizeLevel);
492 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
494 ModulePassManager MPM(DebugLogging);
496 // Do basic inference of function attributes from known properties of system
497 // libraries and other oracles.
498 MPM.addPass(InferFunctionAttrsPass());
500 // Create an early function pass manager to cleanup the output of the
502 FunctionPassManager EarlyFPM(DebugLogging);
503 EarlyFPM.addPass(SimplifyCFGPass());
504 EarlyFPM.addPass(SROA());
505 EarlyFPM.addPass(EarlyCSEPass());
506 EarlyFPM.addPass(LowerExpectIntrinsicPass());
507 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
509 // Interprocedural constant propagation now that basic cleanup has occured
510 // and prior to optimizing globals.
511 // FIXME: This position in the pipeline hasn't been carefully considered in
512 // years, it should be re-analyzed.
513 MPM.addPass(IPSCCPPass());
515 // Optimize globals to try and fold them into constants.
516 MPM.addPass(GlobalOptPass());
518 // Promote any localized globals to SSA registers.
519 // FIXME: Should this instead by a run of SROA?
520 // FIXME: We should probably run instcombine and simplify-cfg afterward to
521 // delete control flows that are dead once globals have been folded to
523 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
525 // Remove any dead arguments exposed by cleanups and constand folding
527 MPM.addPass(DeadArgumentEliminationPass());
529 // Create a small function pass pipeline to cleanup after all the global
531 FunctionPassManager GlobalCleanupPM(DebugLogging);
532 GlobalCleanupPM.addPass(InstCombinePass());
533 GlobalCleanupPM.addPass(SimplifyCFGPass());
534 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
536 // Add all the requested passes for PGO, if requested.
538 assert(PGOOpt->RunProfileGen || !PGOOpt->SampleProfileFile.empty() ||
539 !PGOOpt->ProfileUseFile.empty());
540 if (PGOOpt->SampleProfileFile.empty())
541 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
542 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile);
544 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile));
546 // Indirect call promotion that promotes intra-module targes only.
547 MPM.addPass(PGOIndirectCallPromotion(
548 false, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
551 // Require the GlobalsAA analysis for the module so we can query it within
552 // the CGSCC pipeline.
553 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
555 // Require the ProfileSummaryAnalysis for the module so we can query it within
557 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
559 // Now begin the main postorder CGSCC pipeline.
560 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
561 // manager and trying to emulate its precise behavior. Much of this doesn't
562 // make a lot of sense and we should revisit the core CGSCC structure.
563 CGSCCPassManager MainCGPipeline(DebugLogging);
565 // Note: historically, the PruneEH pass was run first to deduce nounwind and
566 // generally clean up exception handling overhead. It isn't clear this is
567 // valuable as the inliner doesn't currently care whether it is inlining an
570 // Run the inliner first. The theory is that we are walking bottom-up and so
571 // the callees have already been fully optimized, and we want to inline them
572 // into the callers so that our optimizations can reflect that.
573 MainCGPipeline.addPass(InlinerPass(getInlineParamsFromOptLevel(Level)));
575 // Now deduce any function attributes based in the current code.
576 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
578 // When at O3 add argument promotion to the pass pipeline.
579 // FIXME: It isn't at all clear why this should be limited to O3.
581 MainCGPipeline.addPass(ArgumentPromotionPass());
583 // Lastly, add the core function simplification pipeline nested inside the
585 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
586 buildFunctionSimplificationPipeline(Level, DebugLogging)));
588 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
589 // to detect when we devirtualize indirect calls and iterate the SCC passes
590 // in that case to try and catch knock-on inlining or function attrs
591 // opportunities. Then we add it to the module pipeline by walking the SCCs
592 // in postorder (or bottom-up).
594 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
595 std::move(MainCGPipeline), MaxDevirtIterations, DebugLogging)));
601 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
603 ModulePassManager MPM(DebugLogging);
605 // Optimize globals now that the module is fully simplified.
606 MPM.addPass(GlobalOptPass());
608 // Run partial inlining pass to partially inline functions that have
610 if (RunPartialInlining)
611 MPM.addPass(PartialInlinerPass());
613 // Remove avail extern fns and globals definitions since we aren't compiling
614 // an object file for later LTO. For LTO we want to preserve these so they
615 // are eligible for inlining at link-time. Note if they are unreferenced they
616 // will be removed by GlobalDCE later, so this only impacts referenced
617 // available externally globals. Eventually they will be suppressed during
618 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
619 // may make globals referenced by available external functions dead and saves
620 // running remaining passes on the eliminated functions.
621 MPM.addPass(EliminateAvailableExternallyPass());
623 // Do RPO function attribute inference across the module to forward-propagate
624 // attributes where applicable.
625 // FIXME: Is this really an optimization rather than a canonicalization?
626 MPM.addPass(ReversePostOrderFunctionAttrsPass());
628 // Re-require GloblasAA here prior to function passes. This is particularly
629 // useful as the above will have inlined, DCE'ed, and function-attr
630 // propagated everything. We should at this point have a reasonably minimal
631 // and richly annotated call graph. By computing aliasing and mod/ref
632 // information for all local globals here, the late loop passes and notably
633 // the vectorizer will be able to use them to help recognize vectorizable
634 // memory operations.
635 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
637 FunctionPassManager OptimizePM(DebugLogging);
638 OptimizePM.addPass(Float2IntPass());
639 // FIXME: We need to run some loop optimizations to re-rotate loops after
640 // simplify-cfg and others undo their rotation.
642 // Optimize the loop execution. These passes operate on entire loop nests
643 // rather than on each loop in an inside-out manner, and so they are actually
646 // First rotate loops that may have been un-rotated by prior passes.
647 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
649 // Distribute loops to allow partial vectorization. I.e. isolate dependences
650 // into separate loop that would otherwise inhibit vectorization. This is
651 // currently only performed for loops marked with the metadata
652 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
653 OptimizePM.addPass(LoopDistributePass());
655 // Now run the core loop vectorizer.
656 OptimizePM.addPass(LoopVectorizePass());
658 // Eliminate loads by forwarding stores from the previous iteration to loads
659 // of the current iteration.
660 OptimizePM.addPass(LoopLoadEliminationPass());
662 // Cleanup after the loop optimization passes.
663 OptimizePM.addPass(InstCombinePass());
666 // Now that we've formed fast to execute loop structures, we do further
667 // optimizations. These are run afterward as they might block doing complex
668 // analyses and transforms such as what are needed for loop vectorization.
670 // Optimize parallel scalar instruction chains into SIMD instructions.
671 OptimizePM.addPass(SLPVectorizerPass());
673 // Cleanup after all of the vectorizers.
674 OptimizePM.addPass(SimplifyCFGPass());
675 OptimizePM.addPass(InstCombinePass());
677 // Unroll small loops to hide loop backedge latency and saturate any parallel
678 // execution resources of an out-of-order processor. We also then need to
679 // clean up redundancies and loop invariant code.
680 // FIXME: It would be really good to use a loop-integrated instruction
681 // combiner for cleanup here so that the unrolling and LICM can be pipelined
682 // across the loop nests.
683 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopUnrollPass::create(Level)));
684 OptimizePM.addPass(InstCombinePass());
685 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
686 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
688 // Now that we've vectorized and unrolled loops, we may have more refined
689 // alignment information, try to re-derive it here.
690 OptimizePM.addPass(AlignmentFromAssumptionsPass());
692 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
693 // canonicalization pass that enables other optimizations. As a result,
694 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
696 OptimizePM.addPass(LoopSinkPass());
698 // And finally clean up LCSSA form before generating code.
699 OptimizePM.addPass(InstSimplifierPass());
701 // LoopSink (and other loop passes since the last simplifyCFG) might have
702 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
703 OptimizePM.addPass(SimplifyCFGPass());
705 // Add the core optimizing pipeline.
706 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
708 // Now we need to do some global optimization transforms.
709 // FIXME: It would seem like these should come first in the optimization
710 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
712 MPM.addPass(GlobalDCEPass());
713 MPM.addPass(ConstantMergePass());
719 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
721 assert(Level != O0 && "Must request optimizations for the default pipeline!");
723 ModulePassManager MPM(DebugLogging);
725 // Force any function attributes we want the rest of the pipeline to observe.
726 MPM.addPass(ForceFunctionAttrsPass());
728 // Add the core simplification pipeline.
729 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
731 // Now add the optimization pipeline.
732 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
738 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
740 assert(Level != O0 && "Must request optimizations for the default pipeline!");
742 ModulePassManager MPM(DebugLogging);
744 // Force any function attributes we want the rest of the pipeline to observe.
745 MPM.addPass(ForceFunctionAttrsPass());
747 // If we are planning to perform ThinLTO later, we don't bloat the code with
748 // unrolling/vectorization/... now. Just simplify the module as much as we
750 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
752 // Run partial inlining pass to partially inline functions that have
754 // FIXME: It isn't clear whether this is really the right place to run this
755 // in ThinLTO. Because there is another canonicalization and simplification
756 // phase that will run after the thin link, running this here ends up with
757 // less information than will be available later and it may grow functions in
758 // ways that aren't beneficial.
759 if (RunPartialInlining)
760 MPM.addPass(PartialInlinerPass());
762 // Reduce the size of the IR as much as possible.
763 MPM.addPass(GlobalOptPass());
769 PassBuilder::buildThinLTODefaultPipeline(OptimizationLevel Level,
771 // FIXME: The summary index is not hooked in the new pass manager yet.
772 // When it's going to be hooked, enable WholeProgramDevirt and LowerTypeTest
775 ModulePassManager MPM(DebugLogging);
777 // Force any function attributes we want the rest of the pipeline to observe.
778 MPM.addPass(ForceFunctionAttrsPass());
780 // During the ThinLTO backend phase we perform early indirect call promotion
781 // here, before globalopt. Otherwise imported available_externally functions
782 // look unreferenced and are removed.
783 MPM.addPass(PGOIndirectCallPromotion(
784 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
785 !PGOOpt->ProfileUseFile.empty()));
787 // Add the core simplification pipeline.
788 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
790 // Now add the optimization pipeline.
791 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
797 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
799 assert(Level != O0 && "Must request optimizations for the default pipeline!");
800 // FIXME: We should use a customized pre-link pipeline!
801 return buildPerModuleDefaultPipeline(Level, DebugLogging);
804 ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
806 assert(Level != O0 && "Must request optimizations for the default pipeline!");
807 ModulePassManager MPM(DebugLogging);
809 // Remove unused virtual tables to improve the quality of code generated by
810 // whole-program devirtualization and bitset lowering.
811 MPM.addPass(GlobalDCEPass());
813 // Force any function attributes we want the rest of the pipeline to observe.
814 MPM.addPass(ForceFunctionAttrsPass());
816 // Do basic inference of function attributes from known properties of system
817 // libraries and other oracles.
818 MPM.addPass(InferFunctionAttrsPass());
821 // Indirect call promotion. This should promote all the targets that are
822 // left by the earlier promotion pass that promotes intra-module targets.
823 // This two-step promotion is to save the compile time. For LTO, it should
824 // produce the same result as if we only do promotion here.
825 MPM.addPass(PGOIndirectCallPromotion(
826 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
828 // Propagate constants at call sites into the functions they call. This
829 // opens opportunities for globalopt (and inlining) by substituting function
830 // pointers passed as arguments to direct uses of functions.
831 MPM.addPass(IPSCCPPass());
834 // Now deduce any function attributes based in the current code.
835 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
836 PostOrderFunctionAttrsPass()));
838 // Do RPO function attribute inference across the module to forward-propagate
839 // attributes where applicable.
840 // FIXME: Is this really an optimization rather than a canonicalization?
841 MPM.addPass(ReversePostOrderFunctionAttrsPass());
843 // Use inragne annotations on GEP indices to split globals where beneficial.
844 MPM.addPass(GlobalSplitPass());
846 // Run whole program optimization of virtual call when the list of callees
848 MPM.addPass(WholeProgramDevirtPass());
854 // Optimize globals to try and fold them into constants.
855 MPM.addPass(GlobalOptPass());
857 // Promote any localized globals to SSA registers.
858 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
860 // Linking modules together can lead to duplicate global constant, only
861 // keep one copy of each constant.
862 MPM.addPass(ConstantMergePass());
864 // Remove unused arguments from functions.
865 MPM.addPass(DeadArgumentEliminationPass());
867 // Reduce the code after globalopt and ipsccp. Both can open up significant
868 // simplification opportunities, and both can propagate functions through
869 // function pointers. When this happens, we often have to resolve varargs
870 // calls, etc, so let instcombine do this.
871 // FIXME: add peephole extensions here as the legacy PM does.
872 MPM.addPass(createModuleToFunctionPassAdaptor(InstCombinePass()));
874 // Note: historically, the PruneEH pass was run first to deduce nounwind and
875 // generally clean up exception handling overhead. It isn't clear this is
876 // valuable as the inliner doesn't currently care whether it is inlining an
878 // Run the inliner now.
879 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
880 InlinerPass(getInlineParamsFromOptLevel(Level))));
882 // Optimize globals again after we ran the inliner.
883 MPM.addPass(GlobalOptPass());
885 // Garbage collect dead functions.
886 // FIXME: Add ArgumentPromotion pass after once it's ported.
887 MPM.addPass(GlobalDCEPass());
889 FunctionPassManager FPM(DebugLogging);
891 // The IPO Passes may leave cruft around. Clean up after them.
892 // FIXME: add peephole extensions here as the legacy PM does.
893 FPM.addPass(InstCombinePass());
894 FPM.addPass(JumpThreadingPass());
899 // Run a few AA driver optimizations here and now to cleanup the code.
900 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
902 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
903 PostOrderFunctionAttrsPass()));
904 // FIXME: here we run IP alias analysis in the legacy PM.
906 FunctionPassManager MainFPM;
908 // FIXME: once we fix LoopPass Manager, add LICM here.
909 // FIXME: once we provide support for enabling MLSM, add it here.
910 // FIXME: once we provide support for enabling NewGVN, add it here.
912 MainFPM.addPass(NewGVNPass());
914 MainFPM.addPass(GVN());
916 // Remove dead memcpy()'s.
917 MainFPM.addPass(MemCpyOptPass());
920 MainFPM.addPass(DSEPass());
922 // FIXME: at this point, we run a bunch of loop passes:
923 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
924 // loopVectorize. Enable them once the remaining issue with LPM
927 MainFPM.addPass(InstCombinePass());
928 MainFPM.addPass(SimplifyCFGPass());
929 MainFPM.addPass(SCCPPass());
930 MainFPM.addPass(InstCombinePass());
931 MainFPM.addPass(BDCEPass());
933 // FIXME: We may want to run SLPVectorizer here.
934 // After vectorization, assume intrinsics may tell us more
935 // about pointer alignments.
937 MainFPM.add(AlignmentFromAssumptionsPass());
940 // FIXME: add peephole extensions to the PM here.
941 MainFPM.addPass(InstCombinePass());
942 MainFPM.addPass(JumpThreadingPass());
943 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
945 // Create a function that performs CFI checks for cross-DSO calls with
946 // targets in the current module.
947 MPM.addPass(CrossDSOCFIPass());
949 // Lower type metadata and the type.test intrinsic. This pass supports
950 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
951 // to be run at link time if CFI is enabled. This pass does nothing if
953 // Enable once we add support for the summary in the new PM.
955 MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export :
956 PassSummaryAction::None,
960 // Add late LTO optimization passes.
961 // Delete basic blocks, which optimization passes may have killed.
962 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
964 // Drop bodies of available eternally objects to improve GlobalDCE.
965 MPM.addPass(EliminateAvailableExternallyPass());
967 // Now that we have optimized the program, discard unreachable functions.
968 MPM.addPass(GlobalDCEPass());
970 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
974 AAManager PassBuilder::buildDefaultAAPipeline() {
977 // The order in which these are registered determines their priority when
980 // First we register the basic alias analysis that provides the majority of
981 // per-function local AA logic. This is a stateless, on-demand local set of
983 AA.registerFunctionAnalysis<BasicAA>();
985 // Next we query fast, specialized alias analyses that wrap IR-embedded
986 // information about aliasing.
987 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
988 AA.registerFunctionAnalysis<TypeBasedAA>();
990 // Add support for querying global aliasing information when available.
991 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
992 // analysis, all that the `AAManager` can do is query for any *cached*
993 // results from `GlobalsAA` through a readonly proxy.
994 AA.registerModuleAnalysis<GlobalsAA>();
999 static Optional<int> parseRepeatPassName(StringRef Name) {
1000 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1003 if (Name.getAsInteger(0, Count) || Count <= 0)
1008 static Optional<int> parseDevirtPassName(StringRef Name) {
1009 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1012 if (Name.getAsInteger(0, Count) || Count <= 0)
1017 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1019 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1020 return Name.startswith("default") || Name.startswith("thinlto") ||
1021 Name.startswith("lto");
1024 static bool isModulePassName(StringRef Name) {
1025 // Manually handle aliases for pre-configured pipeline fragments.
1026 if (startsWithDefaultPipelineAliasPrefix(Name))
1027 return DefaultAliasRegex.match(Name);
1029 // Explicitly handle pass manager names.
1030 if (Name == "module")
1032 if (Name == "cgscc")
1034 if (Name == "function")
1037 // Explicitly handle custom-parsed pass names.
1038 if (parseRepeatPassName(Name))
1041 #define MODULE_PASS(NAME, CREATE_PASS) \
1044 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1045 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1047 #include "PassRegistry.def"
1052 static bool isCGSCCPassName(StringRef Name) {
1053 // Explicitly handle pass manager names.
1054 if (Name == "cgscc")
1056 if (Name == "function")
1059 // Explicitly handle custom-parsed pass names.
1060 if (parseRepeatPassName(Name))
1062 if (parseDevirtPassName(Name))
1065 #define CGSCC_PASS(NAME, CREATE_PASS) \
1068 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1069 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1071 #include "PassRegistry.def"
1076 static bool isFunctionPassName(StringRef Name) {
1077 // Explicitly handle pass manager names.
1078 if (Name == "function")
1083 // Explicitly handle custom-parsed pass names.
1084 if (parseRepeatPassName(Name))
1087 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1090 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1091 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1093 #include "PassRegistry.def"
1098 static bool isLoopPassName(StringRef Name) {
1099 // Explicitly handle pass manager names.
1103 // Explicitly handle custom-parsed pass names.
1104 if (parseRepeatPassName(Name))
1107 #define LOOP_PASS(NAME, CREATE_PASS) \
1110 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1111 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1113 #include "PassRegistry.def"
1118 Optional<std::vector<PassBuilder::PipelineElement>>
1119 PassBuilder::parsePipelineText(StringRef Text) {
1120 std::vector<PipelineElement> ResultPipeline;
1122 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1125 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1126 size_t Pos = Text.find_first_of(",()");
1127 Pipeline.push_back({Text.substr(0, Pos), {}});
1129 // If we have a single terminating name, we're done.
1130 if (Pos == Text.npos)
1133 char Sep = Text[Pos];
1134 Text = Text.substr(Pos + 1);
1136 // Just a name ending in a comma, continue.
1140 // Push the inner pipeline onto the stack to continue processing.
1141 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1145 assert(Sep == ')' && "Bogus separator!");
1146 // When handling the close parenthesis, we greedily consume them to avoid
1147 // empty strings in the pipeline.
1149 // If we try to pop the outer pipeline we have unbalanced parentheses.
1150 if (PipelineStack.size() == 1)
1153 PipelineStack.pop_back();
1154 } while (Text.consume_front(")"));
1156 // Check if we've finished parsing.
1160 // Otherwise, the end of an inner pipeline always has to be followed by
1161 // a comma, and then we can continue.
1162 if (!Text.consume_front(","))
1166 if (PipelineStack.size() > 1)
1167 // Unbalanced paretheses.
1170 assert(PipelineStack.back() == &ResultPipeline &&
1171 "Wrong pipeline at the bottom of the stack!");
1172 return {std::move(ResultPipeline)};
1175 bool PassBuilder::parseModulePass(ModulePassManager &MPM,
1176 const PipelineElement &E, bool VerifyEachPass,
1177 bool DebugLogging) {
1178 auto &Name = E.Name;
1179 auto &InnerPipeline = E.InnerPipeline;
1181 // First handle complex passes like the pass managers which carry pipelines.
1182 if (!InnerPipeline.empty()) {
1183 if (Name == "module") {
1184 ModulePassManager NestedMPM(DebugLogging);
1185 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1188 MPM.addPass(std::move(NestedMPM));
1191 if (Name == "cgscc") {
1192 CGSCCPassManager CGPM(DebugLogging);
1193 if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1196 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM),
1200 if (Name == "function") {
1201 FunctionPassManager FPM(DebugLogging);
1202 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1205 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1208 if (auto Count = parseRepeatPassName(Name)) {
1209 ModulePassManager NestedMPM(DebugLogging);
1210 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1213 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1216 // Normal passes can't have pipelines.
1220 // Manually handle aliases for pre-configured pipeline fragments.
1221 if (startsWithDefaultPipelineAliasPrefix(Name)) {
1222 SmallVector<StringRef, 3> Matches;
1223 if (!DefaultAliasRegex.match(Name, &Matches))
1225 assert(Matches.size() == 3 && "Must capture two matched strings!");
1227 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1235 // At O0 we do nothing at all!
1238 if (Matches[1] == "default") {
1239 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1240 } else if (Matches[1] == "thinlto-pre-link") {
1241 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1242 } else if (Matches[1] == "thinlto") {
1243 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging));
1244 } else if (Matches[1] == "lto-pre-link") {
1245 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1247 assert(Matches[1] == "lto" && "Not one of the matched options!");
1248 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging));
1253 // Finally expand the basic registered passes from the .inc file.
1254 #define MODULE_PASS(NAME, CREATE_PASS) \
1255 if (Name == NAME) { \
1256 MPM.addPass(CREATE_PASS); \
1259 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1260 if (Name == "require<" NAME ">") { \
1262 RequireAnalysisPass< \
1263 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
1266 if (Name == "invalidate<" NAME ">") { \
1267 MPM.addPass(InvalidateAnalysisPass< \
1268 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1271 #include "PassRegistry.def"
1276 bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1277 const PipelineElement &E, bool VerifyEachPass,
1278 bool DebugLogging) {
1279 auto &Name = E.Name;
1280 auto &InnerPipeline = E.InnerPipeline;
1282 // First handle complex passes like the pass managers which carry pipelines.
1283 if (!InnerPipeline.empty()) {
1284 if (Name == "cgscc") {
1285 CGSCCPassManager NestedCGPM(DebugLogging);
1286 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1289 // Add the nested pass manager with the appropriate adaptor.
1290 CGPM.addPass(std::move(NestedCGPM));
1293 if (Name == "function") {
1294 FunctionPassManager FPM(DebugLogging);
1295 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1298 // Add the nested pass manager with the appropriate adaptor.
1300 createCGSCCToFunctionPassAdaptor(std::move(FPM), DebugLogging));
1303 if (auto Count = parseRepeatPassName(Name)) {
1304 CGSCCPassManager NestedCGPM(DebugLogging);
1305 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1308 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1311 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1312 CGSCCPassManager NestedCGPM(DebugLogging);
1313 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1316 CGPM.addPass(createDevirtSCCRepeatedPass(std::move(NestedCGPM),
1317 *MaxRepetitions, DebugLogging));
1320 // Normal passes can't have pipelines.
1324 // Now expand the basic registered passes from the .inc file.
1325 #define CGSCC_PASS(NAME, CREATE_PASS) \
1326 if (Name == NAME) { \
1327 CGPM.addPass(CREATE_PASS); \
1330 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1331 if (Name == "require<" NAME ">") { \
1332 CGPM.addPass(RequireAnalysisPass< \
1333 std::remove_reference<decltype(CREATE_PASS)>::type, \
1334 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1335 CGSCCUpdateResult &>()); \
1338 if (Name == "invalidate<" NAME ">") { \
1339 CGPM.addPass(InvalidateAnalysisPass< \
1340 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1343 #include "PassRegistry.def"
1348 bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1349 const PipelineElement &E,
1350 bool VerifyEachPass, bool DebugLogging) {
1351 auto &Name = E.Name;
1352 auto &InnerPipeline = E.InnerPipeline;
1354 // First handle complex passes like the pass managers which carry pipelines.
1355 if (!InnerPipeline.empty()) {
1356 if (Name == "function") {
1357 FunctionPassManager NestedFPM(DebugLogging);
1358 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1361 // Add the nested pass manager with the appropriate adaptor.
1362 FPM.addPass(std::move(NestedFPM));
1365 if (Name == "loop") {
1366 LoopPassManager LPM(DebugLogging);
1367 if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1370 // Add the nested pass manager with the appropriate adaptor.
1371 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
1374 if (auto Count = parseRepeatPassName(Name)) {
1375 FunctionPassManager NestedFPM(DebugLogging);
1376 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1379 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1382 // Normal passes can't have pipelines.
1386 // Now expand the basic registered passes from the .inc file.
1387 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1388 if (Name == NAME) { \
1389 FPM.addPass(CREATE_PASS); \
1392 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1393 if (Name == "require<" NAME ">") { \
1395 RequireAnalysisPass< \
1396 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
1399 if (Name == "invalidate<" NAME ">") { \
1400 FPM.addPass(InvalidateAnalysisPass< \
1401 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1404 #include "PassRegistry.def"
1409 bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1410 bool VerifyEachPass, bool DebugLogging) {
1411 StringRef Name = E.Name;
1412 auto &InnerPipeline = E.InnerPipeline;
1414 // First handle complex passes like the pass managers which carry pipelines.
1415 if (!InnerPipeline.empty()) {
1416 if (Name == "loop") {
1417 LoopPassManager NestedLPM(DebugLogging);
1418 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1421 // Add the nested pass manager with the appropriate adaptor.
1422 LPM.addPass(std::move(NestedLPM));
1425 if (auto Count = parseRepeatPassName(Name)) {
1426 LoopPassManager NestedLPM(DebugLogging);
1427 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1430 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1433 // Normal passes can't have pipelines.
1437 // Now expand the basic registered passes from the .inc file.
1438 #define LOOP_PASS(NAME, CREATE_PASS) \
1439 if (Name == NAME) { \
1440 LPM.addPass(CREATE_PASS); \
1443 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1444 if (Name == "require<" NAME ">") { \
1445 LPM.addPass(RequireAnalysisPass< \
1446 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1447 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1451 if (Name == "invalidate<" NAME ">") { \
1452 LPM.addPass(InvalidateAnalysisPass< \
1453 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1456 #include "PassRegistry.def"
1461 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1462 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1463 if (Name == NAME) { \
1464 AA.registerModuleAnalysis< \
1465 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1468 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1469 if (Name == NAME) { \
1470 AA.registerFunctionAnalysis< \
1471 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1474 #include "PassRegistry.def"
1479 bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1480 ArrayRef<PipelineElement> Pipeline,
1481 bool VerifyEachPass,
1482 bool DebugLogging) {
1483 for (const auto &Element : Pipeline) {
1484 if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1486 // FIXME: No verifier support for Loop passes!
1491 bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1492 ArrayRef<PipelineElement> Pipeline,
1493 bool VerifyEachPass,
1494 bool DebugLogging) {
1495 for (const auto &Element : Pipeline) {
1496 if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1499 FPM.addPass(VerifierPass());
1504 bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1505 ArrayRef<PipelineElement> Pipeline,
1506 bool VerifyEachPass,
1507 bool DebugLogging) {
1508 for (const auto &Element : Pipeline) {
1509 if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1511 // FIXME: No verifier support for CGSCC passes!
1516 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1517 FunctionAnalysisManager &FAM,
1518 CGSCCAnalysisManager &CGAM,
1519 ModuleAnalysisManager &MAM) {
1520 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1521 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1522 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1523 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1524 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1525 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1526 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1529 bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1530 ArrayRef<PipelineElement> Pipeline,
1531 bool VerifyEachPass,
1532 bool DebugLogging) {
1533 for (const auto &Element : Pipeline) {
1534 if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1537 MPM.addPass(VerifierPass());
1542 // Primary pass pipeline description parsing routine.
1543 // FIXME: Should this routine accept a TargetMachine or require the caller to
1544 // pre-populate the analysis managers with target-specific stuff?
1545 bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1546 StringRef PipelineText, bool VerifyEachPass,
1547 bool DebugLogging) {
1548 auto Pipeline = parsePipelineText(PipelineText);
1549 if (!Pipeline || Pipeline->empty())
1552 // If the first name isn't at the module layer, wrap the pipeline up
1554 StringRef FirstName = Pipeline->front().Name;
1556 if (!isModulePassName(FirstName)) {
1557 if (isCGSCCPassName(FirstName))
1558 Pipeline = {{"cgscc", std::move(*Pipeline)}};
1559 else if (isFunctionPassName(FirstName))
1560 Pipeline = {{"function", std::move(*Pipeline)}};
1561 else if (isLoopPassName(FirstName))
1562 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
1564 // Unknown pass name!
1568 return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
1571 bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
1572 // If the pipeline just consists of the word 'default' just replace the AA
1573 // manager with our default one.
1574 if (PipelineText == "default") {
1575 AA = buildDefaultAAPipeline();
1579 while (!PipelineText.empty()) {
1581 std::tie(Name, PipelineText) = PipelineText.split(',');
1582 if (!parseAAPassName(AA, Name))