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