[DWARF] Fix referencing Range List Tables from CUs for DWARF64.
[llvm-complete.git] / lib / Passes / PassBuilder.cpp
blobcbb1b5c946b21197910aafd3f608673ba6735bc5
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 //===----------------------------------------------------------------------===//
17 #include "llvm/Passes/PassBuilder.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/AliasAnalysisEvaluator.h"
21 #include "llvm/Analysis/AssumptionCache.h"
22 #include "llvm/Analysis/BasicAliasAnalysis.h"
23 #include "llvm/Analysis/BlockFrequencyInfo.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/CFGPrinter.h"
26 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
28 #include "llvm/Analysis/CGSCCPassManager.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Analysis/DemandedBits.h"
31 #include "llvm/Analysis/DependenceAnalysis.h"
32 #include "llvm/Analysis/DominanceFrontier.h"
33 #include "llvm/Analysis/GlobalsModRef.h"
34 #include "llvm/Analysis/IVUsers.h"
35 #include "llvm/Analysis/LazyCallGraph.h"
36 #include "llvm/Analysis/LazyValueInfo.h"
37 #include "llvm/Analysis/LoopAccessAnalysis.h"
38 #include "llvm/Analysis/LoopCacheAnalysis.h"
39 #include "llvm/Analysis/LoopInfo.h"
40 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
41 #include "llvm/Analysis/MemorySSA.h"
42 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
43 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
44 #include "llvm/Analysis/PhiValues.h"
45 #include "llvm/Analysis/PostDominators.h"
46 #include "llvm/Analysis/ProfileSummaryInfo.h"
47 #include "llvm/Analysis/RegionInfo.h"
48 #include "llvm/Analysis/ScalarEvolution.h"
49 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
50 #include "llvm/Analysis/ScopedNoAliasAA.h"
51 #include "llvm/Analysis/StackSafetyAnalysis.h"
52 #include "llvm/Analysis/TargetLibraryInfo.h"
53 #include "llvm/Analysis/TargetTransformInfo.h"
54 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
55 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
56 #include "llvm/CodeGen/UnreachableBlockElim.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/IRPrintingPasses.h"
59 #include "llvm/IR/PassManager.h"
60 #include "llvm/IR/SafepointIRVerifier.h"
61 #include "llvm/IR/Verifier.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/FormatVariadic.h"
64 #include "llvm/Support/Regex.h"
65 #include "llvm/Target/TargetMachine.h"
66 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
67 #include "llvm/Transforms/IPO/AlwaysInliner.h"
68 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
69 #include "llvm/Transforms/IPO/Attributor.h"
70 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
71 #include "llvm/Transforms/IPO/ConstantMerge.h"
72 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
73 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
74 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
75 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
76 #include "llvm/Transforms/IPO/FunctionAttrs.h"
77 #include "llvm/Transforms/IPO/FunctionImport.h"
78 #include "llvm/Transforms/IPO/GlobalDCE.h"
79 #include "llvm/Transforms/IPO/GlobalOpt.h"
80 #include "llvm/Transforms/IPO/GlobalSplit.h"
81 #include "llvm/Transforms/IPO/HotColdSplitting.h"
82 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
83 #include "llvm/Transforms/IPO/Inliner.h"
84 #include "llvm/Transforms/IPO/Internalize.h"
85 #include "llvm/Transforms/IPO/LowerTypeTests.h"
86 #include "llvm/Transforms/IPO/PartialInlining.h"
87 #include "llvm/Transforms/IPO/SCCP.h"
88 #include "llvm/Transforms/IPO/SampleProfile.h"
89 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
90 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
91 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
92 #include "llvm/Transforms/InstCombine/InstCombine.h"
93 #include "llvm/Transforms/Instrumentation.h"
94 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
95 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
96 #include "llvm/Transforms/Instrumentation/CGProfile.h"
97 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
98 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
99 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
100 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
101 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
102 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
103 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
104 #include "llvm/Transforms/Instrumentation/PoisonChecking.h"
105 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
106 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
107 #include "llvm/Transforms/Scalar/ADCE.h"
108 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
109 #include "llvm/Transforms/Scalar/BDCE.h"
110 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
111 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
112 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
113 #include "llvm/Transforms/Scalar/DCE.h"
114 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
115 #include "llvm/Transforms/Scalar/DivRemPairs.h"
116 #include "llvm/Transforms/Scalar/EarlyCSE.h"
117 #include "llvm/Transforms/Scalar/Float2Int.h"
118 #include "llvm/Transforms/Scalar/GVN.h"
119 #include "llvm/Transforms/Scalar/GuardWidening.h"
120 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
121 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
122 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
123 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
124 #include "llvm/Transforms/Scalar/JumpThreading.h"
125 #include "llvm/Transforms/Scalar/LICM.h"
126 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
127 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
128 #include "llvm/Transforms/Scalar/LoopDeletion.h"
129 #include "llvm/Transforms/Scalar/LoopDistribute.h"
130 #include "llvm/Transforms/Scalar/LoopFuse.h"
131 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
132 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
133 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
134 #include "llvm/Transforms/Scalar/LoopPassManager.h"
135 #include "llvm/Transforms/Scalar/LoopPredication.h"
136 #include "llvm/Transforms/Scalar/LoopRotation.h"
137 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
138 #include "llvm/Transforms/Scalar/LoopSink.h"
139 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
140 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
141 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
142 #include "llvm/Transforms/Scalar/LowerAtomic.h"
143 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
144 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
145 #include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
146 #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
147 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
148 #include "llvm/Transforms/Scalar/MergeICmps.h"
149 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
150 #include "llvm/Transforms/Scalar/NaryReassociate.h"
151 #include "llvm/Transforms/Scalar/NewGVN.h"
152 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
153 #include "llvm/Transforms/Scalar/Reassociate.h"
154 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
155 #include "llvm/Transforms/Scalar/SCCP.h"
156 #include "llvm/Transforms/Scalar/SROA.h"
157 #include "llvm/Transforms/Scalar/Scalarizer.h"
158 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
159 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
160 #include "llvm/Transforms/Scalar/Sink.h"
161 #include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
162 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
163 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
164 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
165 #include "llvm/Transforms/Utils/AddDiscriminators.h"
166 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
167 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
168 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
169 #include "llvm/Transforms/Utils/LCSSA.h"
170 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
171 #include "llvm/Transforms/Utils/LoopSimplify.h"
172 #include "llvm/Transforms/Utils/LowerInvoke.h"
173 #include "llvm/Transforms/Utils/Mem2Reg.h"
174 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
175 #include "llvm/Transforms/Utils/SymbolRewriter.h"
176 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
177 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
178 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
180 using namespace llvm;
182 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
183 cl::ReallyHidden, cl::init(4));
184 static cl::opt<bool>
185 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
186 cl::Hidden, cl::ZeroOrMore,
187 cl::desc("Run Partial inlinining pass"));
189 static cl::opt<bool>
190 RunNewGVN("enable-npm-newgvn", cl::init(false),
191 cl::Hidden, cl::ZeroOrMore,
192 cl::desc("Run NewGVN instead of GVN"));
194 static cl::opt<bool> EnableGVNHoist(
195 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
196 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
198 static cl::opt<bool> EnableGVNSink(
199 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
200 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
202 static cl::opt<bool> EnableUnrollAndJam(
203 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
204 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
206 static cl::opt<bool> EnableSyntheticCounts(
207 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
208 cl::desc("Run synthetic function entry count generation "
209 "pass"));
211 static Regex DefaultAliasRegex(
212 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
214 // This option is used in simplifying testing SampleFDO optimizations for
215 // profile loading.
216 static cl::opt<bool>
217 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
218 cl::desc("Enable control height reduction optimization (CHR)"));
220 PipelineTuningOptions::PipelineTuningOptions() {
221 LoopInterleaving = EnableLoopInterleaving;
222 LoopVectorization = EnableLoopVectorization;
223 SLPVectorization = RunSLPVectorization;
224 LoopUnrolling = true;
225 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
226 LicmMssaOptCap = SetLicmMssaOptCap;
227 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
230 extern cl::opt<bool> EnableHotColdSplit;
231 extern cl::opt<bool> EnableOrderFileInstrumentation;
233 extern cl::opt<bool> FlattenedProfileUsed;
235 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
236 switch (Level) {
237 case PassBuilder::O0:
238 case PassBuilder::O1:
239 case PassBuilder::O2:
240 case PassBuilder::O3:
241 return false;
243 case PassBuilder::Os:
244 case PassBuilder::Oz:
245 return true;
247 llvm_unreachable("Invalid optimization level!");
250 namespace {
252 /// No-op module pass which does nothing.
253 struct NoOpModulePass {
254 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
255 return PreservedAnalyses::all();
257 static StringRef name() { return "NoOpModulePass"; }
260 /// No-op module analysis.
261 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
262 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
263 static AnalysisKey Key;
265 public:
266 struct Result {};
267 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
268 static StringRef name() { return "NoOpModuleAnalysis"; }
271 /// No-op CGSCC pass which does nothing.
272 struct NoOpCGSCCPass {
273 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
274 LazyCallGraph &, CGSCCUpdateResult &UR) {
275 return PreservedAnalyses::all();
277 static StringRef name() { return "NoOpCGSCCPass"; }
280 /// No-op CGSCC analysis.
281 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
282 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
283 static AnalysisKey Key;
285 public:
286 struct Result {};
287 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
288 return Result();
290 static StringRef name() { return "NoOpCGSCCAnalysis"; }
293 /// No-op function pass which does nothing.
294 struct NoOpFunctionPass {
295 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
296 return PreservedAnalyses::all();
298 static StringRef name() { return "NoOpFunctionPass"; }
301 /// No-op function analysis.
302 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
303 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
304 static AnalysisKey Key;
306 public:
307 struct Result {};
308 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
309 static StringRef name() { return "NoOpFunctionAnalysis"; }
312 /// No-op loop pass which does nothing.
313 struct NoOpLoopPass {
314 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
315 LoopStandardAnalysisResults &, LPMUpdater &) {
316 return PreservedAnalyses::all();
318 static StringRef name() { return "NoOpLoopPass"; }
321 /// No-op loop analysis.
322 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
323 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
324 static AnalysisKey Key;
326 public:
327 struct Result {};
328 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
329 return Result();
331 static StringRef name() { return "NoOpLoopAnalysis"; }
334 AnalysisKey NoOpModuleAnalysis::Key;
335 AnalysisKey NoOpCGSCCAnalysis::Key;
336 AnalysisKey NoOpFunctionAnalysis::Key;
337 AnalysisKey NoOpLoopAnalysis::Key;
339 } // End anonymous namespace.
341 void PassBuilder::invokePeepholeEPCallbacks(
342 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
343 for (auto &C : PeepholeEPCallbacks)
344 C(FPM, Level);
347 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
348 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
349 MAM.registerPass([&] { return CREATE_PASS; });
350 #include "PassRegistry.def"
352 for (auto &C : ModuleAnalysisRegistrationCallbacks)
353 C(MAM);
356 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
357 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
358 CGAM.registerPass([&] { return CREATE_PASS; });
359 #include "PassRegistry.def"
361 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
362 C(CGAM);
365 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
366 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
367 FAM.registerPass([&] { return CREATE_PASS; });
368 #include "PassRegistry.def"
370 for (auto &C : FunctionAnalysisRegistrationCallbacks)
371 C(FAM);
374 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
375 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
376 LAM.registerPass([&] { return CREATE_PASS; });
377 #include "PassRegistry.def"
379 for (auto &C : LoopAnalysisRegistrationCallbacks)
380 C(LAM);
383 FunctionPassManager
384 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
385 ThinLTOPhase Phase,
386 bool DebugLogging) {
387 assert(Level != O0 && "Must request optimizations!");
388 FunctionPassManager FPM(DebugLogging);
390 // Form SSA out of local memory accesses after breaking apart aggregates into
391 // scalars.
392 FPM.addPass(SROA());
394 // Catch trivial redundancies
395 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
397 // Hoisting of scalars and load expressions.
398 if (EnableGVNHoist)
399 FPM.addPass(GVNHoistPass());
401 // Global value numbering based sinking.
402 if (EnableGVNSink) {
403 FPM.addPass(GVNSinkPass());
404 FPM.addPass(SimplifyCFGPass());
407 // Speculative execution if the target has divergent branches; otherwise nop.
408 FPM.addPass(SpeculativeExecutionPass());
410 // Optimize based on known information about branches, and cleanup afterward.
411 FPM.addPass(JumpThreadingPass());
412 FPM.addPass(CorrelatedValuePropagationPass());
413 FPM.addPass(SimplifyCFGPass());
414 if (Level == O3)
415 FPM.addPass(AggressiveInstCombinePass());
416 FPM.addPass(InstCombinePass());
418 if (!isOptimizingForSize(Level))
419 FPM.addPass(LibCallsShrinkWrapPass());
421 invokePeepholeEPCallbacks(FPM, Level);
423 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
424 // using the size value profile. Don't perform this when optimizing for size.
425 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
426 !isOptimizingForSize(Level))
427 FPM.addPass(PGOMemOPSizeOpt());
429 FPM.addPass(TailCallElimPass());
430 FPM.addPass(SimplifyCFGPass());
432 // Form canonically associated expression trees, and simplify the trees using
433 // basic mathematical properties. For example, this will form (nearly)
434 // minimal multiplication trees.
435 FPM.addPass(ReassociatePass());
437 // Add the primary loop simplification pipeline.
438 // FIXME: Currently this is split into two loop pass pipelines because we run
439 // some function passes in between them. These can and should be removed
440 // and/or replaced by scheduling the loop pass equivalents in the correct
441 // positions. But those equivalent passes aren't powerful enough yet.
442 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
443 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
444 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
445 // `LoopInstSimplify`.
446 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
448 // Simplify the loop body. We do this initially to clean up after other loop
449 // passes run, either when iterating on a loop or on inner loops with
450 // implications on the outer loop.
451 LPM1.addPass(LoopInstSimplifyPass());
452 LPM1.addPass(LoopSimplifyCFGPass());
454 // Rotate Loop - disable header duplication at -Oz
455 LPM1.addPass(LoopRotatePass(Level != Oz));
456 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
457 LPM1.addPass(SimpleLoopUnswitchPass());
458 LPM2.addPass(IndVarSimplifyPass());
459 LPM2.addPass(LoopIdiomRecognizePass());
461 for (auto &C : LateLoopOptimizationsEPCallbacks)
462 C(LPM2, Level);
464 LPM2.addPass(LoopDeletionPass());
465 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
466 // because it changes IR to makes profile annotation in back compile
467 // inaccurate.
468 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
469 PGOOpt->Action != PGOOptions::SampleUse) &&
470 PTO.LoopUnrolling)
471 LPM2.addPass(
472 LoopFullUnrollPass(Level, false, PTO.ForgetAllSCEVInLoopUnroll));
474 for (auto &C : LoopOptimizerEndEPCallbacks)
475 C(LPM2, Level);
477 // We provide the opt remark emitter pass for LICM to use. We only need to do
478 // this once as it is immutable.
479 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
480 FPM.addPass(createFunctionToLoopPassAdaptor(
481 std::move(LPM1), EnableMSSALoopDependency, DebugLogging));
482 FPM.addPass(SimplifyCFGPass());
483 FPM.addPass(InstCombinePass());
484 // The loop passes in LPM2 (IndVarSimplifyPass, LoopIdiomRecognizePass,
485 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
486 // *All* loop passes must preserve it, in order to be able to use it.
487 FPM.addPass(createFunctionToLoopPassAdaptor(
488 std::move(LPM2), /*UseMemorySSA=*/false, DebugLogging));
490 // Eliminate redundancies.
491 if (Level != O1) {
492 // These passes add substantial compile time so skip them at O1.
493 FPM.addPass(MergedLoadStoreMotionPass());
494 if (RunNewGVN)
495 FPM.addPass(NewGVNPass());
496 else
497 FPM.addPass(GVN());
500 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
501 FPM.addPass(MemCpyOptPass());
503 // Sparse conditional constant propagation.
504 // FIXME: It isn't clear why we do this *after* loop passes rather than
505 // before...
506 FPM.addPass(SCCPPass());
508 // Delete dead bit computations (instcombine runs after to fold away the dead
509 // computations, and then ADCE will run later to exploit any new DCE
510 // opportunities that creates).
511 FPM.addPass(BDCEPass());
513 // Run instcombine after redundancy and dead bit elimination to exploit
514 // opportunities opened up by them.
515 FPM.addPass(InstCombinePass());
516 invokePeepholeEPCallbacks(FPM, Level);
518 // Re-consider control flow based optimizations after redundancy elimination,
519 // redo DCE, etc.
520 FPM.addPass(JumpThreadingPass());
521 FPM.addPass(CorrelatedValuePropagationPass());
522 FPM.addPass(DSEPass());
523 FPM.addPass(createFunctionToLoopPassAdaptor(
524 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
525 EnableMSSALoopDependency, DebugLogging));
527 for (auto &C : ScalarOptimizerLateEPCallbacks)
528 C(FPM, Level);
530 // Finally, do an expensive DCE pass to catch all the dead code exposed by
531 // the simplifications and basic cleanup after all the simplifications.
532 FPM.addPass(ADCEPass());
533 FPM.addPass(SimplifyCFGPass());
534 FPM.addPass(InstCombinePass());
535 invokePeepholeEPCallbacks(FPM, Level);
537 if (EnableCHR && Level == O3 && PGOOpt &&
538 (PGOOpt->Action == PGOOptions::IRUse ||
539 PGOOpt->Action == PGOOptions::SampleUse))
540 FPM.addPass(ControlHeightReductionPass());
542 return FPM;
545 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
546 PassBuilder::OptimizationLevel Level,
547 bool RunProfileGen, bool IsCS,
548 std::string ProfileFile,
549 std::string ProfileRemappingFile) {
550 assert(Level != O0 && "Not expecting O0 here!");
551 // Generally running simplification passes and the inliner with an high
552 // threshold results in smaller executables, but there may be cases where
553 // the size grows, so let's be conservative here and skip this simplification
554 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
555 // IsCS is true).
556 if (!isOptimizingForSize(Level) && !IsCS) {
557 InlineParams IP;
559 // In the old pass manager, this is a cl::opt. Should still this be one?
560 IP.DefaultThreshold = 75;
562 // FIXME: The hint threshold has the same value used by the regular inliner.
563 // This should probably be lowered after performance testing.
564 // FIXME: this comment is cargo culted from the old pass manager, revisit).
565 IP.HintThreshold = 325;
567 CGSCCPassManager CGPipeline(DebugLogging);
569 CGPipeline.addPass(InlinerPass(IP));
571 FunctionPassManager FPM;
572 FPM.addPass(SROA());
573 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
574 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
575 FPM.addPass(InstCombinePass()); // Combine silly sequences.
576 invokePeepholeEPCallbacks(FPM, Level);
578 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
580 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
582 // Delete anything that is now dead to make sure that we don't instrument
583 // dead code. Instrumentation can end up keeping dead code around and
584 // dramatically increase code size.
585 MPM.addPass(GlobalDCEPass());
588 if (!RunProfileGen) {
589 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
590 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
591 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
592 // RequireAnalysisPass for PSI before subsequent non-module passes.
593 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
594 return;
597 // Perform PGO instrumentation.
598 MPM.addPass(PGOInstrumentationGen(IsCS));
600 FunctionPassManager FPM;
601 FPM.addPass(createFunctionToLoopPassAdaptor(
602 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
603 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
605 // Add the profile lowering pass.
606 InstrProfOptions Options;
607 if (!ProfileFile.empty())
608 Options.InstrProfileOutput = ProfileFile;
609 // Do counter promotion at Level greater than O0.
610 Options.DoCounterPromotion = true;
611 Options.UseBFIInPromotion = IsCS;
612 MPM.addPass(InstrProfiling(Options, IsCS));
615 void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
616 bool DebugLogging, bool RunProfileGen,
617 bool IsCS, std::string ProfileFile,
618 std::string ProfileRemappingFile) {
619 if (!RunProfileGen) {
620 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
621 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
622 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
623 // RequireAnalysisPass for PSI before subsequent non-module passes.
624 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
625 return;
628 // Perform PGO instrumentation.
629 MPM.addPass(PGOInstrumentationGen(IsCS));
630 // Add the profile lowering pass.
631 InstrProfOptions Options;
632 if (!ProfileFile.empty())
633 Options.InstrProfileOutput = ProfileFile;
634 // Do not do counter promotion at O0.
635 Options.DoCounterPromotion = false;
636 Options.UseBFIInPromotion = IsCS;
637 MPM.addPass(InstrProfiling(Options, IsCS));
640 static InlineParams
641 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
642 auto O3 = PassBuilder::O3;
643 unsigned OptLevel = Level > O3 ? 2 : Level;
644 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
645 return getInlineParams(OptLevel, SizeLevel);
648 ModulePassManager
649 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
650 ThinLTOPhase Phase,
651 bool DebugLogging) {
652 ModulePassManager MPM(DebugLogging);
654 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
656 // In ThinLTO mode, when flattened profile is used, all the available
657 // profile information will be annotated in PreLink phase so there is
658 // no need to load the profile again in PostLink.
659 bool LoadSampleProfile =
660 HasSampleProfile &&
661 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
663 // During the ThinLTO backend phase we perform early indirect call promotion
664 // here, before globalopt. Otherwise imported available_externally functions
665 // look unreferenced and are removed. If we are going to load the sample
666 // profile then defer until later.
667 // TODO: See if we can move later and consolidate with the location where
668 // we perform ICP when we are loading a sample profile.
669 // TODO: We pass HasSampleProfile (whether there was a sample profile file
670 // passed to the compile) to the SamplePGO flag of ICP. This is used to
671 // determine whether the new direct calls are annotated with prof metadata.
672 // Ideally this should be determined from whether the IR is annotated with
673 // sample profile, and not whether the a sample profile was provided on the
674 // command line. E.g. for flattened profiles where we will not be reloading
675 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
676 // provide the sample profile file.
677 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
678 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
680 // Do basic inference of function attributes from known properties of system
681 // libraries and other oracles.
682 MPM.addPass(InferFunctionAttrsPass());
684 // Create an early function pass manager to cleanup the output of the
685 // frontend.
686 FunctionPassManager EarlyFPM(DebugLogging);
687 EarlyFPM.addPass(SimplifyCFGPass());
688 EarlyFPM.addPass(SROA());
689 EarlyFPM.addPass(EarlyCSEPass());
690 EarlyFPM.addPass(LowerExpectIntrinsicPass());
691 if (Level == O3)
692 EarlyFPM.addPass(CallSiteSplittingPass());
694 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
695 // to convert bitcast to direct calls so that they can be inlined during the
696 // profile annotation prepration step.
697 // More details about SamplePGO design can be found in:
698 // https://research.google.com/pubs/pub45290.html
699 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
700 if (LoadSampleProfile)
701 EarlyFPM.addPass(InstCombinePass());
702 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
704 if (LoadSampleProfile) {
705 // Annotate sample profile right after early FPM to ensure freshness of
706 // the debug info.
707 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
708 PGOOpt->ProfileRemappingFile,
709 Phase == ThinLTOPhase::PreLink));
710 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
711 // RequireAnalysisPass for PSI before subsequent non-module passes.
712 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
713 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
714 // for the profile annotation to be accurate in the ThinLTO backend.
715 if (Phase != ThinLTOPhase::PreLink)
716 // We perform early indirect call promotion here, before globalopt.
717 // This is important for the ThinLTO backend phase because otherwise
718 // imported available_externally functions look unreferenced and are
719 // removed.
720 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
721 true /* SamplePGO */));
724 // Interprocedural constant propagation now that basic cleanup has occurred
725 // and prior to optimizing globals.
726 // FIXME: This position in the pipeline hasn't been carefully considered in
727 // years, it should be re-analyzed.
728 MPM.addPass(IPSCCPPass());
730 // Attach metadata to indirect call sites indicating the set of functions
731 // they may target at run-time. This should follow IPSCCP.
732 MPM.addPass(CalledValuePropagationPass());
734 // Optimize globals to try and fold them into constants.
735 MPM.addPass(GlobalOptPass());
737 // Promote any localized globals to SSA registers.
738 // FIXME: Should this instead by a run of SROA?
739 // FIXME: We should probably run instcombine and simplify-cfg afterward to
740 // delete control flows that are dead once globals have been folded to
741 // constants.
742 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
744 // Remove any dead arguments exposed by cleanups and constand folding
745 // globals.
746 MPM.addPass(DeadArgumentEliminationPass());
748 // Create a small function pass pipeline to cleanup after all the global
749 // optimizations.
750 FunctionPassManager GlobalCleanupPM(DebugLogging);
751 GlobalCleanupPM.addPass(InstCombinePass());
752 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
754 GlobalCleanupPM.addPass(SimplifyCFGPass());
755 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
757 // Add all the requested passes for instrumentation PGO, if requested.
758 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
759 (PGOOpt->Action == PGOOptions::IRInstr ||
760 PGOOpt->Action == PGOOptions::IRUse)) {
761 addPGOInstrPasses(MPM, DebugLogging, Level,
762 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
763 /* IsCS */ false, PGOOpt->ProfileFile,
764 PGOOpt->ProfileRemappingFile);
765 MPM.addPass(PGOIndirectCallPromotion(false, false));
767 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
768 PGOOpt->CSAction == PGOOptions::CSIRInstr)
769 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
771 // Synthesize function entry counts for non-PGO compilation.
772 if (EnableSyntheticCounts && !PGOOpt)
773 MPM.addPass(SyntheticCountsPropagation());
775 // Require the GlobalsAA analysis for the module so we can query it within
776 // the CGSCC pipeline.
777 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
779 // Require the ProfileSummaryAnalysis for the module so we can query it within
780 // the inliner pass.
781 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
783 // Now begin the main postorder CGSCC pipeline.
784 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
785 // manager and trying to emulate its precise behavior. Much of this doesn't
786 // make a lot of sense and we should revisit the core CGSCC structure.
787 CGSCCPassManager MainCGPipeline(DebugLogging);
789 // Note: historically, the PruneEH pass was run first to deduce nounwind and
790 // generally clean up exception handling overhead. It isn't clear this is
791 // valuable as the inliner doesn't currently care whether it is inlining an
792 // invoke or a call.
794 // Run the inliner first. The theory is that we are walking bottom-up and so
795 // the callees have already been fully optimized, and we want to inline them
796 // into the callers so that our optimizations can reflect that.
797 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
798 // because it makes profile annotation in the backend inaccurate.
799 InlineParams IP = getInlineParamsFromOptLevel(Level);
800 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
801 PGOOpt->Action == PGOOptions::SampleUse)
802 IP.HotCallSiteThreshold = 0;
803 MainCGPipeline.addPass(InlinerPass(IP));
805 // Now deduce any function attributes based in the current code.
806 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
808 // When at O3 add argument promotion to the pass pipeline.
809 // FIXME: It isn't at all clear why this should be limited to O3.
810 if (Level == O3)
811 MainCGPipeline.addPass(ArgumentPromotionPass());
813 // Lastly, add the core function simplification pipeline nested inside the
814 // CGSCC walk.
815 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
816 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
818 for (auto &C : CGSCCOptimizerLateEPCallbacks)
819 C(MainCGPipeline, Level);
821 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
822 // to detect when we devirtualize indirect calls and iterate the SCC passes
823 // in that case to try and catch knock-on inlining or function attrs
824 // opportunities. Then we add it to the module pipeline by walking the SCCs
825 // in postorder (or bottom-up).
826 MPM.addPass(
827 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
828 std::move(MainCGPipeline), MaxDevirtIterations)));
830 return MPM;
833 ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
834 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
835 ModulePassManager MPM(DebugLogging);
837 // Optimize globals now that the module is fully simplified.
838 MPM.addPass(GlobalOptPass());
839 MPM.addPass(GlobalDCEPass());
841 // Run partial inlining pass to partially inline functions that have
842 // large bodies.
843 if (RunPartialInlining)
844 MPM.addPass(PartialInlinerPass());
846 // Remove avail extern fns and globals definitions since we aren't compiling
847 // an object file for later LTO. For LTO we want to preserve these so they
848 // are eligible for inlining at link-time. Note if they are unreferenced they
849 // will be removed by GlobalDCE later, so this only impacts referenced
850 // available externally globals. Eventually they will be suppressed during
851 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
852 // may make globals referenced by available external functions dead and saves
853 // running remaining passes on the eliminated functions. These should be
854 // preserved during prelinking for link-time inlining decisions.
855 if (!LTOPreLink)
856 MPM.addPass(EliminateAvailableExternallyPass());
858 if (EnableOrderFileInstrumentation)
859 MPM.addPass(InstrOrderFilePass());
861 // Do RPO function attribute inference across the module to forward-propagate
862 // attributes where applicable.
863 // FIXME: Is this really an optimization rather than a canonicalization?
864 MPM.addPass(ReversePostOrderFunctionAttrsPass());
866 // Do a post inline PGO instrumentation and use pass. This is a context
867 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
868 // cross-module inline has not been done yet. The context sensitive
869 // instrumentation is after all the inlines are done.
870 if (!LTOPreLink && PGOOpt) {
871 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
872 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
873 /* IsCS */ true, PGOOpt->CSProfileGenFile,
874 PGOOpt->ProfileRemappingFile);
875 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
876 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
877 /* IsCS */ true, PGOOpt->ProfileFile,
878 PGOOpt->ProfileRemappingFile);
881 // Re-require GloblasAA here prior to function passes. This is particularly
882 // useful as the above will have inlined, DCE'ed, and function-attr
883 // propagated everything. We should at this point have a reasonably minimal
884 // and richly annotated call graph. By computing aliasing and mod/ref
885 // information for all local globals here, the late loop passes and notably
886 // the vectorizer will be able to use them to help recognize vectorizable
887 // memory operations.
888 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
890 FunctionPassManager OptimizePM(DebugLogging);
891 OptimizePM.addPass(Float2IntPass());
892 // FIXME: We need to run some loop optimizations to re-rotate loops after
893 // simplify-cfg and others undo their rotation.
895 // Optimize the loop execution. These passes operate on entire loop nests
896 // rather than on each loop in an inside-out manner, and so they are actually
897 // function passes.
899 for (auto &C : VectorizerStartEPCallbacks)
900 C(OptimizePM, Level);
902 // First rotate loops that may have been un-rotated by prior passes.
903 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
904 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
906 // Distribute loops to allow partial vectorization. I.e. isolate dependences
907 // into separate loop that would otherwise inhibit vectorization. This is
908 // currently only performed for loops marked with the metadata
909 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
910 OptimizePM.addPass(LoopDistributePass());
912 // Now run the core loop vectorizer.
913 OptimizePM.addPass(LoopVectorizePass(
914 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
916 // Eliminate loads by forwarding stores from the previous iteration to loads
917 // of the current iteration.
918 OptimizePM.addPass(LoopLoadEliminationPass());
920 // Cleanup after the loop optimization passes.
921 OptimizePM.addPass(InstCombinePass());
923 // Now that we've formed fast to execute loop structures, we do further
924 // optimizations. These are run afterward as they might block doing complex
925 // analyses and transforms such as what are needed for loop vectorization.
927 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
928 // GVN, loop transforms, and others have already run, so it's now better to
929 // convert to more optimized IR using more aggressive simplify CFG options.
930 // The extra sinking transform can create larger basic blocks, so do this
931 // before SLP vectorization.
932 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
933 forwardSwitchCondToPhi(true).
934 convertSwitchToLookupTable(true).
935 needCanonicalLoops(false).
936 sinkCommonInsts(true)));
938 // Optimize parallel scalar instruction chains into SIMD instructions.
939 if (PTO.SLPVectorization)
940 OptimizePM.addPass(SLPVectorizerPass());
942 OptimizePM.addPass(InstCombinePass());
944 // Unroll small loops to hide loop backedge latency and saturate any parallel
945 // execution resources of an out-of-order processor. We also then need to
946 // clean up redundancies and loop invariant code.
947 // FIXME: It would be really good to use a loop-integrated instruction
948 // combiner for cleanup here so that the unrolling and LICM can be pipelined
949 // across the loop nests.
950 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
951 if (EnableUnrollAndJam) {
952 OptimizePM.addPass(
953 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
955 if (PTO.LoopUnrolling)
956 OptimizePM.addPass(LoopUnrollPass(
957 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
958 OptimizePM.addPass(WarnMissedTransformationsPass());
959 OptimizePM.addPass(InstCombinePass());
960 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
961 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
962 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
963 EnableMSSALoopDependency, DebugLogging));
965 // Now that we've vectorized and unrolled loops, we may have more refined
966 // alignment information, try to re-derive it here.
967 OptimizePM.addPass(AlignmentFromAssumptionsPass());
969 // Split out cold code. Splitting is done late to avoid hiding context from
970 // other optimizations and inadvertently regressing performance. The tradeoff
971 // is that this has a higher code size cost than splitting early.
972 if (EnableHotColdSplit && !LTOPreLink)
973 MPM.addPass(HotColdSplittingPass());
975 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
976 // canonicalization pass that enables other optimizations. As a result,
977 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
978 // result too early.
979 OptimizePM.addPass(LoopSinkPass());
981 // And finally clean up LCSSA form before generating code.
982 OptimizePM.addPass(InstSimplifyPass());
984 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
985 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
986 // flattening of blocks.
987 OptimizePM.addPass(DivRemPairsPass());
989 // LoopSink (and other loop passes since the last simplifyCFG) might have
990 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
991 OptimizePM.addPass(SimplifyCFGPass());
993 // Optimize PHIs by speculating around them when profitable. Note that this
994 // pass needs to be run after any PRE or similar pass as it is essentially
995 // inserting redundancies into the program. This even includes SimplifyCFG.
996 OptimizePM.addPass(SpeculateAroundPHIsPass());
998 for (auto &C : OptimizerLastEPCallbacks)
999 C(OptimizePM, Level);
1001 // Add the core optimizing pipeline.
1002 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
1004 MPM.addPass(CGProfilePass());
1006 // Now we need to do some global optimization transforms.
1007 // FIXME: It would seem like these should come first in the optimization
1008 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1009 // ordering here.
1010 MPM.addPass(GlobalDCEPass());
1011 MPM.addPass(ConstantMergePass());
1013 return MPM;
1016 ModulePassManager
1017 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
1018 bool DebugLogging, bool LTOPreLink) {
1019 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1021 ModulePassManager MPM(DebugLogging);
1023 // Force any function attributes we want the rest of the pipeline to observe.
1024 MPM.addPass(ForceFunctionAttrsPass());
1026 // Apply module pipeline start EP callback.
1027 for (auto &C : PipelineStartEPCallbacks)
1028 C(MPM);
1030 if (PGOOpt && PGOOpt->SamplePGOSupport)
1031 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1033 // Add the core simplification pipeline.
1034 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
1035 DebugLogging));
1037 // Now add the optimization pipeline.
1038 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
1040 return MPM;
1043 ModulePassManager
1044 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1045 bool DebugLogging) {
1046 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1048 ModulePassManager MPM(DebugLogging);
1050 // Force any function attributes we want the rest of the pipeline to observe.
1051 MPM.addPass(ForceFunctionAttrsPass());
1053 if (PGOOpt && PGOOpt->SamplePGOSupport)
1054 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1056 // Apply module pipeline start EP callback.
1057 for (auto &C : PipelineStartEPCallbacks)
1058 C(MPM);
1060 // If we are planning to perform ThinLTO later, we don't bloat the code with
1061 // unrolling/vectorization/... now. Just simplify the module as much as we
1062 // can.
1063 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1064 DebugLogging));
1066 // Run partial inlining pass to partially inline functions that have
1067 // large bodies.
1068 // FIXME: It isn't clear whether this is really the right place to run this
1069 // in ThinLTO. Because there is another canonicalization and simplification
1070 // phase that will run after the thin link, running this here ends up with
1071 // less information than will be available later and it may grow functions in
1072 // ways that aren't beneficial.
1073 if (RunPartialInlining)
1074 MPM.addPass(PartialInlinerPass());
1076 // Reduce the size of the IR as much as possible.
1077 MPM.addPass(GlobalOptPass());
1079 return MPM;
1082 ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1083 OptimizationLevel Level, bool DebugLogging,
1084 const ModuleSummaryIndex *ImportSummary) {
1085 ModulePassManager MPM(DebugLogging);
1087 if (ImportSummary) {
1088 // These passes import type identifier resolutions for whole-program
1089 // devirtualization and CFI. They must run early because other passes may
1090 // disturb the specific instruction patterns that these passes look for,
1091 // creating dependencies on resolutions that may not appear in the summary.
1093 // For example, GVN may transform the pattern assume(type.test) appearing in
1094 // two basic blocks into assume(phi(type.test, type.test)), which would
1095 // transform a dependency on a WPD resolution into a dependency on a type
1096 // identifier resolution for CFI.
1098 // Also, WPD has access to more precise information than ICP and can
1099 // devirtualize more effectively, so it should operate on the IR first.
1101 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1102 // metadata and intrinsics.
1103 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1104 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1107 if (Level == O0)
1108 return MPM;
1110 // Force any function attributes we want the rest of the pipeline to observe.
1111 MPM.addPass(ForceFunctionAttrsPass());
1113 // Add the core simplification pipeline.
1114 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1115 DebugLogging));
1117 // Now add the optimization pipeline.
1118 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1120 return MPM;
1123 ModulePassManager
1124 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1125 bool DebugLogging) {
1126 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1127 // FIXME: We should use a customized pre-link pipeline!
1128 return buildPerModuleDefaultPipeline(Level, DebugLogging,
1129 /* LTOPreLink */true);
1132 ModulePassManager
1133 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1134 ModuleSummaryIndex *ExportSummary) {
1135 ModulePassManager MPM(DebugLogging);
1137 if (Level == O0) {
1138 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1139 // metadata and intrinsics.
1140 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1141 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1142 return MPM;
1145 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1146 // Load sample profile before running the LTO optimization pipeline.
1147 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1148 PGOOpt->ProfileRemappingFile,
1149 false /* ThinLTOPhase::PreLink */));
1150 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1151 // RequireAnalysisPass for PSI before subsequent non-module passes.
1152 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
1155 // Remove unused virtual tables to improve the quality of code generated by
1156 // whole-program devirtualization and bitset lowering.
1157 MPM.addPass(GlobalDCEPass());
1159 // Force any function attributes we want the rest of the pipeline to observe.
1160 MPM.addPass(ForceFunctionAttrsPass());
1162 // Do basic inference of function attributes from known properties of system
1163 // libraries and other oracles.
1164 MPM.addPass(InferFunctionAttrsPass());
1166 if (Level > 1) {
1167 FunctionPassManager EarlyFPM(DebugLogging);
1168 EarlyFPM.addPass(CallSiteSplittingPass());
1169 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1171 // Indirect call promotion. This should promote all the targets that are
1172 // left by the earlier promotion pass that promotes intra-module targets.
1173 // This two-step promotion is to save the compile time. For LTO, it should
1174 // produce the same result as if we only do promotion here.
1175 MPM.addPass(PGOIndirectCallPromotion(
1176 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1177 // Propagate constants at call sites into the functions they call. This
1178 // opens opportunities for globalopt (and inlining) by substituting function
1179 // pointers passed as arguments to direct uses of functions.
1180 MPM.addPass(IPSCCPPass());
1182 // Attach metadata to indirect call sites indicating the set of functions
1183 // they may target at run-time. This should follow IPSCCP.
1184 MPM.addPass(CalledValuePropagationPass());
1187 // Now deduce any function attributes based in the current code.
1188 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1189 PostOrderFunctionAttrsPass()));
1191 // Do RPO function attribute inference across the module to forward-propagate
1192 // attributes where applicable.
1193 // FIXME: Is this really an optimization rather than a canonicalization?
1194 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1196 // Use in-range annotations on GEP indices to split globals where beneficial.
1197 MPM.addPass(GlobalSplitPass());
1199 // Run whole program optimization of virtual call when the list of callees
1200 // is fixed.
1201 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1203 // Stop here at -O1.
1204 if (Level == 1) {
1205 // The LowerTypeTestsPass needs to run to lower type metadata and the
1206 // type.test intrinsics. The pass does nothing if CFI is disabled.
1207 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1208 return MPM;
1211 // Optimize globals to try and fold them into constants.
1212 MPM.addPass(GlobalOptPass());
1214 // Promote any localized globals to SSA registers.
1215 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1217 // Linking modules together can lead to duplicate global constant, only
1218 // keep one copy of each constant.
1219 MPM.addPass(ConstantMergePass());
1221 // Remove unused arguments from functions.
1222 MPM.addPass(DeadArgumentEliminationPass());
1224 // Reduce the code after globalopt and ipsccp. Both can open up significant
1225 // simplification opportunities, and both can propagate functions through
1226 // function pointers. When this happens, we often have to resolve varargs
1227 // calls, etc, so let instcombine do this.
1228 FunctionPassManager PeepholeFPM(DebugLogging);
1229 if (Level == O3)
1230 PeepholeFPM.addPass(AggressiveInstCombinePass());
1231 PeepholeFPM.addPass(InstCombinePass());
1232 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1234 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
1236 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1237 // generally clean up exception handling overhead. It isn't clear this is
1238 // valuable as the inliner doesn't currently care whether it is inlining an
1239 // invoke or a call.
1240 // Run the inliner now.
1241 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1242 InlinerPass(getInlineParamsFromOptLevel(Level))));
1244 // Optimize globals again after we ran the inliner.
1245 MPM.addPass(GlobalOptPass());
1247 // Garbage collect dead functions.
1248 // FIXME: Add ArgumentPromotion pass after once it's ported.
1249 MPM.addPass(GlobalDCEPass());
1251 FunctionPassManager FPM(DebugLogging);
1252 // The IPO Passes may leave cruft around. Clean up after them.
1253 FPM.addPass(InstCombinePass());
1254 invokePeepholeEPCallbacks(FPM, Level);
1256 FPM.addPass(JumpThreadingPass());
1258 // Do a post inline PGO instrumentation and use pass. This is a context
1259 // sensitive PGO pass.
1260 if (PGOOpt) {
1261 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1262 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1263 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1264 PGOOpt->ProfileRemappingFile);
1265 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1266 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1267 /* IsCS */ true, PGOOpt->ProfileFile,
1268 PGOOpt->ProfileRemappingFile);
1271 // Break up allocas
1272 FPM.addPass(SROA());
1274 // LTO provides additional opportunities for tailcall elimination due to
1275 // link-time inlining, and visibility of nocapture attribute.
1276 FPM.addPass(TailCallElimPass());
1278 // Run a few AA driver optimizations here and now to cleanup the code.
1279 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1281 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1282 PostOrderFunctionAttrsPass()));
1283 // FIXME: here we run IP alias analysis in the legacy PM.
1285 FunctionPassManager MainFPM;
1287 // FIXME: once we fix LoopPass Manager, add LICM here.
1288 // FIXME: once we provide support for enabling MLSM, add it here.
1289 if (RunNewGVN)
1290 MainFPM.addPass(NewGVNPass());
1291 else
1292 MainFPM.addPass(GVN());
1294 // Remove dead memcpy()'s.
1295 MainFPM.addPass(MemCpyOptPass());
1297 // Nuke dead stores.
1298 MainFPM.addPass(DSEPass());
1300 // FIXME: at this point, we run a bunch of loop passes:
1301 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
1302 // loopVectorize. Enable them once the remaining issue with LPM
1303 // are sorted out.
1305 MainFPM.addPass(InstCombinePass());
1306 MainFPM.addPass(SimplifyCFGPass());
1307 MainFPM.addPass(SCCPPass());
1308 MainFPM.addPass(InstCombinePass());
1309 MainFPM.addPass(BDCEPass());
1311 // FIXME: We may want to run SLPVectorizer here.
1312 // After vectorization, assume intrinsics may tell us more
1313 // about pointer alignments.
1314 #if 0
1315 MainFPM.add(AlignmentFromAssumptionsPass());
1316 #endif
1318 // FIXME: Conditionally run LoadCombine here, after it's ported
1319 // (in case we still have this pass, given its questionable usefulness).
1321 MainFPM.addPass(InstCombinePass());
1322 invokePeepholeEPCallbacks(MainFPM, Level);
1323 MainFPM.addPass(JumpThreadingPass());
1324 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1326 // Create a function that performs CFI checks for cross-DSO calls with
1327 // targets in the current module.
1328 MPM.addPass(CrossDSOCFIPass());
1330 // Lower type metadata and the type.test intrinsic. This pass supports
1331 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1332 // to be run at link time if CFI is enabled. This pass does nothing if
1333 // CFI is disabled.
1334 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1336 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1337 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1338 if (EnableHotColdSplit)
1339 MPM.addPass(HotColdSplittingPass());
1341 // Add late LTO optimization passes.
1342 // Delete basic blocks, which optimization passes may have killed.
1343 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1345 // Drop bodies of available eternally objects to improve GlobalDCE.
1346 MPM.addPass(EliminateAvailableExternallyPass());
1348 // Now that we have optimized the program, discard unreachable functions.
1349 MPM.addPass(GlobalDCEPass());
1351 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
1352 return MPM;
1355 AAManager PassBuilder::buildDefaultAAPipeline() {
1356 AAManager AA;
1358 // The order in which these are registered determines their priority when
1359 // being queried.
1361 // First we register the basic alias analysis that provides the majority of
1362 // per-function local AA logic. This is a stateless, on-demand local set of
1363 // AA techniques.
1364 AA.registerFunctionAnalysis<BasicAA>();
1366 // Next we query fast, specialized alias analyses that wrap IR-embedded
1367 // information about aliasing.
1368 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1369 AA.registerFunctionAnalysis<TypeBasedAA>();
1371 // Add support for querying global aliasing information when available.
1372 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1373 // analysis, all that the `AAManager` can do is query for any *cached*
1374 // results from `GlobalsAA` through a readonly proxy.
1375 AA.registerModuleAnalysis<GlobalsAA>();
1377 return AA;
1380 static Optional<int> parseRepeatPassName(StringRef Name) {
1381 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1382 return None;
1383 int Count;
1384 if (Name.getAsInteger(0, Count) || Count <= 0)
1385 return None;
1386 return Count;
1389 static Optional<int> parseDevirtPassName(StringRef Name) {
1390 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1391 return None;
1392 int Count;
1393 if (Name.getAsInteger(0, Count) || Count <= 0)
1394 return None;
1395 return Count;
1398 static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1399 if (!Name.consume_front(PassName))
1400 return false;
1401 // normal pass name w/o parameters == default parameters
1402 if (Name.empty())
1403 return true;
1404 return Name.startswith("<") && Name.endswith(">");
1407 namespace {
1409 /// This performs customized parsing of pass name with parameters.
1411 /// We do not need parametrization of passes in textual pipeline very often,
1412 /// yet on a rare occasion ability to specify parameters right there can be
1413 /// useful.
1415 /// \p Name - parameterized specification of a pass from a textual pipeline
1416 /// is a string in a form of :
1417 /// PassName '<' parameter-list '>'
1419 /// Parameter list is being parsed by the parser callable argument, \p Parser,
1420 /// It takes a string-ref of parameters and returns either StringError or a
1421 /// parameter list in a form of a custom parameters type, all wrapped into
1422 /// Expected<> template class.
1424 template <typename ParametersParseCallableT>
1425 auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1426 StringRef PassName) -> decltype(Parser(StringRef{})) {
1427 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1429 StringRef Params = Name;
1430 if (!Params.consume_front(PassName)) {
1431 assert(false &&
1432 "unable to strip pass name from parametrized pass specification");
1434 if (Params.empty())
1435 return ParametersT{};
1436 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1437 assert(false && "invalid format for parametrized pass name");
1440 Expected<ParametersT> Result = Parser(Params);
1441 assert((Result || Result.template errorIsA<StringError>()) &&
1442 "Pass parameter parser can only return StringErrors.");
1443 return std::move(Result);
1446 /// Parser of parameters for LoopUnroll pass.
1447 Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1448 LoopUnrollOptions UnrollOpts;
1449 while (!Params.empty()) {
1450 StringRef ParamName;
1451 std::tie(ParamName, Params) = Params.split(';');
1452 int OptLevel = StringSwitch<int>(ParamName)
1453 .Case("O0", 0)
1454 .Case("O1", 1)
1455 .Case("O2", 2)
1456 .Case("O3", 3)
1457 .Default(-1);
1458 if (OptLevel >= 0) {
1459 UnrollOpts.setOptLevel(OptLevel);
1460 continue;
1463 bool Enable = !ParamName.consume_front("no-");
1464 if (ParamName == "partial") {
1465 UnrollOpts.setPartial(Enable);
1466 } else if (ParamName == "peeling") {
1467 UnrollOpts.setPeeling(Enable);
1468 } else if (ParamName == "profile-peeling") {
1469 UnrollOpts.setProfileBasedPeeling(Enable);
1470 } else if (ParamName == "runtime") {
1471 UnrollOpts.setRuntime(Enable);
1472 } else if (ParamName == "upperbound") {
1473 UnrollOpts.setUpperBound(Enable);
1474 } else {
1475 return make_error<StringError>(
1476 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1477 inconvertibleErrorCode());
1480 return UnrollOpts;
1483 Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1484 MemorySanitizerOptions Result;
1485 while (!Params.empty()) {
1486 StringRef ParamName;
1487 std::tie(ParamName, Params) = Params.split(';');
1489 if (ParamName == "recover") {
1490 Result.Recover = true;
1491 } else if (ParamName == "kernel") {
1492 Result.Kernel = true;
1493 } else if (ParamName.consume_front("track-origins=")) {
1494 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1495 return make_error<StringError>(
1496 formatv("invalid argument to MemorySanitizer pass track-origins "
1497 "parameter: '{0}' ",
1498 ParamName)
1499 .str(),
1500 inconvertibleErrorCode());
1501 } else {
1502 return make_error<StringError>(
1503 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1504 .str(),
1505 inconvertibleErrorCode());
1508 return Result;
1511 /// Parser of parameters for SimplifyCFG pass.
1512 Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1513 SimplifyCFGOptions Result;
1514 while (!Params.empty()) {
1515 StringRef ParamName;
1516 std::tie(ParamName, Params) = Params.split(';');
1518 bool Enable = !ParamName.consume_front("no-");
1519 if (ParamName == "forward-switch-cond") {
1520 Result.forwardSwitchCondToPhi(Enable);
1521 } else if (ParamName == "switch-to-lookup") {
1522 Result.convertSwitchToLookupTable(Enable);
1523 } else if (ParamName == "keep-loops") {
1524 Result.needCanonicalLoops(Enable);
1525 } else if (ParamName == "sink-common-insts") {
1526 Result.sinkCommonInsts(Enable);
1527 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1528 APInt BonusInstThreshold;
1529 if (ParamName.getAsInteger(0, BonusInstThreshold))
1530 return make_error<StringError>(
1531 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1532 "parameter: '{0}' ",
1533 ParamName).str(),
1534 inconvertibleErrorCode());
1535 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1536 } else {
1537 return make_error<StringError>(
1538 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1539 inconvertibleErrorCode());
1542 return Result;
1545 /// Parser of parameters for LoopVectorize pass.
1546 Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1547 LoopVectorizeOptions Opts;
1548 while (!Params.empty()) {
1549 StringRef ParamName;
1550 std::tie(ParamName, Params) = Params.split(';');
1552 bool Enable = !ParamName.consume_front("no-");
1553 if (ParamName == "interleave-forced-only") {
1554 Opts.setInterleaveOnlyWhenForced(Enable);
1555 } else if (ParamName == "vectorize-forced-only") {
1556 Opts.setVectorizeOnlyWhenForced(Enable);
1557 } else {
1558 return make_error<StringError>(
1559 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1560 inconvertibleErrorCode());
1563 return Opts;
1566 Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1567 bool Result = false;
1568 while (!Params.empty()) {
1569 StringRef ParamName;
1570 std::tie(ParamName, Params) = Params.split(';');
1572 bool Enable = !ParamName.consume_front("no-");
1573 if (ParamName == "nontrivial") {
1574 Result = Enable;
1575 } else {
1576 return make_error<StringError>(
1577 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1578 .str(),
1579 inconvertibleErrorCode());
1582 return Result;
1584 } // namespace
1586 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1587 /// alias.
1588 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1589 return Name.startswith("default") || Name.startswith("thinlto") ||
1590 Name.startswith("lto");
1593 /// Tests whether registered callbacks will accept a given pass name.
1595 /// When parsing a pipeline text, the type of the outermost pipeline may be
1596 /// omitted, in which case the type is automatically determined from the first
1597 /// pass name in the text. This may be a name that is handled through one of the
1598 /// callbacks. We check this through the oridinary parsing callbacks by setting
1599 /// up a dummy PassManager in order to not force the client to also handle this
1600 /// type of query.
1601 template <typename PassManagerT, typename CallbacksT>
1602 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1603 if (!Callbacks.empty()) {
1604 PassManagerT DummyPM;
1605 for (auto &CB : Callbacks)
1606 if (CB(Name, DummyPM, {}))
1607 return true;
1609 return false;
1612 template <typename CallbacksT>
1613 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
1614 // Manually handle aliases for pre-configured pipeline fragments.
1615 if (startsWithDefaultPipelineAliasPrefix(Name))
1616 return DefaultAliasRegex.match(Name);
1618 // Explicitly handle pass manager names.
1619 if (Name == "module")
1620 return true;
1621 if (Name == "cgscc")
1622 return true;
1623 if (Name == "function")
1624 return true;
1626 // Explicitly handle custom-parsed pass names.
1627 if (parseRepeatPassName(Name))
1628 return true;
1630 #define MODULE_PASS(NAME, CREATE_PASS) \
1631 if (Name == NAME) \
1632 return true;
1633 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1634 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1635 return true;
1636 #include "PassRegistry.def"
1638 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
1641 template <typename CallbacksT>
1642 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
1643 // Explicitly handle pass manager names.
1644 if (Name == "cgscc")
1645 return true;
1646 if (Name == "function")
1647 return true;
1649 // Explicitly handle custom-parsed pass names.
1650 if (parseRepeatPassName(Name))
1651 return true;
1652 if (parseDevirtPassName(Name))
1653 return true;
1655 #define CGSCC_PASS(NAME, CREATE_PASS) \
1656 if (Name == NAME) \
1657 return true;
1658 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1659 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1660 return true;
1661 #include "PassRegistry.def"
1663 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
1666 template <typename CallbacksT>
1667 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
1668 // Explicitly handle pass manager names.
1669 if (Name == "function")
1670 return true;
1671 if (Name == "loop" || Name == "loop-mssa")
1672 return true;
1674 // Explicitly handle custom-parsed pass names.
1675 if (parseRepeatPassName(Name))
1676 return true;
1678 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1679 if (Name == NAME) \
1680 return true;
1681 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1682 if (checkParametrizedPassName(Name, NAME)) \
1683 return true;
1684 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1685 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1686 return true;
1687 #include "PassRegistry.def"
1689 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
1692 template <typename CallbacksT>
1693 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
1694 // Explicitly handle pass manager names.
1695 if (Name == "loop" || Name == "loop-mssa")
1696 return true;
1698 // Explicitly handle custom-parsed pass names.
1699 if (parseRepeatPassName(Name))
1700 return true;
1702 #define LOOP_PASS(NAME, CREATE_PASS) \
1703 if (Name == NAME) \
1704 return true;
1705 #define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1706 if (checkParametrizedPassName(Name, NAME)) \
1707 return true;
1708 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1709 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1710 return true;
1711 #include "PassRegistry.def"
1713 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1716 Optional<std::vector<PassBuilder::PipelineElement>>
1717 PassBuilder::parsePipelineText(StringRef Text) {
1718 std::vector<PipelineElement> ResultPipeline;
1720 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1721 &ResultPipeline};
1722 for (;;) {
1723 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1724 size_t Pos = Text.find_first_of(",()");
1725 Pipeline.push_back({Text.substr(0, Pos), {}});
1727 // If we have a single terminating name, we're done.
1728 if (Pos == Text.npos)
1729 break;
1731 char Sep = Text[Pos];
1732 Text = Text.substr(Pos + 1);
1733 if (Sep == ',')
1734 // Just a name ending in a comma, continue.
1735 continue;
1737 if (Sep == '(') {
1738 // Push the inner pipeline onto the stack to continue processing.
1739 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1740 continue;
1743 assert(Sep == ')' && "Bogus separator!");
1744 // When handling the close parenthesis, we greedily consume them to avoid
1745 // empty strings in the pipeline.
1746 do {
1747 // If we try to pop the outer pipeline we have unbalanced parentheses.
1748 if (PipelineStack.size() == 1)
1749 return None;
1751 PipelineStack.pop_back();
1752 } while (Text.consume_front(")"));
1754 // Check if we've finished parsing.
1755 if (Text.empty())
1756 break;
1758 // Otherwise, the end of an inner pipeline always has to be followed by
1759 // a comma, and then we can continue.
1760 if (!Text.consume_front(","))
1761 return None;
1764 if (PipelineStack.size() > 1)
1765 // Unbalanced paretheses.
1766 return None;
1768 assert(PipelineStack.back() == &ResultPipeline &&
1769 "Wrong pipeline at the bottom of the stack!");
1770 return {std::move(ResultPipeline)};
1773 Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1774 const PipelineElement &E,
1775 bool VerifyEachPass, bool DebugLogging) {
1776 auto &Name = E.Name;
1777 auto &InnerPipeline = E.InnerPipeline;
1779 // First handle complex passes like the pass managers which carry pipelines.
1780 if (!InnerPipeline.empty()) {
1781 if (Name == "module") {
1782 ModulePassManager NestedMPM(DebugLogging);
1783 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1784 VerifyEachPass, DebugLogging))
1785 return Err;
1786 MPM.addPass(std::move(NestedMPM));
1787 return Error::success();
1789 if (Name == "cgscc") {
1790 CGSCCPassManager CGPM(DebugLogging);
1791 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1792 DebugLogging))
1793 return Err;
1794 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1795 return Error::success();
1797 if (Name == "function") {
1798 FunctionPassManager FPM(DebugLogging);
1799 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1800 VerifyEachPass, DebugLogging))
1801 return Err;
1802 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1803 return Error::success();
1805 if (auto Count = parseRepeatPassName(Name)) {
1806 ModulePassManager NestedMPM(DebugLogging);
1807 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1808 VerifyEachPass, DebugLogging))
1809 return Err;
1810 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1811 return Error::success();
1814 for (auto &C : ModulePipelineParsingCallbacks)
1815 if (C(Name, MPM, InnerPipeline))
1816 return Error::success();
1818 // Normal passes can't have pipelines.
1819 return make_error<StringError>(
1820 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1821 inconvertibleErrorCode());
1825 // Manually handle aliases for pre-configured pipeline fragments.
1826 if (startsWithDefaultPipelineAliasPrefix(Name)) {
1827 SmallVector<StringRef, 3> Matches;
1828 if (!DefaultAliasRegex.match(Name, &Matches))
1829 return make_error<StringError>(
1830 formatv("unknown default pipeline alias '{0}'", Name).str(),
1831 inconvertibleErrorCode());
1833 assert(Matches.size() == 3 && "Must capture two matched strings!");
1835 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1836 .Case("O0", O0)
1837 .Case("O1", O1)
1838 .Case("O2", O2)
1839 .Case("O3", O3)
1840 .Case("Os", Os)
1841 .Case("Oz", Oz);
1842 if (L == O0) {
1843 // Add instrumentation PGO passes -- at O0 we can still do PGO.
1844 if (PGOOpt && Matches[1] != "thinlto" &&
1845 (PGOOpt->Action == PGOOptions::IRInstr ||
1846 PGOOpt->Action == PGOOptions::IRUse))
1847 addPGOInstrPassesForO0(
1848 MPM, DebugLogging,
1849 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1850 /* IsCS */ false, PGOOpt->ProfileFile,
1851 PGOOpt->ProfileRemappingFile);
1852 // Do nothing else at all!
1853 return Error::success();
1856 if (Matches[1] == "default") {
1857 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1858 } else if (Matches[1] == "thinlto-pre-link") {
1859 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1860 } else if (Matches[1] == "thinlto") {
1861 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
1862 } else if (Matches[1] == "lto-pre-link") {
1863 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1864 } else {
1865 assert(Matches[1] == "lto" && "Not one of the matched options!");
1866 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
1868 return Error::success();
1871 // Finally expand the basic registered passes from the .inc file.
1872 #define MODULE_PASS(NAME, CREATE_PASS) \
1873 if (Name == NAME) { \
1874 MPM.addPass(CREATE_PASS); \
1875 return Error::success(); \
1877 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1878 if (Name == "require<" NAME ">") { \
1879 MPM.addPass( \
1880 RequireAnalysisPass< \
1881 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
1882 return Error::success(); \
1884 if (Name == "invalidate<" NAME ">") { \
1885 MPM.addPass(InvalidateAnalysisPass< \
1886 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1887 return Error::success(); \
1889 #include "PassRegistry.def"
1891 for (auto &C : ModulePipelineParsingCallbacks)
1892 if (C(Name, MPM, InnerPipeline))
1893 return Error::success();
1894 return make_error<StringError>(
1895 formatv("unknown module pass '{0}'", Name).str(),
1896 inconvertibleErrorCode());
1899 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1900 const PipelineElement &E, bool VerifyEachPass,
1901 bool DebugLogging) {
1902 auto &Name = E.Name;
1903 auto &InnerPipeline = E.InnerPipeline;
1905 // First handle complex passes like the pass managers which carry pipelines.
1906 if (!InnerPipeline.empty()) {
1907 if (Name == "cgscc") {
1908 CGSCCPassManager NestedCGPM(DebugLogging);
1909 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1910 VerifyEachPass, DebugLogging))
1911 return Err;
1912 // Add the nested pass manager with the appropriate adaptor.
1913 CGPM.addPass(std::move(NestedCGPM));
1914 return Error::success();
1916 if (Name == "function") {
1917 FunctionPassManager FPM(DebugLogging);
1918 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1919 VerifyEachPass, DebugLogging))
1920 return Err;
1921 // Add the nested pass manager with the appropriate adaptor.
1922 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1923 return Error::success();
1925 if (auto Count = parseRepeatPassName(Name)) {
1926 CGSCCPassManager NestedCGPM(DebugLogging);
1927 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1928 VerifyEachPass, DebugLogging))
1929 return Err;
1930 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1931 return Error::success();
1933 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1934 CGSCCPassManager NestedCGPM(DebugLogging);
1935 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1936 VerifyEachPass, DebugLogging))
1937 return Err;
1938 CGPM.addPass(
1939 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
1940 return Error::success();
1943 for (auto &C : CGSCCPipelineParsingCallbacks)
1944 if (C(Name, CGPM, InnerPipeline))
1945 return Error::success();
1947 // Normal passes can't have pipelines.
1948 return make_error<StringError>(
1949 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1950 inconvertibleErrorCode());
1953 // Now expand the basic registered passes from the .inc file.
1954 #define CGSCC_PASS(NAME, CREATE_PASS) \
1955 if (Name == NAME) { \
1956 CGPM.addPass(CREATE_PASS); \
1957 return Error::success(); \
1959 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1960 if (Name == "require<" NAME ">") { \
1961 CGPM.addPass(RequireAnalysisPass< \
1962 std::remove_reference<decltype(CREATE_PASS)>::type, \
1963 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1964 CGSCCUpdateResult &>()); \
1965 return Error::success(); \
1967 if (Name == "invalidate<" NAME ">") { \
1968 CGPM.addPass(InvalidateAnalysisPass< \
1969 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1970 return Error::success(); \
1972 #include "PassRegistry.def"
1974 for (auto &C : CGSCCPipelineParsingCallbacks)
1975 if (C(Name, CGPM, InnerPipeline))
1976 return Error::success();
1977 return make_error<StringError>(
1978 formatv("unknown cgscc pass '{0}'", Name).str(),
1979 inconvertibleErrorCode());
1982 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1983 const PipelineElement &E,
1984 bool VerifyEachPass, bool DebugLogging) {
1985 auto &Name = E.Name;
1986 auto &InnerPipeline = E.InnerPipeline;
1988 // First handle complex passes like the pass managers which carry pipelines.
1989 if (!InnerPipeline.empty()) {
1990 if (Name == "function") {
1991 FunctionPassManager NestedFPM(DebugLogging);
1992 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1993 VerifyEachPass, DebugLogging))
1994 return Err;
1995 // Add the nested pass manager with the appropriate adaptor.
1996 FPM.addPass(std::move(NestedFPM));
1997 return Error::success();
1999 if (Name == "loop" || Name == "loop-mssa") {
2000 LoopPassManager LPM(DebugLogging);
2001 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
2002 DebugLogging))
2003 return Err;
2004 // Add the nested pass manager with the appropriate adaptor.
2005 bool UseMemorySSA = (Name == "loop-mssa");
2006 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
2007 DebugLogging));
2008 return Error::success();
2010 if (auto Count = parseRepeatPassName(Name)) {
2011 FunctionPassManager NestedFPM(DebugLogging);
2012 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2013 VerifyEachPass, DebugLogging))
2014 return Err;
2015 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
2016 return Error::success();
2019 for (auto &C : FunctionPipelineParsingCallbacks)
2020 if (C(Name, FPM, InnerPipeline))
2021 return Error::success();
2023 // Normal passes can't have pipelines.
2024 return make_error<StringError>(
2025 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
2026 inconvertibleErrorCode());
2029 // Now expand the basic registered passes from the .inc file.
2030 #define FUNCTION_PASS(NAME, CREATE_PASS) \
2031 if (Name == NAME) { \
2032 FPM.addPass(CREATE_PASS); \
2033 return Error::success(); \
2035 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2036 if (checkParametrizedPassName(Name, NAME)) { \
2037 auto Params = parsePassParameters(PARSER, Name, NAME); \
2038 if (!Params) \
2039 return Params.takeError(); \
2040 FPM.addPass(CREATE_PASS(Params.get())); \
2041 return Error::success(); \
2043 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
2044 if (Name == "require<" NAME ">") { \
2045 FPM.addPass( \
2046 RequireAnalysisPass< \
2047 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
2048 return Error::success(); \
2050 if (Name == "invalidate<" NAME ">") { \
2051 FPM.addPass(InvalidateAnalysisPass< \
2052 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
2053 return Error::success(); \
2055 #include "PassRegistry.def"
2057 for (auto &C : FunctionPipelineParsingCallbacks)
2058 if (C(Name, FPM, InnerPipeline))
2059 return Error::success();
2060 return make_error<StringError>(
2061 formatv("unknown function pass '{0}'", Name).str(),
2062 inconvertibleErrorCode());
2065 Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2066 bool VerifyEachPass, bool DebugLogging) {
2067 StringRef Name = E.Name;
2068 auto &InnerPipeline = E.InnerPipeline;
2070 // First handle complex passes like the pass managers which carry pipelines.
2071 if (!InnerPipeline.empty()) {
2072 if (Name == "loop") {
2073 LoopPassManager NestedLPM(DebugLogging);
2074 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2075 VerifyEachPass, DebugLogging))
2076 return Err;
2077 // Add the nested pass manager with the appropriate adaptor.
2078 LPM.addPass(std::move(NestedLPM));
2079 return Error::success();
2081 if (auto Count = parseRepeatPassName(Name)) {
2082 LoopPassManager NestedLPM(DebugLogging);
2083 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2084 VerifyEachPass, DebugLogging))
2085 return Err;
2086 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
2087 return Error::success();
2090 for (auto &C : LoopPipelineParsingCallbacks)
2091 if (C(Name, LPM, InnerPipeline))
2092 return Error::success();
2094 // Normal passes can't have pipelines.
2095 return make_error<StringError>(
2096 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2097 inconvertibleErrorCode());
2100 // Now expand the basic registered passes from the .inc file.
2101 #define LOOP_PASS(NAME, CREATE_PASS) \
2102 if (Name == NAME) { \
2103 LPM.addPass(CREATE_PASS); \
2104 return Error::success(); \
2106 #define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2107 if (checkParametrizedPassName(Name, NAME)) { \
2108 auto Params = parsePassParameters(PARSER, Name, NAME); \
2109 if (!Params) \
2110 return Params.takeError(); \
2111 LPM.addPass(CREATE_PASS(Params.get())); \
2112 return Error::success(); \
2114 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2115 if (Name == "require<" NAME ">") { \
2116 LPM.addPass(RequireAnalysisPass< \
2117 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2118 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2119 LPMUpdater &>()); \
2120 return Error::success(); \
2122 if (Name == "invalidate<" NAME ">") { \
2123 LPM.addPass(InvalidateAnalysisPass< \
2124 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
2125 return Error::success(); \
2127 #include "PassRegistry.def"
2129 for (auto &C : LoopPipelineParsingCallbacks)
2130 if (C(Name, LPM, InnerPipeline))
2131 return Error::success();
2132 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2133 inconvertibleErrorCode());
2136 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
2137 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2138 if (Name == NAME) { \
2139 AA.registerModuleAnalysis< \
2140 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2141 return true; \
2143 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2144 if (Name == NAME) { \
2145 AA.registerFunctionAnalysis< \
2146 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2147 return true; \
2149 #include "PassRegistry.def"
2151 for (auto &C : AAParsingCallbacks)
2152 if (C(Name, AA))
2153 return true;
2154 return false;
2157 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
2158 ArrayRef<PipelineElement> Pipeline,
2159 bool VerifyEachPass,
2160 bool DebugLogging) {
2161 for (const auto &Element : Pipeline) {
2162 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2163 return Err;
2164 // FIXME: No verifier support for Loop passes!
2166 return Error::success();
2169 Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2170 ArrayRef<PipelineElement> Pipeline,
2171 bool VerifyEachPass,
2172 bool DebugLogging) {
2173 for (const auto &Element : Pipeline) {
2174 if (auto Err =
2175 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2176 return Err;
2177 if (VerifyEachPass)
2178 FPM.addPass(VerifierPass());
2180 return Error::success();
2183 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2184 ArrayRef<PipelineElement> Pipeline,
2185 bool VerifyEachPass,
2186 bool DebugLogging) {
2187 for (const auto &Element : Pipeline) {
2188 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2189 return Err;
2190 // FIXME: No verifier support for CGSCC passes!
2192 return Error::success();
2195 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2196 FunctionAnalysisManager &FAM,
2197 CGSCCAnalysisManager &CGAM,
2198 ModuleAnalysisManager &MAM) {
2199 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2200 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
2201 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2202 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2203 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2204 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2205 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2208 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2209 ArrayRef<PipelineElement> Pipeline,
2210 bool VerifyEachPass,
2211 bool DebugLogging) {
2212 for (const auto &Element : Pipeline) {
2213 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2214 return Err;
2215 if (VerifyEachPass)
2216 MPM.addPass(VerifierPass());
2218 return Error::success();
2221 // Primary pass pipeline description parsing routine for a \c ModulePassManager
2222 // FIXME: Should this routine accept a TargetMachine or require the caller to
2223 // pre-populate the analysis managers with target-specific stuff?
2224 Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2225 StringRef PipelineText,
2226 bool VerifyEachPass, bool DebugLogging) {
2227 auto Pipeline = parsePipelineText(PipelineText);
2228 if (!Pipeline || Pipeline->empty())
2229 return make_error<StringError>(
2230 formatv("invalid pipeline '{0}'", PipelineText).str(),
2231 inconvertibleErrorCode());
2233 // If the first name isn't at the module layer, wrap the pipeline up
2234 // automatically.
2235 StringRef FirstName = Pipeline->front().Name;
2237 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2238 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
2239 Pipeline = {{"cgscc", std::move(*Pipeline)}};
2240 } else if (isFunctionPassName(FirstName,
2241 FunctionPipelineParsingCallbacks)) {
2242 Pipeline = {{"function", std::move(*Pipeline)}};
2243 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
2244 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
2245 } else {
2246 for (auto &C : TopLevelPipelineParsingCallbacks)
2247 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2248 return Error::success();
2250 // Unknown pass or pipeline name!
2251 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2252 return make_error<StringError>(
2253 formatv("unknown {0} name '{1}'",
2254 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2255 .str(),
2256 inconvertibleErrorCode());
2260 if (auto Err =
2261 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2262 return Err;
2263 return Error::success();
2266 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
2267 Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2268 StringRef PipelineText,
2269 bool VerifyEachPass, bool DebugLogging) {
2270 auto Pipeline = parsePipelineText(PipelineText);
2271 if (!Pipeline || Pipeline->empty())
2272 return make_error<StringError>(
2273 formatv("invalid pipeline '{0}'", PipelineText).str(),
2274 inconvertibleErrorCode());
2276 StringRef FirstName = Pipeline->front().Name;
2277 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
2278 return make_error<StringError>(
2279 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2280 PipelineText)
2281 .str(),
2282 inconvertibleErrorCode());
2284 if (auto Err =
2285 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2286 return Err;
2287 return Error::success();
2290 // Primary pass pipeline description parsing routine for a \c
2291 // FunctionPassManager
2292 Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2293 StringRef PipelineText,
2294 bool VerifyEachPass, bool DebugLogging) {
2295 auto Pipeline = parsePipelineText(PipelineText);
2296 if (!Pipeline || Pipeline->empty())
2297 return make_error<StringError>(
2298 formatv("invalid pipeline '{0}'", PipelineText).str(),
2299 inconvertibleErrorCode());
2301 StringRef FirstName = Pipeline->front().Name;
2302 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
2303 return make_error<StringError>(
2304 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2305 PipelineText)
2306 .str(),
2307 inconvertibleErrorCode());
2309 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2310 DebugLogging))
2311 return Err;
2312 return Error::success();
2315 // Primary pass pipeline description parsing routine for a \c LoopPassManager
2316 Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2317 StringRef PipelineText,
2318 bool VerifyEachPass, bool DebugLogging) {
2319 auto Pipeline = parsePipelineText(PipelineText);
2320 if (!Pipeline || Pipeline->empty())
2321 return make_error<StringError>(
2322 formatv("invalid pipeline '{0}'", PipelineText).str(),
2323 inconvertibleErrorCode());
2325 if (auto Err =
2326 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2327 return Err;
2329 return Error::success();
2332 Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
2333 // If the pipeline just consists of the word 'default' just replace the AA
2334 // manager with our default one.
2335 if (PipelineText == "default") {
2336 AA = buildDefaultAAPipeline();
2337 return Error::success();
2340 while (!PipelineText.empty()) {
2341 StringRef Name;
2342 std::tie(Name, PipelineText) = PipelineText.split(',');
2343 if (!parseAAPassName(AA, Name))
2344 return make_error<StringError>(
2345 formatv("unknown alias analysis name '{0}'", Name).str(),
2346 inconvertibleErrorCode());
2349 return Error::success();