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