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