xref: /freebsd/contrib/llvm-project/llvm/lib/Passes/PassBuilder.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===- Parsing and selection 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/CFGSCCPrinter.h"
27 #include "llvm/Analysis/CGSCCPassManager.h"
28 #include "llvm/Analysis/CallGraph.h"
29 #include "llvm/Analysis/CallPrinter.h"
30 #include "llvm/Analysis/CostModel.h"
31 #include "llvm/Analysis/CycleAnalysis.h"
32 #include "llvm/Analysis/DDG.h"
33 #include "llvm/Analysis/DDGPrinter.h"
34 #include "llvm/Analysis/Delinearization.h"
35 #include "llvm/Analysis/DemandedBits.h"
36 #include "llvm/Analysis/DependenceAnalysis.h"
37 #include "llvm/Analysis/DomPrinter.h"
38 #include "llvm/Analysis/DominanceFrontier.h"
39 #include "llvm/Analysis/FunctionPropertiesAnalysis.h"
40 #include "llvm/Analysis/GlobalsModRef.h"
41 #include "llvm/Analysis/IRSimilarityIdentifier.h"
42 #include "llvm/Analysis/IVUsers.h"
43 #include "llvm/Analysis/InlineAdvisor.h"
44 #include "llvm/Analysis/InlineSizeEstimatorAnalysis.h"
45 #include "llvm/Analysis/InstCount.h"
46 #include "llvm/Analysis/LazyCallGraph.h"
47 #include "llvm/Analysis/LazyValueInfo.h"
48 #include "llvm/Analysis/Lint.h"
49 #include "llvm/Analysis/LoopAccessAnalysis.h"
50 #include "llvm/Analysis/LoopCacheAnalysis.h"
51 #include "llvm/Analysis/LoopInfo.h"
52 #include "llvm/Analysis/LoopNestAnalysis.h"
53 #include "llvm/Analysis/MemDerefPrinter.h"
54 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
55 #include "llvm/Analysis/MemorySSA.h"
56 #include "llvm/Analysis/ModuleDebugInfoPrinter.h"
57 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
58 #include "llvm/Analysis/MustExecute.h"
59 #include "llvm/Analysis/ObjCARCAliasAnalysis.h"
60 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
61 #include "llvm/Analysis/PhiValues.h"
62 #include "llvm/Analysis/PostDominators.h"
63 #include "llvm/Analysis/ProfileSummaryInfo.h"
64 #include "llvm/Analysis/RegionInfo.h"
65 #include "llvm/Analysis/ScalarEvolution.h"
66 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
67 #include "llvm/Analysis/ScopedNoAliasAA.h"
68 #include "llvm/Analysis/StackLifetime.h"
69 #include "llvm/Analysis/StackSafetyAnalysis.h"
70 #include "llvm/Analysis/StructuralHash.h"
71 #include "llvm/Analysis/TargetLibraryInfo.h"
72 #include "llvm/Analysis/TargetTransformInfo.h"
73 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
74 #include "llvm/Analysis/UniformityAnalysis.h"
75 #include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
76 #include "llvm/CodeGen/CallBrPrepare.h"
77 #include "llvm/CodeGen/CodeGenPrepare.h"
78 #include "llvm/CodeGen/DwarfEHPrepare.h"
79 #include "llvm/CodeGen/ExpandLargeDivRem.h"
80 #include "llvm/CodeGen/ExpandLargeFpConvert.h"
81 #include "llvm/CodeGen/ExpandMemCmp.h"
82 #include "llvm/CodeGen/GCMetadata.h"
83 #include "llvm/CodeGen/HardwareLoops.h"
84 #include "llvm/CodeGen/IndirectBrExpand.h"
85 #include "llvm/CodeGen/InterleavedAccess.h"
86 #include "llvm/CodeGen/InterleavedLoadCombine.h"
87 #include "llvm/CodeGen/JMCInstrumenter.h"
88 #include "llvm/CodeGen/LowerEmuTLS.h"
89 #include "llvm/CodeGen/SafeStack.h"
90 #include "llvm/CodeGen/SelectOptimize.h"
91 #include "llvm/CodeGen/ShadowStackGCLowering.h"
92 #include "llvm/CodeGen/SjLjEHPrepare.h"
93 #include "llvm/CodeGen/StackProtector.h"
94 #include "llvm/CodeGen/TypePromotion.h"
95 #include "llvm/CodeGen/WasmEHPrepare.h"
96 #include "llvm/CodeGen/WinEHPrepare.h"
97 #include "llvm/IR/DebugInfo.h"
98 #include "llvm/IR/Dominators.h"
99 #include "llvm/IR/PassManager.h"
100 #include "llvm/IR/PrintPasses.h"
101 #include "llvm/IR/SafepointIRVerifier.h"
102 #include "llvm/IR/Verifier.h"
103 #include "llvm/IRPrinter/IRPrintingPasses.h"
104 #include "llvm/Passes/OptimizationLevel.h"
105 #include "llvm/Support/CommandLine.h"
106 #include "llvm/Support/Debug.h"
107 #include "llvm/Support/ErrorHandling.h"
108 #include "llvm/Support/FormatVariadic.h"
109 #include "llvm/Support/Regex.h"
110 #include "llvm/Target/TargetMachine.h"
111 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
112 #include "llvm/Transforms/CFGuard.h"
113 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
114 #include "llvm/Transforms/Coroutines/CoroConditionalWrapper.h"
115 #include "llvm/Transforms/Coroutines/CoroEarly.h"
116 #include "llvm/Transforms/Coroutines/CoroElide.h"
117 #include "llvm/Transforms/Coroutines/CoroSplit.h"
118 #include "llvm/Transforms/HipStdPar/HipStdPar.h"
119 #include "llvm/Transforms/IPO/AlwaysInliner.h"
120 #include "llvm/Transforms/IPO/Annotation2Metadata.h"
121 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
122 #include "llvm/Transforms/IPO/Attributor.h"
123 #include "llvm/Transforms/IPO/BlockExtractor.h"
124 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
125 #include "llvm/Transforms/IPO/ConstantMerge.h"
126 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
127 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
128 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
129 #include "llvm/Transforms/IPO/EmbedBitcodePass.h"
130 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
131 #include "llvm/Transforms/IPO/FunctionAttrs.h"
132 #include "llvm/Transforms/IPO/FunctionImport.h"
133 #include "llvm/Transforms/IPO/GlobalDCE.h"
134 #include "llvm/Transforms/IPO/GlobalOpt.h"
135 #include "llvm/Transforms/IPO/GlobalSplit.h"
136 #include "llvm/Transforms/IPO/HotColdSplitting.h"
137 #include "llvm/Transforms/IPO/IROutliner.h"
138 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
139 #include "llvm/Transforms/IPO/Inliner.h"
140 #include "llvm/Transforms/IPO/Internalize.h"
141 #include "llvm/Transforms/IPO/LoopExtractor.h"
142 #include "llvm/Transforms/IPO/LowerTypeTests.h"
143 #include "llvm/Transforms/IPO/MemProfContextDisambiguation.h"
144 #include "llvm/Transforms/IPO/MergeFunctions.h"
145 #include "llvm/Transforms/IPO/ModuleInliner.h"
146 #include "llvm/Transforms/IPO/OpenMPOpt.h"
147 #include "llvm/Transforms/IPO/PartialInlining.h"
148 #include "llvm/Transforms/IPO/SCCP.h"
149 #include "llvm/Transforms/IPO/SampleProfile.h"
150 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
151 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
152 #include "llvm/Transforms/IPO/StripSymbols.h"
153 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
154 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
155 #include "llvm/Transforms/InstCombine/InstCombine.h"
156 #include "llvm/Transforms/Instrumentation.h"
157 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
158 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
159 #include "llvm/Transforms/Instrumentation/CGProfile.h"
160 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
161 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
162 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
163 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
164 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
165 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
166 #include "llvm/Transforms/Instrumentation/KCFI.h"
167 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
168 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
169 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
170 #include "llvm/Transforms/Instrumentation/PoisonChecking.h"
171 #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
172 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
173 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
174 #include "llvm/Transforms/ObjCARC.h"
175 #include "llvm/Transforms/Scalar/ADCE.h"
176 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
177 #include "llvm/Transforms/Scalar/AnnotationRemarks.h"
178 #include "llvm/Transforms/Scalar/BDCE.h"
179 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
180 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
181 #include "llvm/Transforms/Scalar/ConstraintElimination.h"
182 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
183 #include "llvm/Transforms/Scalar/DCE.h"
184 #include "llvm/Transforms/Scalar/DFAJumpThreading.h"
185 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
186 #include "llvm/Transforms/Scalar/DivRemPairs.h"
187 #include "llvm/Transforms/Scalar/EarlyCSE.h"
188 #include "llvm/Transforms/Scalar/FlattenCFG.h"
189 #include "llvm/Transforms/Scalar/Float2Int.h"
190 #include "llvm/Transforms/Scalar/GVN.h"
191 #include "llvm/Transforms/Scalar/GuardWidening.h"
192 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
193 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
194 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
195 #include "llvm/Transforms/Scalar/InferAddressSpaces.h"
196 #include "llvm/Transforms/Scalar/InferAlignment.h"
197 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
198 #include "llvm/Transforms/Scalar/JumpThreading.h"
199 #include "llvm/Transforms/Scalar/LICM.h"
200 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
201 #include "llvm/Transforms/Scalar/LoopBoundSplit.h"
202 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
203 #include "llvm/Transforms/Scalar/LoopDeletion.h"
204 #include "llvm/Transforms/Scalar/LoopDistribute.h"
205 #include "llvm/Transforms/Scalar/LoopFlatten.h"
206 #include "llvm/Transforms/Scalar/LoopFuse.h"
207 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
208 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
209 #include "llvm/Transforms/Scalar/LoopInterchange.h"
210 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
211 #include "llvm/Transforms/Scalar/LoopPassManager.h"
212 #include "llvm/Transforms/Scalar/LoopPredication.h"
213 #include "llvm/Transforms/Scalar/LoopReroll.h"
214 #include "llvm/Transforms/Scalar/LoopRotation.h"
215 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
216 #include "llvm/Transforms/Scalar/LoopSink.h"
217 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
218 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
219 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
220 #include "llvm/Transforms/Scalar/LoopVersioningLICM.h"
221 #include "llvm/Transforms/Scalar/LowerAtomicPass.h"
222 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
223 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
224 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
225 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
226 #include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
227 #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
228 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
229 #include "llvm/Transforms/Scalar/MergeICmps.h"
230 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
231 #include "llvm/Transforms/Scalar/NaryReassociate.h"
232 #include "llvm/Transforms/Scalar/NewGVN.h"
233 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
234 #include "llvm/Transforms/Scalar/PlaceSafepoints.h"
235 #include "llvm/Transforms/Scalar/Reassociate.h"
236 #include "llvm/Transforms/Scalar/Reg2Mem.h"
237 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
238 #include "llvm/Transforms/Scalar/SCCP.h"
239 #include "llvm/Transforms/Scalar/SROA.h"
240 #include "llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h"
241 #include "llvm/Transforms/Scalar/Scalarizer.h"
242 #include "llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h"
243 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
244 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
245 #include "llvm/Transforms/Scalar/Sink.h"
246 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
247 #include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h"
248 #include "llvm/Transforms/Scalar/StructurizeCFG.h"
249 #include "llvm/Transforms/Scalar/TLSVariableHoist.h"
250 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
251 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
252 #include "llvm/Transforms/Utils/AddDiscriminators.h"
253 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
254 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
255 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
256 #include "llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h"
257 #include "llvm/Transforms/Utils/CountVisits.h"
258 #include "llvm/Transforms/Utils/DXILUpgrade.h"
259 #include "llvm/Transforms/Utils/Debugify.h"
260 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
261 #include "llvm/Transforms/Utils/FixIrreducible.h"
262 #include "llvm/Transforms/Utils/HelloWorld.h"
263 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
264 #include "llvm/Transforms/Utils/InstructionNamer.h"
265 #include "llvm/Transforms/Utils/LCSSA.h"
266 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
267 #include "llvm/Transforms/Utils/LoopSimplify.h"
268 #include "llvm/Transforms/Utils/LoopVersioning.h"
269 #include "llvm/Transforms/Utils/LowerGlobalDtors.h"
270 #include "llvm/Transforms/Utils/LowerIFunc.h"
271 #include "llvm/Transforms/Utils/LowerInvoke.h"
272 #include "llvm/Transforms/Utils/LowerSwitch.h"
273 #include "llvm/Transforms/Utils/Mem2Reg.h"
274 #include "llvm/Transforms/Utils/MetaRenamer.h"
275 #include "llvm/Transforms/Utils/MoveAutoInit.h"
276 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
277 #include "llvm/Transforms/Utils/PredicateInfo.h"
278 #include "llvm/Transforms/Utils/RelLookupTableConverter.h"
279 #include "llvm/Transforms/Utils/StripGCRelocates.h"
280 #include "llvm/Transforms/Utils/StripNonLineTableDebugInfo.h"
281 #include "llvm/Transforms/Utils/SymbolRewriter.h"
282 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
283 #include "llvm/Transforms/Utils/UnifyLoopExits.h"
284 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
285 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
286 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
287 #include "llvm/Transforms/Vectorize/VectorCombine.h"
288 #include <optional>
289 
290 using namespace llvm;
291 
292 static const Regex DefaultAliasRegex(
293     "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
294 
295 namespace llvm {
296 cl::opt<bool> PrintPipelinePasses(
297     "print-pipeline-passes",
298     cl::desc("Print a '-passes' compatible string describing the pipeline "
299              "(best-effort only)."));
300 } // namespace llvm
301 
302 namespace {
303 
304 // The following passes/analyses have custom names, otherwise their name will
305 // include `(anonymous namespace)`. These are special since they are only for
306 // testing purposes and don't live in a header file.
307 
308 /// No-op module pass which does nothing.
309 struct NoOpModulePass : PassInfoMixin<NoOpModulePass> {
310   PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
311     return PreservedAnalyses::all();
312   }
313 
314   static StringRef name() { return "NoOpModulePass"; }
315 };
316 
317 /// No-op module analysis.
318 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
319   friend AnalysisInfoMixin<NoOpModuleAnalysis>;
320   static AnalysisKey Key;
321 
322 public:
323   struct Result {};
324   Result run(Module &, ModuleAnalysisManager &) { return Result(); }
325   static StringRef name() { return "NoOpModuleAnalysis"; }
326 };
327 
328 /// No-op CGSCC pass which does nothing.
329 struct NoOpCGSCCPass : PassInfoMixin<NoOpCGSCCPass> {
330   PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
331                         LazyCallGraph &, CGSCCUpdateResult &UR) {
332     return PreservedAnalyses::all();
333   }
334   static StringRef name() { return "NoOpCGSCCPass"; }
335 };
336 
337 /// No-op CGSCC analysis.
338 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
339   friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
340   static AnalysisKey Key;
341 
342 public:
343   struct Result {};
344   Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
345     return Result();
346   }
347   static StringRef name() { return "NoOpCGSCCAnalysis"; }
348 };
349 
350 /// No-op function pass which does nothing.
351 struct NoOpFunctionPass : PassInfoMixin<NoOpFunctionPass> {
352   PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
353     return PreservedAnalyses::all();
354   }
355   static StringRef name() { return "NoOpFunctionPass"; }
356 };
357 
358 /// No-op function analysis.
359 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
360   friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
361   static AnalysisKey Key;
362 
363 public:
364   struct Result {};
365   Result run(Function &, FunctionAnalysisManager &) { return Result(); }
366   static StringRef name() { return "NoOpFunctionAnalysis"; }
367 };
368 
369 /// No-op loop nest pass which does nothing.
370 struct NoOpLoopNestPass : PassInfoMixin<NoOpLoopNestPass> {
371   PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &,
372                         LoopStandardAnalysisResults &, LPMUpdater &) {
373     return PreservedAnalyses::all();
374   }
375   static StringRef name() { return "NoOpLoopNestPass"; }
376 };
377 
378 /// No-op loop pass which does nothing.
379 struct NoOpLoopPass : PassInfoMixin<NoOpLoopPass> {
380   PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
381                         LoopStandardAnalysisResults &, LPMUpdater &) {
382     return PreservedAnalyses::all();
383   }
384   static StringRef name() { return "NoOpLoopPass"; }
385 };
386 
387 /// No-op loop analysis.
388 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
389   friend AnalysisInfoMixin<NoOpLoopAnalysis>;
390   static AnalysisKey Key;
391 
392 public:
393   struct Result {};
394   Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
395     return Result();
396   }
397   static StringRef name() { return "NoOpLoopAnalysis"; }
398 };
399 
400 AnalysisKey NoOpModuleAnalysis::Key;
401 AnalysisKey NoOpCGSCCAnalysis::Key;
402 AnalysisKey NoOpFunctionAnalysis::Key;
403 AnalysisKey NoOpLoopAnalysis::Key;
404 
405 /// Whether or not we should populate a PassInstrumentationCallbacks's class to
406 /// pass name map.
407 ///
408 /// This is for optimization purposes so we don't populate it if we never use
409 /// it. This should be updated if new pass instrumentation wants to use the map.
410 /// We currently only use this for --print-before/after.
411 bool shouldPopulateClassToPassNames() {
412   return PrintPipelinePasses || !printBeforePasses().empty() ||
413          !printAfterPasses().empty() || !isFilterPassesEmpty();
414 }
415 
416 // A pass for testing -print-on-crash.
417 // DO NOT USE THIS EXCEPT FOR TESTING!
418 class TriggerCrashPass : public PassInfoMixin<TriggerCrashPass> {
419 public:
420   PreservedAnalyses run(Module &, ModuleAnalysisManager &) {
421     abort();
422     return PreservedAnalyses::all();
423   }
424   static StringRef name() { return "TriggerCrashPass"; }
425 };
426 
427 // A pass for testing message reporting of -verify-each failures.
428 // DO NOT USE THIS EXCEPT FOR TESTING!
429 class TriggerVerifierErrorPass
430     : public PassInfoMixin<TriggerVerifierErrorPass> {
431 public:
432   PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
433     // Intentionally break the Module by creating an alias without setting the
434     // aliasee.
435     auto *PtrTy = llvm::PointerType::getUnqual(M.getContext());
436     GlobalAlias::create(PtrTy, PtrTy->getAddressSpace(),
437                         GlobalValue::LinkageTypes::InternalLinkage,
438                         "__bad_alias", nullptr, &M);
439     return PreservedAnalyses::none();
440   }
441 
442   PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
443     // Intentionally break the Function by inserting a terminator
444     // instruction in the middle of a basic block.
445     BasicBlock &BB = F.getEntryBlock();
446     new UnreachableInst(F.getContext(), BB.getTerminator());
447     return PreservedAnalyses::none();
448   }
449 
450   static StringRef name() { return "TriggerVerifierErrorPass"; }
451 };
452 
453 } // namespace
454 
455 PassBuilder::PassBuilder(TargetMachine *TM, PipelineTuningOptions PTO,
456                          std::optional<PGOOptions> PGOOpt,
457                          PassInstrumentationCallbacks *PIC)
458     : TM(TM), PTO(PTO), PGOOpt(PGOOpt), PIC(PIC) {
459   bool ShouldPopulateClassToPassNames = PIC && shouldPopulateClassToPassNames();
460   if (TM)
461     TM->registerPassBuilderCallbacks(*this, ShouldPopulateClassToPassNames);
462   if (ShouldPopulateClassToPassNames) {
463 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
464   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
465 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)      \
466   PIC->addClassToPassName(CLASS, NAME);
467 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
468   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
469 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
470   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
471 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
472   PIC->addClassToPassName(CLASS, NAME);
473 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
474   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
475 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
476   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
477 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
478   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
479 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
480   PIC->addClassToPassName(CLASS, NAME);
481 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
482   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
483 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
484   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
485 #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)       \
486   PIC->addClassToPassName(CLASS, NAME);
487 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
488   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
489 #include "PassRegistry.def"
490   }
491 }
492 
493 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
494 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
495   MAM.registerPass([&] { return CREATE_PASS; });
496 #include "PassRegistry.def"
497 
498   for (auto &C : ModuleAnalysisRegistrationCallbacks)
499     C(MAM);
500 }
501 
502 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
503 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
504   CGAM.registerPass([&] { return CREATE_PASS; });
505 #include "PassRegistry.def"
506 
507   for (auto &C : CGSCCAnalysisRegistrationCallbacks)
508     C(CGAM);
509 }
510 
511 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
512   // We almost always want the default alias analysis pipeline.
513   // If a user wants a different one, they can register their own before calling
514   // registerFunctionAnalyses().
515   FAM.registerPass([&] { return buildDefaultAAPipeline(); });
516 
517 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
518   FAM.registerPass([&] { return CREATE_PASS; });
519 #include "PassRegistry.def"
520 
521   for (auto &C : FunctionAnalysisRegistrationCallbacks)
522     C(FAM);
523 }
524 
525 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
526 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
527   LAM.registerPass([&] { return CREATE_PASS; });
528 #include "PassRegistry.def"
529 
530   for (auto &C : LoopAnalysisRegistrationCallbacks)
531     C(LAM);
532 }
533 
534 static std::optional<int> parseRepeatPassName(StringRef Name) {
535   if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
536     return std::nullopt;
537   int Count;
538   if (Name.getAsInteger(0, Count) || Count <= 0)
539     return std::nullopt;
540   return Count;
541 }
542 
543 static std::optional<std::pair<bool, bool>>
544 parseFunctionPipelineName(StringRef Name) {
545   std::pair<bool, bool> Params;
546   if (!Name.consume_front("function"))
547     return std::nullopt;
548   if (Name.empty())
549     return Params;
550   if (!Name.consume_front("<") || !Name.consume_back(">"))
551     return std::nullopt;
552   while (!Name.empty()) {
553     auto [Front, Back] = Name.split(';');
554     Name = Back;
555     if (Front == "eager-inv")
556       Params.first = true;
557     else if (Front == "no-rerun")
558       Params.second = true;
559     else
560       return std::nullopt;
561   }
562   return Params;
563 }
564 
565 static std::optional<int> parseDevirtPassName(StringRef Name) {
566   if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
567     return std::nullopt;
568   int Count;
569   if (Name.getAsInteger(0, Count) || Count < 0)
570     return std::nullopt;
571   return Count;
572 }
573 
574 static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
575   if (!Name.consume_front(PassName))
576     return false;
577   // normal pass name w/o parameters == default parameters
578   if (Name.empty())
579     return true;
580   return Name.starts_with("<") && Name.ends_with(">");
581 }
582 
583 static std::optional<OptimizationLevel> parseOptLevel(StringRef S) {
584   return StringSwitch<std::optional<OptimizationLevel>>(S)
585       .Case("O0", OptimizationLevel::O0)
586       .Case("O1", OptimizationLevel::O1)
587       .Case("O2", OptimizationLevel::O2)
588       .Case("O3", OptimizationLevel::O3)
589       .Case("Os", OptimizationLevel::Os)
590       .Case("Oz", OptimizationLevel::Oz)
591       .Default(std::nullopt);
592 }
593 
594 namespace {
595 
596 /// This performs customized parsing of pass name with parameters.
597 ///
598 /// We do not need parametrization of passes in textual pipeline very often,
599 /// yet on a rare occasion ability to specify parameters right there can be
600 /// useful.
601 ///
602 /// \p Name - parameterized specification of a pass from a textual pipeline
603 /// is a string in a form of :
604 ///      PassName '<' parameter-list '>'
605 ///
606 /// Parameter list is being parsed by the parser callable argument, \p Parser,
607 /// It takes a string-ref of parameters and returns either StringError or a
608 /// parameter list in a form of a custom parameters type, all wrapped into
609 /// Expected<> template class.
610 ///
611 template <typename ParametersParseCallableT>
612 auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
613                          StringRef PassName) -> decltype(Parser(StringRef{})) {
614   using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
615 
616   StringRef Params = Name;
617   if (!Params.consume_front(PassName)) {
618     assert(false &&
619            "unable to strip pass name from parametrized pass specification");
620   }
621   if (!Params.empty() &&
622       (!Params.consume_front("<") || !Params.consume_back(">"))) {
623     assert(false && "invalid format for parametrized pass name");
624   }
625 
626   Expected<ParametersT> Result = Parser(Params);
627   assert((Result || Result.template errorIsA<StringError>()) &&
628          "Pass parameter parser can only return StringErrors.");
629   return Result;
630 }
631 
632 /// Parser of parameters for HardwareLoops  pass.
633 Expected<HardwareLoopOptions> parseHardwareLoopOptions(StringRef Params) {
634   HardwareLoopOptions HardwareLoopOpts;
635 
636   while (!Params.empty()) {
637     StringRef ParamName;
638     std::tie(ParamName, Params) = Params.split(';');
639     if (ParamName.consume_front("hardware-loop-decrement=")) {
640       int Count;
641       if (ParamName.getAsInteger(0, Count))
642         return make_error<StringError>(
643             formatv("invalid HardwareLoopPass parameter '{0}' ", ParamName).str(),
644             inconvertibleErrorCode());
645       HardwareLoopOpts.setDecrement(Count);
646       continue;
647     }
648     if (ParamName.consume_front("hardware-loop-counter-bitwidth=")) {
649       int Count;
650       if (ParamName.getAsInteger(0, Count))
651         return make_error<StringError>(
652             formatv("invalid HardwareLoopPass parameter '{0}' ", ParamName).str(),
653             inconvertibleErrorCode());
654       HardwareLoopOpts.setCounterBitwidth(Count);
655       continue;
656     }
657     if (ParamName == "force-hardware-loops") {
658       HardwareLoopOpts.setForce(true);
659     } else if (ParamName == "force-hardware-loop-phi") {
660       HardwareLoopOpts.setForcePhi(true);
661     } else if (ParamName == "force-nested-hardware-loop") {
662       HardwareLoopOpts.setForceNested(true);
663     } else if (ParamName == "force-hardware-loop-guard") {
664       HardwareLoopOpts.setForceGuard(true);
665     } else {
666       return make_error<StringError>(
667           formatv("invalid HardwarePass parameter '{0}' ", ParamName).str(),
668           inconvertibleErrorCode());
669     }
670   }
671   return HardwareLoopOpts;
672 }
673 
674 /// Parser of parameters for LoopUnroll pass.
675 Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
676   LoopUnrollOptions UnrollOpts;
677   while (!Params.empty()) {
678     StringRef ParamName;
679     std::tie(ParamName, Params) = Params.split(';');
680     std::optional<OptimizationLevel> OptLevel = parseOptLevel(ParamName);
681     // Don't accept -Os/-Oz.
682     if (OptLevel && !OptLevel->isOptimizingForSize()) {
683       UnrollOpts.setOptLevel(OptLevel->getSpeedupLevel());
684       continue;
685     }
686     if (ParamName.consume_front("full-unroll-max=")) {
687       int Count;
688       if (ParamName.getAsInteger(0, Count))
689         return make_error<StringError>(
690             formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
691             inconvertibleErrorCode());
692       UnrollOpts.setFullUnrollMaxCount(Count);
693       continue;
694     }
695 
696     bool Enable = !ParamName.consume_front("no-");
697     if (ParamName == "partial") {
698       UnrollOpts.setPartial(Enable);
699     } else if (ParamName == "peeling") {
700       UnrollOpts.setPeeling(Enable);
701     } else if (ParamName == "profile-peeling") {
702       UnrollOpts.setProfileBasedPeeling(Enable);
703     } else if (ParamName == "runtime") {
704       UnrollOpts.setRuntime(Enable);
705     } else if (ParamName == "upperbound") {
706       UnrollOpts.setUpperBound(Enable);
707     } else {
708       return make_error<StringError>(
709           formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
710           inconvertibleErrorCode());
711     }
712   }
713   return UnrollOpts;
714 }
715 
716 Expected<bool> parseSinglePassOption(StringRef Params, StringRef OptionName,
717                                      StringRef PassName) {
718   bool Result = false;
719   while (!Params.empty()) {
720     StringRef ParamName;
721     std::tie(ParamName, Params) = Params.split(';');
722 
723     if (ParamName == OptionName) {
724       Result = true;
725     } else {
726       return make_error<StringError>(
727           formatv("invalid {1} pass parameter '{0}' ", ParamName, PassName)
728               .str(),
729           inconvertibleErrorCode());
730     }
731   }
732   return Result;
733 }
734 
735 Expected<bool> parseGlobalDCEPassOptions(StringRef Params) {
736   return parseSinglePassOption(Params, "vfe-linkage-unit-visibility", "GlobalDCE");
737 }
738 
739 Expected<bool> parseInlinerPassOptions(StringRef Params) {
740   return parseSinglePassOption(Params, "only-mandatory", "InlinerPass");
741 }
742 
743 Expected<bool> parseCoroSplitPassOptions(StringRef Params) {
744   return parseSinglePassOption(Params, "reuse-storage", "CoroSplitPass");
745 }
746 
747 Expected<bool> parsePostOrderFunctionAttrsPassOptions(StringRef Params) {
748   return parseSinglePassOption(Params, "skip-non-recursive-function-attrs",
749                                "PostOrderFunctionAttrs");
750 }
751 
752 Expected<CFGuardPass::Mechanism> parseCFGuardPassOptions(StringRef Params) {
753   if (Params.empty())
754     return CFGuardPass::Mechanism::Check;
755 
756   auto [Param, RHS] = Params.split(';');
757   if (!RHS.empty())
758     return make_error<StringError>(
759         formatv("too many CFGuardPass parameters '{0}' ", Params).str(),
760         inconvertibleErrorCode());
761 
762   if (Param == "check")
763     return CFGuardPass::Mechanism::Check;
764   if (Param == "dispatch")
765     return CFGuardPass::Mechanism::Dispatch;
766 
767   return make_error<StringError>(
768       formatv("invalid CFGuardPass mechanism: '{0}' ", Param).str(),
769       inconvertibleErrorCode());
770 }
771 
772 Expected<bool> parseEarlyCSEPassOptions(StringRef Params) {
773   return parseSinglePassOption(Params, "memssa", "EarlyCSE");
774 }
775 
776 Expected<bool> parseEntryExitInstrumenterPassOptions(StringRef Params) {
777   return parseSinglePassOption(Params, "post-inline", "EntryExitInstrumenter");
778 }
779 
780 Expected<bool> parseLoopExtractorPassOptions(StringRef Params) {
781   return parseSinglePassOption(Params, "single", "LoopExtractor");
782 }
783 
784 Expected<bool> parseLowerMatrixIntrinsicsPassOptions(StringRef Params) {
785   return parseSinglePassOption(Params, "minimal", "LowerMatrixIntrinsics");
786 }
787 
788 Expected<AddressSanitizerOptions> parseASanPassOptions(StringRef Params) {
789   AddressSanitizerOptions Result;
790   while (!Params.empty()) {
791     StringRef ParamName;
792     std::tie(ParamName, Params) = Params.split(';');
793 
794     if (ParamName == "kernel") {
795       Result.CompileKernel = true;
796     } else {
797       return make_error<StringError>(
798           formatv("invalid AddressSanitizer pass parameter '{0}' ", ParamName)
799               .str(),
800           inconvertibleErrorCode());
801     }
802   }
803   return Result;
804 }
805 
806 Expected<HWAddressSanitizerOptions> parseHWASanPassOptions(StringRef Params) {
807   HWAddressSanitizerOptions Result;
808   while (!Params.empty()) {
809     StringRef ParamName;
810     std::tie(ParamName, Params) = Params.split(';');
811 
812     if (ParamName == "recover") {
813       Result.Recover = true;
814     } else if (ParamName == "kernel") {
815       Result.CompileKernel = true;
816     } else {
817       return make_error<StringError>(
818           formatv("invalid HWAddressSanitizer pass parameter '{0}' ", ParamName)
819               .str(),
820           inconvertibleErrorCode());
821     }
822   }
823   return Result;
824 }
825 
826 Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
827   MemorySanitizerOptions Result;
828   while (!Params.empty()) {
829     StringRef ParamName;
830     std::tie(ParamName, Params) = Params.split(';');
831 
832     if (ParamName == "recover") {
833       Result.Recover = true;
834     } else if (ParamName == "kernel") {
835       Result.Kernel = true;
836     } else if (ParamName.consume_front("track-origins=")) {
837       if (ParamName.getAsInteger(0, Result.TrackOrigins))
838         return make_error<StringError>(
839             formatv("invalid argument to MemorySanitizer pass track-origins "
840                     "parameter: '{0}' ",
841                     ParamName)
842                 .str(),
843             inconvertibleErrorCode());
844     } else if (ParamName == "eager-checks") {
845       Result.EagerChecks = true;
846     } else {
847       return make_error<StringError>(
848           formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
849               .str(),
850           inconvertibleErrorCode());
851     }
852   }
853   return Result;
854 }
855 
856 /// Parser of parameters for SimplifyCFG pass.
857 Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
858   SimplifyCFGOptions Result;
859   while (!Params.empty()) {
860     StringRef ParamName;
861     std::tie(ParamName, Params) = Params.split(';');
862 
863     bool Enable = !ParamName.consume_front("no-");
864     if (ParamName == "speculate-blocks") {
865       Result.speculateBlocks(Enable);
866     } else if (ParamName == "simplify-cond-branch") {
867       Result.setSimplifyCondBranch(Enable);
868     } else if (ParamName == "forward-switch-cond") {
869       Result.forwardSwitchCondToPhi(Enable);
870     } else if (ParamName == "switch-range-to-icmp") {
871       Result.convertSwitchRangeToICmp(Enable);
872     } else if (ParamName == "switch-to-lookup") {
873       Result.convertSwitchToLookupTable(Enable);
874     } else if (ParamName == "keep-loops") {
875       Result.needCanonicalLoops(Enable);
876     } else if (ParamName == "hoist-common-insts") {
877       Result.hoistCommonInsts(Enable);
878     } else if (ParamName == "sink-common-insts") {
879       Result.sinkCommonInsts(Enable);
880     } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
881       APInt BonusInstThreshold;
882       if (ParamName.getAsInteger(0, BonusInstThreshold))
883         return make_error<StringError>(
884             formatv("invalid argument to SimplifyCFG pass bonus-threshold "
885                     "parameter: '{0}' ",
886                     ParamName).str(),
887             inconvertibleErrorCode());
888       Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
889     } else {
890       return make_error<StringError>(
891           formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
892           inconvertibleErrorCode());
893     }
894   }
895   return Result;
896 }
897 
898 Expected<InstCombineOptions> parseInstCombineOptions(StringRef Params) {
899   InstCombineOptions Result;
900   // When specifying "instcombine" in -passes enable fix-point verification by
901   // default, as this is what most tests should use.
902   Result.setVerifyFixpoint(true);
903   while (!Params.empty()) {
904     StringRef ParamName;
905     std::tie(ParamName, Params) = Params.split(';');
906 
907     bool Enable = !ParamName.consume_front("no-");
908     if (ParamName == "use-loop-info") {
909       Result.setUseLoopInfo(Enable);
910     } else if (ParamName == "verify-fixpoint") {
911       Result.setVerifyFixpoint(Enable);
912     } else if (Enable && ParamName.consume_front("max-iterations=")) {
913       APInt MaxIterations;
914       if (ParamName.getAsInteger(0, MaxIterations))
915         return make_error<StringError>(
916             formatv("invalid argument to InstCombine pass max-iterations "
917                     "parameter: '{0}' ",
918                     ParamName).str(),
919             inconvertibleErrorCode());
920       Result.setMaxIterations((unsigned)MaxIterations.getZExtValue());
921     } else {
922       return make_error<StringError>(
923           formatv("invalid InstCombine pass parameter '{0}' ", ParamName).str(),
924           inconvertibleErrorCode());
925     }
926   }
927   return Result;
928 }
929 
930 /// Parser of parameters for LoopVectorize pass.
931 Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
932   LoopVectorizeOptions Opts;
933   while (!Params.empty()) {
934     StringRef ParamName;
935     std::tie(ParamName, Params) = Params.split(';');
936 
937     bool Enable = !ParamName.consume_front("no-");
938     if (ParamName == "interleave-forced-only") {
939       Opts.setInterleaveOnlyWhenForced(Enable);
940     } else if (ParamName == "vectorize-forced-only") {
941       Opts.setVectorizeOnlyWhenForced(Enable);
942     } else {
943       return make_error<StringError>(
944           formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
945           inconvertibleErrorCode());
946     }
947   }
948   return Opts;
949 }
950 
951 Expected<std::pair<bool, bool>> parseLoopUnswitchOptions(StringRef Params) {
952   std::pair<bool, bool> Result = {false, true};
953   while (!Params.empty()) {
954     StringRef ParamName;
955     std::tie(ParamName, Params) = Params.split(';');
956 
957     bool Enable = !ParamName.consume_front("no-");
958     if (ParamName == "nontrivial") {
959       Result.first = Enable;
960     } else if (ParamName == "trivial") {
961       Result.second = Enable;
962     } else {
963       return make_error<StringError>(
964           formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
965               .str(),
966           inconvertibleErrorCode());
967     }
968   }
969   return Result;
970 }
971 
972 Expected<LICMOptions> parseLICMOptions(StringRef Params) {
973   LICMOptions Result;
974   while (!Params.empty()) {
975     StringRef ParamName;
976     std::tie(ParamName, Params) = Params.split(';');
977 
978     bool Enable = !ParamName.consume_front("no-");
979     if (ParamName == "allowspeculation") {
980       Result.AllowSpeculation = Enable;
981     } else {
982       return make_error<StringError>(
983           formatv("invalid LICM pass parameter '{0}' ", ParamName).str(),
984           inconvertibleErrorCode());
985     }
986   }
987   return Result;
988 }
989 
990 Expected<std::pair<bool, bool>> parseLoopRotateOptions(StringRef Params) {
991   std::pair<bool, bool> Result = {true, false};
992   while (!Params.empty()) {
993     StringRef ParamName;
994     std::tie(ParamName, Params) = Params.split(';');
995 
996     bool Enable = !ParamName.consume_front("no-");
997     if (ParamName == "header-duplication") {
998       Result.first = Enable;
999     } else if (ParamName == "prepare-for-lto") {
1000       Result.second = Enable;
1001     } else {
1002       return make_error<StringError>(
1003           formatv("invalid LoopRotate pass parameter '{0}' ", ParamName).str(),
1004           inconvertibleErrorCode());
1005     }
1006   }
1007   return Result;
1008 }
1009 
1010 Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
1011   bool Result = false;
1012   while (!Params.empty()) {
1013     StringRef ParamName;
1014     std::tie(ParamName, Params) = Params.split(';');
1015 
1016     bool Enable = !ParamName.consume_front("no-");
1017     if (ParamName == "split-footer-bb") {
1018       Result = Enable;
1019     } else {
1020       return make_error<StringError>(
1021           formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
1022                   ParamName)
1023               .str(),
1024           inconvertibleErrorCode());
1025     }
1026   }
1027   return Result;
1028 }
1029 
1030 Expected<GVNOptions> parseGVNOptions(StringRef Params) {
1031   GVNOptions Result;
1032   while (!Params.empty()) {
1033     StringRef ParamName;
1034     std::tie(ParamName, Params) = Params.split(';');
1035 
1036     bool Enable = !ParamName.consume_front("no-");
1037     if (ParamName == "pre") {
1038       Result.setPRE(Enable);
1039     } else if (ParamName == "load-pre") {
1040       Result.setLoadPRE(Enable);
1041     } else if (ParamName == "split-backedge-load-pre") {
1042       Result.setLoadPRESplitBackedge(Enable);
1043     } else if (ParamName == "memdep") {
1044       Result.setMemDep(Enable);
1045     } else {
1046       return make_error<StringError>(
1047           formatv("invalid GVN pass parameter '{0}' ", ParamName).str(),
1048           inconvertibleErrorCode());
1049     }
1050   }
1051   return Result;
1052 }
1053 
1054 Expected<IPSCCPOptions> parseIPSCCPOptions(StringRef Params) {
1055   IPSCCPOptions Result;
1056   while (!Params.empty()) {
1057     StringRef ParamName;
1058     std::tie(ParamName, Params) = Params.split(';');
1059 
1060     bool Enable = !ParamName.consume_front("no-");
1061     if (ParamName == "func-spec")
1062       Result.setFuncSpec(Enable);
1063     else
1064       return make_error<StringError>(
1065           formatv("invalid IPSCCP pass parameter '{0}' ", ParamName).str(),
1066           inconvertibleErrorCode());
1067   }
1068   return Result;
1069 }
1070 
1071 Expected<SROAOptions> parseSROAOptions(StringRef Params) {
1072   if (Params.empty() || Params == "modify-cfg")
1073     return SROAOptions::ModifyCFG;
1074   if (Params == "preserve-cfg")
1075     return SROAOptions::PreserveCFG;
1076   return make_error<StringError>(
1077       formatv("invalid SROA pass parameter '{0}' (either preserve-cfg or "
1078               "modify-cfg can be specified)",
1079               Params)
1080           .str(),
1081       inconvertibleErrorCode());
1082 }
1083 
1084 Expected<StackLifetime::LivenessType>
1085 parseStackLifetimeOptions(StringRef Params) {
1086   StackLifetime::LivenessType Result = StackLifetime::LivenessType::May;
1087   while (!Params.empty()) {
1088     StringRef ParamName;
1089     std::tie(ParamName, Params) = Params.split(';');
1090 
1091     if (ParamName == "may") {
1092       Result = StackLifetime::LivenessType::May;
1093     } else if (ParamName == "must") {
1094       Result = StackLifetime::LivenessType::Must;
1095     } else {
1096       return make_error<StringError>(
1097           formatv("invalid StackLifetime parameter '{0}' ", ParamName).str(),
1098           inconvertibleErrorCode());
1099     }
1100   }
1101   return Result;
1102 }
1103 
1104 Expected<bool> parseDependenceAnalysisPrinterOptions(StringRef Params) {
1105   return parseSinglePassOption(Params, "normalized-results",
1106                                "DependenceAnalysisPrinter");
1107 }
1108 
1109 Expected<bool> parseSeparateConstOffsetFromGEPPassOptions(StringRef Params) {
1110   return parseSinglePassOption(Params, "lower-gep",
1111                                "SeparateConstOffsetFromGEP");
1112 }
1113 
1114 Expected<OptimizationLevel>
1115 parseFunctionSimplificationPipelineOptions(StringRef Params) {
1116   std::optional<OptimizationLevel> L = parseOptLevel(Params);
1117   if (!L || *L == OptimizationLevel::O0) {
1118     return make_error<StringError>(
1119         formatv("invalid function-simplification parameter '{0}' ", Params)
1120             .str(),
1121         inconvertibleErrorCode());
1122   };
1123   return *L;
1124 }
1125 
1126 Expected<bool> parseMemorySSAPrinterPassOptions(StringRef Params) {
1127   return parseSinglePassOption(Params, "no-ensure-optimized-uses",
1128                                "MemorySSAPrinterPass");
1129 }
1130 
1131 Expected<bool> parseSpeculativeExecutionPassOptions(StringRef Params) {
1132   return parseSinglePassOption(Params, "only-if-divergent-target",
1133                                "SpeculativeExecutionPass");
1134 }
1135 
1136 Expected<std::string> parseMemProfUsePassOptions(StringRef Params) {
1137   std::string Result;
1138   while (!Params.empty()) {
1139     StringRef ParamName;
1140     std::tie(ParamName, Params) = Params.split(';');
1141 
1142     if (ParamName.consume_front("profile-filename=")) {
1143       Result = ParamName.str();
1144     } else {
1145       return make_error<StringError>(
1146           formatv("invalid MemProfUse pass parameter '{0}' ", ParamName).str(),
1147           inconvertibleErrorCode());
1148     }
1149   }
1150   return Result;
1151 }
1152 
1153 Expected<bool> parseStructuralHashPrinterPassOptions(StringRef Params) {
1154   return parseSinglePassOption(Params, "detailed",
1155                                "StructuralHashPrinterPass");
1156 }
1157 
1158 Expected<bool> parseWinEHPrepareOptions(StringRef Params) {
1159   return parseSinglePassOption(Params, "demote-catchswitch-only",
1160                                "WinEHPreparePass");
1161 }
1162 
1163 } // namespace
1164 
1165 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1166 /// alias.
1167 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1168   return Name.starts_with("default") || Name.starts_with("thinlto") ||
1169          Name.starts_with("lto");
1170 }
1171 
1172 /// Tests whether registered callbacks will accept a given pass name.
1173 ///
1174 /// When parsing a pipeline text, the type of the outermost pipeline may be
1175 /// omitted, in which case the type is automatically determined from the first
1176 /// pass name in the text. This may be a name that is handled through one of the
1177 /// callbacks. We check this through the oridinary parsing callbacks by setting
1178 /// up a dummy PassManager in order to not force the client to also handle this
1179 /// type of query.
1180 template <typename PassManagerT, typename CallbacksT>
1181 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1182   if (!Callbacks.empty()) {
1183     PassManagerT DummyPM;
1184     for (auto &CB : Callbacks)
1185       if (CB(Name, DummyPM, {}))
1186         return true;
1187   }
1188   return false;
1189 }
1190 
1191 template <typename CallbacksT>
1192 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
1193   // Manually handle aliases for pre-configured pipeline fragments.
1194   if (startsWithDefaultPipelineAliasPrefix(Name))
1195     return DefaultAliasRegex.match(Name);
1196 
1197   StringRef NameNoBracket = Name.take_until([](char C) { return C == '<'; });
1198 
1199   // Explicitly handle pass manager names.
1200   if (Name == "module")
1201     return true;
1202   if (Name == "cgscc")
1203     return true;
1204   if (NameNoBracket == "function")
1205     return true;
1206   if (Name == "coro-cond")
1207     return true;
1208 
1209   // Explicitly handle custom-parsed pass names.
1210   if (parseRepeatPassName(Name))
1211     return true;
1212 
1213 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
1214   if (Name == NAME)                                                            \
1215     return true;
1216 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)      \
1217   if (checkParametrizedPassName(Name, NAME))                                   \
1218     return true;
1219 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1220   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1221     return true;
1222 #include "PassRegistry.def"
1223 
1224   return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
1225 }
1226 
1227 template <typename CallbacksT>
1228 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
1229   // Explicitly handle pass manager names.
1230   StringRef NameNoBracket = Name.take_until([](char C) { return C == '<'; });
1231   if (Name == "cgscc")
1232     return true;
1233   if (NameNoBracket == "function")
1234     return true;
1235 
1236   // Explicitly handle custom-parsed pass names.
1237   if (parseRepeatPassName(Name))
1238     return true;
1239   if (parseDevirtPassName(Name))
1240     return true;
1241 
1242 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1243   if (Name == NAME)                                                            \
1244     return true;
1245 #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)       \
1246   if (checkParametrizedPassName(Name, NAME))                                   \
1247     return true;
1248 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1249   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1250     return true;
1251 #include "PassRegistry.def"
1252 
1253   return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
1254 }
1255 
1256 template <typename CallbacksT>
1257 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
1258   // Explicitly handle pass manager names.
1259   StringRef NameNoBracket = Name.take_until([](char C) { return C == '<'; });
1260   if (NameNoBracket == "function")
1261     return true;
1262   if (Name == "loop" || Name == "loop-mssa")
1263     return true;
1264 
1265   // Explicitly handle custom-parsed pass names.
1266   if (parseRepeatPassName(Name))
1267     return true;
1268 
1269 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1270   if (Name == NAME)                                                            \
1271     return true;
1272 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
1273   if (checkParametrizedPassName(Name, NAME))                                   \
1274     return true;
1275 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1276   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1277     return true;
1278 #include "PassRegistry.def"
1279 
1280   return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
1281 }
1282 
1283 template <typename CallbacksT>
1284 static bool isLoopNestPassName(StringRef Name, CallbacksT &Callbacks,
1285                                bool &UseMemorySSA) {
1286   UseMemorySSA = false;
1287 
1288   // Explicitly handle custom-parsed pass names.
1289   if (parseRepeatPassName(Name))
1290     return true;
1291 
1292   if (checkParametrizedPassName(Name, "lnicm")) {
1293     UseMemorySSA = true;
1294     return true;
1295   }
1296 
1297 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
1298   if (Name == NAME)                                                            \
1299     return true;
1300 #include "PassRegistry.def"
1301 
1302   return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1303 }
1304 
1305 template <typename CallbacksT>
1306 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks,
1307                            bool &UseMemorySSA) {
1308   UseMemorySSA = false;
1309 
1310   // Explicitly handle custom-parsed pass names.
1311   if (parseRepeatPassName(Name))
1312     return true;
1313 
1314   if (checkParametrizedPassName(Name, "licm")) {
1315     UseMemorySSA = true;
1316     return true;
1317   }
1318 
1319 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1320   if (Name == NAME)                                                            \
1321     return true;
1322 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
1323   if (checkParametrizedPassName(Name, NAME))                                   \
1324     return true;
1325 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1326   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1327     return true;
1328 #include "PassRegistry.def"
1329 
1330   return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1331 }
1332 
1333 std::optional<std::vector<PassBuilder::PipelineElement>>
1334 PassBuilder::parsePipelineText(StringRef Text) {
1335   std::vector<PipelineElement> ResultPipeline;
1336 
1337   SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1338       &ResultPipeline};
1339   for (;;) {
1340     std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1341     size_t Pos = Text.find_first_of(",()");
1342     Pipeline.push_back({Text.substr(0, Pos), {}});
1343 
1344     // If we have a single terminating name, we're done.
1345     if (Pos == Text.npos)
1346       break;
1347 
1348     char Sep = Text[Pos];
1349     Text = Text.substr(Pos + 1);
1350     if (Sep == ',')
1351       // Just a name ending in a comma, continue.
1352       continue;
1353 
1354     if (Sep == '(') {
1355       // Push the inner pipeline onto the stack to continue processing.
1356       PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1357       continue;
1358     }
1359 
1360     assert(Sep == ')' && "Bogus separator!");
1361     // When handling the close parenthesis, we greedily consume them to avoid
1362     // empty strings in the pipeline.
1363     do {
1364       // If we try to pop the outer pipeline we have unbalanced parentheses.
1365       if (PipelineStack.size() == 1)
1366         return std::nullopt;
1367 
1368       PipelineStack.pop_back();
1369     } while (Text.consume_front(")"));
1370 
1371     // Check if we've finished parsing.
1372     if (Text.empty())
1373       break;
1374 
1375     // Otherwise, the end of an inner pipeline always has to be followed by
1376     // a comma, and then we can continue.
1377     if (!Text.consume_front(","))
1378       return std::nullopt;
1379   }
1380 
1381   if (PipelineStack.size() > 1)
1382     // Unbalanced paretheses.
1383     return std::nullopt;
1384 
1385   assert(PipelineStack.back() == &ResultPipeline &&
1386          "Wrong pipeline at the bottom of the stack!");
1387   return {std::move(ResultPipeline)};
1388 }
1389 
1390 Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1391                                    const PipelineElement &E) {
1392   auto &Name = E.Name;
1393   auto &InnerPipeline = E.InnerPipeline;
1394 
1395   // First handle complex passes like the pass managers which carry pipelines.
1396   if (!InnerPipeline.empty()) {
1397     if (Name == "module") {
1398       ModulePassManager NestedMPM;
1399       if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
1400         return Err;
1401       MPM.addPass(std::move(NestedMPM));
1402       return Error::success();
1403     }
1404     if (Name == "coro-cond") {
1405       ModulePassManager NestedMPM;
1406       if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
1407         return Err;
1408       MPM.addPass(CoroConditionalWrapper(std::move(NestedMPM)));
1409       return Error::success();
1410     }
1411     if (Name == "cgscc") {
1412       CGSCCPassManager CGPM;
1413       if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline))
1414         return Err;
1415       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1416       return Error::success();
1417     }
1418     if (auto Params = parseFunctionPipelineName(Name)) {
1419       if (Params->second)
1420         return make_error<StringError>(
1421             "cannot have a no-rerun module to function adaptor",
1422             inconvertibleErrorCode());
1423       FunctionPassManager FPM;
1424       if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
1425         return Err;
1426       MPM.addPass(
1427           createModuleToFunctionPassAdaptor(std::move(FPM), Params->first));
1428       return Error::success();
1429     }
1430     if (auto Count = parseRepeatPassName(Name)) {
1431       ModulePassManager NestedMPM;
1432       if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
1433         return Err;
1434       MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1435       return Error::success();
1436     }
1437 
1438     for (auto &C : ModulePipelineParsingCallbacks)
1439       if (C(Name, MPM, InnerPipeline))
1440         return Error::success();
1441 
1442     // Normal passes can't have pipelines.
1443     return make_error<StringError>(
1444         formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1445         inconvertibleErrorCode());
1446     ;
1447   }
1448 
1449   // Manually handle aliases for pre-configured pipeline fragments.
1450   if (startsWithDefaultPipelineAliasPrefix(Name)) {
1451     SmallVector<StringRef, 3> Matches;
1452     if (!DefaultAliasRegex.match(Name, &Matches))
1453       return make_error<StringError>(
1454           formatv("unknown default pipeline alias '{0}'", Name).str(),
1455           inconvertibleErrorCode());
1456 
1457     assert(Matches.size() == 3 && "Must capture two matched strings!");
1458 
1459     OptimizationLevel L = *parseOptLevel(Matches[2]);
1460 
1461     // This is consistent with old pass manager invoked via opt, but
1462     // inconsistent with clang. Clang doesn't enable loop vectorization
1463     // but does enable slp vectorization at Oz.
1464     PTO.LoopVectorization =
1465         L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
1466     PTO.SLPVectorization =
1467         L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
1468 
1469     if (Matches[1] == "default") {
1470       MPM.addPass(buildPerModuleDefaultPipeline(L));
1471     } else if (Matches[1] == "thinlto-pre-link") {
1472       MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L));
1473     } else if (Matches[1] == "thinlto") {
1474       MPM.addPass(buildThinLTODefaultPipeline(L, nullptr));
1475     } else if (Matches[1] == "lto-pre-link") {
1476       if (PTO.UnifiedLTO)
1477         // When UnifiedLTO is enabled, use the ThinLTO pre-link pipeline. This
1478         // avoids compile-time performance regressions and keeps the pre-link
1479         // LTO pipeline "unified" for both LTO modes.
1480         MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L));
1481       else
1482         MPM.addPass(buildLTOPreLinkDefaultPipeline(L));
1483     } else {
1484       assert(Matches[1] == "lto" && "Not one of the matched options!");
1485       MPM.addPass(buildLTODefaultPipeline(L, nullptr));
1486     }
1487     return Error::success();
1488   }
1489 
1490   // Finally expand the basic registered passes from the .inc file.
1491 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
1492   if (Name == NAME) {                                                          \
1493     MPM.addPass(CREATE_PASS);                                                  \
1494     return Error::success();                                                   \
1495   }
1496 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)      \
1497   if (checkParametrizedPassName(Name, NAME)) {                                 \
1498     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1499     if (!Params)                                                               \
1500       return Params.takeError();                                               \
1501     MPM.addPass(CREATE_PASS(Params.get()));                                    \
1502     return Error::success();                                                   \
1503   }
1504 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1505   if (Name == "require<" NAME ">") {                                           \
1506     MPM.addPass(                                                               \
1507         RequireAnalysisPass<                                                   \
1508             std::remove_reference_t<decltype(CREATE_PASS)>, Module>());        \
1509     return Error::success();                                                   \
1510   }                                                                            \
1511   if (Name == "invalidate<" NAME ">") {                                        \
1512     MPM.addPass(InvalidateAnalysisPass<                                        \
1513                 std::remove_reference_t<decltype(CREATE_PASS)>>());            \
1514     return Error::success();                                                   \
1515   }
1516 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1517   if (Name == NAME) {                                                          \
1518     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS));         \
1519     return Error::success();                                                   \
1520   }
1521 #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)       \
1522   if (checkParametrizedPassName(Name, NAME)) {                                 \
1523     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1524     if (!Params)                                                               \
1525       return Params.takeError();                                               \
1526     MPM.addPass(                                                               \
1527         createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS(Params.get())));   \
1528     return Error::success();                                                   \
1529   }
1530 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1531   if (Name == NAME) {                                                          \
1532     MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS));               \
1533     return Error::success();                                                   \
1534   }
1535 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
1536   if (checkParametrizedPassName(Name, NAME)) {                                 \
1537     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1538     if (!Params)                                                               \
1539       return Params.takeError();                                               \
1540     MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
1541     return Error::success();                                                   \
1542   }
1543 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
1544   if (Name == NAME) {                                                          \
1545     MPM.addPass(createModuleToFunctionPassAdaptor(                             \
1546         createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)));          \
1547     return Error::success();                                                   \
1548   }
1549 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1550   if (Name == NAME) {                                                          \
1551     MPM.addPass(createModuleToFunctionPassAdaptor(                             \
1552         createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)));          \
1553     return Error::success();                                                   \
1554   }
1555 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
1556   if (checkParametrizedPassName(Name, NAME)) {                                 \
1557     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1558     if (!Params)                                                               \
1559       return Params.takeError();                                               \
1560     MPM.addPass(                                                               \
1561         createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(     \
1562             CREATE_PASS(Params.get()), false, false)));                        \
1563     return Error::success();                                                   \
1564   }
1565 #include "PassRegistry.def"
1566 
1567   for (auto &C : ModulePipelineParsingCallbacks)
1568     if (C(Name, MPM, InnerPipeline))
1569       return Error::success();
1570   return make_error<StringError>(
1571       formatv("unknown module pass '{0}'", Name).str(),
1572       inconvertibleErrorCode());
1573 }
1574 
1575 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1576                                   const PipelineElement &E) {
1577   auto &Name = E.Name;
1578   auto &InnerPipeline = E.InnerPipeline;
1579 
1580   // First handle complex passes like the pass managers which carry pipelines.
1581   if (!InnerPipeline.empty()) {
1582     if (Name == "cgscc") {
1583       CGSCCPassManager NestedCGPM;
1584       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
1585         return Err;
1586       // Add the nested pass manager with the appropriate adaptor.
1587       CGPM.addPass(std::move(NestedCGPM));
1588       return Error::success();
1589     }
1590     if (auto Params = parseFunctionPipelineName(Name)) {
1591       FunctionPassManager FPM;
1592       if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
1593         return Err;
1594       // Add the nested pass manager with the appropriate adaptor.
1595       CGPM.addPass(createCGSCCToFunctionPassAdaptor(
1596           std::move(FPM), Params->first, Params->second));
1597       return Error::success();
1598     }
1599     if (auto Count = parseRepeatPassName(Name)) {
1600       CGSCCPassManager NestedCGPM;
1601       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
1602         return Err;
1603       CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1604       return Error::success();
1605     }
1606     if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1607       CGSCCPassManager NestedCGPM;
1608       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
1609         return Err;
1610       CGPM.addPass(
1611           createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
1612       return Error::success();
1613     }
1614 
1615     for (auto &C : CGSCCPipelineParsingCallbacks)
1616       if (C(Name, CGPM, InnerPipeline))
1617         return Error::success();
1618 
1619     // Normal passes can't have pipelines.
1620     return make_error<StringError>(
1621         formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1622         inconvertibleErrorCode());
1623   }
1624 
1625 // Now expand the basic registered passes from the .inc file.
1626 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1627   if (Name == NAME) {                                                          \
1628     CGPM.addPass(CREATE_PASS);                                                 \
1629     return Error::success();                                                   \
1630   }
1631 #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)       \
1632   if (checkParametrizedPassName(Name, NAME)) {                                 \
1633     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1634     if (!Params)                                                               \
1635       return Params.takeError();                                               \
1636     CGPM.addPass(CREATE_PASS(Params.get()));                                   \
1637     return Error::success();                                                   \
1638   }
1639 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1640   if (Name == "require<" NAME ">") {                                           \
1641     CGPM.addPass(RequireAnalysisPass<                                          \
1642                  std::remove_reference_t<decltype(CREATE_PASS)>,               \
1643                  LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,    \
1644                  CGSCCUpdateResult &>());                                      \
1645     return Error::success();                                                   \
1646   }                                                                            \
1647   if (Name == "invalidate<" NAME ">") {                                        \
1648     CGPM.addPass(InvalidateAnalysisPass<                                       \
1649                  std::remove_reference_t<decltype(CREATE_PASS)>>());           \
1650     return Error::success();                                                   \
1651   }
1652 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1653   if (Name == NAME) {                                                          \
1654     CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS));               \
1655     return Error::success();                                                   \
1656   }
1657 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
1658   if (checkParametrizedPassName(Name, NAME)) {                                 \
1659     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1660     if (!Params)                                                               \
1661       return Params.takeError();                                               \
1662     CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
1663     return Error::success();                                                   \
1664   }
1665 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
1666   if (Name == NAME) {                                                          \
1667     CGPM.addPass(createCGSCCToFunctionPassAdaptor(                             \
1668         createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)));          \
1669     return Error::success();                                                   \
1670   }
1671 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1672   if (Name == NAME) {                                                          \
1673     CGPM.addPass(createCGSCCToFunctionPassAdaptor(                             \
1674         createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)));          \
1675     return Error::success();                                                   \
1676   }
1677 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
1678   if (checkParametrizedPassName(Name, NAME)) {                                 \
1679     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1680     if (!Params)                                                               \
1681       return Params.takeError();                                               \
1682     CGPM.addPass(                                                              \
1683         createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(      \
1684             CREATE_PASS(Params.get()), false, false)));                        \
1685     return Error::success();                                                   \
1686   }
1687 #include "PassRegistry.def"
1688 
1689   for (auto &C : CGSCCPipelineParsingCallbacks)
1690     if (C(Name, CGPM, InnerPipeline))
1691       return Error::success();
1692   return make_error<StringError>(
1693       formatv("unknown cgscc pass '{0}'", Name).str(),
1694       inconvertibleErrorCode());
1695 }
1696 
1697 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1698                                      const PipelineElement &E) {
1699   auto &Name = E.Name;
1700   auto &InnerPipeline = E.InnerPipeline;
1701 
1702   // First handle complex passes like the pass managers which carry pipelines.
1703   if (!InnerPipeline.empty()) {
1704     if (Name == "function") {
1705       FunctionPassManager NestedFPM;
1706       if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
1707         return Err;
1708       // Add the nested pass manager with the appropriate adaptor.
1709       FPM.addPass(std::move(NestedFPM));
1710       return Error::success();
1711     }
1712     if (Name == "loop" || Name == "loop-mssa") {
1713       LoopPassManager LPM;
1714       if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline))
1715         return Err;
1716       // Add the nested pass manager with the appropriate adaptor.
1717       bool UseMemorySSA = (Name == "loop-mssa");
1718       bool UseBFI = llvm::any_of(InnerPipeline, [](auto Pipeline) {
1719         return Pipeline.Name.contains("simple-loop-unswitch");
1720       });
1721       bool UseBPI = llvm::any_of(InnerPipeline, [](auto Pipeline) {
1722         return Pipeline.Name == "loop-predication";
1723       });
1724       FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
1725                                                   UseBFI, UseBPI));
1726       return Error::success();
1727     }
1728     if (auto Count = parseRepeatPassName(Name)) {
1729       FunctionPassManager NestedFPM;
1730       if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
1731         return Err;
1732       FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1733       return Error::success();
1734     }
1735 
1736     for (auto &C : FunctionPipelineParsingCallbacks)
1737       if (C(Name, FPM, InnerPipeline))
1738         return Error::success();
1739 
1740     // Normal passes can't have pipelines.
1741     return make_error<StringError>(
1742         formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1743         inconvertibleErrorCode());
1744   }
1745 
1746 // Now expand the basic registered passes from the .inc file.
1747 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1748   if (Name == NAME) {                                                          \
1749     FPM.addPass(CREATE_PASS);                                                  \
1750     return Error::success();                                                   \
1751   }
1752 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
1753   if (checkParametrizedPassName(Name, NAME)) {                                 \
1754     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1755     if (!Params)                                                               \
1756       return Params.takeError();                                               \
1757     FPM.addPass(CREATE_PASS(Params.get()));                                    \
1758     return Error::success();                                                   \
1759   }
1760 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1761   if (Name == "require<" NAME ">") {                                           \
1762     FPM.addPass(                                                               \
1763         RequireAnalysisPass<                                                   \
1764             std::remove_reference_t<decltype(CREATE_PASS)>, Function>());      \
1765     return Error::success();                                                   \
1766   }                                                                            \
1767   if (Name == "invalidate<" NAME ">") {                                        \
1768     FPM.addPass(InvalidateAnalysisPass<                                        \
1769                 std::remove_reference_t<decltype(CREATE_PASS)>>());            \
1770     return Error::success();                                                   \
1771   }
1772 // FIXME: UseMemorySSA is set to false. Maybe we could do things like:
1773 //        bool UseMemorySSA = !("canon-freeze" || "loop-predication" ||
1774 //                              "guard-widening");
1775 //        The risk is that it may become obsolete if we're not careful.
1776 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
1777   if (Name == NAME) {                                                          \
1778     FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false));   \
1779     return Error::success();                                                   \
1780   }
1781 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1782   if (Name == NAME) {                                                          \
1783     FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false));   \
1784     return Error::success();                                                   \
1785   }
1786 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
1787   if (checkParametrizedPassName(Name, NAME)) {                                 \
1788     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1789     if (!Params)                                                               \
1790       return Params.takeError();                                               \
1791     FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS(Params.get()),     \
1792                                                 false, false));                \
1793     return Error::success();                                                   \
1794   }
1795 #include "PassRegistry.def"
1796 
1797   for (auto &C : FunctionPipelineParsingCallbacks)
1798     if (C(Name, FPM, InnerPipeline))
1799       return Error::success();
1800   return make_error<StringError>(
1801       formatv("unknown function pass '{0}'", Name).str(),
1802       inconvertibleErrorCode());
1803 }
1804 
1805 Error PassBuilder::parseLoopPass(LoopPassManager &LPM,
1806                                  const PipelineElement &E) {
1807   StringRef Name = E.Name;
1808   auto &InnerPipeline = E.InnerPipeline;
1809 
1810   // First handle complex passes like the pass managers which carry pipelines.
1811   if (!InnerPipeline.empty()) {
1812     if (Name == "loop") {
1813       LoopPassManager NestedLPM;
1814       if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
1815         return Err;
1816       // Add the nested pass manager with the appropriate adaptor.
1817       LPM.addPass(std::move(NestedLPM));
1818       return Error::success();
1819     }
1820     if (auto Count = parseRepeatPassName(Name)) {
1821       LoopPassManager NestedLPM;
1822       if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
1823         return Err;
1824       LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1825       return Error::success();
1826     }
1827 
1828     for (auto &C : LoopPipelineParsingCallbacks)
1829       if (C(Name, LPM, InnerPipeline))
1830         return Error::success();
1831 
1832     // Normal passes can't have pipelines.
1833     return make_error<StringError>(
1834         formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1835         inconvertibleErrorCode());
1836   }
1837 
1838 // Now expand the basic registered passes from the .inc file.
1839 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
1840   if (Name == NAME) {                                                          \
1841     LPM.addPass(CREATE_PASS);                                                  \
1842     return Error::success();                                                   \
1843   }
1844 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1845   if (Name == NAME) {                                                          \
1846     LPM.addPass(CREATE_PASS);                                                  \
1847     return Error::success();                                                   \
1848   }
1849 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
1850   if (checkParametrizedPassName(Name, NAME)) {                                 \
1851     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1852     if (!Params)                                                               \
1853       return Params.takeError();                                               \
1854     LPM.addPass(CREATE_PASS(Params.get()));                                    \
1855     return Error::success();                                                   \
1856   }
1857 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1858   if (Name == "require<" NAME ">") {                                           \
1859     LPM.addPass(RequireAnalysisPass<                                           \
1860                 std::remove_reference_t<decltype(CREATE_PASS)>, Loop,          \
1861                 LoopAnalysisManager, LoopStandardAnalysisResults &,            \
1862                 LPMUpdater &>());                                              \
1863     return Error::success();                                                   \
1864   }                                                                            \
1865   if (Name == "invalidate<" NAME ">") {                                        \
1866     LPM.addPass(InvalidateAnalysisPass<                                        \
1867                 std::remove_reference_t<decltype(CREATE_PASS)>>());            \
1868     return Error::success();                                                   \
1869   }
1870 #include "PassRegistry.def"
1871 
1872   for (auto &C : LoopPipelineParsingCallbacks)
1873     if (C(Name, LPM, InnerPipeline))
1874       return Error::success();
1875   return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1876                                  inconvertibleErrorCode());
1877 }
1878 
1879 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1880 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
1881   if (Name == NAME) {                                                          \
1882     AA.registerModuleAnalysis<                                                 \
1883         std::remove_reference_t<decltype(CREATE_PASS)>>();                     \
1884     return true;                                                               \
1885   }
1886 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
1887   if (Name == NAME) {                                                          \
1888     AA.registerFunctionAnalysis<                                               \
1889         std::remove_reference_t<decltype(CREATE_PASS)>>();                     \
1890     return true;                                                               \
1891   }
1892 #include "PassRegistry.def"
1893 
1894   for (auto &C : AAParsingCallbacks)
1895     if (C(Name, AA))
1896       return true;
1897   return false;
1898 }
1899 
1900 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1901                                          ArrayRef<PipelineElement> Pipeline) {
1902   for (const auto &Element : Pipeline) {
1903     if (auto Err = parseLoopPass(LPM, Element))
1904       return Err;
1905   }
1906   return Error::success();
1907 }
1908 
1909 Error PassBuilder::parseFunctionPassPipeline(
1910     FunctionPassManager &FPM, ArrayRef<PipelineElement> Pipeline) {
1911   for (const auto &Element : Pipeline) {
1912     if (auto Err = parseFunctionPass(FPM, Element))
1913       return Err;
1914   }
1915   return Error::success();
1916 }
1917 
1918 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1919                                           ArrayRef<PipelineElement> Pipeline) {
1920   for (const auto &Element : Pipeline) {
1921     if (auto Err = parseCGSCCPass(CGPM, Element))
1922       return Err;
1923   }
1924   return Error::success();
1925 }
1926 
1927 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1928                                        FunctionAnalysisManager &FAM,
1929                                        CGSCCAnalysisManager &CGAM,
1930                                        ModuleAnalysisManager &MAM) {
1931   MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1932   MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1933   CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1934   FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1935   FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1936   FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1937   LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1938 }
1939 
1940 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1941                                            ArrayRef<PipelineElement> Pipeline) {
1942   for (const auto &Element : Pipeline) {
1943     if (auto Err = parseModulePass(MPM, Element))
1944       return Err;
1945   }
1946   return Error::success();
1947 }
1948 
1949 // Primary pass pipeline description parsing routine for a \c ModulePassManager
1950 // FIXME: Should this routine accept a TargetMachine or require the caller to
1951 // pre-populate the analysis managers with target-specific stuff?
1952 Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1953                                      StringRef PipelineText) {
1954   auto Pipeline = parsePipelineText(PipelineText);
1955   if (!Pipeline || Pipeline->empty())
1956     return make_error<StringError>(
1957         formatv("invalid pipeline '{0}'", PipelineText).str(),
1958         inconvertibleErrorCode());
1959 
1960   // If the first name isn't at the module layer, wrap the pipeline up
1961   // automatically.
1962   StringRef FirstName = Pipeline->front().Name;
1963 
1964   if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1965     bool UseMemorySSA;
1966     if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
1967       Pipeline = {{"cgscc", std::move(*Pipeline)}};
1968     } else if (isFunctionPassName(FirstName,
1969                                   FunctionPipelineParsingCallbacks)) {
1970       Pipeline = {{"function", std::move(*Pipeline)}};
1971     } else if (isLoopNestPassName(FirstName, LoopPipelineParsingCallbacks,
1972                                   UseMemorySSA)) {
1973       Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop",
1974                                  std::move(*Pipeline)}}}};
1975     } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks,
1976                               UseMemorySSA)) {
1977       Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop",
1978                                  std::move(*Pipeline)}}}};
1979     } else {
1980       for (auto &C : TopLevelPipelineParsingCallbacks)
1981         if (C(MPM, *Pipeline))
1982           return Error::success();
1983 
1984       // Unknown pass or pipeline name!
1985       auto &InnerPipeline = Pipeline->front().InnerPipeline;
1986       return make_error<StringError>(
1987           formatv("unknown {0} name '{1}'",
1988                   (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1989               .str(),
1990           inconvertibleErrorCode());
1991     }
1992   }
1993 
1994   if (auto Err = parseModulePassPipeline(MPM, *Pipeline))
1995     return Err;
1996   return Error::success();
1997 }
1998 
1999 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
2000 Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2001                                      StringRef PipelineText) {
2002   auto Pipeline = parsePipelineText(PipelineText);
2003   if (!Pipeline || Pipeline->empty())
2004     return make_error<StringError>(
2005         formatv("invalid pipeline '{0}'", PipelineText).str(),
2006         inconvertibleErrorCode());
2007 
2008   StringRef FirstName = Pipeline->front().Name;
2009   if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
2010     return make_error<StringError>(
2011         formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2012                 PipelineText)
2013             .str(),
2014         inconvertibleErrorCode());
2015 
2016   if (auto Err = parseCGSCCPassPipeline(CGPM, *Pipeline))
2017     return Err;
2018   return Error::success();
2019 }
2020 
2021 // Primary pass pipeline description parsing routine for a \c
2022 // FunctionPassManager
2023 Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2024                                      StringRef PipelineText) {
2025   auto Pipeline = parsePipelineText(PipelineText);
2026   if (!Pipeline || Pipeline->empty())
2027     return make_error<StringError>(
2028         formatv("invalid pipeline '{0}'", PipelineText).str(),
2029         inconvertibleErrorCode());
2030 
2031   StringRef FirstName = Pipeline->front().Name;
2032   if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
2033     return make_error<StringError>(
2034         formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2035                 PipelineText)
2036             .str(),
2037         inconvertibleErrorCode());
2038 
2039   if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline))
2040     return Err;
2041   return Error::success();
2042 }
2043 
2044 // Primary pass pipeline description parsing routine for a \c LoopPassManager
2045 Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2046                                      StringRef PipelineText) {
2047   auto Pipeline = parsePipelineText(PipelineText);
2048   if (!Pipeline || Pipeline->empty())
2049     return make_error<StringError>(
2050         formatv("invalid pipeline '{0}'", PipelineText).str(),
2051         inconvertibleErrorCode());
2052 
2053   if (auto Err = parseLoopPassPipeline(CGPM, *Pipeline))
2054     return Err;
2055 
2056   return Error::success();
2057 }
2058 
2059 Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
2060   // If the pipeline just consists of the word 'default' just replace the AA
2061   // manager with our default one.
2062   if (PipelineText == "default") {
2063     AA = buildDefaultAAPipeline();
2064     return Error::success();
2065   }
2066 
2067   while (!PipelineText.empty()) {
2068     StringRef Name;
2069     std::tie(Name, PipelineText) = PipelineText.split(',');
2070     if (!parseAAPassName(AA, Name))
2071       return make_error<StringError>(
2072           formatv("unknown alias analysis name '{0}'", Name).str(),
2073           inconvertibleErrorCode());
2074   }
2075 
2076   return Error::success();
2077 }
2078 
2079 static void printPassName(StringRef PassName, raw_ostream &OS) {
2080   OS << "  " << PassName << "\n";
2081 }
2082 static void printPassName(StringRef PassName, StringRef Params,
2083                           raw_ostream &OS) {
2084   OS << "  " << PassName << "<" << Params << ">\n";
2085 }
2086 
2087 void PassBuilder::printPassNames(raw_ostream &OS) {
2088   // TODO: print pass descriptions when they are available
2089 
2090   OS << "Module passes:\n";
2091 #define MODULE_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
2092 #include "PassRegistry.def"
2093 
2094   OS << "Module passes with params:\n";
2095 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)      \
2096   printPassName(NAME, PARAMS, OS);
2097 #include "PassRegistry.def"
2098 
2099   OS << "Module analyses:\n";
2100 #define MODULE_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
2101 #include "PassRegistry.def"
2102 
2103   OS << "Module alias analyses:\n";
2104 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
2105 #include "PassRegistry.def"
2106 
2107   OS << "CGSCC passes:\n";
2108 #define CGSCC_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
2109 #include "PassRegistry.def"
2110 
2111   OS << "CGSCC passes with params:\n";
2112 #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)       \
2113   printPassName(NAME, PARAMS, OS);
2114 #include "PassRegistry.def"
2115 
2116   OS << "CGSCC analyses:\n";
2117 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
2118 #include "PassRegistry.def"
2119 
2120   OS << "Function passes:\n";
2121 #define FUNCTION_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
2122 #include "PassRegistry.def"
2123 
2124   OS << "Function passes with params:\n";
2125 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
2126   printPassName(NAME, PARAMS, OS);
2127 #include "PassRegistry.def"
2128 
2129   OS << "Function analyses:\n";
2130 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
2131 #include "PassRegistry.def"
2132 
2133   OS << "Function alias analyses:\n";
2134 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
2135 #include "PassRegistry.def"
2136 
2137   OS << "LoopNest passes:\n";
2138 #define LOOPNEST_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
2139 #include "PassRegistry.def"
2140 
2141   OS << "Loop passes:\n";
2142 #define LOOP_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
2143 #include "PassRegistry.def"
2144 
2145   OS << "Loop passes with params:\n";
2146 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
2147   printPassName(NAME, PARAMS, OS);
2148 #include "PassRegistry.def"
2149 
2150   OS << "Loop analyses:\n";
2151 #define LOOP_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
2152 #include "PassRegistry.def"
2153 }
2154 
2155 void PassBuilder::registerParseTopLevelPipelineCallback(
2156     const std::function<bool(ModulePassManager &, ArrayRef<PipelineElement>)>
2157         &C) {
2158   TopLevelPipelineParsingCallbacks.push_back(C);
2159 }
2160