1 //===- Parsing, selection, and construction of pass pipelines -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 ///
10 /// This file provides the implementation of the PassBuilder based on our
11 /// static pass registry as well as related functionality. It also provides
12 /// helpers to aid in analyzing, debugging, and testing passes and pass
13 /// pipelines.
14 ///
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Passes/PassBuilder.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/Analysis/AliasAnalysisEvaluator.h"
20 #include "llvm/Analysis/AliasSetTracker.h"
21 #include "llvm/Analysis/AssumptionCache.h"
22 #include "llvm/Analysis/BasicAliasAnalysis.h"
23 #include "llvm/Analysis/BlockFrequencyInfo.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/CFGPrinter.h"
26 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
28 #include "llvm/Analysis/CGSCCPassManager.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Analysis/DDG.h"
31 #include "llvm/Analysis/DDGPrinter.h"
32 #include "llvm/Analysis/Delinearization.h"
33 #include "llvm/Analysis/DemandedBits.h"
34 #include "llvm/Analysis/DependenceAnalysis.h"
35 #include "llvm/Analysis/DivergenceAnalysis.h"
36 #include "llvm/Analysis/DominanceFrontier.h"
37 #include "llvm/Analysis/FunctionPropertiesAnalysis.h"
38 #include "llvm/Analysis/GlobalsModRef.h"
39 #include "llvm/Analysis/IRSimilarityIdentifier.h"
40 #include "llvm/Analysis/IVUsers.h"
41 #include "llvm/Analysis/InlineAdvisor.h"
42 #include "llvm/Analysis/InlineSizeEstimatorAnalysis.h"
43 #include "llvm/Analysis/InstCount.h"
44 #include "llvm/Analysis/LazyCallGraph.h"
45 #include "llvm/Analysis/LazyValueInfo.h"
46 #include "llvm/Analysis/Lint.h"
47 #include "llvm/Analysis/LoopAccessAnalysis.h"
48 #include "llvm/Analysis/LoopCacheAnalysis.h"
49 #include "llvm/Analysis/LoopInfo.h"
50 #include "llvm/Analysis/LoopNestAnalysis.h"
51 #include "llvm/Analysis/MemDerefPrinter.h"
52 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
53 #include "llvm/Analysis/MemorySSA.h"
54 #include "llvm/Analysis/ModuleDebugInfoPrinter.h"
55 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
56 #include "llvm/Analysis/MustExecute.h"
57 #include "llvm/Analysis/ObjCARCAliasAnalysis.h"
58 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
59 #include "llvm/Analysis/PhiValues.h"
60 #include "llvm/Analysis/PostDominators.h"
61 #include "llvm/Analysis/ProfileSummaryInfo.h"
62 #include "llvm/Analysis/RegionInfo.h"
63 #include "llvm/Analysis/ScalarEvolution.h"
64 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
65 #include "llvm/Analysis/ScopedNoAliasAA.h"
66 #include "llvm/Analysis/StackLifetime.h"
67 #include "llvm/Analysis/StackSafetyAnalysis.h"
68 #include "llvm/Analysis/TargetLibraryInfo.h"
69 #include "llvm/Analysis/TargetTransformInfo.h"
70 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
71 #include "llvm/IR/Dominators.h"
72 #include "llvm/IR/IRPrintingPasses.h"
73 #include "llvm/IR/PassManager.h"
74 #include "llvm/IR/PrintPasses.h"
75 #include "llvm/IR/SafepointIRVerifier.h"
76 #include "llvm/IR/Verifier.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Debug.h"
79 #include "llvm/Support/ErrorHandling.h"
80 #include "llvm/Support/FormatVariadic.h"
81 #include "llvm/Support/Regex.h"
82 #include "llvm/Target/TargetMachine.h"
83 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
84 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
85 #include "llvm/Transforms/Coroutines/CoroEarly.h"
86 #include "llvm/Transforms/Coroutines/CoroElide.h"
87 #include "llvm/Transforms/Coroutines/CoroSplit.h"
88 #include "llvm/Transforms/IPO/AlwaysInliner.h"
89 #include "llvm/Transforms/IPO/Annotation2Metadata.h"
90 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
91 #include "llvm/Transforms/IPO/Attributor.h"
92 #include "llvm/Transforms/IPO/BlockExtractor.h"
93 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
94 #include "llvm/Transforms/IPO/ConstantMerge.h"
95 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
96 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
97 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
98 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
99 #include "llvm/Transforms/IPO/FunctionAttrs.h"
100 #include "llvm/Transforms/IPO/FunctionImport.h"
101 #include "llvm/Transforms/IPO/GlobalDCE.h"
102 #include "llvm/Transforms/IPO/GlobalOpt.h"
103 #include "llvm/Transforms/IPO/GlobalSplit.h"
104 #include "llvm/Transforms/IPO/HotColdSplitting.h"
105 #include "llvm/Transforms/IPO/IROutliner.h"
106 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
107 #include "llvm/Transforms/IPO/Inliner.h"
108 #include "llvm/Transforms/IPO/Internalize.h"
109 #include "llvm/Transforms/IPO/LoopExtractor.h"
110 #include "llvm/Transforms/IPO/LowerTypeTests.h"
111 #include "llvm/Transforms/IPO/MergeFunctions.h"
112 #include "llvm/Transforms/IPO/OpenMPOpt.h"
113 #include "llvm/Transforms/IPO/PartialInlining.h"
114 #include "llvm/Transforms/IPO/SCCP.h"
115 #include "llvm/Transforms/IPO/SampleProfile.h"
116 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
117 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
118 #include "llvm/Transforms/IPO/StripSymbols.h"
119 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
120 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
121 #include "llvm/Transforms/InstCombine/InstCombine.h"
122 #include "llvm/Transforms/Instrumentation.h"
123 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
124 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
125 #include "llvm/Transforms/Instrumentation/CGProfile.h"
126 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
127 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
128 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
129 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
130 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
131 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
132 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
133 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
134 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
135 #include "llvm/Transforms/Instrumentation/PoisonChecking.h"
136 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
137 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
138 #include "llvm/Transforms/ObjCARC.h"
139 #include "llvm/Transforms/Scalar/ADCE.h"
140 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
141 #include "llvm/Transforms/Scalar/AnnotationRemarks.h"
142 #include "llvm/Transforms/Scalar/BDCE.h"
143 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
144 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
145 #include "llvm/Transforms/Scalar/ConstraintElimination.h"
146 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
147 #include "llvm/Transforms/Scalar/DCE.h"
148 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
149 #include "llvm/Transforms/Scalar/DivRemPairs.h"
150 #include "llvm/Transforms/Scalar/EarlyCSE.h"
151 #include "llvm/Transforms/Scalar/Float2Int.h"
152 #include "llvm/Transforms/Scalar/GVN.h"
153 #include "llvm/Transforms/Scalar/GuardWidening.h"
154 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
155 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
156 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
157 #include "llvm/Transforms/Scalar/InferAddressSpaces.h"
158 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
159 #include "llvm/Transforms/Scalar/JumpThreading.h"
160 #include "llvm/Transforms/Scalar/LICM.h"
161 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
162 #include "llvm/Transforms/Scalar/LoopBoundSplit.h"
163 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
164 #include "llvm/Transforms/Scalar/LoopDeletion.h"
165 #include "llvm/Transforms/Scalar/LoopDistribute.h"
166 #include "llvm/Transforms/Scalar/LoopFlatten.h"
167 #include "llvm/Transforms/Scalar/LoopFuse.h"
168 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
169 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
170 #include "llvm/Transforms/Scalar/LoopInterchange.h"
171 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
172 #include "llvm/Transforms/Scalar/LoopPassManager.h"
173 #include "llvm/Transforms/Scalar/LoopPredication.h"
174 #include "llvm/Transforms/Scalar/LoopReroll.h"
175 #include "llvm/Transforms/Scalar/LoopRotation.h"
176 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
177 #include "llvm/Transforms/Scalar/LoopSink.h"
178 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
179 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
180 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
181 #include "llvm/Transforms/Scalar/LoopVersioningLICM.h"
182 #include "llvm/Transforms/Scalar/LowerAtomic.h"
183 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
184 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
185 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
186 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
187 #include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
188 #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
189 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
190 #include "llvm/Transforms/Scalar/MergeICmps.h"
191 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
192 #include "llvm/Transforms/Scalar/NaryReassociate.h"
193 #include "llvm/Transforms/Scalar/NewGVN.h"
194 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
195 #include "llvm/Transforms/Scalar/Reassociate.h"
196 #include "llvm/Transforms/Scalar/Reg2Mem.h"
197 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
198 #include "llvm/Transforms/Scalar/SCCP.h"
199 #include "llvm/Transforms/Scalar/SROA.h"
200 #include "llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h"
201 #include "llvm/Transforms/Scalar/Scalarizer.h"
202 #include "llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h"
203 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
204 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
205 #include "llvm/Transforms/Scalar/Sink.h"
206 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
207 #include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h"
208 #include "llvm/Transforms/Scalar/StructurizeCFG.h"
209 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
210 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
211 #include "llvm/Transforms/Utils/AddDiscriminators.h"
212 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
213 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
214 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
215 #include "llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h"
216 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
217 #include "llvm/Transforms/Utils/FixIrreducible.h"
218 #include "llvm/Transforms/Utils/HelloWorld.h"
219 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
220 #include "llvm/Transforms/Utils/InstructionNamer.h"
221 #include "llvm/Transforms/Utils/LCSSA.h"
222 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
223 #include "llvm/Transforms/Utils/LoopSimplify.h"
224 #include "llvm/Transforms/Utils/LoopVersioning.h"
225 #include "llvm/Transforms/Utils/LowerInvoke.h"
226 #include "llvm/Transforms/Utils/LowerSwitch.h"
227 #include "llvm/Transforms/Utils/Mem2Reg.h"
228 #include "llvm/Transforms/Utils/MetaRenamer.h"
229 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
230 #include "llvm/Transforms/Utils/RelLookupTableConverter.h"
231 #include "llvm/Transforms/Utils/StripGCRelocates.h"
232 #include "llvm/Transforms/Utils/StripNonLineTableDebugInfo.h"
233 #include "llvm/Transforms/Utils/SymbolRewriter.h"
234 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
235 #include "llvm/Transforms/Utils/UnifyLoopExits.h"
236 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
237 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
238 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
239 #include "llvm/Transforms/Vectorize/VectorCombine.h"
240 
241 using namespace llvm;
242 
243 static cl::opt<InliningAdvisorMode> UseInlineAdvisor(
244     "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden,
245     cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"),
246     cl::values(clEnumValN(InliningAdvisorMode::Default, "default",
247                           "Heuristics-based inliner version."),
248                clEnumValN(InliningAdvisorMode::Development, "development",
249                           "Use development mode (runtime-loadable model)."),
250                clEnumValN(InliningAdvisorMode::Release, "release",
251                           "Use release mode (AOT-compiled model).")));
252 
253 static cl::opt<bool> EnableSyntheticCounts(
254     "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
255     cl::desc("Run synthetic function entry count generation "
256              "pass"));
257 
258 static const Regex DefaultAliasRegex(
259     "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
260 
261 /// Flag to enable inline deferral during PGO.
262 static cl::opt<bool>
263     EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true),
264                             cl::Hidden,
265                             cl::desc("Enable inline deferral during PGO"));
266 
267 static cl::opt<bool> EnableMemProfiler("enable-mem-prof", cl::init(false),
268                                        cl::Hidden, cl::ZeroOrMore,
269                                        cl::desc("Enable memory profiler"));
270 
271 static cl::opt<bool> PerformMandatoryInliningsFirst(
272     "mandatory-inlining-first", cl::init(true), cl::Hidden, cl::ZeroOrMore,
273     cl::desc("Perform mandatory inlinings module-wide, before performing "
274              "inlining."));
275 
276 static cl::opt<bool> EnableO3NonTrivialUnswitching(
277     "enable-npm-O3-nontrivial-unswitch", cl::init(true), cl::Hidden,
278     cl::ZeroOrMore, cl::desc("Enable non-trivial loop unswitching for -O3"));
279 
280 PipelineTuningOptions::PipelineTuningOptions() {
281   LoopInterleaving = true;
282   LoopVectorization = true;
283   SLPVectorization = false;
284   LoopUnrolling = true;
285   ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
286   LicmMssaOptCap = SetLicmMssaOptCap;
287   LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
288   CallGraphProfile = true;
289   MergeFunctions = false;
290 }
291 
292 namespace llvm {
293 extern cl::opt<unsigned> MaxDevirtIterations;
294 extern cl::opt<bool> EnableConstraintElimination;
295 extern cl::opt<bool> EnableFunctionSpecialization;
296 extern cl::opt<bool> EnableGVNHoist;
297 extern cl::opt<bool> EnableGVNSink;
298 extern cl::opt<bool> EnableHotColdSplit;
299 extern cl::opt<bool> EnableIROutliner;
300 extern cl::opt<bool> EnableOrderFileInstrumentation;
301 extern cl::opt<bool> EnableCHR;
302 extern cl::opt<bool> EnableLoopInterchange;
303 extern cl::opt<bool> EnableUnrollAndJam;
304 extern cl::opt<bool> EnableLoopFlatten;
305 extern cl::opt<bool> RunNewGVN;
306 extern cl::opt<bool> RunPartialInlining;
307 extern cl::opt<bool> ExtraVectorizerPasses;
308 
309 extern cl::opt<bool> FlattenedProfileUsed;
310 
311 extern cl::opt<AttributorRunOption> AttributorRun;
312 extern cl::opt<bool> EnableKnowledgeRetention;
313 
314 extern cl::opt<bool> EnableMatrix;
315 
316 extern cl::opt<bool> DisablePreInliner;
317 extern cl::opt<int> PreInlineThreshold;
318 } // namespace llvm
319 
320 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O0 = {
321     /*SpeedLevel*/ 0,
322     /*SizeLevel*/ 0};
323 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O1 = {
324     /*SpeedLevel*/ 1,
325     /*SizeLevel*/ 0};
326 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O2 = {
327     /*SpeedLevel*/ 2,
328     /*SizeLevel*/ 0};
329 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O3 = {
330     /*SpeedLevel*/ 3,
331     /*SizeLevel*/ 0};
332 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::Os = {
333     /*SpeedLevel*/ 2,
334     /*SizeLevel*/ 1};
335 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::Oz = {
336     /*SpeedLevel*/ 2,
337     /*SizeLevel*/ 2};
338 
339 namespace {
340 
341 // The following passes/analyses have custom names, otherwise their name will
342 // include `(anonymous namespace)`. These are special since they are only for
343 // testing purposes and don't live in a header file.
344 
345 /// No-op module pass which does nothing.
346 struct NoOpModulePass : PassInfoMixin<NoOpModulePass> {
347   PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
348     return PreservedAnalyses::all();
349   }
350 
351   static StringRef name() { return "NoOpModulePass"; }
352 };
353 
354 /// No-op module analysis.
355 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
356   friend AnalysisInfoMixin<NoOpModuleAnalysis>;
357   static AnalysisKey Key;
358 
359 public:
360   struct Result {};
361   Result run(Module &, ModuleAnalysisManager &) { return Result(); }
362   static StringRef name() { return "NoOpModuleAnalysis"; }
363 };
364 
365 /// No-op CGSCC pass which does nothing.
366 struct NoOpCGSCCPass : PassInfoMixin<NoOpCGSCCPass> {
367   PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
368                         LazyCallGraph &, CGSCCUpdateResult &UR) {
369     return PreservedAnalyses::all();
370   }
371   static StringRef name() { return "NoOpCGSCCPass"; }
372 };
373 
374 /// No-op CGSCC analysis.
375 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
376   friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
377   static AnalysisKey Key;
378 
379 public:
380   struct Result {};
381   Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
382     return Result();
383   }
384   static StringRef name() { return "NoOpCGSCCAnalysis"; }
385 };
386 
387 /// No-op function pass which does nothing.
388 struct NoOpFunctionPass : PassInfoMixin<NoOpFunctionPass> {
389   PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
390     return PreservedAnalyses::all();
391   }
392   static StringRef name() { return "NoOpFunctionPass"; }
393 };
394 
395 /// No-op function analysis.
396 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
397   friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
398   static AnalysisKey Key;
399 
400 public:
401   struct Result {};
402   Result run(Function &, FunctionAnalysisManager &) { return Result(); }
403   static StringRef name() { return "NoOpFunctionAnalysis"; }
404 };
405 
406 /// No-op loop pass which does nothing.
407 struct NoOpLoopPass : PassInfoMixin<NoOpLoopPass> {
408   PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
409                         LoopStandardAnalysisResults &, LPMUpdater &) {
410     return PreservedAnalyses::all();
411   }
412   static StringRef name() { return "NoOpLoopPass"; }
413 };
414 
415 /// No-op loop analysis.
416 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
417   friend AnalysisInfoMixin<NoOpLoopAnalysis>;
418   static AnalysisKey Key;
419 
420 public:
421   struct Result {};
422   Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
423     return Result();
424   }
425   static StringRef name() { return "NoOpLoopAnalysis"; }
426 };
427 
428 AnalysisKey NoOpModuleAnalysis::Key;
429 AnalysisKey NoOpCGSCCAnalysis::Key;
430 AnalysisKey NoOpFunctionAnalysis::Key;
431 AnalysisKey NoOpLoopAnalysis::Key;
432 
433 /// Whether or not we should populate a PassInstrumentationCallbacks's class to
434 /// pass name map.
435 ///
436 /// This is for optimization purposes so we don't populate it if we never use
437 /// it. This should be updated if new pass instrumentation wants to use the map.
438 /// We currently only use this for --print-before/after.
439 bool shouldPopulateClassToPassNames() {
440   return !printBeforePasses().empty() || !printAfterPasses().empty();
441 }
442 
443 } // namespace
444 
445 PassBuilder::PassBuilder(TargetMachine *TM, PipelineTuningOptions PTO,
446                          Optional<PGOOptions> PGOOpt,
447                          PassInstrumentationCallbacks *PIC)
448     : TM(TM), PTO(PTO), PGOOpt(PGOOpt), PIC(PIC) {
449   if (TM)
450     TM->registerPassBuilderCallbacks(*this);
451   if (PIC && shouldPopulateClassToPassNames()) {
452 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
453   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
454 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
455   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
456 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
457   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
458 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
459   PIC->addClassToPassName(CLASS, NAME);
460 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
461   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
462 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
463   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
464 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
465   PIC->addClassToPassName(CLASS, NAME);
466 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
467   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
468 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
469   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
470 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
471   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
472 #include "PassRegistry.def"
473   }
474 }
475 
476 void PassBuilder::invokePeepholeEPCallbacks(
477     FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
478   for (auto &C : PeepholeEPCallbacks)
479     C(FPM, Level);
480 }
481 
482 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
483 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
484   MAM.registerPass([&] { return CREATE_PASS; });
485 #include "PassRegistry.def"
486 
487   for (auto &C : ModuleAnalysisRegistrationCallbacks)
488     C(MAM);
489 }
490 
491 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
492 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
493   CGAM.registerPass([&] { return CREATE_PASS; });
494 #include "PassRegistry.def"
495 
496   for (auto &C : CGSCCAnalysisRegistrationCallbacks)
497     C(CGAM);
498 }
499 
500 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
501 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
502   FAM.registerPass([&] { return CREATE_PASS; });
503 #include "PassRegistry.def"
504 
505   for (auto &C : FunctionAnalysisRegistrationCallbacks)
506     C(FAM);
507 }
508 
509 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
510 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
511   LAM.registerPass([&] { return CREATE_PASS; });
512 #include "PassRegistry.def"
513 
514   for (auto &C : LoopAnalysisRegistrationCallbacks)
515     C(LAM);
516 }
517 
518 // Helper to add AnnotationRemarksPass.
519 static void addAnnotationRemarksPass(ModulePassManager &MPM) {
520   FunctionPassManager FPM;
521   FPM.addPass(AnnotationRemarksPass());
522   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
523 }
524 
525 // Helper to check if the current compilation phase is preparing for LTO
526 static bool isLTOPreLink(ThinOrFullLTOPhase Phase) {
527   return Phase == ThinOrFullLTOPhase::ThinLTOPreLink ||
528          Phase == ThinOrFullLTOPhase::FullLTOPreLink;
529 }
530 
531 // TODO: Investigate the cost/benefit of tail call elimination on debugging.
532 FunctionPassManager
533 PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
534                                                    ThinOrFullLTOPhase Phase) {
535 
536   FunctionPassManager FPM;
537 
538   // Form SSA out of local memory accesses after breaking apart aggregates into
539   // scalars.
540   FPM.addPass(SROA());
541 
542   // Catch trivial redundancies
543   FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
544 
545   // Hoisting of scalars and load expressions.
546   FPM.addPass(SimplifyCFGPass());
547   FPM.addPass(InstCombinePass());
548 
549   FPM.addPass(LibCallsShrinkWrapPass());
550 
551   invokePeepholeEPCallbacks(FPM, Level);
552 
553   FPM.addPass(SimplifyCFGPass());
554 
555   // Form canonically associated expression trees, and simplify the trees using
556   // basic mathematical properties. For example, this will form (nearly)
557   // minimal multiplication trees.
558   FPM.addPass(ReassociatePass());
559 
560   // Add the primary loop simplification pipeline.
561   // FIXME: Currently this is split into two loop pass pipelines because we run
562   // some function passes in between them. These can and should be removed
563   // and/or replaced by scheduling the loop pass equivalents in the correct
564   // positions. But those equivalent passes aren't powerful enough yet.
565   // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
566   // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
567   // fully replace `SimplifyCFGPass`, and the closest to the other we have is
568   // `LoopInstSimplify`.
569   LoopPassManager LPM1, LPM2;
570 
571   // Simplify the loop body. We do this initially to clean up after other loop
572   // passes run, either when iterating on a loop or on inner loops with
573   // implications on the outer loop.
574   LPM1.addPass(LoopInstSimplifyPass());
575   LPM1.addPass(LoopSimplifyCFGPass());
576 
577   // Try to remove as much code from the loop header as possible,
578   // to reduce amount of IR that will have to be duplicated.
579   // TODO: Investigate promotion cap for O1.
580   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
581 
582   LPM1.addPass(LoopRotatePass(/* Disable header duplication */ true,
583                               isLTOPreLink(Phase)));
584   // TODO: Investigate promotion cap for O1.
585   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
586   LPM1.addPass(SimpleLoopUnswitchPass());
587 
588   LPM2.addPass(LoopIdiomRecognizePass());
589   LPM2.addPass(IndVarSimplifyPass());
590 
591   for (auto &C : LateLoopOptimizationsEPCallbacks)
592     C(LPM2, Level);
593 
594   LPM2.addPass(LoopDeletionPass());
595 
596   if (EnableLoopInterchange)
597     LPM2.addPass(LoopInterchangePass());
598 
599   // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
600   // because it changes IR to makes profile annotation in back compile
601   // inaccurate. The normal unroller doesn't pay attention to forced full unroll
602   // attributes so we need to make sure and allow the full unroll pass to pay
603   // attention to it.
604   if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt ||
605       PGOOpt->Action != PGOOptions::SampleUse)
606     LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
607                                     /* OnlyWhenForced= */ !PTO.LoopUnrolling,
608                                     PTO.ForgetAllSCEVInLoopUnroll));
609 
610   for (auto &C : LoopOptimizerEndEPCallbacks)
611     C(LPM2, Level);
612 
613   // We provide the opt remark emitter pass for LICM to use. We only need to do
614   // this once as it is immutable.
615   FPM.addPass(
616       RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
617   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
618                                               EnableMSSALoopDependency,
619                                               /*UseBlockFrequencyInfo=*/true));
620   FPM.addPass(SimplifyCFGPass());
621   FPM.addPass(InstCombinePass());
622   if (EnableLoopFlatten)
623     FPM.addPass(createFunctionToLoopPassAdaptor(LoopFlattenPass()));
624   // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
625   // *All* loop passes must preserve it, in order to be able to use it.
626   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
627                                               /*UseMemorySSA=*/false,
628                                               /*UseBlockFrequencyInfo=*/false));
629 
630   // Delete small array after loop unroll.
631   FPM.addPass(SROA());
632 
633   // Specially optimize memory movement as it doesn't look like dataflow in SSA.
634   FPM.addPass(MemCpyOptPass());
635 
636   // Sparse conditional constant propagation.
637   // FIXME: It isn't clear why we do this *after* loop passes rather than
638   // before...
639   FPM.addPass(SCCPPass());
640 
641   // Delete dead bit computations (instcombine runs after to fold away the dead
642   // computations, and then ADCE will run later to exploit any new DCE
643   // opportunities that creates).
644   FPM.addPass(BDCEPass());
645 
646   // Run instcombine after redundancy and dead bit elimination to exploit
647   // opportunities opened up by them.
648   FPM.addPass(InstCombinePass());
649   invokePeepholeEPCallbacks(FPM, Level);
650 
651   FPM.addPass(CoroElidePass());
652 
653   for (auto &C : ScalarOptimizerLateEPCallbacks)
654     C(FPM, Level);
655 
656   // Finally, do an expensive DCE pass to catch all the dead code exposed by
657   // the simplifications and basic cleanup after all the simplifications.
658   // TODO: Investigate if this is too expensive.
659   FPM.addPass(ADCEPass());
660   FPM.addPass(SimplifyCFGPass());
661   FPM.addPass(InstCombinePass());
662   invokePeepholeEPCallbacks(FPM, Level);
663 
664   return FPM;
665 }
666 
667 FunctionPassManager
668 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
669                                                  ThinOrFullLTOPhase Phase) {
670   assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
671 
672   // The O1 pipeline has a separate pipeline creation function to simplify
673   // construction readability.
674   if (Level.getSpeedupLevel() == 1)
675     return buildO1FunctionSimplificationPipeline(Level, Phase);
676 
677   FunctionPassManager FPM;
678 
679   // Form SSA out of local memory accesses after breaking apart aggregates into
680   // scalars.
681   FPM.addPass(SROA());
682 
683   // Catch trivial redundancies
684   FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
685   if (EnableKnowledgeRetention)
686     FPM.addPass(AssumeSimplifyPass());
687 
688   // Hoisting of scalars and load expressions.
689   if (EnableGVNHoist)
690     FPM.addPass(GVNHoistPass());
691 
692   // Global value numbering based sinking.
693   if (EnableGVNSink) {
694     FPM.addPass(GVNSinkPass());
695     FPM.addPass(SimplifyCFGPass());
696   }
697 
698   if (EnableConstraintElimination)
699     FPM.addPass(ConstraintEliminationPass());
700 
701   // Speculative execution if the target has divergent branches; otherwise nop.
702   FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
703 
704   // Optimize based on known information about branches, and cleanup afterward.
705   FPM.addPass(JumpThreadingPass());
706   FPM.addPass(CorrelatedValuePropagationPass());
707 
708   FPM.addPass(SimplifyCFGPass());
709   if (Level == OptimizationLevel::O3)
710     FPM.addPass(AggressiveInstCombinePass());
711   FPM.addPass(InstCombinePass());
712 
713   if (!Level.isOptimizingForSize())
714     FPM.addPass(LibCallsShrinkWrapPass());
715 
716   invokePeepholeEPCallbacks(FPM, Level);
717 
718   // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
719   // using the size value profile. Don't perform this when optimizing for size.
720   if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
721       !Level.isOptimizingForSize())
722     FPM.addPass(PGOMemOPSizeOpt());
723 
724   FPM.addPass(TailCallElimPass());
725   FPM.addPass(SimplifyCFGPass());
726 
727   // Form canonically associated expression trees, and simplify the trees using
728   // basic mathematical properties. For example, this will form (nearly)
729   // minimal multiplication trees.
730   FPM.addPass(ReassociatePass());
731 
732   // Add the primary loop simplification pipeline.
733   // FIXME: Currently this is split into two loop pass pipelines because we run
734   // some function passes in between them. These can and should be removed
735   // and/or replaced by scheduling the loop pass equivalents in the correct
736   // positions. But those equivalent passes aren't powerful enough yet.
737   // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
738   // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
739   // fully replace `SimplifyCFGPass`, and the closest to the other we have is
740   // `LoopInstSimplify`.
741   LoopPassManager LPM1, LPM2;
742 
743   // Simplify the loop body. We do this initially to clean up after other loop
744   // passes run, either when iterating on a loop or on inner loops with
745   // implications on the outer loop.
746   LPM1.addPass(LoopInstSimplifyPass());
747   LPM1.addPass(LoopSimplifyCFGPass());
748 
749   // Try to remove as much code from the loop header as possible,
750   // to reduce amount of IR that will have to be duplicated.
751   // TODO: Investigate promotion cap for O1.
752   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
753 
754   // Disable header duplication in loop rotation at -Oz.
755   LPM1.addPass(
756       LoopRotatePass(Level != OptimizationLevel::Oz, isLTOPreLink(Phase)));
757   // TODO: Investigate promotion cap for O1.
758   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
759   LPM1.addPass(
760       SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3 &&
761                              EnableO3NonTrivialUnswitching));
762   LPM2.addPass(LoopIdiomRecognizePass());
763   LPM2.addPass(IndVarSimplifyPass());
764 
765   for (auto &C : LateLoopOptimizationsEPCallbacks)
766     C(LPM2, Level);
767 
768   LPM2.addPass(LoopDeletionPass());
769 
770   if (EnableLoopInterchange)
771     LPM2.addPass(LoopInterchangePass());
772 
773   // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
774   // because it changes IR to makes profile annotation in back compile
775   // inaccurate. The normal unroller doesn't pay attention to forced full unroll
776   // attributes so we need to make sure and allow the full unroll pass to pay
777   // attention to it.
778   if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt ||
779       PGOOpt->Action != PGOOptions::SampleUse)
780     LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
781                                     /* OnlyWhenForced= */ !PTO.LoopUnrolling,
782                                     PTO.ForgetAllSCEVInLoopUnroll));
783 
784   for (auto &C : LoopOptimizerEndEPCallbacks)
785     C(LPM2, Level);
786 
787   // We provide the opt remark emitter pass for LICM to use. We only need to do
788   // this once as it is immutable.
789   FPM.addPass(
790       RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
791   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
792                                               EnableMSSALoopDependency,
793                                               /*UseBlockFrequencyInfo=*/true));
794   FPM.addPass(SimplifyCFGPass());
795   FPM.addPass(InstCombinePass());
796   if (EnableLoopFlatten)
797     FPM.addPass(createFunctionToLoopPassAdaptor(LoopFlattenPass()));
798   // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
799   // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
800   // *All* loop passes must preserve it, in order to be able to use it.
801   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
802                                               /*UseMemorySSA=*/false,
803                                               /*UseBlockFrequencyInfo=*/false));
804 
805   // Delete small array after loop unroll.
806   FPM.addPass(SROA());
807 
808   // Eliminate redundancies.
809   FPM.addPass(MergedLoadStoreMotionPass());
810   if (RunNewGVN)
811     FPM.addPass(NewGVNPass());
812   else
813     FPM.addPass(GVN());
814 
815   // Sparse conditional constant propagation.
816   // FIXME: It isn't clear why we do this *after* loop passes rather than
817   // before...
818   FPM.addPass(SCCPPass());
819 
820   // Delete dead bit computations (instcombine runs after to fold away the dead
821   // computations, and then ADCE will run later to exploit any new DCE
822   // opportunities that creates).
823   FPM.addPass(BDCEPass());
824 
825   // Run instcombine after redundancy and dead bit elimination to exploit
826   // opportunities opened up by them.
827   FPM.addPass(InstCombinePass());
828   invokePeepholeEPCallbacks(FPM, Level);
829 
830   // Re-consider control flow based optimizations after redundancy elimination,
831   // redo DCE, etc.
832   FPM.addPass(JumpThreadingPass());
833   FPM.addPass(CorrelatedValuePropagationPass());
834 
835   // Finally, do an expensive DCE pass to catch all the dead code exposed by
836   // the simplifications and basic cleanup after all the simplifications.
837   // TODO: Investigate if this is too expensive.
838   FPM.addPass(ADCEPass());
839 
840   // Specially optimize memory movement as it doesn't look like dataflow in SSA.
841   FPM.addPass(MemCpyOptPass());
842 
843   FPM.addPass(DSEPass());
844   FPM.addPass(createFunctionToLoopPassAdaptor(
845       LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
846       EnableMSSALoopDependency, /*UseBlockFrequencyInfo=*/true));
847 
848   FPM.addPass(CoroElidePass());
849 
850   for (auto &C : ScalarOptimizerLateEPCallbacks)
851     C(FPM, Level);
852 
853   FPM.addPass(SimplifyCFGPass(
854       SimplifyCFGOptions().hoistCommonInsts(true).sinkCommonInsts(true)));
855   FPM.addPass(InstCombinePass());
856   invokePeepholeEPCallbacks(FPM, Level);
857 
858   if (EnableCHR && Level == OptimizationLevel::O3 && PGOOpt &&
859       (PGOOpt->Action == PGOOptions::IRUse ||
860        PGOOpt->Action == PGOOptions::SampleUse))
861     FPM.addPass(ControlHeightReductionPass());
862 
863   return FPM;
864 }
865 
866 void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
867   MPM.addPass(CanonicalizeAliasesPass());
868   MPM.addPass(NameAnonGlobalPass());
869 }
870 
871 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
872                                     PassBuilder::OptimizationLevel Level,
873                                     bool RunProfileGen, bool IsCS,
874                                     std::string ProfileFile,
875                                     std::string ProfileRemappingFile) {
876   assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
877   if (!IsCS && !DisablePreInliner) {
878     InlineParams IP;
879 
880     IP.DefaultThreshold = PreInlineThreshold;
881 
882     // FIXME: The hint threshold has the same value used by the regular inliner
883     // when not optimzing for size. This should probably be lowered after
884     // performance testing.
885     // FIXME: this comment is cargo culted from the old pass manager, revisit).
886     IP.HintThreshold = Level.isOptimizingForSize() ? PreInlineThreshold : 325;
887     ModuleInlinerWrapperPass MIWP(IP);
888     CGSCCPassManager &CGPipeline = MIWP.getPM();
889 
890     FunctionPassManager FPM;
891     FPM.addPass(SROA());
892     FPM.addPass(EarlyCSEPass());    // Catch trivial redundancies.
893     FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
894     FPM.addPass(InstCombinePass()); // Combine silly sequences.
895     invokePeepholeEPCallbacks(FPM, Level);
896 
897     CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
898 
899     MPM.addPass(std::move(MIWP));
900 
901     // Delete anything that is now dead to make sure that we don't instrument
902     // dead code. Instrumentation can end up keeping dead code around and
903     // dramatically increase code size.
904     MPM.addPass(GlobalDCEPass());
905   }
906 
907   if (!RunProfileGen) {
908     assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
909     MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
910     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
911     // RequireAnalysisPass for PSI before subsequent non-module passes.
912     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
913     return;
914   }
915 
916   // Perform PGO instrumentation.
917   MPM.addPass(PGOInstrumentationGen(IsCS));
918 
919   FunctionPassManager FPM;
920   // Disable header duplication in loop rotation at -Oz.
921   FPM.addPass(createFunctionToLoopPassAdaptor(
922       LoopRotatePass(Level != OptimizationLevel::Oz), EnableMSSALoopDependency,
923       /*UseBlockFrequencyInfo=*/false));
924   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
925 
926   // Add the profile lowering pass.
927   InstrProfOptions Options;
928   if (!ProfileFile.empty())
929     Options.InstrProfileOutput = ProfileFile;
930   // Do counter promotion at Level greater than O0.
931   Options.DoCounterPromotion = true;
932   Options.UseBFIInPromotion = IsCS;
933   MPM.addPass(InstrProfiling(Options, IsCS));
934 }
935 
936 void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
937                                          bool RunProfileGen, bool IsCS,
938                                          std::string ProfileFile,
939                                          std::string ProfileRemappingFile) {
940   if (!RunProfileGen) {
941     assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
942     MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
943     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
944     // RequireAnalysisPass for PSI before subsequent non-module passes.
945     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
946     return;
947   }
948 
949   // Perform PGO instrumentation.
950   MPM.addPass(PGOInstrumentationGen(IsCS));
951   // Add the profile lowering pass.
952   InstrProfOptions Options;
953   if (!ProfileFile.empty())
954     Options.InstrProfileOutput = ProfileFile;
955   // Do not do counter promotion at O0.
956   Options.DoCounterPromotion = false;
957   Options.UseBFIInPromotion = IsCS;
958   MPM.addPass(InstrProfiling(Options, IsCS));
959 }
960 
961 static InlineParams
962 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
963   return getInlineParams(Level.getSpeedupLevel(), Level.getSizeLevel());
964 }
965 
966 ModuleInlinerWrapperPass
967 PassBuilder::buildInlinerPipeline(OptimizationLevel Level,
968                                   ThinOrFullLTOPhase Phase) {
969   InlineParams IP = getInlineParamsFromOptLevel(Level);
970   if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
971       PGOOpt->Action == PGOOptions::SampleUse)
972     IP.HotCallSiteThreshold = 0;
973 
974   if (PGOOpt)
975     IP.EnableDeferral = EnablePGOInlineDeferral;
976 
977   ModuleInlinerWrapperPass MIWP(IP, PerformMandatoryInliningsFirst,
978                                 UseInlineAdvisor, MaxDevirtIterations);
979 
980   // Require the GlobalsAA analysis for the module so we can query it within
981   // the CGSCC pipeline.
982   MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>());
983   // Invalidate AAManager so it can be recreated and pick up the newly available
984   // GlobalsAA.
985   MIWP.addModulePass(
986       createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>()));
987 
988   // Require the ProfileSummaryAnalysis for the module so we can query it within
989   // the inliner pass.
990   MIWP.addModulePass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
991 
992   // Now begin the main postorder CGSCC pipeline.
993   // FIXME: The current CGSCC pipeline has its origins in the legacy pass
994   // manager and trying to emulate its precise behavior. Much of this doesn't
995   // make a lot of sense and we should revisit the core CGSCC structure.
996   CGSCCPassManager &MainCGPipeline = MIWP.getPM();
997 
998   // Note: historically, the PruneEH pass was run first to deduce nounwind and
999   // generally clean up exception handling overhead. It isn't clear this is
1000   // valuable as the inliner doesn't currently care whether it is inlining an
1001   // invoke or a call.
1002 
1003   if (AttributorRun & AttributorRunOption::CGSCC)
1004     MainCGPipeline.addPass(AttributorCGSCCPass());
1005 
1006   // Now deduce any function attributes based in the current code.
1007   MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
1008 
1009   // When at O3 add argument promotion to the pass pipeline.
1010   // FIXME: It isn't at all clear why this should be limited to O3.
1011   if (Level == OptimizationLevel::O3)
1012     MainCGPipeline.addPass(ArgumentPromotionPass());
1013 
1014   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
1015   // there are no OpenMP runtime calls present in the module.
1016   if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
1017     MainCGPipeline.addPass(OpenMPOptCGSCCPass());
1018 
1019   for (auto &C : CGSCCOptimizerLateEPCallbacks)
1020     C(MainCGPipeline, Level);
1021 
1022   // Lastly, add the core function simplification pipeline nested inside the
1023   // CGSCC walk.
1024   MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
1025       buildFunctionSimplificationPipeline(Level, Phase)));
1026 
1027   MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
1028 
1029   return MIWP;
1030 }
1031 
1032 ModulePassManager
1033 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
1034                                                ThinOrFullLTOPhase Phase) {
1035   ModulePassManager MPM;
1036 
1037   // Place pseudo probe instrumentation as the first pass of the pipeline to
1038   // minimize the impact of optimization changes.
1039   if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1040       Phase != ThinOrFullLTOPhase::ThinLTOPostLink)
1041     MPM.addPass(SampleProfileProbePass(TM));
1042 
1043   bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
1044 
1045   // In ThinLTO mode, when flattened profile is used, all the available
1046   // profile information will be annotated in PreLink phase so there is
1047   // no need to load the profile again in PostLink.
1048   bool LoadSampleProfile =
1049       HasSampleProfile &&
1050       !(FlattenedProfileUsed && Phase == ThinOrFullLTOPhase::ThinLTOPostLink);
1051 
1052   // During the ThinLTO backend phase we perform early indirect call promotion
1053   // here, before globalopt. Otherwise imported available_externally functions
1054   // look unreferenced and are removed. If we are going to load the sample
1055   // profile then defer until later.
1056   // TODO: See if we can move later and consolidate with the location where
1057   // we perform ICP when we are loading a sample profile.
1058   // TODO: We pass HasSampleProfile (whether there was a sample profile file
1059   // passed to the compile) to the SamplePGO flag of ICP. This is used to
1060   // determine whether the new direct calls are annotated with prof metadata.
1061   // Ideally this should be determined from whether the IR is annotated with
1062   // sample profile, and not whether the a sample profile was provided on the
1063   // command line. E.g. for flattened profiles where we will not be reloading
1064   // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1065   // provide the sample profile file.
1066   if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink && !LoadSampleProfile)
1067     MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
1068 
1069   // Do basic inference of function attributes from known properties of system
1070   // libraries and other oracles.
1071   MPM.addPass(InferFunctionAttrsPass());
1072 
1073   // Create an early function pass manager to cleanup the output of the
1074   // frontend.
1075   FunctionPassManager EarlyFPM;
1076   // Lower llvm.expect to metadata before attempting transforms.
1077   // Compare/branch metadata may alter the behavior of passes like SimplifyCFG.
1078   EarlyFPM.addPass(LowerExpectIntrinsicPass());
1079   EarlyFPM.addPass(SimplifyCFGPass());
1080   EarlyFPM.addPass(SROA());
1081   EarlyFPM.addPass(EarlyCSEPass());
1082   EarlyFPM.addPass(CoroEarlyPass());
1083   if (Level == OptimizationLevel::O3)
1084     EarlyFPM.addPass(CallSiteSplittingPass());
1085 
1086   // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
1087   // to convert bitcast to direct calls so that they can be inlined during the
1088   // profile annotation prepration step.
1089   // More details about SamplePGO design can be found in:
1090   // https://research.google.com/pubs/pub45290.html
1091   // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
1092   if (LoadSampleProfile)
1093     EarlyFPM.addPass(InstCombinePass());
1094   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1095 
1096   if (LoadSampleProfile) {
1097     // Annotate sample profile right after early FPM to ensure freshness of
1098     // the debug info.
1099     MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1100                                         PGOOpt->ProfileRemappingFile, Phase));
1101     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1102     // RequireAnalysisPass for PSI before subsequent non-module passes.
1103     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
1104     // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1105     // for the profile annotation to be accurate in the LTO backend.
1106     if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink &&
1107         Phase != ThinOrFullLTOPhase::FullLTOPreLink)
1108       // We perform early indirect call promotion here, before globalopt.
1109       // This is important for the ThinLTO backend phase because otherwise
1110       // imported available_externally functions look unreferenced and are
1111       // removed.
1112       MPM.addPass(
1113           PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
1114   }
1115 
1116   // Try to perform OpenMP specific optimizations on the module. This is a
1117   // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1118   if (Level != OptimizationLevel::O0)
1119     MPM.addPass(OpenMPOptPass());
1120 
1121   if (AttributorRun & AttributorRunOption::MODULE)
1122     MPM.addPass(AttributorPass());
1123 
1124   // Lower type metadata and the type.test intrinsic in the ThinLTO
1125   // post link pipeline after ICP. This is to enable usage of the type
1126   // tests in ICP sequences.
1127   if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink)
1128     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1129 
1130   for (auto &C : PipelineEarlySimplificationEPCallbacks)
1131     C(MPM, Level);
1132 
1133   // Specialize functions with IPSCCP.
1134   if (EnableFunctionSpecialization)
1135     MPM.addPass(FunctionSpecializationPass());
1136 
1137   // Interprocedural constant propagation now that basic cleanup has occurred
1138   // and prior to optimizing globals.
1139   // FIXME: This position in the pipeline hasn't been carefully considered in
1140   // years, it should be re-analyzed.
1141   MPM.addPass(IPSCCPPass());
1142 
1143   // Attach metadata to indirect call sites indicating the set of functions
1144   // they may target at run-time. This should follow IPSCCP.
1145   MPM.addPass(CalledValuePropagationPass());
1146 
1147   // Optimize globals to try and fold them into constants.
1148   MPM.addPass(GlobalOptPass());
1149 
1150   // Promote any localized globals to SSA registers.
1151   // FIXME: Should this instead by a run of SROA?
1152   // FIXME: We should probably run instcombine and simplifycfg afterward to
1153   // delete control flows that are dead once globals have been folded to
1154   // constants.
1155   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1156 
1157   // Remove any dead arguments exposed by cleanups and constant folding
1158   // globals.
1159   MPM.addPass(DeadArgumentEliminationPass());
1160 
1161   // Create a small function pass pipeline to cleanup after all the global
1162   // optimizations.
1163   FunctionPassManager GlobalCleanupPM;
1164   GlobalCleanupPM.addPass(InstCombinePass());
1165   invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1166 
1167   GlobalCleanupPM.addPass(SimplifyCFGPass());
1168   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
1169 
1170   // Add all the requested passes for instrumentation PGO, if requested.
1171   if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
1172       (PGOOpt->Action == PGOOptions::IRInstr ||
1173        PGOOpt->Action == PGOOptions::IRUse)) {
1174     addPGOInstrPasses(MPM, Level,
1175                       /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
1176                       /* IsCS */ false, PGOOpt->ProfileFile,
1177                       PGOOpt->ProfileRemappingFile);
1178     MPM.addPass(PGOIndirectCallPromotion(false, false));
1179   }
1180   if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
1181       PGOOpt->CSAction == PGOOptions::CSIRInstr)
1182     MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
1183 
1184   // Synthesize function entry counts for non-PGO compilation.
1185   if (EnableSyntheticCounts && !PGOOpt)
1186     MPM.addPass(SyntheticCountsPropagation());
1187 
1188   MPM.addPass(buildInlinerPipeline(Level, Phase));
1189 
1190   if (EnableMemProfiler && Phase != ThinOrFullLTOPhase::ThinLTOPreLink) {
1191     MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1192     MPM.addPass(ModuleMemProfilerPass());
1193   }
1194 
1195   return MPM;
1196 }
1197 
1198 /// TODO: Should LTO cause any differences to this set of passes?
1199 void PassBuilder::addVectorPasses(OptimizationLevel Level,
1200                                   FunctionPassManager &FPM, bool IsFullLTO) {
1201   FPM.addPass(LoopVectorizePass(
1202       LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
1203 
1204   if (IsFullLTO) {
1205     // The vectorizer may have significantly shortened a loop body; unroll
1206     // again. Unroll small loops to hide loop backedge latency and saturate any
1207     // parallel execution resources of an out-of-order processor. We also then
1208     // need to clean up redundancies and loop invariant code.
1209     // FIXME: It would be really good to use a loop-integrated instruction
1210     // combiner for cleanup here so that the unrolling and LICM can be pipelined
1211     // across the loop nests.
1212     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1213     if (EnableUnrollAndJam && PTO.LoopUnrolling)
1214       FPM.addPass(createFunctionToLoopPassAdaptor(
1215           LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1216     FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1217         Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1218         PTO.ForgetAllSCEVInLoopUnroll)));
1219     FPM.addPass(WarnMissedTransformationsPass());
1220   }
1221 
1222   if (!IsFullLTO) {
1223     // Eliminate loads by forwarding stores from the previous iteration to loads
1224     // of the current iteration.
1225     FPM.addPass(LoopLoadEliminationPass());
1226   }
1227   // Cleanup after the loop optimization passes.
1228   FPM.addPass(InstCombinePass());
1229 
1230   if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1231     // At higher optimization levels, try to clean up any runtime overlap and
1232     // alignment checks inserted by the vectorizer. We want to track correlated
1233     // runtime checks for two inner loops in the same outer loop, fold any
1234     // common computations, hoist loop-invariant aspects out of any outer loop,
1235     // and unswitch the runtime checks if possible. Once hoisted, we may have
1236     // dead (or speculatable) control flows or more combining opportunities.
1237     FPM.addPass(EarlyCSEPass());
1238     FPM.addPass(CorrelatedValuePropagationPass());
1239     FPM.addPass(InstCombinePass());
1240     LoopPassManager LPM;
1241     LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
1242     LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1243                                        OptimizationLevel::O3));
1244     FPM.addPass(
1245         RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
1246     FPM.addPass(createFunctionToLoopPassAdaptor(
1247         std::move(LPM), EnableMSSALoopDependency,
1248         /*UseBlockFrequencyInfo=*/true));
1249     FPM.addPass(SimplifyCFGPass());
1250     FPM.addPass(InstCombinePass());
1251   }
1252 
1253   // Now that we've formed fast to execute loop structures, we do further
1254   // optimizations. These are run afterward as they might block doing complex
1255   // analyses and transforms such as what are needed for loop vectorization.
1256 
1257   // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1258   // GVN, loop transforms, and others have already run, so it's now better to
1259   // convert to more optimized IR using more aggressive simplify CFG options.
1260   // The extra sinking transform can create larger basic blocks, so do this
1261   // before SLP vectorization.
1262   FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1263                                   .forwardSwitchCondToPhi(true)
1264                                   .convertSwitchToLookupTable(true)
1265                                   .needCanonicalLoops(false)
1266                                   .hoistCommonInsts(true)
1267                                   .sinkCommonInsts(true)));
1268 
1269   if (IsFullLTO) {
1270     FPM.addPass(SCCPPass());
1271     FPM.addPass(InstCombinePass());
1272     FPM.addPass(BDCEPass());
1273   }
1274 
1275   // Optimize parallel scalar instruction chains into SIMD instructions.
1276   if (PTO.SLPVectorization) {
1277     FPM.addPass(SLPVectorizerPass());
1278     if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1279       FPM.addPass(EarlyCSEPass());
1280     }
1281   }
1282   // Enhance/cleanup vector code.
1283   FPM.addPass(VectorCombinePass());
1284 
1285   if (!IsFullLTO) {
1286     FPM.addPass(InstCombinePass());
1287     // Unroll small loops to hide loop backedge latency and saturate any
1288     // parallel execution resources of an out-of-order processor. We also then
1289     // need to clean up redundancies and loop invariant code.
1290     // FIXME: It would be really good to use a loop-integrated instruction
1291     // combiner for cleanup here so that the unrolling and LICM can be pipelined
1292     // across the loop nests.
1293     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1294     if (EnableUnrollAndJam && PTO.LoopUnrolling) {
1295       FPM.addPass(createFunctionToLoopPassAdaptor(
1296           LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1297     }
1298     FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1299         Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1300         PTO.ForgetAllSCEVInLoopUnroll)));
1301     FPM.addPass(WarnMissedTransformationsPass());
1302     FPM.addPass(InstCombinePass());
1303     FPM.addPass(
1304         RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
1305     FPM.addPass(createFunctionToLoopPassAdaptor(
1306         LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
1307         EnableMSSALoopDependency, /*UseBlockFrequencyInfo=*/true));
1308   }
1309 
1310   // Now that we've vectorized and unrolled loops, we may have more refined
1311   // alignment information, try to re-derive it here.
1312   FPM.addPass(AlignmentFromAssumptionsPass());
1313 
1314   if (IsFullLTO)
1315     FPM.addPass(InstCombinePass());
1316 }
1317 
1318 ModulePassManager
1319 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
1320                                              bool LTOPreLink) {
1321   ModulePassManager MPM;
1322 
1323   // Optimize globals now that the module is fully simplified.
1324   MPM.addPass(GlobalOptPass());
1325   MPM.addPass(GlobalDCEPass());
1326 
1327   // Run partial inlining pass to partially inline functions that have
1328   // large bodies.
1329   if (RunPartialInlining)
1330     MPM.addPass(PartialInlinerPass());
1331 
1332   // Remove avail extern fns and globals definitions since we aren't compiling
1333   // an object file for later LTO. For LTO we want to preserve these so they
1334   // are eligible for inlining at link-time. Note if they are unreferenced they
1335   // will be removed by GlobalDCE later, so this only impacts referenced
1336   // available externally globals. Eventually they will be suppressed during
1337   // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1338   // may make globals referenced by available external functions dead and saves
1339   // running remaining passes on the eliminated functions. These should be
1340   // preserved during prelinking for link-time inlining decisions.
1341   if (!LTOPreLink)
1342     MPM.addPass(EliminateAvailableExternallyPass());
1343 
1344   if (EnableOrderFileInstrumentation)
1345     MPM.addPass(InstrOrderFilePass());
1346 
1347   // Do RPO function attribute inference across the module to forward-propagate
1348   // attributes where applicable.
1349   // FIXME: Is this really an optimization rather than a canonicalization?
1350   MPM.addPass(ReversePostOrderFunctionAttrsPass());
1351 
1352   // Do a post inline PGO instrumentation and use pass. This is a context
1353   // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1354   // cross-module inline has not been done yet. The context sensitive
1355   // instrumentation is after all the inlines are done.
1356   if (!LTOPreLink && PGOOpt) {
1357     if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1358       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
1359                         /* IsCS */ true, PGOOpt->CSProfileGenFile,
1360                         PGOOpt->ProfileRemappingFile);
1361     else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1362       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
1363                         /* IsCS */ true, PGOOpt->ProfileFile,
1364                         PGOOpt->ProfileRemappingFile);
1365   }
1366 
1367   // Re-require GloblasAA here prior to function passes. This is particularly
1368   // useful as the above will have inlined, DCE'ed, and function-attr
1369   // propagated everything. We should at this point have a reasonably minimal
1370   // and richly annotated call graph. By computing aliasing and mod/ref
1371   // information for all local globals here, the late loop passes and notably
1372   // the vectorizer will be able to use them to help recognize vectorizable
1373   // memory operations.
1374   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
1375 
1376   FunctionPassManager OptimizePM;
1377   OptimizePM.addPass(Float2IntPass());
1378   OptimizePM.addPass(LowerConstantIntrinsicsPass());
1379 
1380   if (EnableMatrix) {
1381     OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1382     OptimizePM.addPass(EarlyCSEPass());
1383   }
1384 
1385   // FIXME: We need to run some loop optimizations to re-rotate loops after
1386   // simplifycfg and others undo their rotation.
1387 
1388   // Optimize the loop execution. These passes operate on entire loop nests
1389   // rather than on each loop in an inside-out manner, and so they are actually
1390   // function passes.
1391 
1392   for (auto &C : VectorizerStartEPCallbacks)
1393     C(OptimizePM, Level);
1394 
1395   // First rotate loops that may have been un-rotated by prior passes.
1396   // Disable header duplication at -Oz.
1397   OptimizePM.addPass(createFunctionToLoopPassAdaptor(
1398       LoopRotatePass(Level != OptimizationLevel::Oz, LTOPreLink),
1399       EnableMSSALoopDependency,
1400       /*UseBlockFrequencyInfo=*/false));
1401 
1402   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
1403   // into separate loop that would otherwise inhibit vectorization.  This is
1404   // currently only performed for loops marked with the metadata
1405   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1406   OptimizePM.addPass(LoopDistributePass());
1407 
1408   // Populates the VFABI attribute with the scalar-to-vector mappings
1409   // from the TargetLibraryInfo.
1410   OptimizePM.addPass(InjectTLIMappings());
1411 
1412   addVectorPasses(Level, OptimizePM, /* IsFullLTO */ false);
1413 
1414   // Split out cold code. Splitting is done late to avoid hiding context from
1415   // other optimizations and inadvertently regressing performance. The tradeoff
1416   // is that this has a higher code size cost than splitting early.
1417   if (EnableHotColdSplit && !LTOPreLink)
1418     MPM.addPass(HotColdSplittingPass());
1419 
1420   // Search the code for similar regions of code. If enough similar regions can
1421   // be found where extracting the regions into their own function will decrease
1422   // the size of the program, we extract the regions, a deduplicate the
1423   // structurally similar regions.
1424   if (EnableIROutliner)
1425     MPM.addPass(IROutlinerPass());
1426 
1427   // Merge functions if requested.
1428   if (PTO.MergeFunctions)
1429     MPM.addPass(MergeFunctionsPass());
1430 
1431   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1432   // canonicalization pass that enables other optimizations. As a result,
1433   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1434   // result too early.
1435   OptimizePM.addPass(LoopSinkPass());
1436 
1437   // And finally clean up LCSSA form before generating code.
1438   OptimizePM.addPass(InstSimplifyPass());
1439 
1440   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1441   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1442   // flattening of blocks.
1443   OptimizePM.addPass(DivRemPairsPass());
1444 
1445   // LoopSink (and other loop passes since the last simplifyCFG) might have
1446   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1447   OptimizePM.addPass(SimplifyCFGPass());
1448 
1449   OptimizePM.addPass(CoroCleanupPass());
1450 
1451   // Add the core optimizing pipeline.
1452   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
1453 
1454   for (auto &C : OptimizerLastEPCallbacks)
1455     C(MPM, Level);
1456 
1457   if (PTO.CallGraphProfile)
1458     MPM.addPass(CGProfilePass());
1459 
1460   // Now we need to do some global optimization transforms.
1461   // FIXME: It would seem like these should come first in the optimization
1462   // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1463   // ordering here.
1464   MPM.addPass(GlobalDCEPass());
1465   MPM.addPass(ConstantMergePass());
1466 
1467   // TODO: Relative look table converter pass caused an issue when full lto is
1468   // enabled. See https://reviews.llvm.org/D94355 for more details.
1469   // Until the issue fixed, disable this pass during pre-linking phase.
1470   if (!LTOPreLink)
1471     MPM.addPass(RelLookupTableConverterPass());
1472 
1473   return MPM;
1474 }
1475 
1476 ModulePassManager
1477 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
1478                                            bool LTOPreLink) {
1479   assert(Level != OptimizationLevel::O0 &&
1480          "Must request optimizations for the default pipeline!");
1481 
1482   ModulePassManager MPM;
1483 
1484   // Convert @llvm.global.annotations to !annotation metadata.
1485   MPM.addPass(Annotation2MetadataPass());
1486 
1487   // Force any function attributes we want the rest of the pipeline to observe.
1488   MPM.addPass(ForceFunctionAttrsPass());
1489 
1490   // Apply module pipeline start EP callback.
1491   for (auto &C : PipelineStartEPCallbacks)
1492     C(MPM, Level);
1493 
1494   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1495     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1496 
1497   // Add the core simplification pipeline.
1498   MPM.addPass(buildModuleSimplificationPipeline(
1499       Level, LTOPreLink ? ThinOrFullLTOPhase::FullLTOPreLink
1500                         : ThinOrFullLTOPhase::None));
1501 
1502   // Now add the optimization pipeline.
1503   MPM.addPass(buildModuleOptimizationPipeline(Level, LTOPreLink));
1504 
1505   if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
1506     MPM.addPass(PseudoProbeUpdatePass());
1507 
1508   // Emit annotation remarks.
1509   addAnnotationRemarksPass(MPM);
1510 
1511   if (LTOPreLink)
1512     addRequiredLTOPreLinkPasses(MPM);
1513 
1514   return MPM;
1515 }
1516 
1517 ModulePassManager
1518 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
1519   assert(Level != OptimizationLevel::O0 &&
1520          "Must request optimizations for the default pipeline!");
1521 
1522   ModulePassManager MPM;
1523 
1524   // Convert @llvm.global.annotations to !annotation metadata.
1525   MPM.addPass(Annotation2MetadataPass());
1526 
1527   // Force any function attributes we want the rest of the pipeline to observe.
1528   MPM.addPass(ForceFunctionAttrsPass());
1529 
1530   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1531     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1532 
1533   // Apply module pipeline start EP callback.
1534   for (auto &C : PipelineStartEPCallbacks)
1535     C(MPM, Level);
1536 
1537   // If we are planning to perform ThinLTO later, we don't bloat the code with
1538   // unrolling/vectorization/... now. Just simplify the module as much as we
1539   // can.
1540   MPM.addPass(buildModuleSimplificationPipeline(
1541       Level, ThinOrFullLTOPhase::ThinLTOPreLink));
1542 
1543   // Run partial inlining pass to partially inline functions that have
1544   // large bodies.
1545   // FIXME: It isn't clear whether this is really the right place to run this
1546   // in ThinLTO. Because there is another canonicalization and simplification
1547   // phase that will run after the thin link, running this here ends up with
1548   // less information than will be available later and it may grow functions in
1549   // ways that aren't beneficial.
1550   if (RunPartialInlining)
1551     MPM.addPass(PartialInlinerPass());
1552 
1553   // Reduce the size of the IR as much as possible.
1554   MPM.addPass(GlobalOptPass());
1555 
1556   // Module simplification splits coroutines, but does not fully clean up
1557   // coroutine intrinsics. To ensure ThinLTO optimization passes don't trip up
1558   // on these, we schedule the cleanup here.
1559   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1560 
1561   if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
1562     MPM.addPass(PseudoProbeUpdatePass());
1563 
1564   // Handle OptimizerLastEPCallbacks added by clang on PreLink. Actual
1565   // optimization is going to be done in PostLink stage, but clang can't
1566   // add callbacks there in case of in-process ThinLTO called by linker.
1567   for (auto &C : OptimizerLastEPCallbacks)
1568     C(MPM, Level);
1569 
1570   // Emit annotation remarks.
1571   addAnnotationRemarksPass(MPM);
1572 
1573   addRequiredLTOPreLinkPasses(MPM);
1574 
1575   return MPM;
1576 }
1577 
1578 ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1579     OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1580   ModulePassManager MPM;
1581 
1582   // Convert @llvm.global.annotations to !annotation metadata.
1583   MPM.addPass(Annotation2MetadataPass());
1584 
1585   if (ImportSummary) {
1586     // These passes import type identifier resolutions for whole-program
1587     // devirtualization and CFI. They must run early because other passes may
1588     // disturb the specific instruction patterns that these passes look for,
1589     // creating dependencies on resolutions that may not appear in the summary.
1590     //
1591     // For example, GVN may transform the pattern assume(type.test) appearing in
1592     // two basic blocks into assume(phi(type.test, type.test)), which would
1593     // transform a dependency on a WPD resolution into a dependency on a type
1594     // identifier resolution for CFI.
1595     //
1596     // Also, WPD has access to more precise information than ICP and can
1597     // devirtualize more effectively, so it should operate on the IR first.
1598     //
1599     // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1600     // metadata and intrinsics.
1601     MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1602     MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1603   }
1604 
1605   if (Level == OptimizationLevel::O0) {
1606     // Run a second time to clean up any type tests left behind by WPD for use
1607     // in ICP.
1608     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1609     // Drop available_externally and unreferenced globals. This is necessary
1610     // with ThinLTO in order to avoid leaving undefined references to dead
1611     // globals in the object file.
1612     MPM.addPass(EliminateAvailableExternallyPass());
1613     MPM.addPass(GlobalDCEPass());
1614     return MPM;
1615   }
1616 
1617   // Force any function attributes we want the rest of the pipeline to observe.
1618   MPM.addPass(ForceFunctionAttrsPass());
1619 
1620   // Add the core simplification pipeline.
1621   MPM.addPass(buildModuleSimplificationPipeline(
1622       Level, ThinOrFullLTOPhase::ThinLTOPostLink));
1623 
1624   // Now add the optimization pipeline.
1625   MPM.addPass(buildModuleOptimizationPipeline(Level));
1626 
1627   // Emit annotation remarks.
1628   addAnnotationRemarksPass(MPM);
1629 
1630   return MPM;
1631 }
1632 
1633 ModulePassManager
1634 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
1635   assert(Level != OptimizationLevel::O0 &&
1636          "Must request optimizations for the default pipeline!");
1637   // FIXME: We should use a customized pre-link pipeline!
1638   return buildPerModuleDefaultPipeline(Level,
1639                                        /* LTOPreLink */ true);
1640 }
1641 
1642 ModulePassManager
1643 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
1644                                      ModuleSummaryIndex *ExportSummary) {
1645   ModulePassManager MPM;
1646 
1647   // Convert @llvm.global.annotations to !annotation metadata.
1648   MPM.addPass(Annotation2MetadataPass());
1649 
1650   // Create a function that performs CFI checks for cross-DSO calls with targets
1651   // in the current module.
1652   MPM.addPass(CrossDSOCFIPass());
1653 
1654   if (Level == OptimizationLevel::O0) {
1655     // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1656     // metadata and intrinsics.
1657     MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1658     MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1659     // Run a second time to clean up any type tests left behind by WPD for use
1660     // in ICP.
1661     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1662 
1663     // Emit annotation remarks.
1664     addAnnotationRemarksPass(MPM);
1665 
1666     return MPM;
1667   }
1668 
1669   if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1670     // Load sample profile before running the LTO optimization pipeline.
1671     MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1672                                         PGOOpt->ProfileRemappingFile,
1673                                         ThinOrFullLTOPhase::FullLTOPostLink));
1674     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1675     // RequireAnalysisPass for PSI before subsequent non-module passes.
1676     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
1677   }
1678 
1679   // Remove unused virtual tables to improve the quality of code generated by
1680   // whole-program devirtualization and bitset lowering.
1681   MPM.addPass(GlobalDCEPass());
1682 
1683   // Force any function attributes we want the rest of the pipeline to observe.
1684   MPM.addPass(ForceFunctionAttrsPass());
1685 
1686   // Do basic inference of function attributes from known properties of system
1687   // libraries and other oracles.
1688   MPM.addPass(InferFunctionAttrsPass());
1689 
1690   if (Level.getSpeedupLevel() > 1) {
1691     FunctionPassManager EarlyFPM;
1692     EarlyFPM.addPass(CallSiteSplittingPass());
1693     MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1694 
1695     // Indirect call promotion. This should promote all the targets that are
1696     // left by the earlier promotion pass that promotes intra-module targets.
1697     // This two-step promotion is to save the compile time. For LTO, it should
1698     // produce the same result as if we only do promotion here.
1699     MPM.addPass(PGOIndirectCallPromotion(
1700         true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1701 
1702     if (EnableFunctionSpecialization)
1703       MPM.addPass(FunctionSpecializationPass());
1704     // Propagate constants at call sites into the functions they call.  This
1705     // opens opportunities for globalopt (and inlining) by substituting function
1706     // pointers passed as arguments to direct uses of functions.
1707     MPM.addPass(IPSCCPPass());
1708 
1709     // Attach metadata to indirect call sites indicating the set of functions
1710     // they may target at run-time. This should follow IPSCCP.
1711     MPM.addPass(CalledValuePropagationPass());
1712   }
1713 
1714   // Now deduce any function attributes based in the current code.
1715   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1716               PostOrderFunctionAttrsPass()));
1717 
1718   // Do RPO function attribute inference across the module to forward-propagate
1719   // attributes where applicable.
1720   // FIXME: Is this really an optimization rather than a canonicalization?
1721   MPM.addPass(ReversePostOrderFunctionAttrsPass());
1722 
1723   // Use in-range annotations on GEP indices to split globals where beneficial.
1724   MPM.addPass(GlobalSplitPass());
1725 
1726   // Run whole program optimization of virtual call when the list of callees
1727   // is fixed.
1728   MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1729 
1730   // Stop here at -O1.
1731   if (Level == OptimizationLevel::O1) {
1732     // The LowerTypeTestsPass needs to run to lower type metadata and the
1733     // type.test intrinsics. The pass does nothing if CFI is disabled.
1734     MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1735     // Run a second time to clean up any type tests left behind by WPD for use
1736     // in ICP (which is performed earlier than this in the regular LTO
1737     // pipeline).
1738     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1739 
1740     // Emit annotation remarks.
1741     addAnnotationRemarksPass(MPM);
1742 
1743     return MPM;
1744   }
1745 
1746   // Optimize globals to try and fold them into constants.
1747   MPM.addPass(GlobalOptPass());
1748 
1749   // Promote any localized globals to SSA registers.
1750   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1751 
1752   // Linking modules together can lead to duplicate global constant, only
1753   // keep one copy of each constant.
1754   MPM.addPass(ConstantMergePass());
1755 
1756   // Remove unused arguments from functions.
1757   MPM.addPass(DeadArgumentEliminationPass());
1758 
1759   // Reduce the code after globalopt and ipsccp.  Both can open up significant
1760   // simplification opportunities, and both can propagate functions through
1761   // function pointers.  When this happens, we often have to resolve varargs
1762   // calls, etc, so let instcombine do this.
1763   FunctionPassManager PeepholeFPM;
1764   if (Level == OptimizationLevel::O3)
1765     PeepholeFPM.addPass(AggressiveInstCombinePass());
1766   PeepholeFPM.addPass(InstCombinePass());
1767   invokePeepholeEPCallbacks(PeepholeFPM, Level);
1768 
1769   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
1770 
1771   // Note: historically, the PruneEH pass was run first to deduce nounwind and
1772   // generally clean up exception handling overhead. It isn't clear this is
1773   // valuable as the inliner doesn't currently care whether it is inlining an
1774   // invoke or a call.
1775   // Run the inliner now.
1776   MPM.addPass(ModuleInlinerWrapperPass(getInlineParamsFromOptLevel(Level)));
1777 
1778   // Optimize globals again after we ran the inliner.
1779   MPM.addPass(GlobalOptPass());
1780 
1781   // Garbage collect dead functions.
1782   // FIXME: Add ArgumentPromotion pass after once it's ported.
1783   MPM.addPass(GlobalDCEPass());
1784 
1785   FunctionPassManager FPM;
1786   // The IPO Passes may leave cruft around. Clean up after them.
1787   FPM.addPass(InstCombinePass());
1788   invokePeepholeEPCallbacks(FPM, Level);
1789 
1790   FPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true));
1791 
1792   // Do a post inline PGO instrumentation and use pass. This is a context
1793   // sensitive PGO pass.
1794   if (PGOOpt) {
1795     if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1796       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
1797                         /* IsCS */ true, PGOOpt->CSProfileGenFile,
1798                         PGOOpt->ProfileRemappingFile);
1799     else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1800       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
1801                         /* IsCS */ true, PGOOpt->ProfileFile,
1802                         PGOOpt->ProfileRemappingFile);
1803   }
1804 
1805   // Break up allocas
1806   FPM.addPass(SROA());
1807 
1808   // LTO provides additional opportunities for tailcall elimination due to
1809   // link-time inlining, and visibility of nocapture attribute.
1810   FPM.addPass(TailCallElimPass());
1811 
1812   // Run a few AA driver optimizations here and now to cleanup the code.
1813   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1814 
1815   MPM.addPass(
1816       createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass()));
1817 
1818   // Require the GlobalsAA analysis for the module so we can query it within
1819   // MainFPM.
1820   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
1821   // Invalidate AAManager so it can be recreated and pick up the newly available
1822   // GlobalsAA.
1823   MPM.addPass(
1824       createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>()));
1825 
1826   FunctionPassManager MainFPM;
1827   MainFPM.addPass(createFunctionToLoopPassAdaptor(
1828       LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
1829       EnableMSSALoopDependency, /*UseBlockFrequencyInfo=*/true));
1830 
1831   if (RunNewGVN)
1832     MainFPM.addPass(NewGVNPass());
1833   else
1834     MainFPM.addPass(GVN());
1835 
1836   // Remove dead memcpy()'s.
1837   MainFPM.addPass(MemCpyOptPass());
1838 
1839   // Nuke dead stores.
1840   MainFPM.addPass(DSEPass());
1841   MainFPM.addPass(MergedLoadStoreMotionPass());
1842 
1843   // More loops are countable; try to optimize them.
1844   if (EnableLoopFlatten && Level.getSpeedupLevel() > 1)
1845     MainFPM.addPass(createFunctionToLoopPassAdaptor(LoopFlattenPass()));
1846 
1847   if (EnableConstraintElimination)
1848     MainFPM.addPass(ConstraintEliminationPass());
1849 
1850   LoopPassManager LPM;
1851   LPM.addPass(IndVarSimplifyPass());
1852   LPM.addPass(LoopDeletionPass());
1853   // FIXME: Add loop interchange.
1854 
1855   // Unroll small loops and perform peeling.
1856   LPM.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
1857                                  /* OnlyWhenForced= */ !PTO.LoopUnrolling,
1858                                  PTO.ForgetAllSCEVInLoopUnroll));
1859   // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
1860   // *All* loop passes must preserve it, in order to be able to use it.
1861   MainFPM.addPass(createFunctionToLoopPassAdaptor(
1862       std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/true));
1863 
1864   MainFPM.addPass(LoopDistributePass());
1865 
1866   addVectorPasses(Level, MainFPM, /* IsFullLTO */ true);
1867 
1868   invokePeepholeEPCallbacks(MainFPM, Level);
1869   MainFPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true));
1870   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1871 
1872   // Lower type metadata and the type.test intrinsic. This pass supports
1873   // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1874   // to be run at link time if CFI is enabled. This pass does nothing if
1875   // CFI is disabled.
1876   MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1877   // Run a second time to clean up any type tests left behind by WPD for use
1878   // in ICP (which is performed earlier than this in the regular LTO pipeline).
1879   MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1880 
1881   // Enable splitting late in the FullLTO post-link pipeline. This is done in
1882   // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1883   if (EnableHotColdSplit)
1884     MPM.addPass(HotColdSplittingPass());
1885 
1886   // Add late LTO optimization passes.
1887   // Delete basic blocks, which optimization passes may have killed.
1888   MPM.addPass(createModuleToFunctionPassAdaptor(
1889       SimplifyCFGPass(SimplifyCFGOptions().hoistCommonInsts(true))));
1890 
1891   // Drop bodies of available eternally objects to improve GlobalDCE.
1892   MPM.addPass(EliminateAvailableExternallyPass());
1893 
1894   // Now that we have optimized the program, discard unreachable functions.
1895   MPM.addPass(GlobalDCEPass());
1896 
1897   if (PTO.MergeFunctions)
1898     MPM.addPass(MergeFunctionsPass());
1899 
1900   // Emit annotation remarks.
1901   addAnnotationRemarksPass(MPM);
1902 
1903   return MPM;
1904 }
1905 
1906 ModulePassManager PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level,
1907                                                       bool LTOPreLink) {
1908   assert(Level == OptimizationLevel::O0 &&
1909          "buildO0DefaultPipeline should only be used with O0");
1910 
1911   ModulePassManager MPM;
1912 
1913   if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1914                  PGOOpt->Action == PGOOptions::IRUse))
1915     addPGOInstrPassesForO0(
1916         MPM,
1917         /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1918         /* IsCS */ false, PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1919 
1920   for (auto &C : PipelineStartEPCallbacks)
1921     C(MPM, Level);
1922 
1923   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1924     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1925 
1926   for (auto &C : PipelineEarlySimplificationEPCallbacks)
1927     C(MPM, Level);
1928 
1929   // Build a minimal pipeline based on the semantics required by LLVM,
1930   // which is just that always inlining occurs. Further, disable generating
1931   // lifetime intrinsics to avoid enabling further optimizations during
1932   // code generation.
1933   MPM.addPass(AlwaysInlinerPass(
1934       /*InsertLifetimeIntrinsics=*/false));
1935 
1936   if (PTO.MergeFunctions)
1937     MPM.addPass(MergeFunctionsPass());
1938 
1939   if (EnableMatrix)
1940     MPM.addPass(
1941         createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass(true)));
1942 
1943   if (!CGSCCOptimizerLateEPCallbacks.empty()) {
1944     CGSCCPassManager CGPM;
1945     for (auto &C : CGSCCOptimizerLateEPCallbacks)
1946       C(CGPM, Level);
1947     if (!CGPM.isEmpty())
1948       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1949   }
1950   if (!LateLoopOptimizationsEPCallbacks.empty()) {
1951     LoopPassManager LPM;
1952     for (auto &C : LateLoopOptimizationsEPCallbacks)
1953       C(LPM, Level);
1954     if (!LPM.isEmpty()) {
1955       MPM.addPass(createModuleToFunctionPassAdaptor(
1956           createFunctionToLoopPassAdaptor(std::move(LPM))));
1957     }
1958   }
1959   if (!LoopOptimizerEndEPCallbacks.empty()) {
1960     LoopPassManager LPM;
1961     for (auto &C : LoopOptimizerEndEPCallbacks)
1962       C(LPM, Level);
1963     if (!LPM.isEmpty()) {
1964       MPM.addPass(createModuleToFunctionPassAdaptor(
1965           createFunctionToLoopPassAdaptor(std::move(LPM))));
1966     }
1967   }
1968   if (!ScalarOptimizerLateEPCallbacks.empty()) {
1969     FunctionPassManager FPM;
1970     for (auto &C : ScalarOptimizerLateEPCallbacks)
1971       C(FPM, Level);
1972     if (!FPM.isEmpty())
1973       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1974   }
1975   if (!VectorizerStartEPCallbacks.empty()) {
1976     FunctionPassManager FPM;
1977     for (auto &C : VectorizerStartEPCallbacks)
1978       C(FPM, Level);
1979     if (!FPM.isEmpty())
1980       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1981   }
1982 
1983   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
1984   CGSCCPassManager CGPM;
1985   CGPM.addPass(CoroSplitPass());
1986   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1987   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1988 
1989   for (auto &C : OptimizerLastEPCallbacks)
1990     C(MPM, Level);
1991 
1992   if (LTOPreLink)
1993     addRequiredLTOPreLinkPasses(MPM);
1994 
1995   return MPM;
1996 }
1997 
1998 AAManager PassBuilder::buildDefaultAAPipeline() {
1999   AAManager AA;
2000 
2001   // The order in which these are registered determines their priority when
2002   // being queried.
2003 
2004   // First we register the basic alias analysis that provides the majority of
2005   // per-function local AA logic. This is a stateless, on-demand local set of
2006   // AA techniques.
2007   AA.registerFunctionAnalysis<BasicAA>();
2008 
2009   // Next we query fast, specialized alias analyses that wrap IR-embedded
2010   // information about aliasing.
2011   AA.registerFunctionAnalysis<ScopedNoAliasAA>();
2012   AA.registerFunctionAnalysis<TypeBasedAA>();
2013 
2014   // Add support for querying global aliasing information when available.
2015   // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2016   // analysis, all that the `AAManager` can do is query for any *cached*
2017   // results from `GlobalsAA` through a readonly proxy.
2018   AA.registerModuleAnalysis<GlobalsAA>();
2019 
2020   // Add target-specific alias analyses.
2021   if (TM)
2022     TM->registerDefaultAliasAnalyses(AA);
2023 
2024   return AA;
2025 }
2026 
2027 static Optional<int> parseRepeatPassName(StringRef Name) {
2028   if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
2029     return None;
2030   int Count;
2031   if (Name.getAsInteger(0, Count) || Count <= 0)
2032     return None;
2033   return Count;
2034 }
2035 
2036 static Optional<int> parseDevirtPassName(StringRef Name) {
2037   if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
2038     return None;
2039   int Count;
2040   if (Name.getAsInteger(0, Count) || Count < 0)
2041     return None;
2042   return Count;
2043 }
2044 
2045 static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
2046   if (!Name.consume_front(PassName))
2047     return false;
2048   // normal pass name w/o parameters == default parameters
2049   if (Name.empty())
2050     return true;
2051   return Name.startswith("<") && Name.endswith(">");
2052 }
2053 
2054 namespace {
2055 
2056 /// This performs customized parsing of pass name with parameters.
2057 ///
2058 /// We do not need parametrization of passes in textual pipeline very often,
2059 /// yet on a rare occasion ability to specify parameters right there can be
2060 /// useful.
2061 ///
2062 /// \p Name - parameterized specification of a pass from a textual pipeline
2063 /// is a string in a form of :
2064 ///      PassName '<' parameter-list '>'
2065 ///
2066 /// Parameter list is being parsed by the parser callable argument, \p Parser,
2067 /// It takes a string-ref of parameters and returns either StringError or a
2068 /// parameter list in a form of a custom parameters type, all wrapped into
2069 /// Expected<> template class.
2070 ///
2071 template <typename ParametersParseCallableT>
2072 auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
2073                          StringRef PassName) -> decltype(Parser(StringRef{})) {
2074   using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
2075 
2076   StringRef Params = Name;
2077   if (!Params.consume_front(PassName)) {
2078     assert(false &&
2079            "unable to strip pass name from parametrized pass specification");
2080   }
2081   if (!Params.empty() &&
2082       (!Params.consume_front("<") || !Params.consume_back(">"))) {
2083     assert(false && "invalid format for parametrized pass name");
2084   }
2085 
2086   Expected<ParametersT> Result = Parser(Params);
2087   assert((Result || Result.template errorIsA<StringError>()) &&
2088          "Pass parameter parser can only return StringErrors.");
2089   return Result;
2090 }
2091 
2092 /// Parser of parameters for LoopUnroll pass.
2093 Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
2094   LoopUnrollOptions UnrollOpts;
2095   while (!Params.empty()) {
2096     StringRef ParamName;
2097     std::tie(ParamName, Params) = Params.split(';');
2098     int OptLevel = StringSwitch<int>(ParamName)
2099                        .Case("O0", 0)
2100                        .Case("O1", 1)
2101                        .Case("O2", 2)
2102                        .Case("O3", 3)
2103                        .Default(-1);
2104     if (OptLevel >= 0) {
2105       UnrollOpts.setOptLevel(OptLevel);
2106       continue;
2107     }
2108     if (ParamName.consume_front("full-unroll-max=")) {
2109       int Count;
2110       if (ParamName.getAsInteger(0, Count))
2111         return make_error<StringError>(
2112             formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
2113             inconvertibleErrorCode());
2114       UnrollOpts.setFullUnrollMaxCount(Count);
2115       continue;
2116     }
2117 
2118     bool Enable = !ParamName.consume_front("no-");
2119     if (ParamName == "partial") {
2120       UnrollOpts.setPartial(Enable);
2121     } else if (ParamName == "peeling") {
2122       UnrollOpts.setPeeling(Enable);
2123     } else if (ParamName == "profile-peeling") {
2124       UnrollOpts.setProfileBasedPeeling(Enable);
2125     } else if (ParamName == "runtime") {
2126       UnrollOpts.setRuntime(Enable);
2127     } else if (ParamName == "upperbound") {
2128       UnrollOpts.setUpperBound(Enable);
2129     } else {
2130       return make_error<StringError>(
2131           formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
2132           inconvertibleErrorCode());
2133     }
2134   }
2135   return UnrollOpts;
2136 }
2137 
2138 Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
2139   MemorySanitizerOptions Result;
2140   while (!Params.empty()) {
2141     StringRef ParamName;
2142     std::tie(ParamName, Params) = Params.split(';');
2143 
2144     if (ParamName == "recover") {
2145       Result.Recover = true;
2146     } else if (ParamName == "kernel") {
2147       Result.Kernel = true;
2148     } else if (ParamName.consume_front("track-origins=")) {
2149       if (ParamName.getAsInteger(0, Result.TrackOrigins))
2150         return make_error<StringError>(
2151             formatv("invalid argument to MemorySanitizer pass track-origins "
2152                     "parameter: '{0}' ",
2153                     ParamName)
2154                 .str(),
2155             inconvertibleErrorCode());
2156     } else {
2157       return make_error<StringError>(
2158           formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
2159               .str(),
2160           inconvertibleErrorCode());
2161     }
2162   }
2163   return Result;
2164 }
2165 
2166 /// Parser of parameters for SimplifyCFG pass.
2167 Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
2168   SimplifyCFGOptions Result;
2169   while (!Params.empty()) {
2170     StringRef ParamName;
2171     std::tie(ParamName, Params) = Params.split(';');
2172 
2173     bool Enable = !ParamName.consume_front("no-");
2174     if (ParamName == "forward-switch-cond") {
2175       Result.forwardSwitchCondToPhi(Enable);
2176     } else if (ParamName == "switch-to-lookup") {
2177       Result.convertSwitchToLookupTable(Enable);
2178     } else if (ParamName == "keep-loops") {
2179       Result.needCanonicalLoops(Enable);
2180     } else if (ParamName == "hoist-common-insts") {
2181       Result.hoistCommonInsts(Enable);
2182     } else if (ParamName == "sink-common-insts") {
2183       Result.sinkCommonInsts(Enable);
2184     } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
2185       APInt BonusInstThreshold;
2186       if (ParamName.getAsInteger(0, BonusInstThreshold))
2187         return make_error<StringError>(
2188             formatv("invalid argument to SimplifyCFG pass bonus-threshold "
2189                     "parameter: '{0}' ",
2190                     ParamName).str(),
2191             inconvertibleErrorCode());
2192       Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
2193     } else {
2194       return make_error<StringError>(
2195           formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
2196           inconvertibleErrorCode());
2197     }
2198   }
2199   return Result;
2200 }
2201 
2202 /// Parser of parameters for LoopVectorize pass.
2203 Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
2204   LoopVectorizeOptions Opts;
2205   while (!Params.empty()) {
2206     StringRef ParamName;
2207     std::tie(ParamName, Params) = Params.split(';');
2208 
2209     bool Enable = !ParamName.consume_front("no-");
2210     if (ParamName == "interleave-forced-only") {
2211       Opts.setInterleaveOnlyWhenForced(Enable);
2212     } else if (ParamName == "vectorize-forced-only") {
2213       Opts.setVectorizeOnlyWhenForced(Enable);
2214     } else {
2215       return make_error<StringError>(
2216           formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
2217           inconvertibleErrorCode());
2218     }
2219   }
2220   return Opts;
2221 }
2222 
2223 Expected<std::pair<bool, bool>> parseLoopUnswitchOptions(StringRef Params) {
2224   std::pair<bool, bool> Result = {false, true};
2225   while (!Params.empty()) {
2226     StringRef ParamName;
2227     std::tie(ParamName, Params) = Params.split(';');
2228 
2229     bool Enable = !ParamName.consume_front("no-");
2230     if (ParamName == "nontrivial") {
2231       Result.first = Enable;
2232     } else if (ParamName == "trivial") {
2233       Result.second = Enable;
2234     } else {
2235       return make_error<StringError>(
2236           formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
2237               .str(),
2238           inconvertibleErrorCode());
2239     }
2240   }
2241   return Result;
2242 }
2243 
2244 Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
2245   bool Result = false;
2246   while (!Params.empty()) {
2247     StringRef ParamName;
2248     std::tie(ParamName, Params) = Params.split(';');
2249 
2250     bool Enable = !ParamName.consume_front("no-");
2251     if (ParamName == "split-footer-bb") {
2252       Result = Enable;
2253     } else {
2254       return make_error<StringError>(
2255           formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
2256                   ParamName)
2257               .str(),
2258           inconvertibleErrorCode());
2259     }
2260   }
2261   return Result;
2262 }
2263 
2264 Expected<GVNOptions> parseGVNOptions(StringRef Params) {
2265   GVNOptions Result;
2266   while (!Params.empty()) {
2267     StringRef ParamName;
2268     std::tie(ParamName, Params) = Params.split(';');
2269 
2270     bool Enable = !ParamName.consume_front("no-");
2271     if (ParamName == "pre") {
2272       Result.setPRE(Enable);
2273     } else if (ParamName == "load-pre") {
2274       Result.setLoadPRE(Enable);
2275     } else if (ParamName == "split-backedge-load-pre") {
2276       Result.setLoadPRESplitBackedge(Enable);
2277     } else if (ParamName == "memdep") {
2278       Result.setMemDep(Enable);
2279     } else {
2280       return make_error<StringError>(
2281           formatv("invalid GVN pass parameter '{0}' ", ParamName).str(),
2282           inconvertibleErrorCode());
2283     }
2284   }
2285   return Result;
2286 }
2287 
2288 Expected<StackLifetime::LivenessType>
2289 parseStackLifetimeOptions(StringRef Params) {
2290   StackLifetime::LivenessType Result = StackLifetime::LivenessType::May;
2291   while (!Params.empty()) {
2292     StringRef ParamName;
2293     std::tie(ParamName, Params) = Params.split(';');
2294 
2295     if (ParamName == "may") {
2296       Result = StackLifetime::LivenessType::May;
2297     } else if (ParamName == "must") {
2298       Result = StackLifetime::LivenessType::Must;
2299     } else {
2300       return make_error<StringError>(
2301           formatv("invalid StackLifetime parameter '{0}' ", ParamName).str(),
2302           inconvertibleErrorCode());
2303     }
2304   }
2305   return Result;
2306 }
2307 
2308 } // namespace
2309 
2310 /// Tests whether a pass name starts with a valid prefix for a default pipeline
2311 /// alias.
2312 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
2313   return Name.startswith("default") || Name.startswith("thinlto") ||
2314          Name.startswith("lto");
2315 }
2316 
2317 /// Tests whether registered callbacks will accept a given pass name.
2318 ///
2319 /// When parsing a pipeline text, the type of the outermost pipeline may be
2320 /// omitted, in which case the type is automatically determined from the first
2321 /// pass name in the text. This may be a name that is handled through one of the
2322 /// callbacks. We check this through the oridinary parsing callbacks by setting
2323 /// up a dummy PassManager in order to not force the client to also handle this
2324 /// type of query.
2325 template <typename PassManagerT, typename CallbacksT>
2326 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
2327   if (!Callbacks.empty()) {
2328     PassManagerT DummyPM;
2329     for (auto &CB : Callbacks)
2330       if (CB(Name, DummyPM, {}))
2331         return true;
2332   }
2333   return false;
2334 }
2335 
2336 template <typename CallbacksT>
2337 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
2338   // Manually handle aliases for pre-configured pipeline fragments.
2339   if (startsWithDefaultPipelineAliasPrefix(Name))
2340     return DefaultAliasRegex.match(Name);
2341 
2342   // Explicitly handle pass manager names.
2343   if (Name == "module")
2344     return true;
2345   if (Name == "cgscc")
2346     return true;
2347   if (Name == "function")
2348     return true;
2349 
2350   // Explicitly handle custom-parsed pass names.
2351   if (parseRepeatPassName(Name))
2352     return true;
2353 
2354 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
2355   if (Name == NAME)                                                            \
2356     return true;
2357 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
2358   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
2359     return true;
2360 #include "PassRegistry.def"
2361 
2362   return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
2363 }
2364 
2365 template <typename CallbacksT>
2366 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
2367   // Explicitly handle pass manager names.
2368   if (Name == "cgscc")
2369     return true;
2370   if (Name == "function")
2371     return true;
2372 
2373   // Explicitly handle custom-parsed pass names.
2374   if (parseRepeatPassName(Name))
2375     return true;
2376   if (parseDevirtPassName(Name))
2377     return true;
2378 
2379 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
2380   if (Name == NAME)                                                            \
2381     return true;
2382 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
2383   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
2384     return true;
2385 #include "PassRegistry.def"
2386 
2387   return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
2388 }
2389 
2390 template <typename CallbacksT>
2391 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
2392   // Explicitly handle pass manager names.
2393   if (Name == "function")
2394     return true;
2395   if (Name == "loop" || Name == "loop-mssa")
2396     return true;
2397 
2398   // Explicitly handle custom-parsed pass names.
2399   if (parseRepeatPassName(Name))
2400     return true;
2401 
2402 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
2403   if (Name == NAME)                                                            \
2404     return true;
2405 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
2406   if (checkParametrizedPassName(Name, NAME))                                   \
2407     return true;
2408 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
2409   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
2410     return true;
2411 #include "PassRegistry.def"
2412 
2413   return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
2414 }
2415 
2416 template <typename CallbacksT>
2417 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
2418   // Explicitly handle pass manager names.
2419   if (Name == "loop" || Name == "loop-mssa")
2420     return true;
2421 
2422   // Explicitly handle custom-parsed pass names.
2423   if (parseRepeatPassName(Name))
2424     return true;
2425 
2426 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
2427   if (Name == NAME)                                                            \
2428     return true;
2429 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
2430   if (checkParametrizedPassName(Name, NAME))                                   \
2431     return true;
2432 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
2433   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
2434     return true;
2435 #include "PassRegistry.def"
2436 
2437   return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
2438 }
2439 
2440 Optional<std::vector<PassBuilder::PipelineElement>>
2441 PassBuilder::parsePipelineText(StringRef Text) {
2442   std::vector<PipelineElement> ResultPipeline;
2443 
2444   SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
2445       &ResultPipeline};
2446   for (;;) {
2447     std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
2448     size_t Pos = Text.find_first_of(",()");
2449     Pipeline.push_back({Text.substr(0, Pos), {}});
2450 
2451     // If we have a single terminating name, we're done.
2452     if (Pos == Text.npos)
2453       break;
2454 
2455     char Sep = Text[Pos];
2456     Text = Text.substr(Pos + 1);
2457     if (Sep == ',')
2458       // Just a name ending in a comma, continue.
2459       continue;
2460 
2461     if (Sep == '(') {
2462       // Push the inner pipeline onto the stack to continue processing.
2463       PipelineStack.push_back(&Pipeline.back().InnerPipeline);
2464       continue;
2465     }
2466 
2467     assert(Sep == ')' && "Bogus separator!");
2468     // When handling the close parenthesis, we greedily consume them to avoid
2469     // empty strings in the pipeline.
2470     do {
2471       // If we try to pop the outer pipeline we have unbalanced parentheses.
2472       if (PipelineStack.size() == 1)
2473         return None;
2474 
2475       PipelineStack.pop_back();
2476     } while (Text.consume_front(")"));
2477 
2478     // Check if we've finished parsing.
2479     if (Text.empty())
2480       break;
2481 
2482     // Otherwise, the end of an inner pipeline always has to be followed by
2483     // a comma, and then we can continue.
2484     if (!Text.consume_front(","))
2485       return None;
2486   }
2487 
2488   if (PipelineStack.size() > 1)
2489     // Unbalanced paretheses.
2490     return None;
2491 
2492   assert(PipelineStack.back() == &ResultPipeline &&
2493          "Wrong pipeline at the bottom of the stack!");
2494   return {std::move(ResultPipeline)};
2495 }
2496 
2497 Error PassBuilder::parseModulePass(ModulePassManager &MPM,
2498                                    const PipelineElement &E) {
2499   auto &Name = E.Name;
2500   auto &InnerPipeline = E.InnerPipeline;
2501 
2502   // First handle complex passes like the pass managers which carry pipelines.
2503   if (!InnerPipeline.empty()) {
2504     if (Name == "module") {
2505       ModulePassManager NestedMPM;
2506       if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
2507         return Err;
2508       MPM.addPass(std::move(NestedMPM));
2509       return Error::success();
2510     }
2511     if (Name == "cgscc") {
2512       CGSCCPassManager CGPM;
2513       if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline))
2514         return Err;
2515       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
2516       return Error::success();
2517     }
2518     if (Name == "function") {
2519       FunctionPassManager FPM;
2520       if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
2521         return Err;
2522       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2523       return Error::success();
2524     }
2525     if (auto Count = parseRepeatPassName(Name)) {
2526       ModulePassManager NestedMPM;
2527       if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
2528         return Err;
2529       MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
2530       return Error::success();
2531     }
2532 
2533     for (auto &C : ModulePipelineParsingCallbacks)
2534       if (C(Name, MPM, InnerPipeline))
2535         return Error::success();
2536 
2537     // Normal passes can't have pipelines.
2538     return make_error<StringError>(
2539         formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
2540         inconvertibleErrorCode());
2541     ;
2542   }
2543 
2544   // Manually handle aliases for pre-configured pipeline fragments.
2545   if (startsWithDefaultPipelineAliasPrefix(Name)) {
2546     SmallVector<StringRef, 3> Matches;
2547     if (!DefaultAliasRegex.match(Name, &Matches))
2548       return make_error<StringError>(
2549           formatv("unknown default pipeline alias '{0}'", Name).str(),
2550           inconvertibleErrorCode());
2551 
2552     assert(Matches.size() == 3 && "Must capture two matched strings!");
2553 
2554     OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
2555                               .Case("O0", OptimizationLevel::O0)
2556                               .Case("O1", OptimizationLevel::O1)
2557                               .Case("O2", OptimizationLevel::O2)
2558                               .Case("O3", OptimizationLevel::O3)
2559                               .Case("Os", OptimizationLevel::Os)
2560                               .Case("Oz", OptimizationLevel::Oz);
2561     if (L == OptimizationLevel::O0 && Matches[1] != "thinlto" &&
2562         Matches[1] != "lto") {
2563       MPM.addPass(buildO0DefaultPipeline(L, Matches[1] == "thinlto-pre-link" ||
2564                                                 Matches[1] == "lto-pre-link"));
2565       return Error::success();
2566     }
2567 
2568     // This is consistent with old pass manager invoked via opt, but
2569     // inconsistent with clang. Clang doesn't enable loop vectorization
2570     // but does enable slp vectorization at Oz.
2571     PTO.LoopVectorization =
2572         L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
2573     PTO.SLPVectorization =
2574         L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
2575 
2576     if (Matches[1] == "default") {
2577       MPM.addPass(buildPerModuleDefaultPipeline(L));
2578     } else if (Matches[1] == "thinlto-pre-link") {
2579       MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L));
2580     } else if (Matches[1] == "thinlto") {
2581       MPM.addPass(buildThinLTODefaultPipeline(L, nullptr));
2582     } else if (Matches[1] == "lto-pre-link") {
2583       MPM.addPass(buildLTOPreLinkDefaultPipeline(L));
2584     } else {
2585       assert(Matches[1] == "lto" && "Not one of the matched options!");
2586       MPM.addPass(buildLTODefaultPipeline(L, nullptr));
2587     }
2588     return Error::success();
2589   }
2590 
2591   // Finally expand the basic registered passes from the .inc file.
2592 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
2593   if (Name == NAME) {                                                          \
2594     MPM.addPass(CREATE_PASS);                                                  \
2595     return Error::success();                                                   \
2596   }
2597 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
2598   if (Name == "require<" NAME ">") {                                           \
2599     MPM.addPass(                                                               \
2600         RequireAnalysisPass<                                                   \
2601             std::remove_reference<decltype(CREATE_PASS)>::type, Module>());    \
2602     return Error::success();                                                   \
2603   }                                                                            \
2604   if (Name == "invalidate<" NAME ">") {                                        \
2605     MPM.addPass(InvalidateAnalysisPass<                                        \
2606                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
2607     return Error::success();                                                   \
2608   }
2609 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
2610   if (Name == NAME) {                                                          \
2611     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS));         \
2612     return Error::success();                                                   \
2613   }
2614 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
2615   if (Name == NAME) {                                                          \
2616     MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS));               \
2617     return Error::success();                                                   \
2618   }
2619 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
2620   if (checkParametrizedPassName(Name, NAME)) {                                 \
2621     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
2622     if (!Params)                                                               \
2623       return Params.takeError();                                               \
2624     MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
2625     return Error::success();                                                   \
2626   }
2627 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
2628   if (Name == NAME) {                                                          \
2629     MPM.addPass(createModuleToFunctionPassAdaptor(                             \
2630         createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)));          \
2631     return Error::success();                                                   \
2632   }
2633 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
2634   if (checkParametrizedPassName(Name, NAME)) {                                 \
2635     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
2636     if (!Params)                                                               \
2637       return Params.takeError();                                               \
2638     MPM.addPass(                                                               \
2639         createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(     \
2640             CREATE_PASS(Params.get()), false, false)));                        \
2641     return Error::success();                                                   \
2642   }
2643 #include "PassRegistry.def"
2644 
2645   for (auto &C : ModulePipelineParsingCallbacks)
2646     if (C(Name, MPM, InnerPipeline))
2647       return Error::success();
2648   return make_error<StringError>(
2649       formatv("unknown module pass '{0}'", Name).str(),
2650       inconvertibleErrorCode());
2651 }
2652 
2653 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
2654                                   const PipelineElement &E) {
2655   auto &Name = E.Name;
2656   auto &InnerPipeline = E.InnerPipeline;
2657 
2658   // First handle complex passes like the pass managers which carry pipelines.
2659   if (!InnerPipeline.empty()) {
2660     if (Name == "cgscc") {
2661       CGSCCPassManager NestedCGPM;
2662       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
2663         return Err;
2664       // Add the nested pass manager with the appropriate adaptor.
2665       CGPM.addPass(std::move(NestedCGPM));
2666       return Error::success();
2667     }
2668     if (Name == "function") {
2669       FunctionPassManager FPM;
2670       if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
2671         return Err;
2672       // Add the nested pass manager with the appropriate adaptor.
2673       CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
2674       return Error::success();
2675     }
2676     if (auto Count = parseRepeatPassName(Name)) {
2677       CGSCCPassManager NestedCGPM;
2678       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
2679         return Err;
2680       CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
2681       return Error::success();
2682     }
2683     if (auto MaxRepetitions = parseDevirtPassName(Name)) {
2684       CGSCCPassManager NestedCGPM;
2685       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
2686         return Err;
2687       CGPM.addPass(
2688           createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
2689       return Error::success();
2690     }
2691 
2692     for (auto &C : CGSCCPipelineParsingCallbacks)
2693       if (C(Name, CGPM, InnerPipeline))
2694         return Error::success();
2695 
2696     // Normal passes can't have pipelines.
2697     return make_error<StringError>(
2698         formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
2699         inconvertibleErrorCode());
2700   }
2701 
2702 // Now expand the basic registered passes from the .inc file.
2703 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
2704   if (Name == NAME) {                                                          \
2705     CGPM.addPass(CREATE_PASS);                                                 \
2706     return Error::success();                                                   \
2707   }
2708 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
2709   if (Name == "require<" NAME ">") {                                           \
2710     CGPM.addPass(RequireAnalysisPass<                                          \
2711                  std::remove_reference<decltype(CREATE_PASS)>::type,           \
2712                  LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,    \
2713                  CGSCCUpdateResult &>());                                      \
2714     return Error::success();                                                   \
2715   }                                                                            \
2716   if (Name == "invalidate<" NAME ">") {                                        \
2717     CGPM.addPass(InvalidateAnalysisPass<                                       \
2718                  std::remove_reference<decltype(CREATE_PASS)>::type>());       \
2719     return Error::success();                                                   \
2720   }
2721 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
2722   if (Name == NAME) {                                                          \
2723     CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS));               \
2724     return Error::success();                                                   \
2725   }
2726 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
2727   if (checkParametrizedPassName(Name, NAME)) {                                 \
2728     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
2729     if (!Params)                                                               \
2730       return Params.takeError();                                               \
2731     CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
2732     return Error::success();                                                   \
2733   }
2734 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
2735   if (Name == NAME) {                                                          \
2736     CGPM.addPass(createCGSCCToFunctionPassAdaptor(                             \
2737         createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)));          \
2738     return Error::success();                                                   \
2739   }
2740 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
2741   if (checkParametrizedPassName(Name, NAME)) {                                 \
2742     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
2743     if (!Params)                                                               \
2744       return Params.takeError();                                               \
2745     CGPM.addPass(                                                              \
2746         createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(      \
2747             CREATE_PASS(Params.get()), false, false)));                        \
2748     return Error::success();                                                   \
2749   }
2750 #include "PassRegistry.def"
2751 
2752   for (auto &C : CGSCCPipelineParsingCallbacks)
2753     if (C(Name, CGPM, InnerPipeline))
2754       return Error::success();
2755   return make_error<StringError>(
2756       formatv("unknown cgscc pass '{0}'", Name).str(),
2757       inconvertibleErrorCode());
2758 }
2759 
2760 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
2761                                      const PipelineElement &E) {
2762   auto &Name = E.Name;
2763   auto &InnerPipeline = E.InnerPipeline;
2764 
2765   // First handle complex passes like the pass managers which carry pipelines.
2766   if (!InnerPipeline.empty()) {
2767     if (Name == "function") {
2768       FunctionPassManager NestedFPM;
2769       if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
2770         return Err;
2771       // Add the nested pass manager with the appropriate adaptor.
2772       FPM.addPass(std::move(NestedFPM));
2773       return Error::success();
2774     }
2775     if (Name == "loop" || Name == "loop-mssa") {
2776       LoopPassManager LPM;
2777       if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline))
2778         return Err;
2779       // Add the nested pass manager with the appropriate adaptor.
2780       bool UseMemorySSA = (Name == "loop-mssa");
2781       bool UseBFI = llvm::any_of(
2782           InnerPipeline, [](auto Pipeline) { return Pipeline.Name == "licm"; });
2783       FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
2784                                                   UseBFI));
2785       return Error::success();
2786     }
2787     if (auto Count = parseRepeatPassName(Name)) {
2788       FunctionPassManager NestedFPM;
2789       if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
2790         return Err;
2791       FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
2792       return Error::success();
2793     }
2794 
2795     for (auto &C : FunctionPipelineParsingCallbacks)
2796       if (C(Name, FPM, InnerPipeline))
2797         return Error::success();
2798 
2799     // Normal passes can't have pipelines.
2800     return make_error<StringError>(
2801         formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
2802         inconvertibleErrorCode());
2803   }
2804 
2805 // Now expand the basic registered passes from the .inc file.
2806 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
2807   if (Name == NAME) {                                                          \
2808     FPM.addPass(CREATE_PASS);                                                  \
2809     return Error::success();                                                   \
2810   }
2811 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
2812   if (checkParametrizedPassName(Name, NAME)) {                                 \
2813     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
2814     if (!Params)                                                               \
2815       return Params.takeError();                                               \
2816     FPM.addPass(CREATE_PASS(Params.get()));                                    \
2817     return Error::success();                                                   \
2818   }
2819 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
2820   if (Name == "require<" NAME ">") {                                           \
2821     FPM.addPass(                                                               \
2822         RequireAnalysisPass<                                                   \
2823             std::remove_reference<decltype(CREATE_PASS)>::type, Function>());  \
2824     return Error::success();                                                   \
2825   }                                                                            \
2826   if (Name == "invalidate<" NAME ">") {                                        \
2827     FPM.addPass(InvalidateAnalysisPass<                                        \
2828                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
2829     return Error::success();                                                   \
2830   }
2831 // FIXME: UseMemorySSA is set to false. Maybe we could do things like:
2832 //        bool UseMemorySSA = !("canon-freeze" || "loop-predication" ||
2833 //                              "guard-widening");
2834 //        The risk is that it may become obsolete if we're not careful.
2835 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
2836   if (Name == NAME) {                                                          \
2837     FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false));   \
2838     return Error::success();                                                   \
2839   }
2840 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
2841   if (checkParametrizedPassName(Name, NAME)) {                                 \
2842     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
2843     if (!Params)                                                               \
2844       return Params.takeError();                                               \
2845     FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS(Params.get()),     \
2846                                                 false, false));                \
2847     return Error::success();                                                   \
2848   }
2849 #include "PassRegistry.def"
2850 
2851   for (auto &C : FunctionPipelineParsingCallbacks)
2852     if (C(Name, FPM, InnerPipeline))
2853       return Error::success();
2854   return make_error<StringError>(
2855       formatv("unknown function pass '{0}'", Name).str(),
2856       inconvertibleErrorCode());
2857 }
2858 
2859 Error PassBuilder::parseLoopPass(LoopPassManager &LPM,
2860                                  const PipelineElement &E) {
2861   StringRef Name = E.Name;
2862   auto &InnerPipeline = E.InnerPipeline;
2863 
2864   // First handle complex passes like the pass managers which carry pipelines.
2865   if (!InnerPipeline.empty()) {
2866     if (Name == "loop") {
2867       LoopPassManager NestedLPM;
2868       if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
2869         return Err;
2870       // Add the nested pass manager with the appropriate adaptor.
2871       LPM.addPass(std::move(NestedLPM));
2872       return Error::success();
2873     }
2874     if (auto Count = parseRepeatPassName(Name)) {
2875       LoopPassManager NestedLPM;
2876       if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
2877         return Err;
2878       LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
2879       return Error::success();
2880     }
2881 
2882     for (auto &C : LoopPipelineParsingCallbacks)
2883       if (C(Name, LPM, InnerPipeline))
2884         return Error::success();
2885 
2886     // Normal passes can't have pipelines.
2887     return make_error<StringError>(
2888         formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2889         inconvertibleErrorCode());
2890   }
2891 
2892 // Now expand the basic registered passes from the .inc file.
2893 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
2894   if (Name == NAME) {                                                          \
2895     LPM.addPass(CREATE_PASS);                                                  \
2896     return Error::success();                                                   \
2897   }
2898 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
2899   if (checkParametrizedPassName(Name, NAME)) {                                 \
2900     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
2901     if (!Params)                                                               \
2902       return Params.takeError();                                               \
2903     LPM.addPass(CREATE_PASS(Params.get()));                                    \
2904     return Error::success();                                                   \
2905   }
2906 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
2907   if (Name == "require<" NAME ">") {                                           \
2908     LPM.addPass(RequireAnalysisPass<                                           \
2909                 std::remove_reference<decltype(CREATE_PASS)>::type, Loop,      \
2910                 LoopAnalysisManager, LoopStandardAnalysisResults &,            \
2911                 LPMUpdater &>());                                              \
2912     return Error::success();                                                   \
2913   }                                                                            \
2914   if (Name == "invalidate<" NAME ">") {                                        \
2915     LPM.addPass(InvalidateAnalysisPass<                                        \
2916                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
2917     return Error::success();                                                   \
2918   }
2919 #include "PassRegistry.def"
2920 
2921   for (auto &C : LoopPipelineParsingCallbacks)
2922     if (C(Name, LPM, InnerPipeline))
2923       return Error::success();
2924   return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2925                                  inconvertibleErrorCode());
2926 }
2927 
2928 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
2929 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
2930   if (Name == NAME) {                                                          \
2931     AA.registerModuleAnalysis<                                                 \
2932         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
2933     return true;                                                               \
2934   }
2935 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
2936   if (Name == NAME) {                                                          \
2937     AA.registerFunctionAnalysis<                                               \
2938         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
2939     return true;                                                               \
2940   }
2941 #include "PassRegistry.def"
2942 
2943   for (auto &C : AAParsingCallbacks)
2944     if (C(Name, AA))
2945       return true;
2946   return false;
2947 }
2948 
2949 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
2950                                          ArrayRef<PipelineElement> Pipeline) {
2951   for (const auto &Element : Pipeline) {
2952     if (auto Err = parseLoopPass(LPM, Element))
2953       return Err;
2954   }
2955   return Error::success();
2956 }
2957 
2958 Error PassBuilder::parseFunctionPassPipeline(
2959     FunctionPassManager &FPM, ArrayRef<PipelineElement> Pipeline) {
2960   for (const auto &Element : Pipeline) {
2961     if (auto Err = parseFunctionPass(FPM, Element))
2962       return Err;
2963   }
2964   return Error::success();
2965 }
2966 
2967 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2968                                           ArrayRef<PipelineElement> Pipeline) {
2969   for (const auto &Element : Pipeline) {
2970     if (auto Err = parseCGSCCPass(CGPM, Element))
2971       return Err;
2972   }
2973   return Error::success();
2974 }
2975 
2976 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2977                                        FunctionAnalysisManager &FAM,
2978                                        CGSCCAnalysisManager &CGAM,
2979                                        ModuleAnalysisManager &MAM) {
2980   MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2981   MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
2982   CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2983   FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2984   FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2985   FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2986   LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2987 }
2988 
2989 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2990                                            ArrayRef<PipelineElement> Pipeline) {
2991   for (const auto &Element : Pipeline) {
2992     if (auto Err = parseModulePass(MPM, Element))
2993       return Err;
2994   }
2995   return Error::success();
2996 }
2997 
2998 // Primary pass pipeline description parsing routine for a \c ModulePassManager
2999 // FIXME: Should this routine accept a TargetMachine or require the caller to
3000 // pre-populate the analysis managers with target-specific stuff?
3001 Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
3002                                      StringRef PipelineText) {
3003   auto Pipeline = parsePipelineText(PipelineText);
3004   if (!Pipeline || Pipeline->empty())
3005     return make_error<StringError>(
3006         formatv("invalid pipeline '{0}'", PipelineText).str(),
3007         inconvertibleErrorCode());
3008 
3009   // If the first name isn't at the module layer, wrap the pipeline up
3010   // automatically.
3011   StringRef FirstName = Pipeline->front().Name;
3012 
3013   if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
3014     if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
3015       Pipeline = {{"cgscc", std::move(*Pipeline)}};
3016     } else if (isFunctionPassName(FirstName,
3017                                   FunctionPipelineParsingCallbacks)) {
3018       Pipeline = {{"function", std::move(*Pipeline)}};
3019     } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
3020       Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
3021     } else {
3022       for (auto &C : TopLevelPipelineParsingCallbacks)
3023         if (C(MPM, *Pipeline))
3024           return Error::success();
3025 
3026       // Unknown pass or pipeline name!
3027       auto &InnerPipeline = Pipeline->front().InnerPipeline;
3028       return make_error<StringError>(
3029           formatv("unknown {0} name '{1}'",
3030                   (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
3031               .str(),
3032           inconvertibleErrorCode());
3033     }
3034   }
3035 
3036   if (auto Err = parseModulePassPipeline(MPM, *Pipeline))
3037     return Err;
3038   return Error::success();
3039 }
3040 
3041 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
3042 Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
3043                                      StringRef PipelineText) {
3044   auto Pipeline = parsePipelineText(PipelineText);
3045   if (!Pipeline || Pipeline->empty())
3046     return make_error<StringError>(
3047         formatv("invalid pipeline '{0}'", PipelineText).str(),
3048         inconvertibleErrorCode());
3049 
3050   StringRef FirstName = Pipeline->front().Name;
3051   if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
3052     return make_error<StringError>(
3053         formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
3054                 PipelineText)
3055             .str(),
3056         inconvertibleErrorCode());
3057 
3058   if (auto Err = parseCGSCCPassPipeline(CGPM, *Pipeline))
3059     return Err;
3060   return Error::success();
3061 }
3062 
3063 // Primary pass pipeline description parsing routine for a \c
3064 // FunctionPassManager
3065 Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
3066                                      StringRef PipelineText) {
3067   auto Pipeline = parsePipelineText(PipelineText);
3068   if (!Pipeline || Pipeline->empty())
3069     return make_error<StringError>(
3070         formatv("invalid pipeline '{0}'", PipelineText).str(),
3071         inconvertibleErrorCode());
3072 
3073   StringRef FirstName = Pipeline->front().Name;
3074   if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
3075     return make_error<StringError>(
3076         formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
3077                 PipelineText)
3078             .str(),
3079         inconvertibleErrorCode());
3080 
3081   if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline))
3082     return Err;
3083   return Error::success();
3084 }
3085 
3086 // Primary pass pipeline description parsing routine for a \c LoopPassManager
3087 Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
3088                                      StringRef PipelineText) {
3089   auto Pipeline = parsePipelineText(PipelineText);
3090   if (!Pipeline || Pipeline->empty())
3091     return make_error<StringError>(
3092         formatv("invalid pipeline '{0}'", PipelineText).str(),
3093         inconvertibleErrorCode());
3094 
3095   if (auto Err = parseLoopPassPipeline(CGPM, *Pipeline))
3096     return Err;
3097 
3098   return Error::success();
3099 }
3100 
3101 Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
3102   // If the pipeline just consists of the word 'default' just replace the AA
3103   // manager with our default one.
3104   if (PipelineText == "default") {
3105     AA = buildDefaultAAPipeline();
3106     return Error::success();
3107   }
3108 
3109   while (!PipelineText.empty()) {
3110     StringRef Name;
3111     std::tie(Name, PipelineText) = PipelineText.split(',');
3112     if (!parseAAPassName(AA, Name))
3113       return make_error<StringError>(
3114           formatv("unknown alias analysis name '{0}'", Name).str(),
3115           inconvertibleErrorCode());
3116   }
3117 
3118   return Error::success();
3119 }
3120 
3121 bool PassBuilder::isAAPassName(StringRef PassName) {
3122 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
3123   if (PassName == NAME)                                                        \
3124     return true;
3125 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
3126   if (PassName == NAME)                                                        \
3127     return true;
3128 #include "PassRegistry.def"
3129   return false;
3130 }
3131 
3132 bool PassBuilder::isAnalysisPassName(StringRef PassName) {
3133 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
3134   if (PassName == NAME)                                                        \
3135     return true;
3136 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
3137   if (PassName == NAME)                                                        \
3138     return true;
3139 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
3140   if (PassName == NAME)                                                        \
3141     return true;
3142 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
3143   if (PassName == NAME)                                                        \
3144     return true;
3145 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
3146   if (PassName == NAME)                                                        \
3147     return true;
3148 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
3149   if (PassName == NAME)                                                        \
3150     return true;
3151 #include "PassRegistry.def"
3152   return false;
3153 }
3154 
3155 static void printPassName(StringRef PassName, raw_ostream &OS) {
3156   OS << "  " << PassName << "\n";
3157 }
3158 static void printPassName(StringRef PassName, StringRef Params,
3159                           raw_ostream &OS) {
3160   OS << "  " << PassName << "<" << Params << ">\n";
3161 }
3162 
3163 void PassBuilder::printPassNames(raw_ostream &OS) {
3164   // TODO: print pass descriptions when they are available
3165 
3166   OS << "Module passes:\n";
3167 #define MODULE_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
3168 #include "PassRegistry.def"
3169 
3170   OS << "Module analyses:\n";
3171 #define MODULE_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
3172 #include "PassRegistry.def"
3173 
3174   OS << "Module alias analyses:\n";
3175 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
3176 #include "PassRegistry.def"
3177 
3178   OS << "CGSCC passes:\n";
3179 #define CGSCC_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
3180 #include "PassRegistry.def"
3181 
3182   OS << "CGSCC analyses:\n";
3183 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
3184 #include "PassRegistry.def"
3185 
3186   OS << "Function passes:\n";
3187 #define FUNCTION_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
3188 #include "PassRegistry.def"
3189 
3190   OS << "Function passes with params:\n";
3191 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
3192   printPassName(NAME, PARAMS, OS);
3193 #include "PassRegistry.def"
3194 
3195   OS << "Function analyses:\n";
3196 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
3197 #include "PassRegistry.def"
3198 
3199   OS << "Function alias analyses:\n";
3200 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
3201 #include "PassRegistry.def"
3202 
3203   OS << "Loop passes:\n";
3204 #define LOOP_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
3205 #include "PassRegistry.def"
3206 
3207   OS << "Loop passes with params:\n";
3208 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
3209   printPassName(NAME, PARAMS, OS);
3210 #include "PassRegistry.def"
3211 
3212   OS << "Loop analyses:\n";
3213 #define LOOP_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
3214 #include "PassRegistry.def"
3215 }
3216 
3217 void PassBuilder::registerParseTopLevelPipelineCallback(
3218     const std::function<bool(ModulePassManager &, ArrayRef<PipelineElement>)>
3219         &C) {
3220   TopLevelPipelineParsingCallbacks.push_back(C);
3221 }
3222