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