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