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