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