1 //===- Parsing, selection, and construction of pass pipelines -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
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
14 /// pipelines.
15 ///
16 //===----------------------------------------------------------------------===//
17 
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"
146 
147 #include <type_traits>
148 
149 using namespace llvm;
150 
151 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
152                                              cl::ReallyHidden, cl::init(4));
153 static cl::opt<bool>
154     RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
155                        cl::Hidden, cl::ZeroOrMore,
156                        cl::desc("Run Partial inlinining pass"));
157 
158 static cl::opt<bool>
159     RunNewGVN("enable-npm-newgvn", cl::init(false),
160               cl::Hidden, cl::ZeroOrMore,
161               cl::desc("Run NewGVN instead of GVN"));
162 
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)"));
166 
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)"));
170 
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)"));
174 
175 static Regex DefaultAliasRegex(
176     "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
177 
178 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
179   switch (Level) {
180   case PassBuilder::O0:
181   case PassBuilder::O1:
182   case PassBuilder::O2:
183   case PassBuilder::O3:
184     return false;
185 
186   case PassBuilder::Os:
187   case PassBuilder::Oz:
188     return true;
189   }
190   llvm_unreachable("Invalid optimization level!");
191 }
192 
193 namespace {
194 
195 /// \brief No-op module pass which does nothing.
196 struct NoOpModulePass {
197   PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
198     return PreservedAnalyses::all();
199   }
200   static StringRef name() { return "NoOpModulePass"; }
201 };
202 
203 /// \brief No-op module analysis.
204 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
205   friend AnalysisInfoMixin<NoOpModuleAnalysis>;
206   static AnalysisKey Key;
207 
208 public:
209   struct Result {};
210   Result run(Module &, ModuleAnalysisManager &) { return Result(); }
211   static StringRef name() { return "NoOpModuleAnalysis"; }
212 };
213 
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();
219   }
220   static StringRef name() { return "NoOpCGSCCPass"; }
221 };
222 
223 /// \brief No-op CGSCC analysis.
224 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
225   friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
226   static AnalysisKey Key;
227 
228 public:
229   struct Result {};
230   Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
231     return Result();
232   }
233   static StringRef name() { return "NoOpCGSCCAnalysis"; }
234 };
235 
236 /// \brief No-op function pass which does nothing.
237 struct NoOpFunctionPass {
238   PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
239     return PreservedAnalyses::all();
240   }
241   static StringRef name() { return "NoOpFunctionPass"; }
242 };
243 
244 /// \brief No-op function analysis.
245 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
246   friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
247   static AnalysisKey Key;
248 
249 public:
250   struct Result {};
251   Result run(Function &, FunctionAnalysisManager &) { return Result(); }
252   static StringRef name() { return "NoOpFunctionAnalysis"; }
253 };
254 
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();
260   }
261   static StringRef name() { return "NoOpLoopPass"; }
262 };
263 
264 /// \brief No-op loop analysis.
265 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
266   friend AnalysisInfoMixin<NoOpLoopAnalysis>;
267   static AnalysisKey Key;
268 
269 public:
270   struct Result {};
271   Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
272     return Result();
273   }
274   static StringRef name() { return "NoOpLoopAnalysis"; }
275 };
276 
277 AnalysisKey NoOpModuleAnalysis::Key;
278 AnalysisKey NoOpCGSCCAnalysis::Key;
279 AnalysisKey NoOpFunctionAnalysis::Key;
280 AnalysisKey NoOpLoopAnalysis::Key;
281 
282 } // End anonymous namespace.
283 
284 void PassBuilder::invokePeepholeEPCallbacks(
285     FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
286   for (auto &C : PeepholeEPCallbacks)
287     C(FPM, Level);
288 }
289 
290 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
291 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
292   MAM.registerPass([&] { return CREATE_PASS; });
293 #include "PassRegistry.def"
294 
295   for (auto &C : ModuleAnalysisRegistrationCallbacks)
296     C(MAM);
297 }
298 
299 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
300 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
301   CGAM.registerPass([&] { return CREATE_PASS; });
302 #include "PassRegistry.def"
303 
304   for (auto &C : CGSCCAnalysisRegistrationCallbacks)
305     C(CGAM);
306 }
307 
308 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
309 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
310   FAM.registerPass([&] { return CREATE_PASS; });
311 #include "PassRegistry.def"
312 
313   for (auto &C : FunctionAnalysisRegistrationCallbacks)
314     C(FAM);
315 }
316 
317 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
318 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
319   LAM.registerPass([&] { return CREATE_PASS; });
320 #include "PassRegistry.def"
321 
322   for (auto &C : LoopAnalysisRegistrationCallbacks)
323     C(LAM);
324 }
325 
326 FunctionPassManager
327 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
328                                                  ThinLTOPhase Phase,
329                                                  bool DebugLogging) {
330   assert(Level != O0 && "Must request optimizations!");
331   FunctionPassManager FPM(DebugLogging);
332 
333   // Form SSA out of local memory accesses after breaking apart aggregates into
334   // scalars.
335   FPM.addPass(SROA());
336 
337   // Catch trivial redundancies
338   FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
339 
340   // Hoisting of scalars and load expressions.
341   if (EnableGVNHoist)
342     FPM.addPass(GVNHoistPass());
343 
344   // Global value numbering based sinking.
345   if (EnableGVNSink) {
346     FPM.addPass(GVNSinkPass());
347     FPM.addPass(SimplifyCFGPass());
348   }
349 
350   // Speculative execution if the target has divergent branches; otherwise nop.
351   FPM.addPass(SpeculativeExecutionPass());
352 
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());
358 
359   if (!isOptimizingForSize(Level))
360     FPM.addPass(LibCallsShrinkWrapPass());
361 
362   invokePeepholeEPCallbacks(FPM, Level);
363 
364   FPM.addPass(TailCallElimPass());
365   FPM.addPass(SimplifyCFGPass());
366 
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());
371 
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);
380 
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());
387 
388   for (auto &C : LateLoopOptimizationsEPCallbacks)
389     C(LPM2, Level);
390 
391   LPM2.addPass(LoopDeletionPass());
392   // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
393   // because it changes IR to makes profile annotation in back compile
394   // inaccurate.
395   if (Phase != ThinLTOPhase::PreLink ||
396       !PGOOpt || PGOOpt->SampleProfileFile.empty())
397     LPM2.addPass(LoopFullUnrollPass(Level));
398 
399   for (auto &C : LoopOptimizerEndEPCallbacks)
400     C(LPM2, Level);
401 
402   // We provide the opt remark emitter pass for LICM to use. We only need to do
403   // this once as it is immutable.
404   FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
405   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1)));
406   FPM.addPass(SimplifyCFGPass());
407   FPM.addPass(InstCombinePass());
408   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2)));
409 
410   // Eliminate redundancies.
411   if (Level != O1) {
412     // These passes add substantial compile time so skip them at O1.
413     FPM.addPass(MergedLoadStoreMotionPass());
414     if (RunNewGVN)
415       FPM.addPass(NewGVNPass());
416     else
417       FPM.addPass(GVN());
418   }
419 
420   // Specially optimize memory movement as it doesn't look like dataflow in SSA.
421   FPM.addPass(MemCpyOptPass());
422 
423   // Sparse conditional constant propagation.
424   // FIXME: It isn't clear why we do this *after* loop passes rather than
425   // before...
426   FPM.addPass(SCCPPass());
427 
428   // Delete dead bit computations (instcombine runs after to fold away the dead
429   // computations, and then ADCE will run later to exploit any new DCE
430   // opportunities that creates).
431   FPM.addPass(BDCEPass());
432 
433   // Run instcombine after redundancy and dead bit elimination to exploit
434   // opportunities opened up by them.
435   FPM.addPass(InstCombinePass());
436   invokePeepholeEPCallbacks(FPM, Level);
437 
438   // Re-consider control flow based optimizations after redundancy elimination,
439   // redo DCE, etc.
440   FPM.addPass(JumpThreadingPass());
441   FPM.addPass(CorrelatedValuePropagationPass());
442   FPM.addPass(DSEPass());
443   FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
444 
445   for (auto &C : ScalarOptimizerLateEPCallbacks)
446     C(FPM, Level);
447 
448   // Finally, do an expensive DCE pass to catch all the dead code exposed by
449   // the simplifications and basic cleanup after all the simplifications.
450   FPM.addPass(ADCEPass());
451   FPM.addPass(SimplifyCFGPass());
452   FPM.addPass(InstCombinePass());
453   invokePeepholeEPCallbacks(FPM, Level);
454 
455   return FPM;
456 }
457 
458 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
459                                     PassBuilder::OptimizationLevel Level,
460                                     bool RunProfileGen,
461                                     std::string ProfileGenFile,
462                                     std::string ProfileUseFile) {
463   // Generally running simplification passes and the inliner with an high
464   // threshold results in smaller executables, but there may be cases where
465   // the size grows, so let's be conservative here and skip this simplification
466   // at -Os/Oz.
467   if (!isOptimizingForSize(Level)) {
468     InlineParams IP;
469 
470     // In the old pass manager, this is a cl::opt. Should still this be one?
471     IP.DefaultThreshold = 75;
472 
473     // FIXME: The hint threshold has the same value used by the regular inliner.
474     // This should probably be lowered after performance testing.
475     // FIXME: this comment is cargo culted from the old pass manager, revisit).
476     IP.HintThreshold = 325;
477 
478     CGSCCPassManager CGPipeline(DebugLogging);
479 
480     CGPipeline.addPass(InlinerPass(IP));
481 
482     FunctionPassManager FPM;
483     FPM.addPass(SROA());
484     FPM.addPass(EarlyCSEPass());    // Catch trivial redundancies.
485     FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
486     FPM.addPass(InstCombinePass()); // Combine silly sequences.
487     invokePeepholeEPCallbacks(FPM, Level);
488 
489     CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
490 
491     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
492   }
493 
494   // Delete anything that is now dead to make sure that we don't instrument
495   // dead code. Instrumentation can end up keeping dead code around and
496   // dramatically increase code size.
497   MPM.addPass(GlobalDCEPass());
498 
499   if (RunProfileGen) {
500     MPM.addPass(PGOInstrumentationGen());
501 
502     FunctionPassManager FPM;
503     FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
504     MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
505 
506     // Add the profile lowering pass.
507     InstrProfOptions Options;
508     if (!ProfileGenFile.empty())
509       Options.InstrProfileOutput = ProfileGenFile;
510     Options.DoCounterPromotion = true;
511     MPM.addPass(InstrProfiling(Options));
512   }
513 
514   if (!ProfileUseFile.empty())
515     MPM.addPass(PGOInstrumentationUse(ProfileUseFile));
516 }
517 
518 static InlineParams
519 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
520   auto O3 = PassBuilder::O3;
521   unsigned OptLevel = Level > O3 ? 2 : Level;
522   unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
523   return getInlineParams(OptLevel, SizeLevel);
524 }
525 
526 ModulePassManager
527 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
528                                                ThinLTOPhase Phase,
529                                                bool DebugLogging) {
530   ModulePassManager MPM(DebugLogging);
531 
532   // Do basic inference of function attributes from known properties of system
533   // libraries and other oracles.
534   MPM.addPass(InferFunctionAttrsPass());
535 
536   // Create an early function pass manager to cleanup the output of the
537   // frontend.
538   FunctionPassManager EarlyFPM(DebugLogging);
539   EarlyFPM.addPass(SimplifyCFGPass());
540   EarlyFPM.addPass(SROA());
541   EarlyFPM.addPass(EarlyCSEPass());
542   EarlyFPM.addPass(LowerExpectIntrinsicPass());
543   // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
544   // to convert bitcast to direct calls so that they can be inlined during the
545   // profile annotation prepration step.
546   // More details about SamplePGO design can be found in:
547   // https://research.google.com/pubs/pub45290.html
548   // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
549   if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
550       Phase == ThinLTOPhase::PostLink)
551     EarlyFPM.addPass(InstCombinePass());
552   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
553 
554   if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
555     // Annotate sample profile right after early FPM to ensure freshness of
556     // the debug info.
557     MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile));
558     // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
559     // for the profile annotation to be accurate in the ThinLTO backend.
560     if (Phase != ThinLTOPhase::PreLink)
561       // We perform early indirect call promotion here, before globalopt.
562       // This is important for the ThinLTO backend phase because otherwise
563       // imported available_externally functions look unreferenced and are
564       // removed.
565       MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
566                                            true));
567   }
568 
569   // Interprocedural constant propagation now that basic cleanup has occured
570   // and prior to optimizing globals.
571   // FIXME: This position in the pipeline hasn't been carefully considered in
572   // years, it should be re-analyzed.
573   MPM.addPass(IPSCCPPass());
574 
575   // Optimize globals to try and fold them into constants.
576   MPM.addPass(GlobalOptPass());
577 
578   // Promote any localized globals to SSA registers.
579   // FIXME: Should this instead by a run of SROA?
580   // FIXME: We should probably run instcombine and simplify-cfg afterward to
581   // delete control flows that are dead once globals have been folded to
582   // constants.
583   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
584 
585   // Remove any dead arguments exposed by cleanups and constand folding
586   // globals.
587   MPM.addPass(DeadArgumentEliminationPass());
588 
589   // Create a small function pass pipeline to cleanup after all the global
590   // optimizations.
591   FunctionPassManager GlobalCleanupPM(DebugLogging);
592   GlobalCleanupPM.addPass(InstCombinePass());
593   invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
594 
595   GlobalCleanupPM.addPass(SimplifyCFGPass());
596   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
597 
598   // Add all the requested passes for instrumentation PGO, if requested.
599   if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
600       (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
601     addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
602                       PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile);
603     MPM.addPass(PGOIndirectCallPromotion(false, false));
604   }
605 
606   // Require the GlobalsAA analysis for the module so we can query it within
607   // the CGSCC pipeline.
608   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
609 
610   // Require the ProfileSummaryAnalysis for the module so we can query it within
611   // the inliner pass.
612   MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
613 
614   // Now begin the main postorder CGSCC pipeline.
615   // FIXME: The current CGSCC pipeline has its origins in the legacy pass
616   // manager and trying to emulate its precise behavior. Much of this doesn't
617   // make a lot of sense and we should revisit the core CGSCC structure.
618   CGSCCPassManager MainCGPipeline(DebugLogging);
619 
620   // Note: historically, the PruneEH pass was run first to deduce nounwind and
621   // generally clean up exception handling overhead. It isn't clear this is
622   // valuable as the inliner doesn't currently care whether it is inlining an
623   // invoke or a call.
624 
625   // Run the inliner first. The theory is that we are walking bottom-up and so
626   // the callees have already been fully optimized, and we want to inline them
627   // into the callers so that our optimizations can reflect that.
628   // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
629   // because it makes profile annotation in the backend inaccurate.
630   InlineParams IP = getInlineParamsFromOptLevel(Level);
631   if (Phase == ThinLTOPhase::PreLink &&
632       PGOOpt && !PGOOpt->SampleProfileFile.empty())
633     IP.HotCallSiteThreshold = 0;
634   MainCGPipeline.addPass(InlinerPass(IP));
635 
636   // Now deduce any function attributes based in the current code.
637   MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
638 
639   // When at O3 add argument promotion to the pass pipeline.
640   // FIXME: It isn't at all clear why this should be limited to O3.
641   if (Level == O3)
642     MainCGPipeline.addPass(ArgumentPromotionPass());
643 
644   // Lastly, add the core function simplification pipeline nested inside the
645   // CGSCC walk.
646   MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
647       buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
648 
649   for (auto &C : CGSCCOptimizerLateEPCallbacks)
650     C(MainCGPipeline, Level);
651 
652   // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
653   // to detect when we devirtualize indirect calls and iterate the SCC passes
654   // in that case to try and catch knock-on inlining or function attrs
655   // opportunities. Then we add it to the module pipeline by walking the SCCs
656   // in postorder (or bottom-up).
657   MPM.addPass(
658       createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
659           std::move(MainCGPipeline), MaxDevirtIterations)));
660 
661   return MPM;
662 }
663 
664 ModulePassManager
665 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
666                                              bool DebugLogging) {
667   ModulePassManager MPM(DebugLogging);
668 
669   // Optimize globals now that the module is fully simplified.
670   MPM.addPass(GlobalOptPass());
671 
672   // Run partial inlining pass to partially inline functions that have
673   // large bodies.
674   if (RunPartialInlining)
675     MPM.addPass(PartialInlinerPass());
676 
677   // Remove avail extern fns and globals definitions since we aren't compiling
678   // an object file for later LTO. For LTO we want to preserve these so they
679   // are eligible for inlining at link-time. Note if they are unreferenced they
680   // will be removed by GlobalDCE later, so this only impacts referenced
681   // available externally globals. Eventually they will be suppressed during
682   // codegen, but eliminating here enables more opportunity for GlobalDCE as it
683   // may make globals referenced by available external functions dead and saves
684   // running remaining passes on the eliminated functions.
685   MPM.addPass(EliminateAvailableExternallyPass());
686 
687   // Do RPO function attribute inference across the module to forward-propagate
688   // attributes where applicable.
689   // FIXME: Is this really an optimization rather than a canonicalization?
690   MPM.addPass(ReversePostOrderFunctionAttrsPass());
691 
692   // Re-require GloblasAA here prior to function passes. This is particularly
693   // useful as the above will have inlined, DCE'ed, and function-attr
694   // propagated everything. We should at this point have a reasonably minimal
695   // and richly annotated call graph. By computing aliasing and mod/ref
696   // information for all local globals here, the late loop passes and notably
697   // the vectorizer will be able to use them to help recognize vectorizable
698   // memory operations.
699   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
700 
701   FunctionPassManager OptimizePM(DebugLogging);
702   OptimizePM.addPass(Float2IntPass());
703   // FIXME: We need to run some loop optimizations to re-rotate loops after
704   // simplify-cfg and others undo their rotation.
705 
706   // Optimize the loop execution. These passes operate on entire loop nests
707   // rather than on each loop in an inside-out manner, and so they are actually
708   // function passes.
709 
710   for (auto &C : VectorizerStartEPCallbacks)
711     C(OptimizePM, Level);
712 
713   // First rotate loops that may have been un-rotated by prior passes.
714   OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
715 
716   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
717   // into separate loop that would otherwise inhibit vectorization.  This is
718   // currently only performed for loops marked with the metadata
719   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
720   OptimizePM.addPass(LoopDistributePass());
721 
722   // Now run the core loop vectorizer.
723   OptimizePM.addPass(LoopVectorizePass());
724 
725   // Eliminate loads by forwarding stores from the previous iteration to loads
726   // of the current iteration.
727   OptimizePM.addPass(LoopLoadEliminationPass());
728 
729   // Cleanup after the loop optimization passes.
730   OptimizePM.addPass(InstCombinePass());
731 
732 
733   // Now that we've formed fast to execute loop structures, we do further
734   // optimizations. These are run afterward as they might block doing complex
735   // analyses and transforms such as what are needed for loop vectorization.
736 
737   // Optimize parallel scalar instruction chains into SIMD instructions.
738   OptimizePM.addPass(SLPVectorizerPass());
739 
740   // Cleanup after all of the vectorizers.
741   OptimizePM.addPass(SimplifyCFGPass());
742   OptimizePM.addPass(InstCombinePass());
743 
744   // Unroll small loops to hide loop backedge latency and saturate any parallel
745   // execution resources of an out-of-order processor. We also then need to
746   // clean up redundancies and loop invariant code.
747   // FIXME: It would be really good to use a loop-integrated instruction
748   // combiner for cleanup here so that the unrolling and LICM can be pipelined
749   // across the loop nests.
750   OptimizePM.addPass(LoopUnrollPass(Level));
751   OptimizePM.addPass(InstCombinePass());
752   OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
753   OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
754 
755   // Now that we've vectorized and unrolled loops, we may have more refined
756   // alignment information, try to re-derive it here.
757   OptimizePM.addPass(AlignmentFromAssumptionsPass());
758 
759   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
760   // canonicalization pass that enables other optimizations. As a result,
761   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
762   // result too early.
763   OptimizePM.addPass(LoopSinkPass());
764 
765   // And finally clean up LCSSA form before generating code.
766   OptimizePM.addPass(InstSimplifierPass());
767 
768   // LoopSink (and other loop passes since the last simplifyCFG) might have
769   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
770   OptimizePM.addPass(SimplifyCFGPass());
771 
772   // Add the core optimizing pipeline.
773   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
774 
775   // Now we need to do some global optimization transforms.
776   // FIXME: It would seem like these should come first in the optimization
777   // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
778   // ordering here.
779   MPM.addPass(GlobalDCEPass());
780   MPM.addPass(ConstantMergePass());
781 
782   return MPM;
783 }
784 
785 ModulePassManager
786 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
787                                            bool DebugLogging) {
788   assert(Level != O0 && "Must request optimizations for the default pipeline!");
789 
790   ModulePassManager MPM(DebugLogging);
791 
792   // Force any function attributes we want the rest of the pipeline to observe.
793   MPM.addPass(ForceFunctionAttrsPass());
794 
795   if (PGOOpt && PGOOpt->SamplePGOSupport)
796     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
797 
798   // Add the core simplification pipeline.
799   MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
800                                                 DebugLogging));
801 
802   // Now add the optimization pipeline.
803   MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
804 
805   return MPM;
806 }
807 
808 ModulePassManager
809 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
810                                                 bool DebugLogging) {
811   assert(Level != O0 && "Must request optimizations for the default pipeline!");
812 
813   ModulePassManager MPM(DebugLogging);
814 
815   // Force any function attributes we want the rest of the pipeline to observe.
816   MPM.addPass(ForceFunctionAttrsPass());
817 
818   if (PGOOpt && PGOOpt->SamplePGOSupport)
819     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
820 
821   // If we are planning to perform ThinLTO later, we don't bloat the code with
822   // unrolling/vectorization/... now. Just simplify the module as much as we
823   // can.
824   MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
825                                                 DebugLogging));
826 
827   // Run partial inlining pass to partially inline functions that have
828   // large bodies.
829   // FIXME: It isn't clear whether this is really the right place to run this
830   // in ThinLTO. Because there is another canonicalization and simplification
831   // phase that will run after the thin link, running this here ends up with
832   // less information than will be available later and it may grow functions in
833   // ways that aren't beneficial.
834   if (RunPartialInlining)
835     MPM.addPass(PartialInlinerPass());
836 
837   // Reduce the size of the IR as much as possible.
838   MPM.addPass(GlobalOptPass());
839 
840   return MPM;
841 }
842 
843 ModulePassManager
844 PassBuilder::buildThinLTODefaultPipeline(OptimizationLevel Level,
845                                          bool DebugLogging) {
846   // FIXME: The summary index is not hooked in the new pass manager yet.
847   // When it's going to be hooked, enable WholeProgramDevirt and LowerTypeTest
848   // here.
849 
850   ModulePassManager MPM(DebugLogging);
851 
852   // Force any function attributes we want the rest of the pipeline to observe.
853   MPM.addPass(ForceFunctionAttrsPass());
854 
855   // During the ThinLTO backend phase we perform early indirect call promotion
856   // here, before globalopt. Otherwise imported available_externally functions
857   // look unreferenced and are removed.
858   // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
859   //        with SamplePGO.
860   if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
861     MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
862                                          false /* SamplePGO */));
863 
864   // Add the core simplification pipeline.
865   MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
866                                                 DebugLogging));
867 
868   // Now add the optimization pipeline.
869   MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
870 
871   return MPM;
872 }
873 
874 ModulePassManager
875 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
876                                             bool DebugLogging) {
877   assert(Level != O0 && "Must request optimizations for the default pipeline!");
878   // FIXME: We should use a customized pre-link pipeline!
879   return buildPerModuleDefaultPipeline(Level, DebugLogging);
880 }
881 
882 ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
883                                                        bool DebugLogging) {
884   assert(Level != O0 && "Must request optimizations for the default pipeline!");
885   ModulePassManager MPM(DebugLogging);
886 
887   // Remove unused virtual tables to improve the quality of code generated by
888   // whole-program devirtualization and bitset lowering.
889   MPM.addPass(GlobalDCEPass());
890 
891   // Force any function attributes we want the rest of the pipeline to observe.
892   MPM.addPass(ForceFunctionAttrsPass());
893 
894   // Do basic inference of function attributes from known properties of system
895   // libraries and other oracles.
896   MPM.addPass(InferFunctionAttrsPass());
897 
898   if (Level > 1) {
899     // Indirect call promotion. This should promote all the targets that are
900     // left by the earlier promotion pass that promotes intra-module targets.
901     // This two-step promotion is to save the compile time. For LTO, it should
902     // produce the same result as if we only do promotion here.
903     MPM.addPass(PGOIndirectCallPromotion(
904         true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
905 
906     // Propagate constants at call sites into the functions they call.  This
907     // opens opportunities for globalopt (and inlining) by substituting function
908     // pointers passed as arguments to direct uses of functions.
909    MPM.addPass(IPSCCPPass());
910   }
911 
912   // Now deduce any function attributes based in the current code.
913   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
914               PostOrderFunctionAttrsPass()));
915 
916   // Do RPO function attribute inference across the module to forward-propagate
917   // attributes where applicable.
918   // FIXME: Is this really an optimization rather than a canonicalization?
919   MPM.addPass(ReversePostOrderFunctionAttrsPass());
920 
921   // Use inragne annotations on GEP indices to split globals where beneficial.
922   MPM.addPass(GlobalSplitPass());
923 
924   // Run whole program optimization of virtual call when the list of callees
925   // is fixed.
926   MPM.addPass(WholeProgramDevirtPass());
927 
928   // Stop here at -O1.
929   if (Level == 1)
930     return MPM;
931 
932   // Optimize globals to try and fold them into constants.
933   MPM.addPass(GlobalOptPass());
934 
935   // Promote any localized globals to SSA registers.
936   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
937 
938   // Linking modules together can lead to duplicate global constant, only
939   // keep one copy of each constant.
940   MPM.addPass(ConstantMergePass());
941 
942   // Remove unused arguments from functions.
943   MPM.addPass(DeadArgumentEliminationPass());
944 
945   // Reduce the code after globalopt and ipsccp.  Both can open up significant
946   // simplification opportunities, and both can propagate functions through
947   // function pointers.  When this happens, we often have to resolve varargs
948   // calls, etc, so let instcombine do this.
949   FunctionPassManager PeepholeFPM(DebugLogging);
950   PeepholeFPM.addPass(InstCombinePass());
951   invokePeepholeEPCallbacks(PeepholeFPM, Level);
952 
953   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
954 
955   // Note: historically, the PruneEH pass was run first to deduce nounwind and
956   // generally clean up exception handling overhead. It isn't clear this is
957   // valuable as the inliner doesn't currently care whether it is inlining an
958   // invoke or a call.
959   // Run the inliner now.
960   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
961       InlinerPass(getInlineParamsFromOptLevel(Level))));
962 
963   // Optimize globals again after we ran the inliner.
964   MPM.addPass(GlobalOptPass());
965 
966   // Garbage collect dead functions.
967   // FIXME: Add ArgumentPromotion pass after once it's ported.
968   MPM.addPass(GlobalDCEPass());
969 
970   FunctionPassManager FPM(DebugLogging);
971   // The IPO Passes may leave cruft around. Clean up after them.
972   FPM.addPass(InstCombinePass());
973   invokePeepholeEPCallbacks(FPM, Level);
974 
975   FPM.addPass(JumpThreadingPass());
976 
977   // Break up allocas
978   FPM.addPass(SROA());
979 
980   // Run a few AA driver optimizations here and now to cleanup the code.
981   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
982 
983   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
984               PostOrderFunctionAttrsPass()));
985   // FIXME: here we run IP alias analysis in the legacy PM.
986 
987   FunctionPassManager MainFPM;
988 
989   // FIXME: once we fix LoopPass Manager, add LICM here.
990   // FIXME: once we provide support for enabling MLSM, add it here.
991   // FIXME: once we provide support for enabling NewGVN, add it here.
992   if (RunNewGVN)
993     MainFPM.addPass(NewGVNPass());
994   else
995     MainFPM.addPass(GVN());
996 
997   // Remove dead memcpy()'s.
998   MainFPM.addPass(MemCpyOptPass());
999 
1000   // Nuke dead stores.
1001   MainFPM.addPass(DSEPass());
1002 
1003   // FIXME: at this point, we run a bunch of loop passes:
1004   // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1005   // loopVectorize. Enable them once the remaining issue with LPM
1006   // are sorted out.
1007 
1008   MainFPM.addPass(InstCombinePass());
1009   MainFPM.addPass(SimplifyCFGPass());
1010   MainFPM.addPass(SCCPPass());
1011   MainFPM.addPass(InstCombinePass());
1012   MainFPM.addPass(BDCEPass());
1013 
1014   // FIXME: We may want to run SLPVectorizer here.
1015   // After vectorization, assume intrinsics may tell us more
1016   // about pointer alignments.
1017 #if 0
1018   MainFPM.add(AlignmentFromAssumptionsPass());
1019 #endif
1020 
1021   // FIXME: Conditionally run LoadCombine here, after it's ported
1022   // (in case we still have this pass, given its questionable usefulness).
1023 
1024   MainFPM.addPass(InstCombinePass());
1025   invokePeepholeEPCallbacks(MainFPM, Level);
1026   MainFPM.addPass(JumpThreadingPass());
1027   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1028 
1029   // Create a function that performs CFI checks for cross-DSO calls with
1030   // targets in the current module.
1031   MPM.addPass(CrossDSOCFIPass());
1032 
1033   // Lower type metadata and the type.test intrinsic. This pass supports
1034   // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1035   // to be run at link time if CFI is enabled. This pass does nothing if
1036   // CFI is disabled.
1037   // Enable once we add support for the summary in the new PM.
1038 #if 0
1039   MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export :
1040                                            PassSummaryAction::None,
1041                                 Summary));
1042 #endif
1043 
1044   // Add late LTO optimization passes.
1045   // Delete basic blocks, which optimization passes may have killed.
1046   MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1047 
1048   // Drop bodies of available eternally objects to improve GlobalDCE.
1049   MPM.addPass(EliminateAvailableExternallyPass());
1050 
1051   // Now that we have optimized the program, discard unreachable functions.
1052   MPM.addPass(GlobalDCEPass());
1053 
1054   // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
1055   return MPM;
1056 }
1057 
1058 AAManager PassBuilder::buildDefaultAAPipeline() {
1059   AAManager AA;
1060 
1061   // The order in which these are registered determines their priority when
1062   // being queried.
1063 
1064   // First we register the basic alias analysis that provides the majority of
1065   // per-function local AA logic. This is a stateless, on-demand local set of
1066   // AA techniques.
1067   AA.registerFunctionAnalysis<BasicAA>();
1068 
1069   // Next we query fast, specialized alias analyses that wrap IR-embedded
1070   // information about aliasing.
1071   AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1072   AA.registerFunctionAnalysis<TypeBasedAA>();
1073 
1074   // Add support for querying global aliasing information when available.
1075   // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1076   // analysis, all that the `AAManager` can do is query for any *cached*
1077   // results from `GlobalsAA` through a readonly proxy.
1078   AA.registerModuleAnalysis<GlobalsAA>();
1079 
1080   return AA;
1081 }
1082 
1083 static Optional<int> parseRepeatPassName(StringRef Name) {
1084   if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1085     return None;
1086   int Count;
1087   if (Name.getAsInteger(0, Count) || Count <= 0)
1088     return None;
1089   return Count;
1090 }
1091 
1092 static Optional<int> parseDevirtPassName(StringRef Name) {
1093   if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1094     return None;
1095   int Count;
1096   if (Name.getAsInteger(0, Count) || Count <= 0)
1097     return None;
1098   return Count;
1099 }
1100 
1101 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1102 /// alias.
1103 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1104   return Name.startswith("default") || Name.startswith("thinlto") ||
1105          Name.startswith("lto");
1106 }
1107 
1108 /// Tests whether registered callbacks will accept a given pass name.
1109 ///
1110 /// When parsing a pipeline text, the type of the outermost pipeline may be
1111 /// omitted, in which case the type is automatically determined from the first
1112 /// pass name in the text. This may be a name that is handled through one of the
1113 /// callbacks. We check this through the oridinary parsing callbacks by setting
1114 /// up a dummy PassManager in order to not force the client to also handle this
1115 /// type of query.
1116 template <typename PassManagerT, typename CallbacksT>
1117 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1118   if (!Callbacks.empty()) {
1119     PassManagerT DummyPM;
1120     for (auto &CB : Callbacks)
1121       if (CB(Name, DummyPM, {}))
1122         return true;
1123   }
1124   return false;
1125 }
1126 
1127 template <typename CallbacksT>
1128 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
1129   // Manually handle aliases for pre-configured pipeline fragments.
1130   if (startsWithDefaultPipelineAliasPrefix(Name))
1131     return DefaultAliasRegex.match(Name);
1132 
1133   // Explicitly handle pass manager names.
1134   if (Name == "module")
1135     return true;
1136   if (Name == "cgscc")
1137     return true;
1138   if (Name == "function")
1139     return true;
1140 
1141   // Explicitly handle custom-parsed pass names.
1142   if (parseRepeatPassName(Name))
1143     return true;
1144 
1145 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
1146   if (Name == NAME)                                                            \
1147     return true;
1148 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1149   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1150     return true;
1151 #include "PassRegistry.def"
1152 
1153   return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
1154 }
1155 
1156 template <typename CallbacksT>
1157 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
1158   // Explicitly handle pass manager names.
1159   if (Name == "cgscc")
1160     return true;
1161   if (Name == "function")
1162     return true;
1163 
1164   // Explicitly handle custom-parsed pass names.
1165   if (parseRepeatPassName(Name))
1166     return true;
1167   if (parseDevirtPassName(Name))
1168     return true;
1169 
1170 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1171   if (Name == NAME)                                                            \
1172     return true;
1173 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1174   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1175     return true;
1176 #include "PassRegistry.def"
1177 
1178   return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
1179 }
1180 
1181 template <typename CallbacksT>
1182 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
1183   // Explicitly handle pass manager names.
1184   if (Name == "function")
1185     return true;
1186   if (Name == "loop")
1187     return true;
1188 
1189   // Explicitly handle custom-parsed pass names.
1190   if (parseRepeatPassName(Name))
1191     return true;
1192 
1193 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1194   if (Name == NAME)                                                            \
1195     return true;
1196 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1197   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1198     return true;
1199 #include "PassRegistry.def"
1200 
1201   return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
1202 }
1203 
1204 template <typename CallbacksT>
1205 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
1206   // Explicitly handle pass manager names.
1207   if (Name == "loop")
1208     return true;
1209 
1210   // Explicitly handle custom-parsed pass names.
1211   if (parseRepeatPassName(Name))
1212     return true;
1213 
1214 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1215   if (Name == NAME)                                                            \
1216     return true;
1217 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1218   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1219     return true;
1220 #include "PassRegistry.def"
1221 
1222   return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1223 }
1224 
1225 Optional<std::vector<PassBuilder::PipelineElement>>
1226 PassBuilder::parsePipelineText(StringRef Text) {
1227   std::vector<PipelineElement> ResultPipeline;
1228 
1229   SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1230       &ResultPipeline};
1231   for (;;) {
1232     std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1233     size_t Pos = Text.find_first_of(",()");
1234     Pipeline.push_back({Text.substr(0, Pos), {}});
1235 
1236     // If we have a single terminating name, we're done.
1237     if (Pos == Text.npos)
1238       break;
1239 
1240     char Sep = Text[Pos];
1241     Text = Text.substr(Pos + 1);
1242     if (Sep == ',')
1243       // Just a name ending in a comma, continue.
1244       continue;
1245 
1246     if (Sep == '(') {
1247       // Push the inner pipeline onto the stack to continue processing.
1248       PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1249       continue;
1250     }
1251 
1252     assert(Sep == ')' && "Bogus separator!");
1253     // When handling the close parenthesis, we greedily consume them to avoid
1254     // empty strings in the pipeline.
1255     do {
1256       // If we try to pop the outer pipeline we have unbalanced parentheses.
1257       if (PipelineStack.size() == 1)
1258         return None;
1259 
1260       PipelineStack.pop_back();
1261     } while (Text.consume_front(")"));
1262 
1263     // Check if we've finished parsing.
1264     if (Text.empty())
1265       break;
1266 
1267     // Otherwise, the end of an inner pipeline always has to be followed by
1268     // a comma, and then we can continue.
1269     if (!Text.consume_front(","))
1270       return None;
1271   }
1272 
1273   if (PipelineStack.size() > 1)
1274     // Unbalanced paretheses.
1275     return None;
1276 
1277   assert(PipelineStack.back() == &ResultPipeline &&
1278          "Wrong pipeline at the bottom of the stack!");
1279   return {std::move(ResultPipeline)};
1280 }
1281 
1282 bool PassBuilder::parseModulePass(ModulePassManager &MPM,
1283                                   const PipelineElement &E, bool VerifyEachPass,
1284                                   bool DebugLogging) {
1285   auto &Name = E.Name;
1286   auto &InnerPipeline = E.InnerPipeline;
1287 
1288   // First handle complex passes like the pass managers which carry pipelines.
1289   if (!InnerPipeline.empty()) {
1290     if (Name == "module") {
1291       ModulePassManager NestedMPM(DebugLogging);
1292       if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1293                                    DebugLogging))
1294         return false;
1295       MPM.addPass(std::move(NestedMPM));
1296       return true;
1297     }
1298     if (Name == "cgscc") {
1299       CGSCCPassManager CGPM(DebugLogging);
1300       if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1301                                   DebugLogging))
1302         return false;
1303       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1304       return true;
1305     }
1306     if (Name == "function") {
1307       FunctionPassManager FPM(DebugLogging);
1308       if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1309                                      DebugLogging))
1310         return false;
1311       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1312       return true;
1313     }
1314     if (auto Count = parseRepeatPassName(Name)) {
1315       ModulePassManager NestedMPM(DebugLogging);
1316       if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1317                                    DebugLogging))
1318         return false;
1319       MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1320       return true;
1321     }
1322 
1323     for (auto &C : ModulePipelineParsingCallbacks)
1324       if (C(Name, MPM, InnerPipeline))
1325         return true;
1326 
1327     // Normal passes can't have pipelines.
1328     return false;
1329   }
1330 
1331   // Manually handle aliases for pre-configured pipeline fragments.
1332   if (startsWithDefaultPipelineAliasPrefix(Name)) {
1333     SmallVector<StringRef, 3> Matches;
1334     if (!DefaultAliasRegex.match(Name, &Matches))
1335       return false;
1336     assert(Matches.size() == 3 && "Must capture two matched strings!");
1337 
1338     OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1339                               .Case("O0", O0)
1340                               .Case("O1", O1)
1341                               .Case("O2", O2)
1342                               .Case("O3", O3)
1343                               .Case("Os", Os)
1344                               .Case("Oz", Oz);
1345     if (L == O0)
1346       // At O0 we do nothing at all!
1347       return true;
1348 
1349     if (Matches[1] == "default") {
1350       MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1351     } else if (Matches[1] == "thinlto-pre-link") {
1352       MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1353     } else if (Matches[1] == "thinlto") {
1354       MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging));
1355     } else if (Matches[1] == "lto-pre-link") {
1356       MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1357     } else {
1358       assert(Matches[1] == "lto" && "Not one of the matched options!");
1359       MPM.addPass(buildLTODefaultPipeline(L, DebugLogging));
1360     }
1361     return true;
1362   }
1363 
1364   // Finally expand the basic registered passes from the .inc file.
1365 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
1366   if (Name == NAME) {                                                          \
1367     MPM.addPass(CREATE_PASS);                                                  \
1368     return true;                                                               \
1369   }
1370 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1371   if (Name == "require<" NAME ">") {                                           \
1372     MPM.addPass(                                                               \
1373         RequireAnalysisPass<                                                   \
1374             std::remove_reference<decltype(CREATE_PASS)>::type, Module>());    \
1375     return true;                                                               \
1376   }                                                                            \
1377   if (Name == "invalidate<" NAME ">") {                                        \
1378     MPM.addPass(InvalidateAnalysisPass<                                        \
1379                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1380     return true;                                                               \
1381   }
1382 #include "PassRegistry.def"
1383 
1384   for (auto &C : ModulePipelineParsingCallbacks)
1385     if (C(Name, MPM, InnerPipeline))
1386       return true;
1387   return false;
1388 }
1389 
1390 bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1391                                  const PipelineElement &E, bool VerifyEachPass,
1392                                  bool DebugLogging) {
1393   auto &Name = E.Name;
1394   auto &InnerPipeline = E.InnerPipeline;
1395 
1396   // First handle complex passes like the pass managers which carry pipelines.
1397   if (!InnerPipeline.empty()) {
1398     if (Name == "cgscc") {
1399       CGSCCPassManager NestedCGPM(DebugLogging);
1400       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1401                                   DebugLogging))
1402         return false;
1403       // Add the nested pass manager with the appropriate adaptor.
1404       CGPM.addPass(std::move(NestedCGPM));
1405       return true;
1406     }
1407     if (Name == "function") {
1408       FunctionPassManager FPM(DebugLogging);
1409       if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1410                                      DebugLogging))
1411         return false;
1412       // Add the nested pass manager with the appropriate adaptor.
1413       CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1414       return true;
1415     }
1416     if (auto Count = parseRepeatPassName(Name)) {
1417       CGSCCPassManager NestedCGPM(DebugLogging);
1418       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1419                                   DebugLogging))
1420         return false;
1421       CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1422       return true;
1423     }
1424     if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1425       CGSCCPassManager NestedCGPM(DebugLogging);
1426       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1427                                   DebugLogging))
1428         return false;
1429       CGPM.addPass(
1430           createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
1431       return true;
1432     }
1433 
1434     for (auto &C : CGSCCPipelineParsingCallbacks)
1435       if (C(Name, CGPM, InnerPipeline))
1436         return true;
1437 
1438     // Normal passes can't have pipelines.
1439     return false;
1440   }
1441 
1442 // Now expand the basic registered passes from the .inc file.
1443 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1444   if (Name == NAME) {                                                          \
1445     CGPM.addPass(CREATE_PASS);                                                 \
1446     return true;                                                               \
1447   }
1448 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1449   if (Name == "require<" NAME ">") {                                           \
1450     CGPM.addPass(RequireAnalysisPass<                                          \
1451                  std::remove_reference<decltype(CREATE_PASS)>::type,           \
1452                  LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,    \
1453                  CGSCCUpdateResult &>());                                      \
1454     return true;                                                               \
1455   }                                                                            \
1456   if (Name == "invalidate<" NAME ">") {                                        \
1457     CGPM.addPass(InvalidateAnalysisPass<                                       \
1458                  std::remove_reference<decltype(CREATE_PASS)>::type>());       \
1459     return true;                                                               \
1460   }
1461 #include "PassRegistry.def"
1462 
1463   for (auto &C : CGSCCPipelineParsingCallbacks)
1464     if (C(Name, CGPM, InnerPipeline))
1465       return true;
1466   return false;
1467 }
1468 
1469 bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1470                                     const PipelineElement &E,
1471                                     bool VerifyEachPass, bool DebugLogging) {
1472   auto &Name = E.Name;
1473   auto &InnerPipeline = E.InnerPipeline;
1474 
1475   // First handle complex passes like the pass managers which carry pipelines.
1476   if (!InnerPipeline.empty()) {
1477     if (Name == "function") {
1478       FunctionPassManager NestedFPM(DebugLogging);
1479       if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1480                                      DebugLogging))
1481         return false;
1482       // Add the nested pass manager with the appropriate adaptor.
1483       FPM.addPass(std::move(NestedFPM));
1484       return true;
1485     }
1486     if (Name == "loop") {
1487       LoopPassManager LPM(DebugLogging);
1488       if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1489                                  DebugLogging))
1490         return false;
1491       // Add the nested pass manager with the appropriate adaptor.
1492       FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
1493       return true;
1494     }
1495     if (auto Count = parseRepeatPassName(Name)) {
1496       FunctionPassManager NestedFPM(DebugLogging);
1497       if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1498                                      DebugLogging))
1499         return false;
1500       FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1501       return true;
1502     }
1503 
1504     for (auto &C : FunctionPipelineParsingCallbacks)
1505       if (C(Name, FPM, InnerPipeline))
1506         return true;
1507 
1508     // Normal passes can't have pipelines.
1509     return false;
1510   }
1511 
1512 // Now expand the basic registered passes from the .inc file.
1513 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1514   if (Name == NAME) {                                                          \
1515     FPM.addPass(CREATE_PASS);                                                  \
1516     return true;                                                               \
1517   }
1518 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1519   if (Name == "require<" NAME ">") {                                           \
1520     FPM.addPass(                                                               \
1521         RequireAnalysisPass<                                                   \
1522             std::remove_reference<decltype(CREATE_PASS)>::type, Function>());  \
1523     return true;                                                               \
1524   }                                                                            \
1525   if (Name == "invalidate<" NAME ">") {                                        \
1526     FPM.addPass(InvalidateAnalysisPass<                                        \
1527                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1528     return true;                                                               \
1529   }
1530 #include "PassRegistry.def"
1531 
1532   for (auto &C : FunctionPipelineParsingCallbacks)
1533     if (C(Name, FPM, InnerPipeline))
1534       return true;
1535   return false;
1536 }
1537 
1538 bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1539                                 bool VerifyEachPass, bool DebugLogging) {
1540   StringRef Name = E.Name;
1541   auto &InnerPipeline = E.InnerPipeline;
1542 
1543   // First handle complex passes like the pass managers which carry pipelines.
1544   if (!InnerPipeline.empty()) {
1545     if (Name == "loop") {
1546       LoopPassManager NestedLPM(DebugLogging);
1547       if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1548                                  DebugLogging))
1549         return false;
1550       // Add the nested pass manager with the appropriate adaptor.
1551       LPM.addPass(std::move(NestedLPM));
1552       return true;
1553     }
1554     if (auto Count = parseRepeatPassName(Name)) {
1555       LoopPassManager NestedLPM(DebugLogging);
1556       if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1557                                  DebugLogging))
1558         return false;
1559       LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1560       return true;
1561     }
1562 
1563     for (auto &C : LoopPipelineParsingCallbacks)
1564       if (C(Name, LPM, InnerPipeline))
1565         return true;
1566 
1567     // Normal passes can't have pipelines.
1568     return false;
1569   }
1570 
1571 // Now expand the basic registered passes from the .inc file.
1572 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1573   if (Name == NAME) {                                                          \
1574     LPM.addPass(CREATE_PASS);                                                  \
1575     return true;                                                               \
1576   }
1577 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1578   if (Name == "require<" NAME ">") {                                           \
1579     LPM.addPass(RequireAnalysisPass<                                           \
1580                 std::remove_reference<decltype(CREATE_PASS)>::type, Loop,      \
1581                 LoopAnalysisManager, LoopStandardAnalysisResults &,            \
1582                 LPMUpdater &>());                                              \
1583     return true;                                                               \
1584   }                                                                            \
1585   if (Name == "invalidate<" NAME ">") {                                        \
1586     LPM.addPass(InvalidateAnalysisPass<                                        \
1587                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1588     return true;                                                               \
1589   }
1590 #include "PassRegistry.def"
1591 
1592   for (auto &C : LoopPipelineParsingCallbacks)
1593     if (C(Name, LPM, InnerPipeline))
1594       return true;
1595   return false;
1596 }
1597 
1598 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1599 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
1600   if (Name == NAME) {                                                          \
1601     AA.registerModuleAnalysis<                                                 \
1602         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
1603     return true;                                                               \
1604   }
1605 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
1606   if (Name == NAME) {                                                          \
1607     AA.registerFunctionAnalysis<                                               \
1608         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
1609     return true;                                                               \
1610   }
1611 #include "PassRegistry.def"
1612 
1613   for (auto &C : AAParsingCallbacks)
1614     if (C(Name, AA))
1615       return true;
1616   return false;
1617 }
1618 
1619 bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1620                                         ArrayRef<PipelineElement> Pipeline,
1621                                         bool VerifyEachPass,
1622                                         bool DebugLogging) {
1623   for (const auto &Element : Pipeline) {
1624     if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1625       return false;
1626     // FIXME: No verifier support for Loop passes!
1627   }
1628   return true;
1629 }
1630 
1631 bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1632                                             ArrayRef<PipelineElement> Pipeline,
1633                                             bool VerifyEachPass,
1634                                             bool DebugLogging) {
1635   for (const auto &Element : Pipeline) {
1636     if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1637       return false;
1638     if (VerifyEachPass)
1639       FPM.addPass(VerifierPass());
1640   }
1641   return true;
1642 }
1643 
1644 bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1645                                          ArrayRef<PipelineElement> Pipeline,
1646                                          bool VerifyEachPass,
1647                                          bool DebugLogging) {
1648   for (const auto &Element : Pipeline) {
1649     if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1650       return false;
1651     // FIXME: No verifier support for CGSCC passes!
1652   }
1653   return true;
1654 }
1655 
1656 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1657                                        FunctionAnalysisManager &FAM,
1658                                        CGSCCAnalysisManager &CGAM,
1659                                        ModuleAnalysisManager &MAM) {
1660   MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1661   MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1662   CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1663   FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1664   FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1665   FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1666   LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1667 }
1668 
1669 bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1670                                           ArrayRef<PipelineElement> Pipeline,
1671                                           bool VerifyEachPass,
1672                                           bool DebugLogging) {
1673   for (const auto &Element : Pipeline) {
1674     if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1675       return false;
1676     if (VerifyEachPass)
1677       MPM.addPass(VerifierPass());
1678   }
1679   return true;
1680 }
1681 
1682 // Primary pass pipeline description parsing routine for a \c ModulePassManager
1683 // FIXME: Should this routine accept a TargetMachine or require the caller to
1684 // pre-populate the analysis managers with target-specific stuff?
1685 bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1686                                     StringRef PipelineText, bool VerifyEachPass,
1687                                     bool DebugLogging) {
1688   auto Pipeline = parsePipelineText(PipelineText);
1689   if (!Pipeline || Pipeline->empty())
1690     return false;
1691 
1692   // If the first name isn't at the module layer, wrap the pipeline up
1693   // automatically.
1694   StringRef FirstName = Pipeline->front().Name;
1695 
1696   if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1697     if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
1698       Pipeline = {{"cgscc", std::move(*Pipeline)}};
1699     } else if (isFunctionPassName(FirstName,
1700                                   FunctionPipelineParsingCallbacks)) {
1701       Pipeline = {{"function", std::move(*Pipeline)}};
1702     } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
1703       Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
1704     } else {
1705       for (auto &C : TopLevelPipelineParsingCallbacks)
1706         if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1707           return true;
1708 
1709       // Unknown pass name!
1710       return false;
1711     }
1712   }
1713 
1714   return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
1715 }
1716 
1717 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
1718 bool PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1719                                     StringRef PipelineText, bool VerifyEachPass,
1720                                     bool DebugLogging) {
1721   auto Pipeline = parsePipelineText(PipelineText);
1722   if (!Pipeline || Pipeline->empty())
1723     return false;
1724 
1725   StringRef FirstName = Pipeline->front().Name;
1726   if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
1727     return false;
1728 
1729   return parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1730 }
1731 
1732 // Primary pass pipeline description parsing routine for a \c
1733 // FunctionPassManager
1734 bool PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1735                                     StringRef PipelineText, bool VerifyEachPass,
1736                                     bool DebugLogging) {
1737   auto Pipeline = parsePipelineText(PipelineText);
1738   if (!Pipeline || Pipeline->empty())
1739     return false;
1740 
1741   StringRef FirstName = Pipeline->front().Name;
1742   if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
1743     return false;
1744 
1745   return parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1746                                    DebugLogging);
1747 }
1748 
1749 // Primary pass pipeline description parsing routine for a \c LoopPassManager
1750 bool PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1751                                     StringRef PipelineText, bool VerifyEachPass,
1752                                     bool DebugLogging) {
1753   auto Pipeline = parsePipelineText(PipelineText);
1754   if (!Pipeline || Pipeline->empty())
1755     return false;
1756 
1757   return parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1758 }
1759 
1760 bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
1761   // If the pipeline just consists of the word 'default' just replace the AA
1762   // manager with our default one.
1763   if (PipelineText == "default") {
1764     AA = buildDefaultAAPipeline();
1765     return true;
1766   }
1767 
1768   while (!PipelineText.empty()) {
1769     StringRef Name;
1770     std::tie(Name, PipelineText) = PipelineText.split(',');
1771     if (!parseAAPassName(AA, Name))
1772       return false;
1773   }
1774 
1775   return true;
1776 }
1777